Skip to main content

xrack_layout/
range.rs

1use crate::{Point, Rect, Size};
2use std::f64::consts::{PI, TAU};
3use xrack_runtime::{DialInputMode, IndicatorState, LayoutDirection, Node, Orientation};
4
5/// Geometry for the default or replacement horizontal progress artwork.
6#[doc(hidden)]
7pub fn progress_fill_bounds(
8    track: Rect,
9    direction: LayoutDirection,
10    state: IndicatorState,
11    phase: Option<f32>,
12) -> Rect {
13    let (fraction, position) = match state {
14        IndicatorState::Hidden => (0.0, 0.0),
15        IndicatorState::Determinate(progress) => (progress as f32, 0.0),
16        IndicatorState::Indeterminate => (
17            0.27,
18            phase.map_or(0.5, |phase| 1.0 - (2.0 * phase.clamp(0.0, 1.0) - 1.0).abs()),
19        ),
20    };
21    let width = track.width * fraction;
22    let fill = Rect::new(
23        track.x + (track.width - width) * position,
24        track.y,
25        width,
26        track.height,
27    );
28    crate::place_in_direction(fill, track, direction)
29}
30
31/// Shared geometry for the saturation and brightness color field.
32pub struct ColorPlaneGeometry {
33    pub field: Rect,
34}
35
36impl ColorPlaneGeometry {
37    pub fn new(bounds: Rect) -> Self {
38        Self {
39            field: bounds.inset(6.0),
40        }
41    }
42
43    pub fn point(&self, saturation: f64, brightness: f64) -> Point {
44        Point {
45            x: self.field.x + self.field.width * saturation.clamp(0.0, 1.0) as f32,
46            y: self.field.y + self.field.height * (1.0 - brightness.clamp(0.0, 1.0)) as f32,
47        }
48    }
49
50    pub fn action_at(&self, point: Point) -> Option<xrack_runtime::RangeAction> {
51        let area = self.field;
52        if area.width <= 0.0 || area.height <= 0.0 || !point.x.is_finite() || !point.y.is_finite() {
53            return None;
54        }
55        Some(xrack_runtime::RangeAction::SetPoint {
56            x: f64::from(((point.x - area.x) / area.width).clamp(0.0, 1.0)),
57            y: f64::from((1.0 - (point.y - area.y) / area.height).clamp(0.0, 1.0)),
58        })
59    }
60}
61
62/// Shared thumb travel for hit mapping and painting.
63pub struct SliderGeometry {
64    start: Point,
65    end: Point,
66    pub radius: f32,
67    thumbs: [Size; Node::RANGE_THUMBS],
68}
69
70impl SliderGeometry {
71    pub fn new(bounds: Rect, orientation: Orientation) -> Self {
72        let radius = (bounds.width.min(bounds.height) * 0.5).clamp(0.0, 8.0);
73        Self::with_travel(
74            bounds,
75            orientation,
76            LayoutDirection::LeftToRight,
77            [Size::new(radius * 2.0, radius * 2.0); 2],
78        )
79    }
80
81    pub fn for_node(bounds: Rect, node: &Node) -> Self {
82        Self::with_layout_direction(bounds, node, node.layout_direction().unwrap_or_default())
83    }
84
85    /// Resolve both painting and pointer positions using the effective direction.
86    pub fn with_layout_direction(bounds: Rect, node: &Node, direction: LayoutDirection) -> Self {
87        let radius = (bounds.width.min(bounds.height) * 0.5).clamp(0.0, 8.0);
88        let parts = if node.kind == "RangeSlider" {
89            Node::RANGE_HANDLE_PARTS
90        } else {
91            ["SliderHandle"; 2]
92        };
93        let thumbs = parts.map(|kind| {
94            let part = node.control_part(kind);
95            let extent = |property, available: f32| {
96                part.and_then(|part| part.length(property))
97                    .unwrap_or(radius * 2.0)
98                    .clamp(0.0, available)
99            };
100            Size::new(
101                extent("width", bounds.width),
102                extent("height", bounds.height),
103            )
104        });
105        Self::with_travel(bounds, node.orientation(), direction, thumbs)
106    }
107
108    fn with_travel(
109        bounds: Rect,
110        orientation: Orientation,
111        direction: LayoutDirection,
112        thumbs: [Size; 2],
113    ) -> Self {
114        let radius = (bounds.width.min(bounds.height) * 0.5).clamp(0.0, 8.0);
115        // Both endpoints must agree on one position when their values are equal.
116        let horizontal = thumbs[0].width.max(thumbs[1].width) * 0.5;
117        let vertical = thumbs[0].height.max(thumbs[1].height) * 0.5;
118        let (mut start, mut end) = match orientation {
119            Orientation::Horizontal => (
120                Point {
121                    x: bounds.x + horizontal,
122                    y: bounds.y + bounds.height * 0.5,
123                },
124                Point {
125                    x: bounds.x + bounds.width - horizontal,
126                    y: bounds.y + bounds.height * 0.5,
127                },
128            ),
129            Orientation::Vertical => (
130                Point {
131                    x: bounds.x + bounds.width * 0.5,
132                    y: bounds.y + bounds.height - vertical,
133                },
134                Point {
135                    x: bounds.x + bounds.width * 0.5,
136                    y: bounds.y + vertical,
137                },
138            ),
139        };
140        if orientation == Orientation::Horizontal && direction == LayoutDirection::RightToLeft {
141            std::mem::swap(&mut start, &mut end);
142        }
143        Self {
144            start,
145            end,
146            radius,
147            thumbs,
148        }
149    }
150
151    pub fn position(&self, fraction: f64) -> Point {
152        let t = fraction.clamp(0.0, 1.0) as f32;
153        Point {
154            x: self.start.x + (self.end.x - self.start.x) * t,
155            y: self.start.y + (self.end.y - self.start.y) * t,
156        }
157    }
158
159    pub fn thumb_bounds(&self, index: usize, fraction: f64) -> Rect {
160        let center = self.position(fraction);
161        let Size { width, height } = self.thumbs[index];
162        Rect::new(
163            center.x - width * 0.5,
164            center.y - height * 0.5,
165            width,
166            height,
167        )
168    }
169
170    pub(crate) fn interval_handle_at(
171        &self,
172        point: Point,
173        fraction: f64,
174        interval: xrack_runtime::SliderInterval,
175    ) -> usize {
176        let [lower, upper] = interval.fractions();
177        match [
178            self.thumb_bounds(0, lower).contains(point),
179            self.thumb_bounds(1, upper).contains(point),
180        ] {
181            [true, false] => 0,
182            [false, true] => 1,
183            _ => interval.nearest_handle(fraction),
184        }
185    }
186
187    pub fn fraction_at(&self, point: Point) -> Option<f64> {
188        let dx = f64::from(self.end.x - self.start.x);
189        let dy = f64::from(self.end.y - self.start.y);
190        let length_squared = dx * dx + dy * dy;
191        if length_squared <= 0.0 {
192            return None;
193        }
194        let x = f64::from(point.x - self.start.x);
195        let y = f64::from(point.y - self.start.y);
196        let fraction = (x * dx + y * dy) / length_squared;
197        fraction.is_finite().then_some(fraction)
198    }
199}
200
201/// The dial arc shared by hit testing, dragging and painting.
202pub struct DialGeometry {
203    pub center: Point,
204    pub face_radius: f32,
205    pub track_radius: f32,
206    pub thumb_radius: f32,
207    start: f64,
208    sweep: f64,
209}
210
211impl DialGeometry {
212    pub fn new(bounds: Rect, node: &Node) -> Self {
213        let default_sweep = if node.boolean("wrap", false) {
214            360.0
215        } else {
216            280.0
217        };
218        let start = node.number("start-angle").unwrap_or(-default_sweep * 0.5);
219        let sweep = node
220            .number("end-angle")
221            .map_or(default_sweep, |end| end - start);
222        let sweep = if sweep > 0.0 {
223            sweep.clamp(1.0, 360.0)
224        } else {
225            default_sweep
226        };
227        let face_radius = bounds.width.min(bounds.height).max(0.0) * 0.5;
228        let thumb_radius = (face_radius * 0.18).min(6.0);
229        Self {
230            center: Point {
231                x: bounds.x + bounds.width * 0.5,
232                y: bounds.y + bounds.height * 0.5,
233            },
234            face_radius,
235            track_radius: (face_radius - thumb_radius - 2.0).max(0.0),
236            thumb_radius,
237            start: start.rem_euclid(360.0).to_radians(),
238            sweep: sweep.to_radians(),
239        }
240    }
241
242    /// Clockwise radians measured from twelve o'clock.
243    pub fn angle(&self, fraction: f64) -> f64 {
244        self.start + self.sweep * fraction.clamp(0.0, 1.0)
245    }
246
247    pub fn position(&self, fraction: f64) -> Point {
248        let (sin, cos) = self.angle(fraction).sin_cos();
249        Point {
250            x: self.center.x + self.track_radius * sin as f32,
251            y: self.center.y - self.track_radius * cos as f32,
252        }
253    }
254
255    pub(crate) fn contains(&self, point: Point) -> bool {
256        (point.x - self.center.x).hypot(point.y - self.center.y) <= self.face_radius
257    }
258
259    pub(crate) fn contains_thumb(&self, fraction: f64, point: Point) -> bool {
260        let thumb = self.position(fraction);
261        (point.x - thumb.x).hypot(point.y - thumb.y) <= self.thumb_radius
262    }
263
264    fn pointer_angle(&self, point: Point) -> Option<f64> {
265        let x = point.x - self.center.x;
266        let y = point.y - self.center.y;
267        // Angles near the center are unstable during a drag.
268        (self.track_radius > 0.0 && x.hypot(y) > self.face_radius * 0.16)
269            .then(|| f64::from(x).atan2(-f64::from(y)))
270    }
271
272    pub(crate) fn fraction_at(&self, point: Point) -> Option<f64> {
273        let phase = (self.pointer_angle(point)? - self.start).rem_euclid(TAU);
274        Some(if phase <= self.sweep {
275            phase / self.sweep
276        } else if phase - self.sweep <= TAU - phase {
277            1.0
278        } else {
279            0.0
280        })
281    }
282
283    pub(crate) fn drag_delta(
284        &self,
285        mode: DialInputMode,
286        previous: Point,
287        next: Point,
288    ) -> Option<f64> {
289        let diameter = f64::from(self.face_radius * 2.0);
290        let delta = match mode {
291            DialInputMode::Circular => {
292                let angle = self.pointer_angle(next)? - self.pointer_angle(previous)?;
293                ((angle + PI).rem_euclid(TAU) - PI) / self.sweep
294            }
295            DialInputMode::Horizontal => f64::from(next.x - previous.x) / diameter,
296            DialInputMode::Vertical => f64::from(previous.y - next.y) / diameter,
297        };
298        (delta.is_finite() && delta != 0.0).then_some(delta)
299    }
300}