Skip to main content

waft_material/
range_slider_parts.rs

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