Skip to main content

waft_material/
slider_parts.rs

1//! Flutter counterpart: material_ui's `slider_parts.dart`.
2//!
3//! [`SliderTickMarkShape`] and [`SliderTrackShape`] are abstract classes users subclass, so
4//! traits held as [`SliderTickMarkShapeRef`] and [`SliderTrackShapeRef`]; the mixin
5//! [`BaseSliderTrackShape`] is a trait with provided bodies that a track's
6//! [`SliderTrackShape`] methods call. A parameter Dart declares optional with no default in
7//! the abstract signature is an `Option`, so an implementation applies its own default as
8//! Dart's override does. A shape's `paint` takes the `App`: the animations and the parent box
9//! live there, and the `Tween` and `ColorTween` Dart makes on each paint are arena objects
10//! that [`evaluate_tween`] and [`evaluate_color_tween`] make and evaluate.
11
12use std::any::Any;
13use std::fmt::Debug;
14use std::rc::Rc;
15
16use waft_animation::{Animatable, AnyAnimation, ColorTween, Tween};
17use waft_embedder::{
18    Canvas, ClipOp, Color, FillRule, Offset, Paint, PaintStyle, Path, PathBuilder, RRect, Radius,
19    Rect, Size, Stroke, TextDirection, rrect_radii_elliptical,
20};
21use waft_foundation::App;
22use waft_painting::{BorderRadius, ClipContext, PaintingBinding, TextPainter, draw_rrect};
23use waft_rendering::{AnyRenderBox, PaintingContext, RenderView};
24use waft_widgets::WidgetStates;
25
26use crate::colors::Colors;
27
28use crate::slider_theme::SliderThemeData;
29use crate::slider_value_indicator_shape::SliderComponentShape;
30
31/// Dart's `ColorTween(begin: begin, end: end).evaluate(animation)`.
32pub(crate) fn evaluate_color_tween(
33    app: &mut App,
34    begin: Option<Color>,
35    end: Option<Color>,
36    animation: AnyAnimation<f64>,
37) -> Option<Color> {
38    let tween = ColorTween::new(app, begin, end);
39    tween.evaluate(app, animation)
40}
41
42/// Dart's `Tween<double>(begin: begin, end: end).evaluate(animation)`.
43pub(crate) fn evaluate_tween(
44    app: &mut App,
45    begin: f64,
46    end: f64,
47    animation: AnyAnimation<f64>,
48) -> f64 {
49    let tween = Tween::new(app, Some(begin), Some(end));
50    tween.evaluate(app, animation)
51}
52
53/// Dart's `canvas.drawShadow(path, color, elevation, transparentOccluder)`, with the device
54/// pixel ratio of the view `parent_box` paints into, which the engine reads from the implicit
55/// view; 1 outside a view, as the engine's is without metrics.
56pub(crate) fn draw_shadow(
57    app: &App,
58    canvas: &mut Canvas,
59    parent_box: AnyRenderBox,
60    path: &Path,
61    color: Color,
62    elevation: f64,
63    transparent_occluder: bool,
64) {
65    let device_pixel_ratio = parent_box
66        .as_object()
67        .owner(app)
68        .and_then(|owner| owner.root_node(app))
69        .and_then(|root| root.downcast::<RenderView>(app))
70        .map_or(1.0, |view| view.configuration(app).device_pixel_ratio);
71    canvas.draw_shadow(
72        path.as_valo(),
73        path.fill_type,
74        color.into(),
75        elevation as f32,
76        transparent_occluder,
77        device_pixel_ratio as f32,
78    );
79}
80
81/// Base class for `Slider` tick mark shapes.
82///
83/// Create a subclass of this if you would like a custom slider tick mark shape.
84///
85/// The tick mark painting can be skipped by specifying
86/// [`no_tick_mark`](<dyn SliderTickMarkShape>::no_tick_mark) for
87/// `SliderThemeData::tick_mark_shape`.
88///
89/// Equality is [`eq_shape`](Self::eq_shape): identity, as Dart's default `==`, unless the
90/// shape overrides it.
91///
92/// See also:
93///
94///  * [`RoundSliderTickMarkShape`], which is the default `Slider`'s tick mark
95///    shape that paints a solid circle.
96///  * [`SliderTrackShape`], which can be used to create custom shapes for the
97///    `Slider`'s track.
98///  * [`SliderComponentShape`], which can be used to create custom shapes for
99///    the `Slider`'s thumb, overlay, and value indicator and the
100///    `RangeSlider`'s overlay.
101pub trait SliderTickMarkShape: Any + Debug {
102    /// Returns the preferred size of the shape.
103    ///
104    /// It is used to help position the tick marks within the slider.
105    ///
106    /// the `slider_theme` argument is the theme assigned to the `Slider` that this
107    /// shape belongs to.
108    ///
109    /// The `is_enabled` argument is false when `Slider::on_changed` is null and true
110    /// otherwise. When true, the slider will respond to input.
111    fn get_preferred_size(&self, slider_theme: &SliderThemeData, is_enabled: bool) -> Size;
112
113    /// Paints the slider track.
114    ///
115    /// The `context` argument is the same as the one that includes the `Slider`'s
116    /// render box.
117    ///
118    /// The `center` argument is the offset for where this shape's center should be
119    /// painted. This offset is relative to the origin of the `context` canvas.
120    ///
121    /// The `parent_box` argument is the `RenderBox` of the `Slider`. Its attributes,
122    /// such as size, can be used to assist in painting this shape.
123    ///
124    /// the `slider_theme` argument is the theme assigned to the `Slider` that this
125    /// shape belongs to.
126    ///
127    /// The `enable_animation` argument is an animation triggered when the `Slider`
128    /// is enabled, and it reverses when the slider is disabled. The `Slider` is
129    /// enabled when `Slider::on_changed` is not null. Use this to paint
130    /// intermediate frames for this shape when the slider changes enabled state.
131    ///
132    /// The `is_enabled` argument is false when `Slider::on_changed` is null and true
133    /// otherwise. When true, the slider will respond to input.
134    ///
135    /// The `text_direction` argument can be used to determine how the tick marks
136    /// are painting depending on whether they are on an active track segment or
137    /// not. The track segment between the start of the slider and the thumb is
138    /// the active track segment. The track segment between the thumb and the end
139    /// of the slider is the inactive track segment. In LTR text direction, the
140    /// start of the slider is on the left, and in RTL text direction, the start
141    /// of the slider is on the right.
142    #[expect(clippy::too_many_arguments, reason = "Dart's parameters, in its order")]
143    fn paint(
144        &self,
145        app: &mut App,
146        context: &mut PaintingContext,
147        center: Offset,
148        parent_box: AnyRenderBox,
149        slider_theme: &SliderThemeData,
150        enable_animation: AnyAnimation<f64>,
151        thumb_center: Offset,
152        is_enabled: bool,
153        text_direction: TextDirection,
154    );
155
156    /// Downcast support for Dart's `is` checks.
157    fn as_any(&self) -> &dyn Any;
158
159    /// Dart's `==`: identity unless a shape overrides it.
160    fn eq_shape(&self, other: &dyn SliderTickMarkShape) -> bool {
161        std::ptr::eq(self.as_any(), other.as_any())
162    }
163}
164
165/// What a field or parameter Dart types as `SliderTickMarkShape` becomes.
166pub type SliderTickMarkShapeRef = Rc<dyn SliderTickMarkShape>;
167
168impl PartialEq for dyn SliderTickMarkShape {
169    fn eq(&self, other: &dyn SliderTickMarkShape) -> bool {
170        self.eq_shape(other)
171    }
172}
173
174thread_local! {
175    static NO_TICK_MARK: SliderTickMarkShapeRef = Rc::new(EmptySliderTickMarkShape);
176}
177
178impl dyn SliderTickMarkShape {
179    /// Special instance of [`SliderTickMarkShape`] to skip the tick mark painting.
180    ///
181    /// Each call hands out the same instance, as Dart's `static final` field is one object.
182    ///
183    /// See also:
184    ///
185    ///  * `SliderThemeData::tick_mark_shape`, which is the shape that the `Slider`
186    ///    uses when painting tick marks.
187    pub fn no_tick_mark() -> SliderTickMarkShapeRef {
188        NO_TICK_MARK.with(Rc::clone)
189    }
190}
191
192/// Base class for slider track shapes.
193///
194/// The slider's thumb moves along the track. A discrete slider's tick marks
195/// are drawn after the track, but before the thumb, and are aligned with the
196/// track.
197///
198/// The [`get_preferred_rect`](Self::get_preferred_rect) helps position the slider thumb and
199/// tick marks relative to the track.
200///
201/// Equality is [`eq_shape`](Self::eq_shape): identity, as Dart's default `==`, unless the
202/// shape overrides it.
203///
204/// See also:
205///
206///  * [`RoundedRectSliderTrackShape`] for the default `Slider`'s track shape that
207///    paints a stadium-like track.
208///  * [`SliderTickMarkShape`], which can be used to create custom shapes for the
209///    `Slider`'s tick marks.
210///  * [`SliderComponentShape`], which can be used to create custom shapes for
211///    the `Slider`'s thumb, overlay, and value indicator and the
212///    `RangeSlider`'s overlay.
213pub trait SliderTrackShape: Any + Debug {
214    /// Returns the preferred bounds of the shape.
215    ///
216    /// It is used to provide horizontal boundaries for the thumb's position, and
217    /// to help position the slider thumb and tick marks relative to the track.
218    ///
219    /// The `parent_box` argument can be used to help determine the preferredRect relative to
220    /// attributes of the render box of the slider itself, such as size.
221    ///
222    /// The `offset` argument is relative to the caller's bounding box. It can be used to
223    /// convert gesture coordinates from global to slider-relative coordinates; Dart's
224    /// default is `Offset.zero`.
225    ///
226    /// the `slider_theme` argument is the theme assigned to the `Slider` that this
227    /// shape belongs to.
228    ///
229    /// The `is_enabled` argument is false when `Slider::on_changed` is null and true
230    /// otherwise. When true, the slider will respond to input. `None` is Dart's argument
231    /// left out.
232    ///
233    /// The `is_discrete` argument is true if `Slider::divisions` is non-null. When
234    /// true, the slider will render tick marks on top of the track. `None` is Dart's
235    /// argument left out.
236    fn get_preferred_rect(
237        &self,
238        app: &App,
239        parent_box: AnyRenderBox,
240        offset: Offset,
241        slider_theme: &SliderThemeData,
242        is_enabled: Option<bool>,
243        is_discrete: Option<bool>,
244    ) -> Rect;
245
246    /// Paints the track shape based on the state passed to it.
247    ///
248    /// The `context` argument is the same as the one that includes the `Slider`'s
249    /// render box.
250    ///
251    /// The `offset` argument the offset of the origin of the `parent_box` to the
252    /// origin of its `context` canvas. This shape must be painted relative to
253    /// this offset. See `PaintingContextCallback`.
254    ///
255    /// The `parent_box` argument is the `RenderBox` of the `Slider`. Its attributes,
256    /// such as size, can be used to assist in painting this shape.
257    ///
258    /// the `slider_theme` argument is the theme assigned to the `Slider` that this
259    /// shape belongs to.
260    ///
261    /// The `enable_animation` argument is an animation triggered when the `Slider`
262    /// is enabled, and it reverses when the slider is disabled. The `Slider` is
263    /// enabled when `Slider::on_changed` is not null. Use this to paint
264    /// intermediate frames for this shape when the slider changes enabled state.
265    ///
266    /// The `thumb_center` argument is the offset of the center of the thumb
267    /// relative to the origin of the `PaintingContext::canvas`. It can be used as
268    /// the point that divides the track into 2 segments.
269    ///
270    /// The `secondary_offset` argument is the offset of the secondary value
271    /// relative to the origin of the `PaintingContext::canvas`.
272    ///
273    /// If not null, the track is divided into 3 segments.
274    ///
275    /// The `is_enabled` argument is false when `Slider::on_changed` is null and true
276    /// otherwise. When true, the slider will respond to input. `None` is Dart's argument
277    /// left out.
278    ///
279    /// The `is_discrete` argument is true if `Slider::divisions` is non-null. When
280    /// true, the slider will render tick marks on top of the track. `None` is Dart's
281    /// argument left out.
282    ///
283    /// The `text_direction` argument can be used to determine how the track
284    /// segments are painted depending on whether they are active or not.
285    ///
286    /// The track segment between the start of the slider and the thumb is the
287    /// active track segment. The track segment between the thumb and the end of the
288    /// slider is the inactive track segment. In `TextDirection::Ltr`, the start of
289    /// the slider is on the left, and in `TextDirection::Rtl`, the start of the
290    /// slider is on the right.
291    #[expect(clippy::too_many_arguments, reason = "Dart's parameters, in its order")]
292    fn paint(
293        &self,
294        app: &mut App,
295        context: &mut PaintingContext,
296        offset: Offset,
297        parent_box: AnyRenderBox,
298        slider_theme: &SliderThemeData,
299        enable_animation: AnyAnimation<f64>,
300        thumb_center: Offset,
301        secondary_offset: Option<Offset>,
302        is_enabled: Option<bool>,
303        is_discrete: Option<bool>,
304        text_direction: TextDirection,
305    );
306
307    /// Whether the track shape is rounded.
308    ///
309    /// This is used to determine the correct position of the thumb in relation to the track.
310    fn is_rounded(&self) -> bool {
311        false
312    }
313
314    /// Downcast support for Dart's `is` checks.
315    fn as_any(&self) -> &dyn Any;
316
317    /// Dart's `==`: identity unless a shape overrides it.
318    fn eq_shape(&self, other: &dyn SliderTrackShape) -> bool {
319        std::ptr::eq(self.as_any(), other.as_any())
320    }
321}
322
323/// What a field or parameter Dart types as `SliderTrackShape` becomes.
324pub type SliderTrackShapeRef = Rc<dyn SliderTrackShape>;
325
326impl PartialEq for dyn SliderTrackShape {
327    fn eq(&self, other: &dyn SliderTrackShape) -> bool {
328        self.eq_shape(other)
329    }
330}
331
332/// Base track shape that provides an implementation of
333/// [`get_preferred_rect`](Self::get_preferred_rect) for default sizing.
334///
335/// The height is set from `SliderThemeData::track_height` and the width of the
336/// parent box less the larger of the widths of `SliderThemeData::thumb_shape` and
337/// `SliderThemeData::overlay_shape`.
338///
339/// A track that mixes it in calls these bodies from its [`SliderTrackShape`] methods.
340///
341/// See also:
342///
343///  * [`RectangularSliderTrackShape`], which is a track shape with sharp
344///    rectangular edges
345///  * [`RoundedRectSliderTrackShape`], which is a track shape with round
346///    stadium-like edges.
347pub trait BaseSliderTrackShape {
348    /// Returns a rect that represents the track bounds that fits within the
349    /// `Slider`.
350    ///
351    /// The width is the width of the `Slider` or `RangeSlider`, but padded by
352    /// the max of the overlay and thumb radius. The height is defined by the
353    /// `SliderThemeData::track_height`.
354    ///
355    /// The [`Rect`] is centered both horizontally and vertically within the slider
356    /// bounds.
357    fn get_preferred_rect(
358        &self,
359        app: &App,
360        parent_box: AnyRenderBox,
361        offset: Offset,
362        slider_theme: &SliderThemeData,
363        is_enabled: Option<bool>,
364        is_discrete: Option<bool>,
365    ) -> Rect {
366        let is_enabled = is_enabled.unwrap_or(false);
367        let is_discrete = is_discrete.unwrap_or(false);
368        let thumb_width = slider_theme
369            .thumb_shape
370            .as_ref()
371            .expect("a slider theme with a thumb shape")
372            .get_preferred_size(is_enabled, is_discrete)
373            .width();
374        let overlay_width = slider_theme
375            .overlay_shape
376            .as_ref()
377            .expect("a slider theme with an overlay shape")
378            .get_preferred_size(is_enabled, is_discrete)
379            .width();
380        let mut track_height = slider_theme
381            .track_height
382            .expect("a slider theme with a track height");
383        debug_assert!(overlay_width >= 0.0);
384        debug_assert!(track_height >= 0.0);
385
386        // If the track colors are transparent, then override only the track height
387        // to maintain overall Slider width.
388        if slider_theme.active_track_color == Some(Colors::TRANSPARENT)
389            && slider_theme.inactive_track_color == Some(Colors::TRANSPARENT)
390        {
391            track_height = 0.0;
392        }
393
394        let parent_size = parent_box.size(app);
395        let track_left = offset.dx()
396            + if slider_theme.padding.is_none() {
397                (overlay_width / 2.0).max(thumb_width / 2.0)
398            } else {
399                0.0
400            };
401        let track_top = offset.dy() + (parent_size.height() - track_height) / 2.0;
402        let track_right = track_left + parent_size.width()
403            - if slider_theme.padding.is_none() {
404                thumb_width.max(overlay_width)
405            } else {
406                0.0
407            };
408        let track_bottom = track_top + track_height;
409        // If the parentBox's size less than slider's size the trackRight will be less than trackLeft, so switch them.
410        Rect::from_ltrb(
411            track_left.min(track_right),
412            track_top,
413            track_left.max(track_right),
414            track_bottom,
415        )
416    }
417
418    /// Whether the track shape is rounded. This is used to determine the correct
419    /// position of the thumb in relation to the track. Defaults to false.
420    fn is_rounded(&self) -> bool {
421        false
422    }
423}
424
425/// A `Slider` track that's a simple rectangle.
426///
427/// It paints a solid colored rectangle, vertically centered in the
428/// `parent_box`. The track rectangle extends to the bounds of the `parent_box`,
429/// but is padded by the `RoundSliderOverlayShape` radius. The height is defined
430/// by the `SliderThemeData::track_height`. The color is determined by the
431/// `Slider`'s enabled state and the track segment's active state which are
432/// defined by:
433///   `SliderThemeData::active_track_color`,
434///   `SliderThemeData::inactive_track_color`,
435///   `SliderThemeData::disabled_active_track_color`,
436///   `SliderThemeData::disabled_inactive_track_color`.
437///
438/// The track segment between the start of the slider and the thumb is the
439/// active track segment. The track segment between the thumb and the end of the
440/// slider is the inactive track segment. In `TextDirection::Ltr`, the start of
441/// the slider is on the left, and in `TextDirection::Rtl`, the start of the
442/// slider is on the right.
443///
444/// See also:
445///
446///  * `Slider`, for the component that is meant to display this shape.
447///  * [`SliderThemeData`], where an instance of this class is set to inform the
448///    slider of the visual details of the its track.
449///  * [`SliderTrackShape`], which can be used to create custom shapes for the
450///    `Slider`'s track.
451///  * [`RoundedRectSliderTrackShape`], for a similar track with rounded edges.
452#[derive(Clone, Copy, Debug, Default, PartialEq)]
453pub struct RectangularSliderTrackShape;
454
455impl RectangularSliderTrackShape {
456    /// Creates a slider track that draws 2 rectangles.
457    pub const fn new() -> RectangularSliderTrackShape {
458        RectangularSliderTrackShape
459    }
460}
461
462impl BaseSliderTrackShape for RectangularSliderTrackShape {}
463
464impl SliderTrackShape for RectangularSliderTrackShape {
465    fn get_preferred_rect(
466        &self,
467        app: &App,
468        parent_box: AnyRenderBox,
469        offset: Offset,
470        slider_theme: &SliderThemeData,
471        is_enabled: Option<bool>,
472        is_discrete: Option<bool>,
473    ) -> Rect {
474        BaseSliderTrackShape::get_preferred_rect(
475            self,
476            app,
477            parent_box,
478            offset,
479            slider_theme,
480            is_enabled,
481            is_discrete,
482        )
483    }
484
485    fn paint(
486        &self,
487        app: &mut App,
488        context: &mut PaintingContext,
489        offset: Offset,
490        parent_box: AnyRenderBox,
491        slider_theme: &SliderThemeData,
492        enable_animation: AnyAnimation<f64>,
493        thumb_center: Offset,
494        secondary_offset: Option<Offset>,
495        is_enabled: Option<bool>,
496        is_discrete: Option<bool>,
497        text_direction: TextDirection,
498    ) {
499        let is_discrete = is_discrete.unwrap_or(false);
500        let is_enabled = is_enabled.unwrap_or(false);
501        debug_assert!(slider_theme.disabled_active_track_color.is_some());
502        debug_assert!(slider_theme.disabled_inactive_track_color.is_some());
503        debug_assert!(slider_theme.active_track_color.is_some());
504        debug_assert!(slider_theme.inactive_track_color.is_some());
505        debug_assert!(slider_theme.thumb_shape.is_some());
506        // If the slider [SliderThemeData.trackHeight] is less than or equal to 0,
507        // then it makes no difference whether the track is painted or not,
508        // therefore the painting can be a no-op.
509        if slider_theme
510            .track_height
511            .expect("a slider theme with a track height")
512            <= 0.0
513        {
514            return;
515        }
516
517        // Assign the track segment paints, which are left: active, right: inactive,
518        // but reversed for right to left text.
519        let active_paint = Paint::from_color(
520            evaluate_color_tween(
521                app,
522                slider_theme.disabled_active_track_color,
523                slider_theme.active_track_color,
524                enable_animation,
525            )
526            .expect("both track colors are set")
527            .into(),
528        );
529        let inactive_paint = Paint::from_color(
530            evaluate_color_tween(
531                app,
532                slider_theme.disabled_inactive_track_color,
533                slider_theme.inactive_track_color,
534                enable_animation,
535            )
536            .expect("both track colors are set")
537            .into(),
538        );
539        let (left_track_paint, right_track_paint) = match text_direction {
540            TextDirection::Ltr => (&active_paint, &inactive_paint),
541            TextDirection::Rtl => (&inactive_paint, &active_paint),
542        };
543
544        let track_rect = SliderTrackShape::get_preferred_rect(
545            self,
546            app,
547            parent_box,
548            offset,
549            slider_theme,
550            Some(is_enabled),
551            Some(is_discrete),
552        );
553
554        let left_track_segment = Rect::from_ltrb(
555            track_rect.left,
556            track_rect.top,
557            thumb_center.dx(),
558            track_rect.bottom,
559        );
560        if !left_track_segment.is_empty() {
561            context
562                .canvas()
563                .draw_rect(left_track_segment, left_track_paint);
564        }
565        let right_track_segment = Rect::from_ltrb(
566            thumb_center.dx(),
567            track_rect.top,
568            track_rect.right,
569            track_rect.bottom,
570        );
571        if !right_track_segment.is_empty() {
572            context
573                .canvas()
574                .draw_rect(right_track_segment, right_track_paint);
575        }
576
577        let show_secondary_track =
578            secondary_offset.is_some_and(|secondary_offset| match text_direction {
579                TextDirection::Rtl => secondary_offset.dx() < thumb_center.dx(),
580                TextDirection::Ltr => secondary_offset.dx() > thumb_center.dx(),
581            });
582
583        if let Some(secondary_offset) = secondary_offset.filter(|_| show_secondary_track) {
584            let secondary_track_paint = Paint::from_color(
585                evaluate_color_tween(
586                    app,
587                    slider_theme.disabled_secondary_active_track_color,
588                    slider_theme.secondary_active_track_color,
589                    enable_animation,
590                )
591                .expect("both secondary track colors are set")
592                .into(),
593            );
594            let secondary_track_segment = match text_direction {
595                TextDirection::Rtl => Rect::from_ltrb(
596                    secondary_offset.dx(),
597                    track_rect.top,
598                    thumb_center.dx(),
599                    track_rect.bottom,
600                ),
601                TextDirection::Ltr => Rect::from_ltrb(
602                    thumb_center.dx(),
603                    track_rect.top,
604                    secondary_offset.dx(),
605                    track_rect.bottom,
606                ),
607            };
608            if !secondary_track_segment.is_empty() {
609                context
610                    .canvas()
611                    .draw_rect(secondary_track_segment, &secondary_track_paint);
612            }
613        }
614    }
615
616    fn is_rounded(&self) -> bool {
617        BaseSliderTrackShape::is_rounded(self)
618    }
619
620    fn as_any(&self) -> &dyn Any {
621        self
622    }
623
624    /// Value equality, as Dart's canonicalized `const` instances are identical.
625    fn eq_shape(&self, other: &dyn SliderTrackShape) -> bool {
626        other.as_any().downcast_ref::<Self>() == Some(self)
627    }
628}
629
630/// Dart's `_TrackSegment`: a horizontal span of the track, and whether it is wide enough to
631/// be painted.
632#[derive(Clone, Copy)]
633struct TrackSegment {
634    draw: bool,
635    left: f64,
636    right: f64,
637}
638
639/// The default shape of a `Slider`'s track.
640///
641/// It paints a solid colored rectangle with rounded edges, vertically centered
642/// in the `parent_box`. The track rectangle extends to the bounds of the
643/// `parent_box`, but is padded by the larger of `RoundSliderOverlayShape`'s
644/// radius and [`RoundSliderThumbShape`]'s radius. The height is defined by the
645/// `SliderThemeData::track_height`. The color is determined by the `Slider`'s
646/// enabled state and the track segment's active state which are defined by:
647///   `SliderThemeData::active_track_color`,
648///   `SliderThemeData::inactive_track_color`,
649///   `SliderThemeData::disabled_active_track_color`,
650///   `SliderThemeData::disabled_inactive_track_color`.
651///
652/// The track segment between the start of the slider and the thumb is the
653/// active track segment. The track segment between the thumb and the end of the
654/// slider is the inactive track segment. In `TextDirection::Ltr`, the start of
655/// the slider is on the left, and in `TextDirection::Rtl`, the start of the
656/// slider is on the right.
657///
658/// See also:
659///
660///  * `Slider`, for the component that is meant to display this shape.
661///  * [`SliderThemeData`], where an instance of this class is set to inform the
662///    slider of the visual details of the its track.
663///  * [`SliderTrackShape`], which can be used to create custom shapes for the
664///    `Slider`'s track.
665///  * [`RectangularSliderTrackShape`], for a similar track with sharp edges.
666#[derive(Clone, Copy, Debug, Default, PartialEq)]
667pub struct RoundedRectSliderTrackShape;
668
669impl RoundedRectSliderTrackShape {
670    /// Create a slider track that draws two rectangles with rounded outer edges.
671    pub const fn new() -> RoundedRectSliderTrackShape {
672        RoundedRectSliderTrackShape
673    }
674
675    /// Dart's `paint` with its extra `additionalActiveTrackHeight` argument, which the
676    /// [`SliderTrackShape::paint`] override passes as Dart's default, 2.
677    #[expect(clippy::too_many_arguments, reason = "Dart's parameters, in its order")]
678    pub fn paint(
679        &self,
680        app: &mut App,
681        context: &mut PaintingContext,
682        offset: Offset,
683        parent_box: AnyRenderBox,
684        slider_theme: &SliderThemeData,
685        enable_animation: AnyAnimation<f64>,
686        text_direction: TextDirection,
687        thumb_center: Offset,
688        secondary_offset: Option<Offset>,
689        is_discrete: bool,
690        is_enabled: bool,
691        additional_active_track_height: f64,
692    ) {
693        debug_assert!(slider_theme.disabled_active_track_color.is_some());
694        debug_assert!(slider_theme.disabled_inactive_track_color.is_some());
695        debug_assert!(slider_theme.active_track_color.is_some());
696        debug_assert!(slider_theme.inactive_track_color.is_some());
697        debug_assert!(slider_theme.thumb_shape.is_some());
698        // If the slider [SliderThemeData.trackHeight] is less than or equal to 0,
699        // then it makes no difference whether the track is painted or not,
700        // therefore the painting can be a no-op.
701        let Some(track_height) = slider_theme.track_height.filter(|height| *height > 0.0) else {
702            return;
703        };
704
705        // Assign the track segment paints, which are leading: active and
706        // trailing: inactive.
707        let active_paint = Paint::from_color(
708            evaluate_color_tween(
709                app,
710                slider_theme.disabled_active_track_color,
711                slider_theme.active_track_color,
712                enable_animation,
713            )
714            .expect("both track colors are set")
715            .into(),
716        );
717        let inactive_paint = Paint::from_color(
718            evaluate_color_tween(
719                app,
720                slider_theme.disabled_inactive_track_color,
721                slider_theme.inactive_track_color,
722                enable_animation,
723            )
724            .expect("both track colors are set")
725            .into(),
726        );
727
728        let track_rect = SliderTrackShape::get_preferred_rect(
729            self,
730            app,
731            parent_box,
732            offset,
733            slider_theme,
734            Some(is_enabled),
735            Some(is_discrete),
736        );
737        let track_radius = Radius::circular(track_rect.height() / 2.0);
738        let active_track_radius =
739            Radius::circular((track_rect.height() + additional_active_track_height) / 2.0);
740        let is_ltr = text_direction == TextDirection::Ltr;
741
742        // Both segments extend past the thumb center by half of the track height.
743        let half_track_height = track_height / 2.0;
744        let left_track = TrackSegment {
745            draw: thumb_center.dx() > track_rect.left + half_track_height,
746            left: track_rect.left,
747            right: thumb_center.dx() + half_track_height,
748        };
749        let right_track = TrackSegment {
750            draw: thumb_center.dx() < track_rect.right - half_track_height,
751            left: thumb_center.dx() - half_track_height,
752            right: track_rect.right,
753        };
754        let (inactive_track, active_track) = if is_ltr {
755            (right_track, left_track)
756        } else {
757            (left_track, right_track)
758        };
759
760        // The segment painted last has its rounded end drawn on top of the other one,
761        // so paint the inactive segment first to keep the active one on top in both
762        // text directions.
763        if inactive_track.draw {
764            draw_rrect(
765                context.canvas(),
766                RRect::from_ltrbr(
767                    inactive_track.left,
768                    track_rect.top,
769                    inactive_track.right,
770                    track_rect.bottom,
771                    track_radius,
772                ),
773                &inactive_paint,
774            );
775        }
776        if active_track.draw {
777            draw_rrect(
778                context.canvas(),
779                RRect::from_ltrbr(
780                    active_track.left,
781                    track_rect.top - (additional_active_track_height / 2.0),
782                    active_track.right,
783                    track_rect.bottom + (additional_active_track_height / 2.0),
784                    active_track_radius,
785                ),
786                &active_paint,
787            );
788        }
789
790        let show_secondary_track = secondary_offset.is_some_and(|secondary_offset| {
791            if is_ltr {
792                secondary_offset.dx() > thumb_center.dx()
793            } else {
794                secondary_offset.dx() < thumb_center.dx()
795            }
796        });
797
798        if let Some(secondary_offset) = secondary_offset.filter(|_| show_secondary_track) {
799            let secondary_track_paint = Paint::from_color(
800                evaluate_color_tween(
801                    app,
802                    slider_theme.disabled_secondary_active_track_color,
803                    slider_theme.secondary_active_track_color,
804                    enable_animation,
805                )
806                .expect("both secondary track colors are set")
807                .into(),
808            );
809            if is_ltr {
810                draw_rrect(
811                    context.canvas(),
812                    RRect::from_ltrb_and_corners(
813                        thumb_center.dx(),
814                        track_rect.top,
815                        secondary_offset.dx(),
816                        track_rect.bottom,
817                        Radius::ZERO,
818                        track_radius,
819                        track_radius,
820                        Radius::ZERO,
821                    ),
822                    &secondary_track_paint,
823                );
824            } else {
825                draw_rrect(
826                    context.canvas(),
827                    RRect::from_ltrb_and_corners(
828                        secondary_offset.dx(),
829                        track_rect.top,
830                        thumb_center.dx(),
831                        track_rect.bottom,
832                        track_radius,
833                        Radius::ZERO,
834                        Radius::ZERO,
835                        track_radius,
836                    ),
837                    &secondary_track_paint,
838                );
839            }
840        }
841    }
842}
843
844impl BaseSliderTrackShape for RoundedRectSliderTrackShape {}
845
846impl SliderTrackShape for RoundedRectSliderTrackShape {
847    fn get_preferred_rect(
848        &self,
849        app: &App,
850        parent_box: AnyRenderBox,
851        offset: Offset,
852        slider_theme: &SliderThemeData,
853        is_enabled: Option<bool>,
854        is_discrete: Option<bool>,
855    ) -> Rect {
856        BaseSliderTrackShape::get_preferred_rect(
857            self,
858            app,
859            parent_box,
860            offset,
861            slider_theme,
862            is_enabled,
863            is_discrete,
864        )
865    }
866
867    fn paint(
868        &self,
869        app: &mut App,
870        context: &mut PaintingContext,
871        offset: Offset,
872        parent_box: AnyRenderBox,
873        slider_theme: &SliderThemeData,
874        enable_animation: AnyAnimation<f64>,
875        thumb_center: Offset,
876        secondary_offset: Option<Offset>,
877        is_enabled: Option<bool>,
878        is_discrete: Option<bool>,
879        text_direction: TextDirection,
880    ) {
881        RoundedRectSliderTrackShape::paint(
882            self,
883            app,
884            context,
885            offset,
886            parent_box,
887            slider_theme,
888            enable_animation,
889            text_direction,
890            thumb_center,
891            secondary_offset,
892            is_discrete.unwrap_or(false),
893            is_enabled.unwrap_or(false),
894            2.0,
895        );
896    }
897
898    fn is_rounded(&self) -> bool {
899        true
900    }
901
902    fn as_any(&self) -> &dyn Any {
903        self
904    }
905
906    /// Value equality, as Dart's canonicalized `const` instances are identical.
907    fn eq_shape(&self, other: &dyn SliderTrackShape) -> bool {
908        other.as_any().downcast_ref::<Self>() == Some(self)
909    }
910}
911
912/// The default shape of each `Slider` tick mark.
913///
914/// Tick marks are only displayed if the slider is discrete, which can be done
915/// by setting the `Slider::divisions` to an integer value.
916///
917/// It paints a solid circle, centered in the on the track.
918/// The color is determined by the `Slider`'s enabled state and track's active
919/// states. These colors are defined in:
920///   `SliderThemeData::active_track_color`,
921///   `SliderThemeData::inactive_track_color`,
922///   `SliderThemeData::disabled_active_track_color`,
923///   `SliderThemeData::disabled_inactive_track_color`.
924///
925/// See also:
926///
927///  * `Slider`, which includes tick marks defined by this shape.
928///  * `SliderTheme`, which can be used to configure the tick mark shape of all
929///    sliders in a widget subtree.
930#[derive(Clone, Copy, Debug, Default, PartialEq)]
931pub struct RoundSliderTickMarkShape {
932    /// The preferred radius of the round tick mark.
933    ///
934    /// If it is not provided, then 1/4 of the `SliderThemeData::track_height` is used.
935    pub tick_mark_radius: Option<f64>,
936}
937
938impl RoundSliderTickMarkShape {
939    /// Create a slider tick mark that draws a circle.
940    pub const fn new() -> RoundSliderTickMarkShape {
941        RoundSliderTickMarkShape {
942            tick_mark_radius: None,
943        }
944    }
945
946    /// Dart `RoundSliderTickMarkShape(tickMarkRadius:)`.
947    pub const fn tick_mark_radius(mut self, tick_mark_radius: f64) -> RoundSliderTickMarkShape {
948        self.tick_mark_radius = Some(tick_mark_radius);
949        self
950    }
951}
952
953impl SliderTickMarkShape for RoundSliderTickMarkShape {
954    fn get_preferred_size(&self, slider_theme: &SliderThemeData, _is_enabled: bool) -> Size {
955        debug_assert!(slider_theme.track_height.is_some());
956        // The tick marks are tiny circles. If no radius is provided, then the
957        // radius is defaulted to be a fraction of the
958        // [SliderThemeData.trackHeight]. The fraction is 1/4.
959        Size::from_radius(self.tick_mark_radius.unwrap_or_else(|| {
960            slider_theme
961                .track_height
962                .expect("a slider theme with a track height")
963                / 4.0
964        }))
965    }
966
967    fn paint(
968        &self,
969        app: &mut App,
970        context: &mut PaintingContext,
971        center: Offset,
972        _parent_box: AnyRenderBox,
973        slider_theme: &SliderThemeData,
974        enable_animation: AnyAnimation<f64>,
975        thumb_center: Offset,
976        is_enabled: bool,
977        text_direction: TextDirection,
978    ) {
979        debug_assert!(slider_theme.disabled_active_tick_mark_color.is_some());
980        debug_assert!(slider_theme.disabled_inactive_tick_mark_color.is_some());
981        debug_assert!(slider_theme.active_tick_mark_color.is_some());
982        debug_assert!(slider_theme.inactive_tick_mark_color.is_some());
983        // The paint color of the tick mark depends on its position relative
984        // to the thumb and the text direction.
985        let x_offset = center.dx() - thumb_center.dx();
986        let (begin, end) = match text_direction {
987            TextDirection::Ltr if x_offset > 0.0 => (
988                slider_theme.disabled_inactive_tick_mark_color,
989                slider_theme.inactive_tick_mark_color,
990            ),
991            TextDirection::Rtl if x_offset < 0.0 => (
992                slider_theme.disabled_inactive_tick_mark_color,
993                slider_theme.inactive_tick_mark_color,
994            ),
995            TextDirection::Ltr | TextDirection::Rtl => (
996                slider_theme.disabled_active_tick_mark_color,
997                slider_theme.active_tick_mark_color,
998            ),
999        };
1000        let paint = Paint::from_color(
1001            evaluate_color_tween(app, begin, end, enable_animation)
1002                .expect("both tick mark colors are set")
1003                .into(),
1004        );
1005
1006        // The tick marks are tiny circles that are the same height as the track.
1007        let tick_mark_radius = self.get_preferred_size(slider_theme, is_enabled).width() / 2.0;
1008        if tick_mark_radius > 0.0 {
1009            context
1010                .canvas()
1011                .draw_circle(center, tick_mark_radius as f32, &paint);
1012        }
1013    }
1014
1015    fn as_any(&self) -> &dyn Any {
1016        self
1017    }
1018
1019    /// Value equality, as Dart's canonicalized `const` instances are identical.
1020    fn eq_shape(&self, other: &dyn SliderTickMarkShape) -> bool {
1021        other.as_any().downcast_ref::<Self>() == Some(self)
1022    }
1023}
1024
1025/// A special version of [`SliderTickMarkShape`] that has a zero size and paints
1026/// nothing.
1027///
1028/// This class is used to create a special instance of a [`SliderTickMarkShape`]
1029/// that will not paint any tick mark shape. A static reference is stored in
1030/// [`no_tick_mark`](<dyn SliderTickMarkShape>::no_tick_mark). When this value is specified for
1031/// `SliderThemeData::tick_mark_shape`, the tick mark painting is skipped.
1032#[derive(Debug)]
1033struct EmptySliderTickMarkShape;
1034
1035impl SliderTickMarkShape for EmptySliderTickMarkShape {
1036    fn get_preferred_size(&self, _slider_theme: &SliderThemeData, _is_enabled: bool) -> Size {
1037        Size::ZERO
1038    }
1039
1040    fn paint(
1041        &self,
1042        _app: &mut App,
1043        _context: &mut PaintingContext,
1044        _center: Offset,
1045        _parent_box: AnyRenderBox,
1046        _slider_theme: &SliderThemeData,
1047        _enable_animation: AnyAnimation<f64>,
1048        _thumb_center: Offset,
1049        _is_enabled: bool,
1050        _text_direction: TextDirection,
1051    ) {
1052        // no-op.
1053    }
1054
1055    fn as_any(&self) -> &dyn Any {
1056        self
1057    }
1058}
1059
1060/// The default shape of a `Slider`'s thumb.
1061///
1062/// There is a shadow for the resting, pressed, hovered, and focused state.
1063///
1064/// See also:
1065///
1066///  * `Slider`, which includes a thumb defined by this shape.
1067///  * `SliderTheme`, which can be used to configure the thumb shape of all
1068///    sliders in a widget subtree.
1069#[derive(Clone, Copy, Debug, PartialEq)]
1070pub struct RoundSliderThumbShape {
1071    /// The preferred radius of the round thumb shape when the slider is enabled.
1072    ///
1073    /// If it is not provided, then the Material Design default of 10 is used.
1074    pub enabled_thumb_radius: f64,
1075
1076    /// The preferred radius of the round thumb shape when the slider is disabled.
1077    ///
1078    /// If no disabledRadius is provided, then it is equal to the
1079    /// [`enabled_thumb_radius`](Self::enabled_thumb_radius)
1080    pub disabled_thumb_radius: Option<f64>,
1081
1082    /// The resting elevation adds shadow to the unpressed thumb.
1083    ///
1084    /// The default is 1.
1085    ///
1086    /// Use 0 for no shadow. The higher the value, the larger the shadow. For
1087    /// example, a value of 12 will create a very large shadow.
1088    pub elevation: f64,
1089
1090    /// The pressed elevation adds shadow to the pressed thumb.
1091    ///
1092    /// The default is 6.
1093    ///
1094    /// Use 0 for no shadow. The higher the value, the larger the shadow. For
1095    /// example, a value of 12 will create a very large shadow.
1096    pub pressed_elevation: f64,
1097}
1098
1099impl RoundSliderThumbShape {
1100    /// Create a slider thumb that draws a circle.
1101    pub const fn new() -> RoundSliderThumbShape {
1102        RoundSliderThumbShape {
1103            enabled_thumb_radius: 10.0,
1104            disabled_thumb_radius: None,
1105            elevation: 1.0,
1106            pressed_elevation: 6.0,
1107        }
1108    }
1109
1110    /// Dart `RoundSliderThumbShape(enabledThumbRadius:)`.
1111    pub const fn enabled_thumb_radius(
1112        mut self,
1113        enabled_thumb_radius: f64,
1114    ) -> RoundSliderThumbShape {
1115        self.enabled_thumb_radius = enabled_thumb_radius;
1116        self
1117    }
1118
1119    /// Dart `RoundSliderThumbShape(disabledThumbRadius:)`.
1120    pub const fn disabled_thumb_radius(
1121        mut self,
1122        disabled_thumb_radius: f64,
1123    ) -> RoundSliderThumbShape {
1124        self.disabled_thumb_radius = Some(disabled_thumb_radius);
1125        self
1126    }
1127
1128    /// Dart `RoundSliderThumbShape(elevation:)`.
1129    pub const fn elevation(mut self, elevation: f64) -> RoundSliderThumbShape {
1130        self.elevation = elevation;
1131        self
1132    }
1133
1134    /// Dart `RoundSliderThumbShape(pressedElevation:)`.
1135    pub const fn pressed_elevation(mut self, pressed_elevation: f64) -> RoundSliderThumbShape {
1136        self.pressed_elevation = pressed_elevation;
1137        self
1138    }
1139
1140    /// Dart's `_disabledThumbRadius`.
1141    fn effective_disabled_thumb_radius(&self) -> f64 {
1142        self.disabled_thumb_radius
1143            .unwrap_or(self.enabled_thumb_radius)
1144    }
1145}
1146
1147impl Default for RoundSliderThumbShape {
1148    fn default() -> RoundSliderThumbShape {
1149        RoundSliderThumbShape::new()
1150    }
1151}
1152
1153impl SliderComponentShape for RoundSliderThumbShape {
1154    fn get_preferred_size(&self, is_enabled: bool, _is_discrete: bool) -> Size {
1155        Size::from_radius(if is_enabled {
1156            self.enabled_thumb_radius
1157        } else {
1158            self.effective_disabled_thumb_radius()
1159        })
1160    }
1161
1162    fn paint(
1163        &self,
1164        app: &mut App,
1165        context: &mut PaintingContext,
1166        center: Offset,
1167        activation_animation: AnyAnimation<f64>,
1168        enable_animation: AnyAnimation<f64>,
1169        _is_discrete: bool,
1170        _label_painter: &mut TextPainter,
1171        parent_box: AnyRenderBox,
1172        slider_theme: &SliderThemeData,
1173        _text_direction: TextDirection,
1174        _value: f64,
1175        _text_scale_factor: f64,
1176        _size_with_overflow: Size,
1177    ) {
1178        debug_assert!(slider_theme.disabled_thumb_color.is_some());
1179        debug_assert!(slider_theme.thumb_color.is_some());
1180
1181        let color = evaluate_color_tween(
1182            app,
1183            slider_theme.disabled_thumb_color,
1184            slider_theme.thumb_color,
1185            enable_animation,
1186        )
1187        .expect("both thumb colors are set");
1188        let radius = evaluate_tween(
1189            app,
1190            self.effective_disabled_thumb_radius(),
1191            self.enabled_thumb_radius,
1192            enable_animation,
1193        );
1194
1195        let evaluated_elevation = evaluate_tween(
1196            app,
1197            self.elevation,
1198            self.pressed_elevation,
1199            activation_animation,
1200        );
1201        let mut path = PathBuilder::new();
1202        path.arc(center, radius as f32, 0.0, std::f32::consts::TAU);
1203        let path = Path::new(path.build());
1204
1205        draw_shadow(
1206            app,
1207            context.canvas(),
1208            parent_box,
1209            &path,
1210            Colors::BLACK,
1211            evaluated_elevation,
1212            true,
1213        );
1214
1215        context
1216            .canvas()
1217            .draw_circle(center, radius as f32, &Paint::from_color(color.into()));
1218    }
1219
1220    fn as_any(&self) -> &dyn Any {
1221        self
1222    }
1223
1224    /// Value equality, as Dart's canonicalized `const` instances are identical.
1225    fn eq_shape(&self, other: &dyn SliderComponentShape) -> bool {
1226        other.as_any().downcast_ref::<Self>() == Some(self)
1227    }
1228}
1229
1230/// The default shape of a Material 3 `Slider`'s value indicator.
1231///
1232/// See also:
1233///
1234///  * `Slider`, which includes a value indicator defined by this shape.
1235///  * `SliderTheme`, which can be used to configure the slider value indicator
1236///    of all sliders in a widget subtree.
1237#[derive(Clone, Copy, Debug, Default, PartialEq)]
1238pub struct DropSliderValueIndicatorShape;
1239
1240impl DropSliderValueIndicatorShape {
1241    const PATH_PAINTER: DropSliderValueIndicatorPathPainter = DropSliderValueIndicatorPathPainter;
1242
1243    /// Create a slider value indicator that resembles a drop shape.
1244    pub const fn new() -> DropSliderValueIndicatorShape {
1245        DropSliderValueIndicatorShape
1246    }
1247
1248    /// Dart's `getPreferredSize` with its optional `labelPainter` and `textScaleFactor`,
1249    /// which this shape needs.
1250    pub fn get_preferred_size(
1251        &self,
1252        _is_enabled: bool,
1253        _is_discrete: bool,
1254        label_painter: Option<&TextPainter>,
1255        text_scale_factor: Option<f64>,
1256    ) -> Size {
1257        debug_assert!(label_painter.is_some());
1258        debug_assert!(text_scale_factor.is_some_and(|factor| factor >= 0.0));
1259        Self::PATH_PAINTER.get_preferred_size(
1260            label_painter.expect("a label painter"),
1261            text_scale_factor.expect("a text scale factor"),
1262        )
1263    }
1264}
1265
1266impl SliderComponentShape for DropSliderValueIndicatorShape {
1267    fn get_preferred_size(&self, is_enabled: bool, is_discrete: bool) -> Size {
1268        DropSliderValueIndicatorShape::get_preferred_size(self, is_enabled, is_discrete, None, None)
1269    }
1270
1271    fn paint(
1272        &self,
1273        app: &mut App,
1274        context: &mut PaintingContext,
1275        center: Offset,
1276        activation_animation: AnyAnimation<f64>,
1277        _enable_animation: AnyAnimation<f64>,
1278        _is_discrete: bool,
1279        label_painter: &mut TextPainter,
1280        parent_box: AnyRenderBox,
1281        slider_theme: &SliderThemeData,
1282        _text_direction: TextDirection,
1283        _value: f64,
1284        text_scale_factor: f64,
1285        size_with_overflow: Size,
1286    ) {
1287        let scale = activation_animation.value(app);
1288        Self::PATH_PAINTER.paint(
1289            app,
1290            parent_box,
1291            context.canvas(),
1292            center,
1293            scale,
1294            label_painter,
1295            text_scale_factor,
1296            size_with_overflow,
1297            slider_theme
1298                .value_indicator_color
1299                .expect("a slider theme with a value indicator color"),
1300            slider_theme.value_indicator_stroke_color,
1301        );
1302    }
1303
1304    fn as_any(&self) -> &dyn Any {
1305        self
1306    }
1307
1308    /// Value equality, as Dart's canonicalized `const` instances are identical.
1309    fn eq_shape(&self, other: &dyn SliderComponentShape) -> bool {
1310        other.as_any().downcast_ref::<Self>() == Some(self)
1311    }
1312}
1313
1314/// Dart's `_DropSliderValueIndicatorPathPainter`.
1315struct DropSliderValueIndicatorPathPainter;
1316
1317impl DropSliderValueIndicatorPathPainter {
1318    const TRIANGLE_HEIGHT: f64 = 10.0;
1319    const LABEL_PADDING: f64 = 8.0;
1320    const PREFERRED_HEIGHT: f64 = 32.0;
1321    const MIN_LABEL_WIDTH: f64 = 20.0;
1322    const MIN_RECT_HEIGHT: f64 = 28.0;
1323    const RECT_Y_OFFSET: f64 = 6.0;
1324    const BOTTOM_TIP_Y_OFFSET: f64 = 16.0;
1325    const PREFERRED_HALF_HEIGHT: f64 = Self::PREFERRED_HEIGHT / 2.0;
1326    const UPPER_RECT_RADIUS: f64 = 4.0;
1327
1328    fn get_preferred_size(&self, label_painter: &TextPainter, text_scale_factor: f64) -> Size {
1329        let width = Self::MIN_LABEL_WIDTH.max(label_painter.width())
1330            + Self::LABEL_PADDING * 2.0 * text_scale_factor;
1331        Size::new(width, Self::PREFERRED_HEIGHT * text_scale_factor)
1332    }
1333
1334    #[expect(clippy::too_many_arguments, reason = "Dart's parameters, in its order")]
1335    fn get_horizontal_shift(
1336        &self,
1337        app: &App,
1338        parent_box: AnyRenderBox,
1339        center: Offset,
1340        label_painter: &TextPainter,
1341        text_scale_factor: f64,
1342        size_with_overflow: Size,
1343        scale: f64,
1344    ) -> f64 {
1345        debug_assert!(!size_with_overflow.is_empty());
1346
1347        const EDGE_PADDING: f64 = 8.0;
1348        let rectangle_width = self.upper_rectangle_width(label_painter, scale);
1349
1350        // Value indicator draws on the Overlay and by using the global Offset
1351        // we are making sure we use the bounds of the Overlay instead of the Slider.
1352        let global_center = parent_box.local_to_global(app, center, None);
1353
1354        // The rectangle must be shifted towards the center so that it minimizes the
1355        // chance of it rendering outside the bounds of the render box. If the shift
1356        // is negative, then the lobe is shifted from right to left, and if it is
1357        // positive, then the lobe is shifted from left to right.
1358        let overflow_left = 0.0_f64.max(rectangle_width / 2.0 - global_center.dx() + EDGE_PADDING);
1359        let overflow_right = 0.0_f64.max(
1360            rectangle_width / 2.0
1361                - (size_with_overflow.width() - global_center.dx() - EDGE_PADDING),
1362        );
1363
1364        if rectangle_width < size_with_overflow.width() {
1365            overflow_left - overflow_right
1366        } else if overflow_left - overflow_right > 0.0 {
1367            overflow_left - (EDGE_PADDING * text_scale_factor)
1368        } else {
1369            -overflow_right + (EDGE_PADDING * text_scale_factor)
1370        }
1371    }
1372
1373    fn upper_rectangle_width(&self, label_painter: &TextPainter, scale: f64) -> f64 {
1374        let unscaled_width = Self::MIN_LABEL_WIDTH.max(label_painter.width()) + Self::LABEL_PADDING;
1375        unscaled_width * scale
1376    }
1377
1378    fn adjust_border_radius(&self, rect: Rect) -> BorderRadius {
1379        const RECTNESS: f64 = 0.0;
1380        BorderRadius::lerp(
1381            Some(BorderRadius::all(Radius::circular(Self::UPPER_RECT_RADIUS))),
1382            Some(BorderRadius::all(Radius::circular(
1383                rect.shortest_side() / 2.0,
1384            ))),
1385            1.0 - RECTNESS,
1386        )
1387        .expect("both radii are set")
1388    }
1389
1390    #[expect(clippy::too_many_arguments, reason = "Dart's parameters, in its order")]
1391    fn paint(
1392        &self,
1393        app: &mut App,
1394        parent_box: AnyRenderBox,
1395        canvas: &mut Canvas,
1396        center: Offset,
1397        scale: f64,
1398        label_painter: &mut TextPainter,
1399        text_scale_factor: f64,
1400        size_with_overflow: Size,
1401        background_paint_color: Color,
1402        stroke_paint_color: Option<Color>,
1403    ) {
1404        if scale == 0.0 {
1405            // Zero scale essentially means "do not draw anything", so it's safe to just return.
1406            return;
1407        }
1408        debug_assert!(!size_with_overflow.is_empty());
1409        let rectangle_width = self.upper_rectangle_width(label_painter, scale);
1410        let horizontal_shift = self.get_horizontal_shift(
1411            app,
1412            parent_box,
1413            center,
1414            label_painter,
1415            text_scale_factor,
1416            size_with_overflow,
1417            scale,
1418        );
1419        let upper_rect = Rect::from_ltwh(
1420            -rectangle_width / 2.0 + horizontal_shift,
1421            -Self::RECT_Y_OFFSET - Self::MIN_RECT_HEIGHT,
1422            rectangle_width,
1423            Self::MIN_RECT_HEIGHT,
1424        );
1425
1426        let fill_paint = Paint::from_color(background_paint_color.into());
1427
1428        canvas.save();
1429        canvas.translate(
1430            center.dx() as f32,
1431            (center.dy() - Self::BOTTOM_TIP_Y_OFFSET) as f32,
1432        );
1433        canvas.scale(scale as f32, scale as f32);
1434
1435        let adjusted_border_radius = self.adjust_border_radius(upper_rect);
1436        let border_rect = adjusted_border_radius
1437            .resolve(label_painter.text_direction())
1438            .to_rrect(upper_rect);
1439        let mut triangle_path = PathBuilder::new();
1440        // Dart's `lineTo` on an empty path starts its contour at the origin.
1441        triangle_path.move_to((0.0, 0.0));
1442        triangle_path
1443            .line_to((-Self::TRIANGLE_HEIGHT as f32, -Self::TRIANGLE_HEIGHT as f32))
1444            .line_to((Self::TRIANGLE_HEIGHT as f32, -Self::TRIANGLE_HEIGHT as f32))
1445            .close();
1446        triangle_path.rrect_radii_elliptical(
1447            border_rect.outer_rect(),
1448            rrect_radii_elliptical(border_rect),
1449        );
1450        let triangle_path = triangle_path.build();
1451
1452        if let Some(stroke_paint_color) = stroke_paint_color {
1453            let stroke_paint = Paint {
1454                color: stroke_paint_color.into(),
1455                style: PaintStyle::Stroke(Stroke::new(1.0)),
1456                ..Paint::default()
1457            };
1458            canvas.draw_path(&triangle_path, FillRule::NonZero, &stroke_paint);
1459        }
1460
1461        canvas.draw_path(&triangle_path, FillRule::NonZero, &fill_paint);
1462
1463        // The label text is centered within the value indicator.
1464        let bottom_tip_to_upper_rect_translate_y =
1465            -Self::PREFERRED_HALF_HEIGHT / 2.0 - upper_rect.height();
1466        canvas.translate(0.0, bottom_tip_to_upper_rect_translate_y as f32);
1467        let box_center = Offset::new(horizontal_shift, upper_rect.height() / 1.75);
1468        let half_label_painter_offset =
1469            Offset::new(label_painter.width() / 2.0, label_painter.height() / 2.0);
1470        let label_offset = box_center - half_label_painter_offset;
1471        let fonts = PaintingBinding::instance(app).fonts(app);
1472        label_painter.paint(app.get_mut(fonts), canvas, label_offset);
1473        canvas.restore();
1474    }
1475}
1476
1477/// The bar shape of a `Slider`'s thumb.
1478///
1479/// When the slider is enabled, the `ColorScheme::primary` color is used for the
1480/// thumb. When the slider is disabled, the `ColorScheme::on_surface` color with an
1481/// opacity of 0.38 is used for the thumb.
1482///
1483/// The thumb bar shape width is reduced when the thumb is pressed.
1484///
1485/// If `SliderThemeData::thumb_size` is null, then the thumb size is 4 pixels for the width
1486/// and 44 pixels for the height.
1487///
1488/// This is the default thumb shape for `Slider`. If `ThemeData::use_material3` is false,
1489/// then the default thumb shape is [`RoundSliderThumbShape`].
1490///
1491/// See also:
1492///
1493///  * `Slider`, which includes an overlay defined by this shape.
1494///  * `SliderTheme`, which can be used to configure the overlay shape of all
1495///    sliders in a widget subtree.
1496#[derive(Clone, Copy, Debug, Default, PartialEq)]
1497pub struct HandleThumbShape;
1498
1499impl HandleThumbShape {
1500    /// Create a slider thumb that draws a bar.
1501    pub const fn new() -> HandleThumbShape {
1502        HandleThumbShape
1503    }
1504}
1505
1506impl SliderComponentShape for HandleThumbShape {
1507    fn get_preferred_size(&self, _is_enabled: bool, _is_discrete: bool) -> Size {
1508        Size::new(4.0, 44.0)
1509    }
1510
1511    fn paint(
1512        &self,
1513        app: &mut App,
1514        context: &mut PaintingContext,
1515        center: Offset,
1516        _activation_animation: AnyAnimation<f64>,
1517        enable_animation: AnyAnimation<f64>,
1518        _is_discrete: bool,
1519        _label_painter: &mut TextPainter,
1520        _parent_box: AnyRenderBox,
1521        slider_theme: &SliderThemeData,
1522        _text_direction: TextDirection,
1523        _value: f64,
1524        _text_scale_factor: f64,
1525        _size_with_overflow: Size,
1526    ) {
1527        debug_assert!(slider_theme.disabled_thumb_color.is_some());
1528        debug_assert!(slider_theme.thumb_color.is_some());
1529        debug_assert!(slider_theme.thumb_size.is_some());
1530
1531        let color = evaluate_color_tween(
1532            app,
1533            slider_theme.disabled_thumb_color,
1534            slider_theme.thumb_color,
1535            enable_animation,
1536        )
1537        .expect("both thumb colors are set");
1538
1539        let thumb_size = slider_theme
1540            .thumb_size
1541            .as_ref()
1542            .expect("a slider theme with a thumb size")
1543            .resolve(&WidgetStates::new())
1544            .expect("a thumb size for no states"); // This is resolved in the paint method.
1545        let rrect = RRect::from_rect_and_radius(
1546            Rect::from_center(center, thumb_size.width(), thumb_size.height()),
1547            Radius::circular(thumb_size.shortest_side() / 2.0),
1548        );
1549        draw_rrect(context.canvas(), rrect, &Paint::from_color(color.into()));
1550    }
1551
1552    fn as_any(&self) -> &dyn Any {
1553        self
1554    }
1555
1556    /// Value equality, as Dart's canonicalized `const` instances are identical.
1557    fn eq_shape(&self, other: &dyn SliderComponentShape) -> bool {
1558        other.as_any().downcast_ref::<Self>() == Some(self)
1559    }
1560}
1561
1562/// The gapped shape of a `Slider`'s track.
1563///
1564/// The [`GappedSliderTrackShape`] consists of active and inactive
1565/// tracks. The active track uses the `SliderThemeData::active_track_color` and the
1566/// inactive track uses the `SliderThemeData::inactive_track_color`.
1567///
1568/// The track shape uses circular corner radius for the edge corners and a corner radius
1569/// of 2 pixels for the inside corners.
1570///
1571/// Between the active and inactive tracks there is a gap of size
1572/// `SliderThemeData::track_gap`. If the `SliderThemeData::thumb_shape` is
1573/// [`HandleThumbShape`] and the thumb is pressed, the thumb's width is reduced; as a result,
1574/// the track gap size in [`GappedSliderTrackShape`] is also reduced.
1575///
1576/// If `SliderThemeData::track_gap` is null, then the track gap size defaults to 6 pixels.
1577///
1578/// This is the default track shape for `Slider`. If `ThemeData::use_material3` is false,
1579/// then the default track shape is [`RoundedRectSliderTrackShape`].
1580///
1581/// See also:
1582///
1583///  * `Slider`, which includes an overlay defined by this shape.
1584///  * `SliderTheme`, which can be used to configure the overlay shape of all
1585///    sliders in a widget subtree.
1586#[derive(Clone, Copy, Debug, Default, PartialEq)]
1587pub struct GappedSliderTrackShape;
1588
1589impl GappedSliderTrackShape {
1590    /// Create a slider track that draws two rectangles with rounded outer edges.
1591    pub const fn new() -> GappedSliderTrackShape {
1592        GappedSliderTrackShape
1593    }
1594
1595    /// Dart's `paint` with its extra `additionalActiveTrackHeight` argument, which the
1596    /// [`SliderTrackShape::paint`] override passes as Dart's default, 2.
1597    #[expect(clippy::too_many_arguments, reason = "Dart's parameters, in its order")]
1598    pub fn paint(
1599        &self,
1600        app: &mut App,
1601        context: &mut PaintingContext,
1602        offset: Offset,
1603        parent_box: AnyRenderBox,
1604        slider_theme: &SliderThemeData,
1605        enable_animation: AnyAnimation<f64>,
1606        text_direction: TextDirection,
1607        thumb_center: Offset,
1608        secondary_offset: Option<Offset>,
1609        is_discrete: bool,
1610        is_enabled: bool,
1611        _additional_active_track_height: f64,
1612    ) {
1613        debug_assert!(slider_theme.disabled_active_track_color.is_some());
1614        debug_assert!(slider_theme.disabled_inactive_track_color.is_some());
1615        debug_assert!(slider_theme.active_track_color.is_some());
1616        debug_assert!(slider_theme.inactive_track_color.is_some());
1617        debug_assert!(slider_theme.thumb_shape.is_some());
1618        debug_assert!(slider_theme.track_gap.is_some());
1619        debug_assert!(
1620            slider_theme
1621                .track_gap
1622                .is_some_and(|gap| !gap.is_sign_negative())
1623        );
1624        // If the slider [SliderThemeData.trackHeight] is less than or equal to 0,
1625        // then it makes no difference whether the track is painted or not,
1626        // therefore the painting can be a no-op.
1627        let Some(track_height) = slider_theme.track_height.filter(|height| *height > 0.0) else {
1628            return;
1629        };
1630
1631        // Assign the track segment paints, which are left: active, right: inactive,
1632        // but reversed for right to left text.
1633        let active_paint = Paint::from_color(
1634            evaluate_color_tween(
1635                app,
1636                slider_theme.disabled_active_track_color,
1637                slider_theme.active_track_color,
1638                enable_animation,
1639            )
1640            .expect("both track colors are set")
1641            .into(),
1642        );
1643        let inactive_paint = Paint::from_color(
1644            evaluate_color_tween(
1645                app,
1646                slider_theme.disabled_inactive_track_color,
1647                slider_theme.inactive_track_color,
1648                enable_animation,
1649            )
1650            .expect("both track colors are set")
1651            .into(),
1652        );
1653        let (left_track_paint, right_track_paint) = match text_direction {
1654            TextDirection::Ltr => (&active_paint, &inactive_paint),
1655            TextDirection::Rtl => (&inactive_paint, &active_paint),
1656        };
1657
1658        // Gap, starting from the middle of the thumb.
1659        let track_gap = slider_theme
1660            .track_gap
1661            .expect("a slider theme with a track gap");
1662
1663        let track_rect = SliderTrackShape::get_preferred_rect(
1664            self,
1665            app,
1666            parent_box,
1667            offset,
1668            slider_theme,
1669            Some(is_enabled),
1670            Some(is_discrete),
1671        );
1672
1673        let track_corner_radius = Radius::circular(track_rect.shortest_side() / 2.0);
1674        const TRACK_INSIDE_CORNER_RADIUS: Radius = Radius::circular(2.0);
1675
1676        let track_rrect = RRect::from_rect_and_corners(
1677            track_rect,
1678            track_corner_radius,
1679            track_corner_radius,
1680            track_corner_radius,
1681            track_corner_radius,
1682        );
1683
1684        let left_rrect = RRect::from_ltrb_and_corners(
1685            track_rect.left,
1686            track_rect.top,
1687            track_rect.left.max(thumb_center.dx() - track_gap),
1688            track_rect.bottom,
1689            track_corner_radius,
1690            TRACK_INSIDE_CORNER_RADIUS,
1691            TRACK_INSIDE_CORNER_RADIUS,
1692            track_corner_radius,
1693        );
1694
1695        let right_rrect = RRect::from_ltrb_and_corners(
1696            thumb_center.dx() + track_gap,
1697            track_rect.top,
1698            track_rect.right,
1699            track_rect.bottom,
1700            TRACK_INSIDE_CORNER_RADIUS,
1701            track_corner_radius,
1702            track_corner_radius,
1703            TRACK_INSIDE_CORNER_RADIUS,
1704        );
1705
1706        let canvas = context.canvas();
1707        canvas.save();
1708        canvas.clip_rrect_radii_elliptical(
1709            track_rrect.outer_rect(),
1710            rrect_radii_elliptical(track_rrect),
1711            ClipOp::Intersect,
1712            true,
1713        );
1714        let draw_left_track = thumb_center.dx() > (left_rrect.left + (track_height / 2.0));
1715        let draw_right_track = thumb_center.dx() < (right_rrect.right - (track_height / 2.0));
1716        if draw_left_track {
1717            draw_rrect(canvas, left_rrect, left_track_paint);
1718        }
1719        if draw_right_track {
1720            draw_rrect(canvas, right_rrect, right_track_paint);
1721        }
1722
1723        let is_ltr = text_direction == TextDirection::Ltr;
1724        let show_secondary_track = secondary_offset.is_some_and(|secondary_offset| match is_ltr {
1725            true => secondary_offset.dx() > thumb_center.dx() + track_gap,
1726            false => secondary_offset.dx() < thumb_center.dx() - track_gap,
1727        });
1728
1729        if let Some(secondary_offset) = secondary_offset.filter(|_| show_secondary_track) {
1730            let secondary_track_paint = Paint::from_color(
1731                evaluate_color_tween(
1732                    app,
1733                    slider_theme.disabled_secondary_active_track_color,
1734                    slider_theme.secondary_active_track_color,
1735                    enable_animation,
1736                )
1737                .expect("both secondary track colors are set")
1738                .into(),
1739            );
1740            let canvas = context.canvas();
1741            if is_ltr {
1742                draw_rrect(
1743                    canvas,
1744                    RRect::from_ltrb_and_corners(
1745                        thumb_center.dx() + track_gap,
1746                        track_rect.top,
1747                        secondary_offset.dx(),
1748                        track_rect.bottom,
1749                        TRACK_INSIDE_CORNER_RADIUS,
1750                        track_corner_radius,
1751                        track_corner_radius,
1752                        TRACK_INSIDE_CORNER_RADIUS,
1753                    ),
1754                    &secondary_track_paint,
1755                );
1756            } else {
1757                draw_rrect(
1758                    canvas,
1759                    RRect::from_ltrb_and_corners(
1760                        secondary_offset.dx(),
1761                        track_rect.top,
1762                        thumb_center.dx() - track_gap,
1763                        track_rect.bottom,
1764                        track_corner_radius,
1765                        TRACK_INSIDE_CORNER_RADIUS,
1766                        TRACK_INSIDE_CORNER_RADIUS,
1767                        track_corner_radius,
1768                    ),
1769                    &secondary_track_paint,
1770                );
1771            }
1772        }
1773        let canvas = context.canvas();
1774        canvas.restore();
1775
1776        const STOP_INDICATOR_RADIUS: f64 = 2.0;
1777        let stop_indicator_trailing_space = track_height / 2.0;
1778        let stop_indicator_offset = Offset::new(
1779            if text_direction == TextDirection::Ltr {
1780                track_rect.center_right().dx() - stop_indicator_trailing_space
1781            } else {
1782                track_rect.center_left().dx() + stop_indicator_trailing_space
1783            },
1784            track_rect.center().dy(),
1785        );
1786
1787        let show_stop_indicator = if text_direction == TextDirection::Ltr {
1788            thumb_center.dx() < stop_indicator_offset.dx()
1789        } else {
1790            thumb_center.dx() > stop_indicator_offset.dx()
1791        };
1792        if show_stop_indicator && !is_discrete {
1793            let stop_indicator_rect =
1794                Rect::from_circle(stop_indicator_offset, STOP_INDICATOR_RADIUS);
1795            canvas.draw_circle(
1796                stop_indicator_rect.center(),
1797                STOP_INDICATOR_RADIUS as f32,
1798                &active_paint,
1799            );
1800        }
1801    }
1802}
1803
1804impl BaseSliderTrackShape for GappedSliderTrackShape {}
1805
1806impl SliderTrackShape for GappedSliderTrackShape {
1807    fn get_preferred_rect(
1808        &self,
1809        app: &App,
1810        parent_box: AnyRenderBox,
1811        offset: Offset,
1812        slider_theme: &SliderThemeData,
1813        is_enabled: Option<bool>,
1814        is_discrete: Option<bool>,
1815    ) -> Rect {
1816        BaseSliderTrackShape::get_preferred_rect(
1817            self,
1818            app,
1819            parent_box,
1820            offset,
1821            slider_theme,
1822            is_enabled,
1823            is_discrete,
1824        )
1825    }
1826
1827    fn paint(
1828        &self,
1829        app: &mut App,
1830        context: &mut PaintingContext,
1831        offset: Offset,
1832        parent_box: AnyRenderBox,
1833        slider_theme: &SliderThemeData,
1834        enable_animation: AnyAnimation<f64>,
1835        thumb_center: Offset,
1836        secondary_offset: Option<Offset>,
1837        is_enabled: Option<bool>,
1838        is_discrete: Option<bool>,
1839        text_direction: TextDirection,
1840    ) {
1841        GappedSliderTrackShape::paint(
1842            self,
1843            app,
1844            context,
1845            offset,
1846            parent_box,
1847            slider_theme,
1848            enable_animation,
1849            text_direction,
1850            thumb_center,
1851            secondary_offset,
1852            is_discrete.unwrap_or(false),
1853            is_enabled.unwrap_or(false),
1854            2.0,
1855        );
1856    }
1857
1858    fn is_rounded(&self) -> bool {
1859        true
1860    }
1861
1862    fn as_any(&self) -> &dyn Any {
1863        self
1864    }
1865
1866    /// Value equality, as Dart's canonicalized `const` instances are identical.
1867    fn eq_shape(&self, other: &dyn SliderTrackShape) -> bool {
1868        other.as_any().downcast_ref::<Self>() == Some(self)
1869    }
1870}
1871
1872/// The rounded rectangle shape of a `Slider`'s value indicator.
1873///
1874/// If the `SliderThemeData::value_indicator_color` is null, then the shape uses the
1875/// `ColorScheme::inverse_surface` color to draw the value indicator.
1876///
1877/// If the `SliderThemeData::value_indicator_text_style` is null, then the indicator label
1878/// text style defaults to `TextTheme::label_medium` with the color set to
1879/// `ColorScheme::on_inverse_surface`. If the `ThemeData::use_material3` is set to false, then
1880/// the indicator label text style defaults to `TextTheme::body_large` with the color set to
1881/// `ColorScheme::on_inverse_surface`.
1882///
1883/// If the `SliderThemeData::value_indicator_stroke_color` is provided, then the value
1884/// indicator is drawn with a stroke border with the color provided.
1885///
1886/// This is the default value indicator shape for `Slider`. If `ThemeData::use_material3` is
1887/// false, then the default value indicator shape is `RectangularSliderValueIndicatorShape`.
1888///
1889/// See also:
1890///
1891///  * `Slider`, which includes a value indicator defined by this shape.
1892///  * `SliderTheme`, which can be used to configure the slider value indicator
1893///    of all sliders in a widget subtree.
1894#[derive(Clone, Copy, Debug, Default, PartialEq)]
1895pub struct RoundedRectSliderValueIndicatorShape;
1896
1897impl RoundedRectSliderValueIndicatorShape {
1898    const PATH_PAINTER: RoundedRectSliderValueIndicatorPathPainter =
1899        RoundedRectSliderValueIndicatorPathPainter;
1900
1901    /// Create a slider value indicator that resembles a rounded rectangle.
1902    pub const fn new() -> RoundedRectSliderValueIndicatorShape {
1903        RoundedRectSliderValueIndicatorShape
1904    }
1905
1906    /// Dart's `getPreferredSize` with its optional `labelPainter` and `textScaleFactor`,
1907    /// which this shape needs.
1908    pub fn get_preferred_size(
1909        &self,
1910        _is_enabled: bool,
1911        _is_discrete: bool,
1912        label_painter: Option<&TextPainter>,
1913        text_scale_factor: Option<f64>,
1914    ) -> Size {
1915        debug_assert!(label_painter.is_some());
1916        debug_assert!(text_scale_factor.is_some_and(|factor| factor >= 0.0));
1917        Self::PATH_PAINTER.get_preferred_size(
1918            label_painter.expect("a label painter"),
1919            text_scale_factor.expect("a text scale factor"),
1920        )
1921    }
1922}
1923
1924impl SliderComponentShape for RoundedRectSliderValueIndicatorShape {
1925    fn get_preferred_size(&self, is_enabled: bool, is_discrete: bool) -> Size {
1926        RoundedRectSliderValueIndicatorShape::get_preferred_size(
1927            self,
1928            is_enabled,
1929            is_discrete,
1930            None,
1931            None,
1932        )
1933    }
1934
1935    fn paint(
1936        &self,
1937        app: &mut App,
1938        context: &mut PaintingContext,
1939        center: Offset,
1940        activation_animation: AnyAnimation<f64>,
1941        _enable_animation: AnyAnimation<f64>,
1942        _is_discrete: bool,
1943        label_painter: &mut TextPainter,
1944        parent_box: AnyRenderBox,
1945        slider_theme: &SliderThemeData,
1946        _text_direction: TextDirection,
1947        _value: f64,
1948        text_scale_factor: f64,
1949        size_with_overflow: Size,
1950    ) {
1951        let scale = activation_animation.value(app);
1952        Self::PATH_PAINTER.paint(
1953            app,
1954            parent_box,
1955            context.canvas(),
1956            center,
1957            scale,
1958            label_painter,
1959            text_scale_factor,
1960            size_with_overflow,
1961            slider_theme
1962                .value_indicator_color
1963                .expect("a slider theme with a value indicator color"),
1964            slider_theme.value_indicator_stroke_color,
1965        );
1966    }
1967
1968    fn as_any(&self) -> &dyn Any {
1969        self
1970    }
1971
1972    /// Value equality, as Dart's canonicalized `const` instances are identical.
1973    fn eq_shape(&self, other: &dyn SliderComponentShape) -> bool {
1974        other.as_any().downcast_ref::<Self>() == Some(self)
1975    }
1976}
1977
1978/// Dart's `_RoundedRectSliderValueIndicatorPathPainter`.
1979struct RoundedRectSliderValueIndicatorPathPainter;
1980
1981impl RoundedRectSliderValueIndicatorPathPainter {
1982    const LABEL_PADDING: f64 = 10.0;
1983    const PREFERRED_HEIGHT: f64 = 32.0;
1984    const MIN_LABEL_WIDTH: f64 = 16.0;
1985    const RECT_Y_OFFSET: f64 = 10.0;
1986    const BOTTOM_TIP_Y_OFFSET: f64 = 16.0;
1987    const PREFERRED_HALF_HEIGHT: f64 = Self::PREFERRED_HEIGHT / 2.0;
1988
1989    fn get_preferred_size(&self, label_painter: &TextPainter, text_scale_factor: f64) -> Size {
1990        let width = Self::MIN_LABEL_WIDTH.max(label_painter.width())
1991            + (Self::LABEL_PADDING * 2.0) * text_scale_factor;
1992        Size::new(width, Self::PREFERRED_HEIGHT * text_scale_factor)
1993    }
1994
1995    #[expect(clippy::too_many_arguments, reason = "Dart's parameters, in its order")]
1996    fn get_horizontal_shift(
1997        &self,
1998        app: &App,
1999        parent_box: AnyRenderBox,
2000        center: Offset,
2001        label_painter: &TextPainter,
2002        text_scale_factor: f64,
2003        size_with_overflow: Size,
2004        scale: f64,
2005    ) -> f64 {
2006        debug_assert!(!size_with_overflow.is_empty());
2007
2008        const EDGE_PADDING: f64 = 8.0;
2009        let rectangle_width = self.upper_rectangle_width(label_painter, scale);
2010
2011        // Value indicator draws on the Overlay and by using the global Offset
2012        // we are making sure we use the bounds of the Overlay instead of the Slider.
2013        let global_center = parent_box.local_to_global(app, center, None);
2014
2015        // The rectangle must be shifted towards the center so that it minimizes the
2016        // chance of it rendering outside the bounds of the render box. If the shift
2017        // is negative, then the lobe is shifted from right to left, and if it is
2018        // positive, then the lobe is shifted from left to right.
2019        let overflow_left = 0.0_f64.max(rectangle_width / 2.0 - global_center.dx() + EDGE_PADDING);
2020        let overflow_right = 0.0_f64.max(
2021            rectangle_width / 2.0
2022                - (size_with_overflow.width() - global_center.dx() - EDGE_PADDING),
2023        );
2024
2025        if rectangle_width < size_with_overflow.width() {
2026            overflow_left - overflow_right
2027        } else if overflow_left - overflow_right > 0.0 {
2028            overflow_left - (EDGE_PADDING * text_scale_factor)
2029        } else {
2030            -overflow_right + (EDGE_PADDING * text_scale_factor)
2031        }
2032    }
2033
2034    fn upper_rectangle_width(&self, label_painter: &TextPainter, scale: f64) -> f64 {
2035        let unscaled_width =
2036            Self::MIN_LABEL_WIDTH.max(label_painter.width()) + (Self::LABEL_PADDING * 2.0);
2037        unscaled_width * scale
2038    }
2039
2040    #[expect(clippy::too_many_arguments, reason = "Dart's parameters, in its order")]
2041    fn paint(
2042        &self,
2043        app: &mut App,
2044        parent_box: AnyRenderBox,
2045        canvas: &mut Canvas,
2046        center: Offset,
2047        scale: f64,
2048        label_painter: &mut TextPainter,
2049        text_scale_factor: f64,
2050        size_with_overflow: Size,
2051        background_paint_color: Color,
2052        stroke_paint_color: Option<Color>,
2053    ) {
2054        if scale == 0.0 {
2055            // Zero scale essentially means "do not draw anything", so it's safe to just return.
2056            return;
2057        }
2058        debug_assert!(!size_with_overflow.is_empty());
2059
2060        let rectangle_width = self.upper_rectangle_width(label_painter, scale);
2061        let horizontal_shift = self.get_horizontal_shift(
2062            app,
2063            parent_box,
2064            center,
2065            label_painter,
2066            text_scale_factor,
2067            size_with_overflow,
2068            scale,
2069        );
2070
2071        let upper_rect = Rect::from_ltwh(
2072            -rectangle_width / 2.0 + horizontal_shift,
2073            -Self::RECT_Y_OFFSET - Self::PREFERRED_HEIGHT,
2074            rectangle_width,
2075            Self::PREFERRED_HEIGHT,
2076        );
2077
2078        let fill_paint = Paint::from_color(background_paint_color.into());
2079
2080        canvas.save();
2081        // Prepare the canvas for the base of the tooltip, which is relative to the
2082        // center of the thumb.
2083        canvas.translate(
2084            center.dx() as f32,
2085            (center.dy() - Self::BOTTOM_TIP_Y_OFFSET) as f32,
2086        );
2087        canvas.scale(scale as f32, scale as f32);
2088
2089        let rrect =
2090            RRect::from_rect_and_radius(upper_rect, Radius::circular(upper_rect.height() / 2.0));
2091        if let Some(stroke_paint_color) = stroke_paint_color {
2092            let stroke_paint = Paint {
2093                color: stroke_paint_color.into(),
2094                style: PaintStyle::Stroke(Stroke::new(1.0)),
2095                ..Paint::default()
2096            };
2097            draw_rrect(canvas, rrect, &stroke_paint);
2098        }
2099
2100        draw_rrect(canvas, rrect, &fill_paint);
2101
2102        // The label text is centered within the value indicator.
2103        let bottom_tip_to_upper_rect_translate_y =
2104            -Self::PREFERRED_HALF_HEIGHT / 2.0 - upper_rect.height();
2105        canvas.translate(0.0, bottom_tip_to_upper_rect_translate_y as f32);
2106        let box_center = Offset::new(horizontal_shift, upper_rect.height() / 2.3);
2107        let half_label_painter_offset =
2108            Offset::new(label_painter.width() / 2.0, label_painter.height() / 2.0);
2109        let label_offset = box_center - half_label_painter_offset;
2110        let fonts = PaintingBinding::instance(app).fonts(app);
2111        label_painter.paint(app.get_mut(fonts), canvas, label_offset);
2112        canvas.restore();
2113    }
2114}
2115
2116#[cfg(test)]
2117mod tests {
2118    use super::*;
2119    use crate::slider_value_indicator_shape::{RoundSliderOverlayShape, SliderComponentShapeRef};
2120
2121    #[test]
2122    fn track_shape_is_rounded_defaults() {
2123        assert!(!SliderTrackShape::is_rounded(
2124            &RectangularSliderTrackShape::new()
2125        ));
2126        assert!(SliderTrackShape::is_rounded(
2127            &RoundedRectSliderTrackShape::new()
2128        ));
2129        assert!(SliderTrackShape::is_rounded(&GappedSliderTrackShape::new()));
2130    }
2131
2132    #[test]
2133    fn round_slider_thumb_shape_prefers_its_enabled_or_disabled_radius() {
2134        let shape = RoundSliderThumbShape::new();
2135        assert_eq!(shape.get_preferred_size(true, false), Size::new(20.0, 20.0));
2136        assert_eq!(
2137            shape.get_preferred_size(false, false),
2138            Size::new(20.0, 20.0)
2139        );
2140        let shape = shape.enabled_thumb_radius(7.0).disabled_thumb_radius(4.0);
2141        assert_eq!(shape.get_preferred_size(true, false), Size::new(14.0, 14.0));
2142        assert_eq!(shape.get_preferred_size(false, false), Size::new(8.0, 8.0));
2143    }
2144
2145    #[test]
2146    fn handle_thumb_shape_prefers_four_by_forty_four() {
2147        assert_eq!(
2148            HandleThumbShape::new().get_preferred_size(true, true),
2149            Size::new(4.0, 44.0)
2150        );
2151    }
2152
2153    #[test]
2154    fn round_tick_mark_defaults_to_a_quarter_of_the_track_height() {
2155        let theme = SliderThemeData::new().track_height(8.0);
2156        assert_eq!(
2157            RoundSliderTickMarkShape::new().get_preferred_size(&theme, true),
2158            Size::new(4.0, 4.0)
2159        );
2160        assert_eq!(
2161            RoundSliderTickMarkShape::new()
2162                .tick_mark_radius(5.0)
2163                .get_preferred_size(&theme, true),
2164            Size::new(10.0, 10.0)
2165        );
2166        assert_eq!(
2167            <dyn SliderTickMarkShape>::no_tick_mark().get_preferred_size(&theme, true),
2168            Size::ZERO
2169        );
2170    }
2171
2172    #[test]
2173    fn built_in_shapes_compare_by_value_and_the_empty_one_by_identity() {
2174        let a: SliderTrackShapeRef = Rc::new(RoundedRectSliderTrackShape::new());
2175        let b: SliderTrackShapeRef = Rc::new(RoundedRectSliderTrackShape::new());
2176        let c: SliderTrackShapeRef = Rc::new(GappedSliderTrackShape::new());
2177        assert!(*a == *b);
2178        assert!(*a != *c);
2179
2180        let thumb: SliderComponentShapeRef =
2181            Rc::new(RoundSliderThumbShape::new().enabled_thumb_radius(7.0));
2182        let same: SliderComponentShapeRef =
2183            Rc::new(RoundSliderThumbShape::new().enabled_thumb_radius(7.0));
2184        let other: SliderComponentShapeRef = Rc::new(RoundSliderThumbShape::new());
2185        let overlay: SliderComponentShapeRef = Rc::new(RoundSliderOverlayShape::new());
2186        assert!(*thumb == *same);
2187        assert!(*thumb != *other);
2188        assert!(*thumb != *overlay);
2189
2190        let tick: SliderTickMarkShapeRef = Rc::new(RoundSliderTickMarkShape::new());
2191        let same_tick: SliderTickMarkShapeRef = Rc::new(RoundSliderTickMarkShape::new());
2192        assert!(*tick == *same_tick);
2193        assert!(Rc::ptr_eq(
2194            &<dyn SliderTickMarkShape>::no_tick_mark(),
2195            &<dyn SliderTickMarkShape>::no_tick_mark()
2196        ));
2197        assert!(*tick != *<dyn SliderTickMarkShape>::no_tick_mark());
2198    }
2199}