Skip to main content

waft_winui/controls/
slider.rs

1//! XAML `Slider` with the `DefaultSliderStyle` of `Slider_themeresources.xaml`.
2//!
3//! Template, top to bottom: a root `Grid` (rows Auto, *) holding `HeaderContentPresenter` in row 0 and, in row 1, `FocusBorder` (the focus visual's target) over `SliderContainer`, the grid that takes the pointer. Inside it `HorizontalTemplate` (columns Auto, Auto, *; rows `SliderPreContentMargin`, Auto, `SliderPostContentMargin`) holds `HorizontalTrackRect` (4 pt tall, every column), `HorizontalDecreaseRect` (column 0, as wide as the value's share of the track), `TopTickBar`, `HorizontalInlineTickBar`, `BottomTickBar` and `HorizontalThumb` (18 × 18, column 1, every row); `VerticalTemplate` is the same turned (rows *, Auto, Auto; columns 14, Auto, 14) with `VerticalTrackRect`, `VerticalDecreaseRect` (row 2), `LeftTickBar`, `VerticalInlineTickBar`, `RightTickBar` and `VerticalThumb`. `Slider::UpdateTrackLayout` swaps the star and the first Auto definition and moves the decrease rect to the other end when `IsDirectionReversed`. The thumb's `SliderThumbStyle` is a `Border` two pixels larger than the thumb on every side (`Margin="-2"`, `SliderThumbCornerRadius`, the elevation stroke) around the 12 pt `SliderInnerThumb` ellipse, which the thumb's own `CommonStates` scale.
4//!
5//! Behaviour is `Slider_Partial.cpp` (with `Thumb_Partial.cpp` for the thumb's drag and `RangeBase.cpp` for the range): a press on `SliderContainer` moves the thumb to the pointer (`OnPointerPressed`, `MoveThumbToPoint`) and keeps following it (`OnPointerMoved`); a press on the thumb drags it by deltas from the value it started at (`OnThumbDragStarted`, `OnThumbDragDelta`); both set `IntermediateValue`, which positions the thumb, and snap `Value` to the nearest `StepFrequency` multiple (`GetClosestStep`); the arrow keys step by `SmallChange`, Home and End go to the ends (`SliderKeyProcess.h`).
6
7use crate::{
8    Brush, ColumnDefinition, CommonState, ControlBorder, FocusVisual, Grid, GridCell, GridLength,
9    PlacementMode, RangeBase, RowDefinition, ThemeResources, TickBar, TickPlacement, ToolTip,
10    ToolTipService, are_close, control_text_style, fast_out_slow_in, fractional,
11};
12use std::{any::TypeId, fmt, rc::Rc, time::Duration};
13use waft_embedder::{Canvas, Color, Offset, PointerDeviceKind, Rect, Size};
14use waft_foundation::{App, Handle};
15use waft_gestures::{EagerGestureRecognizer, K_PRIMARY_BUTTON, PointerDownEvent};
16use waft_painting::{AlignmentGeometry, EdgeInsetsGeometry, draw_oval};
17use waft_rendering::{BoxConstraints, CustomPainter, HitTestBehavior};
18use waft_services::{KeyEvent, LogicalKeyboardKey};
19use waft_widgets::Listener as PointerListener;
20use waft_widgets::*;
21
22/// XAML `SliderSnapsTo`: what `Value` snaps to while the thumb moves.
23#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
24pub enum SliderSnapsTo {
25    /// Multiples of `StepFrequency`.
26    #[default]
27    StepValues,
28    /// Multiples of `TickFrequency`.
29    Ticks,
30}
31
32/// `Slider_Partial.h`: `Slider::GetDefaultValue2` raises `RangeBase`'s `Maximum` to 100.
33pub const SLIDER_DEFAULT_MAXIMUM: f64 = 100.0;
34/// `Slider_Partial.h`: `SmallChange`, the arrow keys' step, defaults to 1.
35pub const SLIDER_DEFAULT_SMALL_CHANGE: f64 = 1.0;
36/// `StepFrequency`'s default of 1 is property metadata the repository does not carry (`PORTING.md`).
37pub const SLIDER_DEFAULT_STEP_FREQUENCY: f64 = 1.0;
38/// `FocusVisualMargin` of the style, around `FocusBorder`.
39pub const SLIDER_FOCUS_VISUAL_MARGIN: [f64; 4] = [-7.0, 0.0, -7.0, 0.0];
40/// `SliderThumbStyle`: `BorderThickness="1"`.
41pub const THUMB_BORDER_THICKNESS: f64 = 1.0;
42/// `SliderThumbStyle`: the `Margin="-2"` its `Border` grows past the thumb by, on every side.
43pub const THUMB_BORDER_OVERHANG: f64 = 2.0;
44/// The tick bars' `Margin` away from the track: `0,0,0,4` on `TopTickBar`, `0,4,0,0` on `BottomTickBar`, and the same turned on `LeftTickBar` and `RightTickBar`.
45pub const TICK_BAR_MARGIN: f64 = 4.0;
46
47/// `SliderInnerThumb`'s `CompositeTransform` scale per thumb state, and the key time it reaches it with `ControlFastOutSlowInKeySpline`: 0.86 over `ControlFastAnimationDuration` (`Normal`), 1.167 over `ControlNormalAnimationDuration` (`PointerOver`), 0.71 over `ControlNormalAnimationDuration` (`Pressed`), 1.167 over `ControlFastAnimationDuration` (`Disabled`).
48pub fn inner_thumb_scale(r: &ThemeResources, state: CommonState) -> (f64, Duration) {
49    match state {
50        CommonState::Normal => (0.86, r.control_fast_animation_duration),
51        CommonState::PointerOver => (1.167, r.control_normal_animation_duration),
52        CommonState::Pressed => (0.71, r.control_normal_animation_duration),
53        CommonState::Disabled => (1.167, r.control_fast_animation_duration),
54    }
55}
56
57/// XAML `ValueChanged` handler, given the value the slider wants.
58pub type ValueChangedHandler = Rc<dyn Fn(&mut App, f64)>;
59
60/// Rust equivalent of `ThumbToolTipValueConverter`, returning the displayed value text.
61pub type ThumbToolTipValueConverter = Rc<dyn Fn(f64) -> String>;
62
63/// The `OnKeyDown` of a control derived from Slider, for a key press or repeat: `None` leaves
64/// the key to the slider's own handling, `Some` is the result of the key without it.
65pub type SliderKeyDownHandler = Rc<dyn Fn(&mut App, LogicalKeyboardKey) -> Option<KeyEventResult>>;
66
67/// Builds a Slider `ControlTemplate` for one set of states, placing `SliderContainer` with
68/// [`SliderTemplateParts::slider_container`].
69pub type SliderTemplateBuilder = Rc<
70    dyn Fn(
71        &mut App,
72        BuildContext,
73        &Slider,
74        SliderTemplateStates,
75        &SliderTemplateParts,
76    ) -> WidgetRef,
77>;
78
79/// A Slider `ControlTemplate` replacing the default style's, as a derived control's style sets
80/// one; the slider keeps its input, value and keyboard behaviour.
81#[derive(Clone)]
82pub struct SliderTemplate {
83    /// Builds the template.
84    pub build: SliderTemplateBuilder,
85    /// How far the template's thumb reaches past its layout slot on every side, where a press
86    /// still lands on the thumb and drags it: the default style's `Margin="-2"` on the thumb's
87    /// border is 2.
88    pub thumb_overhang: f64,
89}
90
91impl SliderTemplate {
92    /// A template built by `build`, with a thumb reaching `thumb_overhang` past its slot.
93    pub fn new(
94        thumb_overhang: f64,
95        build: impl Fn(
96            &mut App,
97            BuildContext,
98            &Slider,
99            SliderTemplateStates,
100            &SliderTemplateParts,
101        ) -> WidgetRef
102        + 'static,
103    ) -> SliderTemplate {
104        SliderTemplate {
105            build: Rc::new(build),
106            thumb_overhang,
107        }
108    }
109}
110
111/// The template parts `Slider::OnApplyTemplate` attaches its behaviour to.
112pub struct SliderTemplateParts {
113    /// Wraps `SliderContainer`'s content in the slider's pointer input and names it.
114    container: Rc<dyn Fn(WidgetRef) -> WidgetRef>,
115}
116
117impl SliderTemplateParts {
118    /// `SliderContainer`: `content` as the element that takes the slider's pointer input, and
119    /// whose size the pointer maths reads as the track's.
120    #[cfg_attr(debug_assertions, track_caller)]
121    pub fn slider_container<K>(&self, content: impl IntoWidget<K>) -> WidgetRef {
122        (self.container)(content.into_widget())
123    }
124}
125
126/// XAML `Slider`: `Value` between `Minimum` and `Maximum` with `ValueChanged`, `StepFrequency`, ticks, `Orientation` and `Header`.
127#[derive(Clone)]
128pub struct Slider {
129    pub value: f64,
130    /// XAML `ValueChanged`, with the value the slider wants; the caller owns `value`.
131    pub value_changed: ValueChangedHandler,
132    pub minimum: f64,
133    pub maximum: f64,
134    /// XAML `StepFrequency`: `Value` snaps to its multiples.
135    pub step_frequency: f64,
136    /// XAML `SmallChange`: the arrow keys' step.
137    pub small_change: f64,
138    /// XAML `TickFrequency`: the tick bars' interval; nothing shows while it is 0.
139    pub tick_frequency: f64,
140    pub tick_placement: TickPlacement,
141    pub snaps_to: SliderSnapsTo,
142    /// XAML `Orientation`: the track runs left to right ([`Axis::Horizontal`]) or bottom to top
143    /// ([`Axis::Vertical`]).
144    pub orientation: Axis,
145    /// XAML `IsDirectionReversed`: the value grows toward the start of the track.
146    pub is_direction_reversed: bool,
147    pub header: Option<WidgetRef>,
148    pub is_enabled: bool,
149    /// XAML `IsThumbToolTipEnabled`; enabled by default.
150    pub is_thumb_tool_tip_enabled: bool,
151    /// Optional replacement for the source step-frequency-based value formatter.
152    pub thumb_tool_tip_value_converter: Option<ThumbToolTipValueConverter>,
153    /// The template of a derived control's style; `None` is `DefaultSliderStyle`'s.
154    pub template: Option<SliderTemplate>,
155    /// The `OnKeyDown` override of a derived control, which sees each key first.
156    pub key_down: Option<SliderKeyDownHandler>,
157    pub key: Option<KeyRef>,
158}
159
160impl Slider {
161    pub fn new(value: f64, value_changed: impl Fn(&mut App, f64) + 'static) -> Slider {
162        Slider {
163            value,
164            value_changed: Rc::new(value_changed),
165            minimum: 0.0,
166            maximum: SLIDER_DEFAULT_MAXIMUM,
167            step_frequency: SLIDER_DEFAULT_STEP_FREQUENCY,
168            small_change: SLIDER_DEFAULT_SMALL_CHANGE,
169            tick_frequency: 0.0,
170            tick_placement: TickPlacement::None,
171            snaps_to: SliderSnapsTo::StepValues,
172            orientation: Axis::Horizontal,
173            is_direction_reversed: false,
174            header: None,
175            is_enabled: true,
176            is_thumb_tool_tip_enabled: true,
177            thumb_tool_tip_value_converter: None,
178            template: None,
179            key_down: None,
180            key: None,
181        }
182    }
183
184    /// Enables the default thumb value tooltip.
185    pub fn is_thumb_tool_tip_enabled(mut self, enabled: bool) -> Self {
186        self.is_thumb_tool_tip_enabled = enabled;
187        self
188    }
189
190    /// Converts `Value` to the text shown in the thumb tooltip.
191    pub fn thumb_tool_tip_value_converter(
192        mut self,
193        converter: impl Fn(f64) -> String + 'static,
194    ) -> Self {
195        self.thumb_tool_tip_value_converter = Some(Rc::new(converter));
196        self
197    }
198
199    /// XAML `Minimum`.
200    pub fn minimum(mut self, minimum: f64) -> Slider {
201        self.minimum = minimum;
202        self
203    }
204
205    /// XAML `Maximum`.
206    pub fn maximum(mut self, maximum: f64) -> Slider {
207        self.maximum = maximum;
208        self
209    }
210
211    /// XAML `StepFrequency`.
212    pub fn step_frequency(mut self, frequency: f64) -> Slider {
213        self.step_frequency = frequency;
214        self
215    }
216
217    /// XAML `SmallChange`.
218    pub fn small_change(mut self, change: f64) -> Slider {
219        self.small_change = change;
220        self
221    }
222
223    /// XAML `TickFrequency`.
224    pub fn tick_frequency(mut self, frequency: f64) -> Slider {
225        self.tick_frequency = frequency;
226        self
227    }
228
229    /// XAML `TickPlacement`.
230    pub fn tick_placement(mut self, placement: TickPlacement) -> Slider {
231        self.tick_placement = placement;
232        self
233    }
234
235    /// XAML `SnapsTo`.
236    pub fn snaps_to(mut self, snaps_to: SliderSnapsTo) -> Slider {
237        self.snaps_to = snaps_to;
238        self
239    }
240
241    /// XAML `Orientation`: [`Axis::Horizontal`] or [`Axis::Vertical`].
242    pub fn orientation(mut self, orientation: Axis) -> Slider {
243        self.orientation = orientation;
244        self
245    }
246
247    /// XAML `IsDirectionReversed`.
248    pub fn is_direction_reversed(mut self, reversed: bool) -> Slider {
249        self.is_direction_reversed = reversed;
250        self
251    }
252
253    /// XAML `Header`.
254    #[cfg_attr(debug_assertions, track_caller)]
255    pub fn header<K>(mut self, header: impl IntoWidget<K>) -> Slider {
256        self.header = Some(header.into_widget());
257        self
258    }
259
260    /// XAML `IsEnabled`.
261    pub fn is_enabled(mut self, enabled: bool) -> Slider {
262        self.is_enabled = enabled;
263        self
264    }
265
266    /// Sets Template, as a derived control's style does.
267    pub fn template(mut self, template: SliderTemplate) -> Slider {
268        self.template = Some(template);
269        self
270    }
271
272    /// Sets the `OnKeyDown` override of a derived control.
273    pub fn key_down(
274        mut self,
275        handler: impl Fn(&mut App, LogicalKeyboardKey) -> Option<KeyEventResult> + 'static,
276    ) -> Slider {
277        self.key_down = Some(Rc::new(handler));
278        self
279    }
280
281    pub fn key(mut self, key: KeyRef) -> Slider {
282        self.key = Some(key);
283        self
284    }
285
286    /// How far the thumb reaches past its slot: the template's, or the default style's.
287    fn thumb_overhang(&self) -> f64 {
288        self.template
289            .as_ref()
290            .map_or(THUMB_BORDER_OVERHANG, |template| template.thumb_overhang)
291    }
292
293    /// `Minimum`, `Maximum` and `Value` as `CRangeBase` coerces them.
294    pub(crate) fn range(&self) -> RangeBase {
295        RangeBase::new(self.minimum, self.maximum, self.value).coerced()
296    }
297
298    /// The interval `Value` snaps to: `TickFrequency` under `SnapsTo="Ticks"`, `StepFrequency` otherwise.
299    fn snap_interval(&self) -> f64 {
300        match self.snaps_to {
301            SliderSnapsTo::StepValues => self.step_frequency,
302            SliderSnapsTo::Ticks => self.tick_frequency,
303        }
304    }
305
306    /// The thumb's extent along the orientation: `Slider::GetThumbLength`.
307    fn thumb_length(&self, r: &ThemeResources) -> f64 {
308        match self.orientation {
309            Axis::Horizontal => r.slider_horizontal_thumb_width,
310            Axis::Vertical => r.slider_vertical_thumb_height,
311        }
312    }
313
314    /// `Slider::GetClosestStep`: the multiple of `step_delta` nearest `from_value`, inside the range.
315    fn closest_step(&self, step_delta: f64, from_value: f64) -> f64 {
316        let range = self.range();
317        let num_steps = from_value / step_delta;
318        let next_step = range.maximum.min(num_steps.ceil() * step_delta);
319        let prev_step = range.minimum.max(num_steps.floor() * step_delta);
320        if next_step - from_value < from_value - prev_step {
321            next_step
322        } else {
323            prev_step
324        }
325    }
326
327    /// `Slider::Step` with `bUseSmallChange`: the value one `SmallChange` (or one tick) from `Value` in `forward`'s direction, kept on the step grid; stepping back from the far end lands on the last multiple before it rather than skipping it.
328    fn step(&self, forward: bool) -> f64 {
329        let step_delta = match self.snaps_to {
330            SliderSnapsTo::StepValues => self.small_change,
331            SliderSnapsTo::Ticks => self.tick_frequency,
332        };
333        let range = self.range();
334        let value = range.value;
335        if !forward
336            && are_close(value, range.maximum)
337            && !are_close(fractional(value / step_delta), 0.0)
338        {
339            (value / step_delta).floor() * step_delta
340        } else {
341            let new_value = if forward {
342                value + step_delta
343            } else {
344                value - step_delta
345            };
346            self.closest_step(step_delta, new_value)
347        }
348    }
349}
350
351impl fmt::Debug for Slider {
352    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
353        f.debug_struct("Slider")
354            .field("value", &self.value)
355            .field("minimum", &self.minimum)
356            .field("maximum", &self.maximum)
357            .field("orientation", &self.orientation)
358            .field("is_enabled", &self.is_enabled)
359            .finish_non_exhaustive()
360    }
361}
362
363/// The slider's own state (`Slider_Partial.h` members) and its thumb's (`Thumb_Partial.h`).
364pub struct SliderState {
365    state: StateData<Slider>,
366    focus_node: Option<FocusNodeRef>,
367    /// `m_IsPointerOver`: a non-touch pointer is over the control.
368    is_pointer_over: bool,
369    /// `m_isPressed`: the track is pressed and the thumb follows the pointer.
370    is_pressed: bool,
371    /// `Thumb::IsDragging`.
372    is_dragging: bool,
373    /// The thumb's own `m_IsPointerOver`.
374    is_thumb_pointer_over: bool,
375    /// The keyboard focus visual shows (`Focused`).
376    focused: bool,
377    /// Source thumb tooltip visibility, independent of mouse hover.
378    tooltip_open: bool,
379    /// Source keyboard/mouse/touch separation from the thumb.
380    tooltip_offset: f64,
381    /// `m_DragValue`: the value the drag started at plus the deltas since.
382    drag_value: f64,
383    /// `IntermediateValue` while a press or drag is in progress; `Value` otherwise.
384    intermediate_value: Option<f64>,
385    /// `Thumb::m_previousPosition`: where the last drag delta was measured from.
386    previous_position: Offset,
387    /// Names `SliderContainer`, whose `ActualWidth` / `ActualHeight` the pointer maths reads.
388    container_key: GlobalKey,
389}
390
391impl StatefulWidget for Slider {
392    type State = SliderState;
393    fn key(&self) -> Option<&KeyRef> {
394        self.key.as_ref()
395    }
396    fn create_state(&self) -> SliderState {
397        SliderState {
398            state: StateData::new(),
399            focus_node: None,
400            is_pointer_over: false,
401            is_pressed: false,
402            is_dragging: false,
403            is_thumb_pointer_over: false,
404            focused: false,
405            tooltip_open: false,
406            tooltip_offset: 12.0,
407            drag_value: 0.0,
408            intermediate_value: None,
409            previous_position: Offset::ZERO,
410            container_key: GlobalKey::new(),
411        }
412    }
413}
414
415impl SliderState {
416    /// `Slider::ChangeVisualState`: the `CommonStates` group of the slider.
417    fn slider_state(self: Handle<Self>, app: &App) -> CommonState {
418        let data = app.get(self);
419        if !self.widget(app).is_enabled {
420            CommonState::Disabled
421        } else if data.is_pressed {
422            CommonState::Pressed
423        } else if data.is_pointer_over {
424            CommonState::PointerOver
425        } else {
426            CommonState::Normal
427        }
428    }
429
430    /// `Thumb::ChangeVisualState`: the `CommonStates` group of the thumb, pressed while it drags.
431    fn thumb_state(self: Handle<Self>, app: &App) -> CommonState {
432        let data = app.get(self);
433        if !self.widget(app).is_enabled {
434            CommonState::Disabled
435        } else if data.is_dragging {
436            CommonState::Pressed
437        } else if data.is_thumb_pointer_over {
438            CommonState::PointerOver
439        } else {
440            CommonState::Normal
441        }
442    }
443
444    /// The value the thumb is laid out at: `IntermediateValue`.
445    fn intermediate_value(self: Handle<Self>, app: &App) -> f64 {
446        app.get(self)
447            .intermediate_value
448            .unwrap_or_else(|| self.widget(app).range().value)
449    }
450
451    /// `SliderContainer`'s `ActualWidth` and `ActualHeight` (`Slider::UpdateTrackLayout`, `MoveThumbToPoint`), from its render object; zero before it is laid out.
452    fn track_size(self: Handle<Self>, app: &mut App) -> Size {
453        let key = app.get(self).container_key.clone();
454        key.current_context(app)
455            .and_then(|context| context.find_render_object(app))
456            .and_then(|object| object.as_box())
457            .map(|render_box| render_box.size(app))
458            .unwrap_or(Size::ZERO)
459    }
460
461    /// The thumb's layout slot in `SliderContainer` coordinates, for the value the thumb is at.
462    fn thumb_rect(self: Handle<Self>, app: &mut App) -> Rect {
463        let r = ThemeResources::of(app, self.context(app));
464        let track_size = self.track_size(app);
465        let widget = self.widget(app);
466        let fraction = widget.range().fraction_of(self.intermediate_value(app));
467        thumb_rect(
468            &r,
469            widget.orientation,
470            widget.is_direction_reversed,
471            track_size,
472            fraction,
473        )
474    }
475
476    /// Whether `point` lands on the thumb: its `Border` reaches the template's overhang past the slot.
477    fn hits_thumb(self: Handle<Self>, app: &mut App, point: Offset) -> bool {
478        let overhang = self.widget(app).thumb_overhang();
479        self.thumb_rect(app).inflate(overhang).contains(point)
480    }
481
482    /// `put_Value`: coerced by `CRangeBase`; `ValueChanged` only when it differs.
483    fn put_value(self: Handle<Self>, app: &mut App, value: f64) {
484        let widget = self.widget(app).clone();
485        let value = widget.range().coerce_value(value);
486        if value != widget.range().value {
487            (widget.value_changed)(app, value);
488        }
489    }
490
491    /// The tail of `MoveThumbToPoint` and `OnThumbDragDelta`: `Value` goes to the step nearest `intermediate_value` when that is not where it already is.
492    fn snap_value(self: Handle<Self>, app: &mut App, intermediate_value: f64) {
493        let widget = self.widget(app).clone();
494        let closest_step = widget.closest_step(widget.snap_interval(), intermediate_value);
495        if !are_close(widget.range().value, closest_step) {
496            self.put_value(app, closest_step);
497        }
498    }
499
500    /// `Slider::MoveThumbToPoint`: the share of the clickable track (the track less the thumb, whose midpoint never reaches the ends) under `point` becomes `IntermediateValue`, and `Value` snaps to it.
501    fn move_thumb_to_point(self: Handle<Self>, app: &mut App, point: Offset) {
502        let r = ThemeResources::of(app, self.context(app));
503        let widget = self.widget(app).clone();
504        let track_size = self.track_size(app);
505        let (track_length, click_delta) = match widget.orientation {
506            Axis::Horizontal => (track_size.width(), point.dx()),
507            Axis::Vertical => (track_size.height(), track_size.height() - point.dy()),
508        };
509        let thumb_length = widget.thumb_length(&r);
510        let clickable_length = (track_length - thumb_length).max(1.0);
511        let mut click_percentage = (click_delta - thumb_length / 2.0) / clickable_length;
512        click_percentage = click_percentage.clamp(0.0, 1.0);
513        if widget.is_direction_reversed {
514            click_percentage = 1.0 - click_percentage;
515        }
516        let range = widget.range();
517        let intermediate_value = range.minimum + click_percentage * range.span();
518        self.set_state(app, |state| {
519            state.intermediate_value = Some(intermediate_value)
520        });
521        self.snap_value(app, intermediate_value);
522    }
523
524    /// `Slider::OnThumbDragDelta`: the pointer's movement along the track, as a share of the track less the thumb, scaled to the range and added to `m_DragValue`.
525    fn thumb_drag_delta(self: Handle<Self>, app: &mut App, change: Offset) {
526        let r = ThemeResources::of(app, self.context(app));
527        let widget = self.widget(app).clone();
528        let track_size = self.track_size(app);
529        let range = widget.range();
530        let (change, actual_size) = match widget.orientation {
531            Axis::Horizontal => (change.dx(), track_size.width()),
532            Axis::Vertical => (-change.dy(), track_size.height()),
533        };
534        let offset = change * range.span() / (actual_size - widget.thumb_length(&r)).max(1.0);
535        if !offset.is_finite() {
536            return;
537        }
538        let drag_value = app.get(self).drag_value
539            + if widget.is_direction_reversed {
540                -offset
541            } else {
542                offset
543            };
544        let intermediate_value = range.coerce_value(drag_value);
545        self.set_state(app, |state| {
546            state.drag_value = drag_value;
547            state.intermediate_value = Some(intermediate_value);
548        });
549        self.snap_value(app, intermediate_value);
550    }
551
552    /// `Slider::OnPointerPressed` for the left button on `SliderContainer`, or `Thumb::OnPointerPressed` when the thumb is under it (the thumb handles the event first).
553    fn pointer_pressed(self: Handle<Self>, app: &mut App, event: &PointerDownEvent) {
554        if event.buttons & K_PRIMARY_BUTTON == 0 {
555            return;
556        }
557        self.set_state(app, |state| {
558            state.tooltip_open = true;
559            state.tooltip_offset = if event.kind == PointerDeviceKind::Touch {
560                44.0
561            } else {
562                20.0
563            };
564        });
565        let point = event.local_position();
566        if self.hits_thumb(app, point) {
567            // `OnThumbDragStarted`: the drag accumulates from the current value.
568            let value = self.widget(app).range().value;
569            self.set_state(app, |state| {
570                state.is_dragging = true;
571                state.previous_position = point;
572                state.drag_value = value;
573            });
574        } else {
575            self.move_thumb_to_point(app, point);
576            self.set_state(app, |state| state.is_pressed = true);
577        }
578    }
579
580    /// `Thumb::OnPointerMoved` while dragging, else `Slider::OnPointerMoved` while pressed.
581    fn pointer_moved(self: Handle<Self>, app: &mut App, point: Offset) {
582        let data = app.get(self);
583        if data.is_dragging {
584            let previous = data.previous_position;
585            if point != previous {
586                app.get_mut(self).previous_position = point;
587                self.thumb_drag_delta(app, point - previous);
588            }
589        } else if data.is_pressed {
590            self.move_thumb_to_point(app, point);
591        }
592    }
593
594    /// `Thumb::OnPointerReleased` (`DragCompleted`) and `Slider::OnPointerReleased` (`PerformPointerUpAction`): `IntermediateValue` settles on `Value`; the thumb's hover state is what the pointer is now over.
595    fn pointer_released(self: Handle<Self>, app: &mut App, point: Offset, kind: PointerDeviceKind) {
596        let over_thumb = kind != PointerDeviceKind::Touch && self.hits_thumb(app, point);
597        self.set_state(app, |state| {
598            state.tooltip_open = false;
599            state.is_dragging = false;
600            state.is_pressed = false;
601            state.intermediate_value = None;
602            state.is_thumb_pointer_over = over_thumb;
603        });
604    }
605
606    /// `Slider::OnPointerCaptureLost` and `Thumb::OnPointerCaptureLost`: everything the pointer held is let go.
607    fn pointer_capture_lost(self: Handle<Self>, app: &mut App) {
608        self.set_state(app, |state| {
609            state.tooltip_open = false;
610            state.is_dragging = false;
611            state.is_pressed = false;
612            state.is_pointer_over = false;
613            state.is_thumb_pointer_over = false;
614            state.intermediate_value = None;
615        });
616    }
617
618    /// `Thumb::OnPointerEntered` / `OnPointerExited` for a pointer moving over the control without pressing (touch is ignored there); while the container holds the pointer the thumb sees nothing.
619    fn pointer_hovered(self: Handle<Self>, app: &mut App, point: Offset, kind: PointerDeviceKind) {
620        let data = app.get(self);
621        if kind == PointerDeviceKind::Touch || data.is_pressed || data.is_dragging {
622            return;
623        }
624        let was_over_thumb = data.is_thumb_pointer_over;
625        let over_thumb = self.hits_thumb(app, point);
626        if over_thumb != was_over_thumb {
627            self.set_state(app, |state| state.is_thumb_pointer_over = over_thumb);
628        }
629    }
630
631    /// `KeyPress::Slider::KeyDown`: the arrow keys step by `SmallChange` (Left and Down toward `Minimum`, mirrored by `IsDirectionReversed`), Home and End go to the ends.
632    fn key_down(self: Handle<Self>, app: &mut App, key: LogicalKeyboardKey) -> KeyEventResult {
633        let widget = self.widget(app).clone();
634        if !widget.is_enabled {
635            return KeyEventResult::Ignored;
636        }
637        if let Some(result) = widget
638            .key_down
639            .as_ref()
640            .and_then(|handler| handler(app, key))
641        {
642            return result;
643        }
644        let reversed = widget.is_direction_reversed;
645        let value = match key {
646            LogicalKeyboardKey::ARROW_LEFT => widget.step(reversed),
647            LogicalKeyboardKey::ARROW_RIGHT => widget.step(!reversed),
648            LogicalKeyboardKey::ARROW_UP => widget.step(!reversed),
649            LogicalKeyboardKey::ARROW_DOWN => widget.step(reversed),
650            LogicalKeyboardKey::HOME => widget.range().minimum,
651            LogicalKeyboardKey::END => widget.range().maximum,
652            _ => return KeyEventResult::Ignored,
653        };
654        self.put_value(app, value);
655        KeyEventResult::Handled
656    }
657
658    /// The pointer handlers `Slider::OnApplyTemplate` attaches to `SliderContainer`, on the container; the thumb's are folded in by hit-testing the thumb's slot.
659    fn pointer_listener(self: Handle<Self>, container: WidgetRef) -> PointerListener {
660        PointerListener::new()
661            .behavior(HitTestBehavior::Opaque)
662            .on_pointer_down(Rc::new(move |app: &mut App, event| {
663                self.pointer_pressed(app, &event);
664            }))
665            .on_pointer_move(Rc::new(move |app: &mut App, event| {
666                self.pointer_moved(app, event.local_position());
667            }))
668            .on_pointer_up(Rc::new(move |app: &mut App, event| {
669                self.pointer_released(app, event.local_position(), event.kind);
670            }))
671            .on_pointer_cancel(Rc::new(move |app: &mut App, _event| {
672                self.pointer_capture_lost(app);
673            }))
674            .on_pointer_hover(Rc::new(move |app: &mut App, event| {
675                self.pointer_hovered(app, event.local_position(), event.kind);
676            }))
677            .child(container)
678    }
679}
680
681impl State for SliderState {
682    type Widget = Slider;
683    waft_widgets::state_accessors!();
684
685    fn init_state(self: Handle<Self>, app: &mut App) {
686        crate::InputDevice::initialize(app);
687        let node: FocusNodeRef = FocusNode::new(app).into_erased();
688        node.set_on_key_event(
689            app,
690            Some(Rc::new(
691                move |app: &mut App, _node, event: &KeyEvent| match event {
692                    KeyEvent::Down(down) => self.key_down(app, down.logical_key),
693                    KeyEvent::Repeat(repeat) => self.key_down(app, repeat.logical_key),
694                    KeyEvent::Up(_) => KeyEventResult::Ignored,
695                },
696            )),
697        );
698        app.get_mut(self).focus_node = Some(node.clone());
699    }
700
701    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &Slider) {
702        // `Slider::OnIsEnabledChanged`: a disabled slider is neither hovered nor pressed.
703        if !self.widget(app).is_enabled {
704            let state = app.get_mut(self);
705            state.is_pointer_over = false;
706            state.is_pressed = false;
707            state.tooltip_open = false;
708            state.is_dragging = false;
709            state.is_thumb_pointer_over = false;
710            state.intermediate_value = None;
711        }
712    }
713
714    fn dispose(self: Handle<Self>, app: &mut App) {
715        if let Some(node) = app.get_mut(self).focus_node.take() {
716            node.dispose(app);
717        }
718    }
719
720    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
721        let widget = self.widget(app).clone();
722        let resources = ThemeResources::of(app, context);
723        let states = SliderTemplateStates {
724            slider: self.slider_state(app),
725            thumb: self.thumb_state(app),
726            focused: app.get(self).focused && widget.is_enabled,
727            intermediate_value: self.intermediate_value(app),
728            zoom_scale: MediaQuery::device_pixel_ratio_of(app, context),
729            tooltip_open: app.get(self).tooltip_open
730                && widget.is_enabled
731                && widget.is_thumb_tool_tip_enabled,
732            tooltip_offset: app.get(self).tooltip_offset,
733        };
734        let container_key: KeyRef = app.get(self).container_key.clone().into();
735        let enabled = widget.is_enabled;
736        let parts = SliderTemplateParts {
737            container: Rc::new(move |content| {
738                let container = KeyedSubtree::new(content)
739                    .key(container_key.clone())
740                    .into_widget();
741                if !enabled {
742                    return container;
743                }
744                // `ManipulationMode="None"`: the slider keeps every pointer that lands on it.
745                RawGestureDetector::new()
746                    .gestures(vec![(
747                        TypeId::of::<EagerGestureRecognizer>(),
748                        GestureRecognizerFactoryWithHandlers::new(
749                            EagerGestureRecognizer::new,
750                            |_, _| {},
751                        )
752                        .into_factory(),
753                    )])
754                    .child(self.pointer_listener(container))
755                    .into_widget()
756            }),
757        };
758        let body = match widget.template.clone() {
759            Some(template) => (template.build)(app, context, &widget, states, &parts),
760            None => default_template(&resources, &widget, states, &parts),
761        };
762        let mut detector = FocusableActionDetector::new(body)
763            .enabled(widget.is_enabled)
764            .on_focus_change(move |app, focused| {
765                let value = focused && crate::FocusState::current(app).shows_focus_visual();
766                self.set_state(app, |state| {
767                    state.focused = value;
768                    if value {
769                        state.tooltip_open = true;
770                        state.tooltip_offset = 12.0;
771                    }
772                    if !focused {
773                        state.tooltip_open = false;
774                    }
775                })
776            })
777            .on_show_hover_highlight(move |app, value| {
778                // `Slider::OnPointerEntered` / `OnPointerExited`; the thumb exits with the control.
779                self.set_state(app, |state| {
780                    state.is_pointer_over = value;
781                    if !value {
782                        state.is_thumb_pointer_over = false;
783                    }
784                })
785            });
786        if let Some(node) = app.get(self).focus_node.clone() {
787            detector = detector.focus_node(node);
788        }
789        detector.into_widget()
790    }
791}
792
793/// What a Slider template is built for: the two `CommonStates` groups, focus, the thumb's value and the pixel scale.
794#[derive(Clone, Copy, Debug, PartialEq)]
795pub struct SliderTemplateStates {
796    /// The slider's `CommonStates`.
797    pub slider: CommonState,
798    /// The thumb's `CommonStates`.
799    pub thumb: CommonState,
800    /// The focus visual shows.
801    pub focused: bool,
802    /// `IntermediateValue`, where the thumb is laid out.
803    pub intermediate_value: f64,
804    /// Physical pixels per logical pixel.
805    pub zoom_scale: f64,
806    /// Source-controlled thumb tooltip visibility.
807    pub tooltip_open: bool,
808    /// Separation chosen by the input that opened the tooltip.
809    pub tooltip_offset: f64,
810}
811
812/// The brushes the slider's `CommonStates` storyboards set for one state.
813struct SliderBrushes {
814    /// `HorizontalTrackRect` / `VerticalTrackRect` `Fill`: the control's `Background`.
815    track: Color,
816    /// `HorizontalDecreaseRect` / `VerticalDecreaseRect` `Fill`: the control's `Foreground`.
817    decrease: Color,
818    /// `HorizontalThumb` / `VerticalThumb` `Background`, which `SliderInnerThumb` fills with.
819    thumb: Color,
820    /// `SliderContainer` `Background`.
821    container: Color,
822    /// `HeaderContentPresenter` `Foreground`.
823    header: Color,
824    /// The outside tick bars' `Fill`.
825    tick_bar: Color,
826}
827
828fn brushes(resources: &ThemeResources, r: &ThemeResources, state: CommonState) -> SliderBrushes {
829    match state {
830        CommonState::Normal => SliderBrushes {
831            track: r.slider_track_fill,
832            decrease: r.slider_track_value_fill,
833            thumb: r.slider_thumb_background,
834            // `SliderContainerBackground`: `ControlFillColorTransparentBrush` in the Light dictionary; the Default dictionary omits the key.
835            container: resources.control_fill_color_transparent,
836            header: r.slider_header_foreground,
837            tick_bar: r.slider_tick_bar_fill,
838        },
839        CommonState::PointerOver => SliderBrushes {
840            track: r.slider_track_fill_pointer_over,
841            decrease: r.slider_track_value_fill_pointer_over,
842            thumb: r.slider_thumb_background_pointer_over,
843            container: r.slider_container_background_pointer_over,
844            header: r.slider_header_foreground,
845            tick_bar: r.slider_tick_bar_fill,
846        },
847        CommonState::Pressed => SliderBrushes {
848            track: r.slider_track_fill_pressed,
849            decrease: r.slider_track_value_fill_pressed,
850            thumb: r.slider_thumb_background_pressed,
851            container: r.slider_container_background_pressed,
852            header: r.slider_header_foreground,
853            tick_bar: r.slider_tick_bar_fill,
854        },
855        CommonState::Disabled => SliderBrushes {
856            track: r.slider_track_fill_disabled,
857            decrease: r.slider_track_value_fill_disabled,
858            thumb: r.slider_thumb_background_disabled,
859            container: r.slider_container_background_disabled,
860            header: r.slider_header_foreground_disabled,
861            tick_bar: r.slider_tick_bar_fill_disabled,
862        },
863    }
864}
865
866/// `DefaultSliderStyle`'s template: `SliderContainer`, its background and the template for the orientation, in the root.
867fn default_template(
868    resources: &ThemeResources,
869    widget: &Slider,
870    states: SliderTemplateStates,
871    parts: &SliderTemplateParts,
872) -> WidgetRef {
873    let container = parts.slider_container(slider_container(resources, widget, states));
874    template(resources, widget, states, container)
875}
876
877/// `Slider::UpdateTrackLayout`: the decrease rect's length is `multiplier × (track − thumb)`, never negative.
878fn decrease_length(track_length: f64, thumb_length: f64, fraction: f64) -> f64 {
879    (fraction * (track_length - thumb_length)).max(0.0)
880}
881
882/// The thumb's slot in the template grid: after the decrease rect along the track (before it when reversed), centred across it in the three rows or columns.
883fn thumb_rect(
884    r: &ThemeResources,
885    orientation: Axis,
886    is_direction_reversed: bool,
887    track_size: Size,
888    fraction: f64,
889) -> Rect {
890    let across =
891        (r.slider_pre_content_margin + r.slider_track_theme_height + r.slider_post_content_margin
892            - r.slider_horizontal_thumb_height)
893            / 2.0;
894    match orientation {
895        Axis::Horizontal => {
896            let thumb = r.slider_horizontal_thumb_width;
897            let decrease = decrease_length(track_size.width(), thumb, fraction);
898            let left = if is_direction_reversed {
899                track_size.width() - decrease - thumb
900            } else {
901                decrease
902            };
903            Rect::from_ltwh(left, across, thumb, r.slider_horizontal_thumb_height)
904        }
905        Axis::Vertical => {
906            let thumb = r.slider_vertical_thumb_height;
907            let decrease = decrease_length(track_size.height(), thumb, fraction);
908            let top = if is_direction_reversed {
909                decrease
910            } else {
911                track_size.height() - decrease - thumb
912            };
913            Rect::from_ltwh(across, top, r.slider_vertical_thumb_width, thumb)
914        }
915    }
916}
917
918/// The root `Grid`: `HeaderContentPresenter` in the Auto row, `FocusBorder` and `SliderContainer` in the star row.
919fn template(
920    resources: &ThemeResources,
921    widget: &Slider,
922    states: SliderTemplateStates,
923    container: WidgetRef,
924) -> WidgetRef {
925    let brushes = brushes(resources, resources, states.slider);
926    let mut children = Vec::new();
927    if let Some(header) = &widget.header {
928        // `HeaderContentPresenter`: `SliderHeaderThemeFontWeight` is Normal; collapsed without a `Header`.
929        let [left, top, right, bottom] = resources.slider_top_header_margin;
930        let text = control_text_style(
931            resources,
932            resources.control_content_theme_font_size,
933            resources.slider_header_theme_font_weight,
934            brushes.header,
935        );
936        children.push(
937            GridCell::new(
938                Padding::new(EdgeInsetsGeometry::from_ltrb(left, top, right, bottom))
939                    .child(DefaultTextStyle::new(text, header.clone())),
940            )
941            .row(0)
942            .into_widget(),
943        );
944    }
945    // `FocusBorder`: the system focus visual around row 1, with the style's `FocusVisualMargin`.
946    children.push(
947        GridCell::new(
948            FocusVisual::new(container, resources.theme)
949                .visible(states.focused)
950                .margin(SLIDER_FOCUS_VISUAL_MARGIN)
951                .corner_radius(resources.control_corner_radius[0]),
952        )
953        .row(1)
954        .into_widget(),
955    );
956    Grid::new()
957        .row_definitions([
958            RowDefinition::new(GridLength::AUTO),
959            RowDefinition::new(GridLength::STAR),
960        ])
961        .children(children)
962        .into_widget()
963}
964
965/// `SliderContainer`'s content: its background and the template for the orientation.
966fn slider_container(
967    resources: &ThemeResources,
968    widget: &Slider,
969    states: SliderTemplateStates,
970) -> WidgetRef {
971    let brushes = brushes(resources, resources, states.slider);
972    let template = match widget.orientation {
973        Axis::Horizontal => horizontal_template(resources, widget, states, &brushes),
974        Axis::Vertical => vertical_template(resources, widget, states, &brushes),
975    };
976    ColoredBox::new(brushes.container)
977        .child(template)
978        .into_widget()
979}
980
981/// `Slider::UpdateTrackLayout` gives the decrease rect `multiplier × (track − thumb)` of the star space and the rest to the star column or row beyond the thumb; the same split as star weights, which need no actual size at build time.
982pub(crate) fn decrease_definitions(
983    fraction: f64,
984    is_direction_reversed: bool,
985) -> (GridLength, GridLength) {
986    let decrease = GridLength::star(fraction);
987    let remainder = GridLength::star(1.0 - fraction);
988    if is_direction_reversed {
989        (remainder, decrease)
990    } else {
991        (decrease, remainder)
992    }
993}
994
995/// `child` stretched along `orientation` to a bounded length, adding nothing to an unbounded one.
996/// The track and tick bars use it so that a slider fills the width or height its parent bounds, as
997/// Flutter's `Slider` does, and in an unbounded length is as long as its thumb, as XAML measures it.
998#[cfg_attr(debug_assertions, track_caller)]
999pub(crate) fn fill_bounded<K>(orientation: Axis, child: impl IntoWidget<K>) -> WidgetRef {
1000    match orientation {
1001        Axis::Horizontal => LimitedBox::new()
1002            .max_width(0.0)
1003            .child(SizedBox::new().width(f64::INFINITY).child(child)),
1004        Axis::Vertical => LimitedBox::new()
1005            .max_height(0.0)
1006            .child(SizedBox::new().height(f64::INFINITY).child(child)),
1007    }
1008    .into_widget()
1009}
1010
1011/// A track `Rectangle`: `RadiusX` / `RadiusY` from the control's `CornerRadius` (`SliderTrackCornerRadius`).
1012fn track_rectangle(r: &ThemeResources, fill: Color) -> ControlBorder {
1013    ControlBorder::new(
1014        Brush::Solid(fill),
1015        Brush::Solid(Color::from_argb(0, 0, 0, 0)),
1016    )
1017    .border_thickness(0.0)
1018    .corner_radius(r.slider_track_corner_radius[0])
1019}
1020
1021/// A `TickBar` of the slider with `fill`, laid out from the slider's properties.
1022fn tick_bar(
1023    r: &ThemeResources,
1024    widget: &Slider,
1025    states: SliderTemplateStates,
1026    fill: Color,
1027) -> TickBar {
1028    let range = widget.range();
1029    TickBar::new(fill, widget.orientation)
1030        .tick_frequency(widget.tick_frequency)
1031        .range(range.minimum, range.maximum)
1032        .thumb_length(widget.thumb_length(r))
1033        .is_direction_reversed(widget.is_direction_reversed)
1034        .zoom_scale(states.zoom_scale)
1035}
1036
1037/// `HorizontalTemplate`.
1038fn horizontal_template(
1039    resources: &ThemeResources,
1040    widget: &Slider,
1041    states: SliderTemplateStates,
1042    brushes: &SliderBrushes,
1043) -> WidgetRef {
1044    let reversed = widget.is_direction_reversed;
1045    let fraction = widget.range().fraction_of(states.intermediate_value);
1046    let placement = widget.tick_placement;
1047    let mut children = vec![
1048        // `HorizontalTrackRect`.
1049        GridCell::new(fill_bounded(
1050            Axis::Horizontal,
1051            SizedBox::new()
1052                .height(resources.slider_track_theme_height)
1053                .child(track_rectangle(resources, brushes.track)),
1054        ))
1055        .row(1)
1056        .column_span(3)
1057        .into_widget(),
1058        // `HorizontalDecreaseRect`: `Grid.Column` 0, or the last column when reversed; its column is its width.
1059        GridCell::new(
1060            SizedBox::new()
1061                .height(resources.slider_track_theme_height)
1062                .child(track_rectangle(resources, brushes.decrease)),
1063        )
1064        .row(1)
1065        .column(if reversed { 2 } else { 0 })
1066        .into_widget(),
1067    ];
1068    if placement.shows_top_left() {
1069        // `TopTickBar`: `VerticalAlignment="Bottom"`, `Margin="0,0,0,4"`, in the pre-content row.
1070        children.push(
1071            GridCell::new(
1072                Padding::new(EdgeInsetsGeometry::from_ltrb(
1073                    0.0,
1074                    0.0,
1075                    0.0,
1076                    TICK_BAR_MARGIN,
1077                ))
1078                .child(
1079                    Align::new()
1080                        .alignment(AlignmentGeometry::BOTTOM_CENTER)
1081                        .child(fill_bounded(
1082                            Axis::Horizontal,
1083                            SizedBox::new()
1084                                .height(resources.slider_outside_tick_bar_theme_height)
1085                                .child(tick_bar(resources, widget, states, brushes.tick_bar)),
1086                        )),
1087                ),
1088            )
1089            .row(0)
1090            .column_span(3)
1091            .into_widget(),
1092        );
1093    }
1094    if placement.shows_inline() {
1095        // `HorizontalInlineTickBar`: over the track, `SliderInlineTickBarFill`.
1096        children.push(
1097            GridCell::new(fill_bounded(
1098                Axis::Horizontal,
1099                SizedBox::new()
1100                    .height(resources.slider_track_theme_height)
1101                    .child(tick_bar(
1102                        resources,
1103                        widget,
1104                        states,
1105                        resources.slider_inline_tick_bar_fill,
1106                    )),
1107            ))
1108            .row(1)
1109            .column_span(3)
1110            .into_widget(),
1111        );
1112    }
1113    if placement.shows_bottom_right() {
1114        // `BottomTickBar`: `VerticalAlignment="Top"`, `Margin="0,4,0,0"`, in the post-content row.
1115        children.push(
1116            GridCell::new(
1117                Padding::new(EdgeInsetsGeometry::from_ltrb(
1118                    0.0,
1119                    TICK_BAR_MARGIN,
1120                    0.0,
1121                    0.0,
1122                ))
1123                .child(
1124                    Align::new()
1125                        .alignment(AlignmentGeometry::TOP_CENTER)
1126                        .child(fill_bounded(
1127                            Axis::Horizontal,
1128                            SizedBox::new()
1129                                .height(resources.slider_outside_tick_bar_theme_height)
1130                                .child(tick_bar(resources, widget, states, brushes.tick_bar)),
1131                        )),
1132                ),
1133            )
1134            .row(2)
1135            .column_span(3)
1136            .into_widget(),
1137        );
1138    }
1139    // `HorizontalThumb`: column 1, all rows, 18 × 18 centred.
1140    children.push(
1141        GridCell::new(
1142            Center::new()
1143                .width_factor(1.0)
1144                .height_factor(1.0)
1145                .child(thumb(
1146                    resources,
1147                    widget,
1148                    states,
1149                    brushes.thumb,
1150                    states.thumb,
1151                    resources.slider_horizontal_thumb_width,
1152                    resources.slider_horizontal_thumb_height,
1153                )),
1154        )
1155        .row(0)
1156        .row_span(3)
1157        .column(1)
1158        .into_widget(),
1159    );
1160    let (first, last) = decrease_definitions(fraction, reversed);
1161    let grid = Grid::new()
1162        .column_definitions([
1163            ColumnDefinition::new(first),
1164            ColumnDefinition::new(GridLength::AUTO),
1165            ColumnDefinition::new(last),
1166        ])
1167        .row_definitions([
1168            RowDefinition::new(GridLength::pixel(resources.slider_pre_content_margin)),
1169            RowDefinition::new(GridLength::AUTO),
1170            RowDefinition::new(GridLength::pixel(resources.slider_post_content_margin)),
1171        ])
1172        .children(children);
1173    // `MinHeight="{ThemeResource SliderHorizontalHeight}"`.
1174    ConstrainedBox::new(BoxConstraints::new().min_height(resources.slider_horizontal_height))
1175        .child(grid)
1176        .into_widget()
1177}
1178
1179/// `VerticalTemplate`.
1180fn vertical_template(
1181    resources: &ThemeResources,
1182    widget: &Slider,
1183    states: SliderTemplateStates,
1184    brushes: &SliderBrushes,
1185) -> WidgetRef {
1186    let reversed = widget.is_direction_reversed;
1187    let fraction = widget.range().fraction_of(states.intermediate_value);
1188    let placement = widget.tick_placement;
1189    let mut children = vec![
1190        // `VerticalTrackRect`.
1191        GridCell::new(fill_bounded(
1192            Axis::Vertical,
1193            SizedBox::new()
1194                .width(resources.slider_track_theme_height)
1195                .child(track_rectangle(resources, brushes.track)),
1196        ))
1197        .column(1)
1198        .row_span(3)
1199        .into_widget(),
1200        // `VerticalDecreaseRect`: `Grid.Row` 2, or row 0 when reversed; its row is its height.
1201        GridCell::new(
1202            SizedBox::new()
1203                .width(resources.slider_track_theme_height)
1204                .child(track_rectangle(resources, brushes.decrease)),
1205        )
1206        .column(1)
1207        .row(if reversed { 0 } else { 2 })
1208        .into_widget(),
1209    ];
1210    if placement.shows_top_left() {
1211        // `LeftTickBar`: `HorizontalAlignment="Right"`, `Margin="0,0,4,0"`, in the pre-content column.
1212        children.push(
1213            GridCell::new(
1214                Padding::new(EdgeInsetsGeometry::from_ltrb(
1215                    0.0,
1216                    0.0,
1217                    TICK_BAR_MARGIN,
1218                    0.0,
1219                ))
1220                .child(
1221                    Align::new()
1222                        .alignment(AlignmentGeometry::CENTER_RIGHT)
1223                        .child(fill_bounded(
1224                            Axis::Vertical,
1225                            SizedBox::new()
1226                                .width(resources.slider_outside_tick_bar_theme_height)
1227                                .child(tick_bar(resources, widget, states, brushes.tick_bar)),
1228                        )),
1229                ),
1230            )
1231            .column(0)
1232            .row_span(3)
1233            .into_widget(),
1234        );
1235    }
1236    if placement.shows_inline() {
1237        // `VerticalInlineTickBar`.
1238        children.push(
1239            GridCell::new(fill_bounded(
1240                Axis::Vertical,
1241                SizedBox::new()
1242                    .width(resources.slider_track_theme_height)
1243                    .child(tick_bar(
1244                        resources,
1245                        widget,
1246                        states,
1247                        resources.slider_inline_tick_bar_fill,
1248                    )),
1249            ))
1250            .column(1)
1251            .row_span(3)
1252            .into_widget(),
1253        );
1254    }
1255    if placement.shows_bottom_right() {
1256        // `RightTickBar`: `HorizontalAlignment="Left"`, `Margin="4,0,0,0"`, in the post-content column.
1257        children.push(
1258            GridCell::new(
1259                Padding::new(EdgeInsetsGeometry::from_ltrb(
1260                    TICK_BAR_MARGIN,
1261                    0.0,
1262                    0.0,
1263                    0.0,
1264                ))
1265                .child(
1266                    Align::new()
1267                        .alignment(AlignmentGeometry::CENTER_LEFT)
1268                        .child(fill_bounded(
1269                            Axis::Vertical,
1270                            SizedBox::new()
1271                                .width(resources.slider_outside_tick_bar_theme_height)
1272                                .child(tick_bar(resources, widget, states, brushes.tick_bar)),
1273                        )),
1274                ),
1275            )
1276            .column(2)
1277            .row_span(3)
1278            .into_widget(),
1279        );
1280    }
1281    // `VerticalThumb`: row 1, all columns, 18 × 18 centred.
1282    children.push(
1283        GridCell::new(
1284            Center::new()
1285                .width_factor(1.0)
1286                .height_factor(1.0)
1287                .child(thumb(
1288                    resources,
1289                    widget,
1290                    states,
1291                    brushes.thumb,
1292                    states.thumb,
1293                    resources.slider_vertical_thumb_width,
1294                    resources.slider_vertical_thumb_height,
1295                )),
1296        )
1297        .row(1)
1298        .column(0)
1299        .column_span(3)
1300        .into_widget(),
1301    );
1302    // The decrease rect is in the last row unless reversed.
1303    let (last, first) = decrease_definitions(fraction, reversed);
1304    let grid = Grid::new()
1305        .row_definitions([
1306            RowDefinition::new(first),
1307            RowDefinition::new(GridLength::AUTO),
1308            RowDefinition::new(last),
1309        ])
1310        .column_definitions([
1311            ColumnDefinition::new(GridLength::pixel(resources.slider_pre_content_margin)),
1312            ColumnDefinition::new(GridLength::AUTO),
1313            ColumnDefinition::new(GridLength::pixel(resources.slider_post_content_margin)),
1314        ])
1315        .children(children);
1316    // `MinWidth="{ThemeResource SliderVerticalWidth}"`.
1317    ConstrainedBox::new(BoxConstraints::new().min_width(resources.slider_vertical_width))
1318        .child(grid)
1319        .into_widget()
1320}
1321
1322/// A `Thumb` with `SliderThumbStyle`: the `Border` overhanging the `width × height` slot by `THUMB_BORDER_OVERHANG`, `SliderOuterThumbBackground` inside `SliderThumbBorderBrush`, around `SliderInnerThumb` at the scale its state animates to.
1323fn thumb(
1324    resources: &ThemeResources,
1325    widget: &Slider,
1326    states: SliderTemplateStates,
1327    fill: Color,
1328    state: CommonState,
1329    width: f64,
1330    height: f64,
1331) -> WidgetRef {
1332    let r = &resources;
1333    let (scale, duration) = inner_thumb_scale(resources, state);
1334    // `SliderInnerThumb`: `Fill="{TemplateBinding Background}"`, scaled about its centre.
1335    let inner = AnimatedContainer::new(duration)
1336        .curve(fast_out_slow_in(resources))
1337        .width(r.slider_inner_thumb_width * scale)
1338        .height(r.slider_inner_thumb_height * scale)
1339        .child(CustomPaint::new().painter(EllipsePainter { fill }));
1340    let border = ControlBorder::new(
1341        Brush::Solid(r.slider_outer_thumb_background),
1342        Brush::ControlElevation(r.slider_thumb_border_brush),
1343    )
1344    .border_thickness(THUMB_BORDER_THICKNESS)
1345    .corner_radius(r.slider_thumb_corner_radius[0])
1346    .child(Center::new().child(inner));
1347    let overhang = 2.0 * THUMB_BORDER_OVERHANG;
1348    let owner = SizedBox::new()
1349        .width(width)
1350        .height(height)
1351        .child(
1352            OverflowBox::new()
1353                .min_width(width + overhang)
1354                .max_width(width + overhang)
1355                .min_height(height + overhang)
1356                .max_height(height + overhang)
1357                .child(border),
1358        )
1359        .into_widget();
1360    let value = widget.range().value;
1361    let text = widget
1362        .thumb_tool_tip_value_converter
1363        .as_ref()
1364        .map(|converter| converter(value))
1365        .unwrap_or_else(|| format_thumb_value(value, widget.step_frequency));
1366    let tooltip = ToolTip::new(Text::new(text).style(control_text_style(
1367        resources,
1368        15.0,
1369        waft_embedder::FontWeight::W400,
1370        resources.text_fill_color_primary,
1371    )))
1372    .padding([8.0, 3.0, 8.0, 5.0])
1373    .placement(if widget.orientation == Axis::Horizontal {
1374        PlacementMode::Top
1375    } else {
1376        PlacementMode::Left
1377    })
1378    .horizontal_offset(states.tooltip_offset)
1379    .vertical_offset(states.tooltip_offset);
1380    ToolTipService::new(owner, tooltip)
1381        .is_open(states.tooltip_open)
1382        .into_widget()
1383}
1384
1385/// DefaultDisambiguationUIConverter: decimal precision follows StepFrequency, capped at four places.
1386fn format_thumb_value(value: f64, mut step: f64) -> String {
1387    let mut places = 0;
1388    while fractional(step).abs() > 0.00001 && places < 4 {
1389        places += 1;
1390        step *= 10.0;
1391    }
1392    let mut scale = 1.0;
1393    for _ in 0..places {
1394        scale /= 10.0;
1395    }
1396    let rounded = (value / scale + 0.5).floor() * scale;
1397    format!("{rounded:.places$}")
1398}
1399
1400/// XAML `Ellipse` with a solid `Fill`, filling its box.
1401#[derive(Clone, Debug, PartialEq)]
1402struct EllipsePainter {
1403    fill: Color,
1404}
1405
1406impl CustomPainter for EllipsePainter {
1407    fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
1408        let bounds = Rect::from_ltwh(0.0, 0.0, size.width(), size.height());
1409        draw_oval(
1410            canvas,
1411            bounds,
1412            &waft_embedder::Paint::from_color(self.fill.into()),
1413        );
1414    }
1415
1416    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
1417        old_delegate.as_any().downcast_ref::<Self>() != Some(self)
1418    }
1419
1420    fn as_any(&self) -> &dyn std::any::Any {
1421        self
1422    }
1423}
1424
1425#[cfg(test)]
1426mod tooltip_tests {
1427    use super::format_thumb_value;
1428    #[test]
1429    fn default_converter_uses_step_precision_capped_at_four_and_source_rounding() {
1430        assert_eq!(format_thumb_value(0.57, 0.1), "0.6");
1431        assert_eq!(format_thumb_value(12.0, 0.01), "12.00");
1432        assert_eq!(format_thumb_value(0.123456, 0.123456), "0.1235");
1433        assert_eq!(format_thumb_value(0.123456, 0.000001), "0");
1434        assert_eq!(format_thumb_value(-0.55, 0.1), "-0.5");
1435    }
1436}