Skip to main content

xrack_runtime/
viewport.rs

1use crate::{Length, Orientation, Property};
2use std::{
3    cell::{Cell, OnceCell, RefCell},
4    fmt,
5    rc::Rc,
6};
7
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
9pub enum ScrollAlignment {
10    Beginning,
11    Center,
12    End,
13    Visible,
14    #[default]
15    Contain,
16}
17
18#[derive(Clone, Copy, Debug, PartialEq)]
19pub enum ScrollAction {
20    CancelFlick,
21    ReturnToBounds,
22    To {
23        x: Length,
24        y: Length,
25    },
26    ToIndex {
27        index: i64,
28        alignment: ScrollAlignment,
29    },
30}
31
32#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
33pub enum ViewportMotion {
34    #[default]
35    Idle,
36    Dragging,
37    Flicking,
38}
39
40/// A viewport's stable identity and reactive geometry, owned by its component instance.
41#[derive(Clone, Default)]
42pub struct ViewportHandle(Rc<ViewportProperties>);
43
44#[derive(Default)]
45struct ViewportProperties {
46    scroll_notifications: bool,
47    motion: Option<Box<MotionProperties>>,
48    content_x: Property<Length>,
49    content_y: Property<Length>,
50    visible_width: Property<Length>,
51    visible_height: Property<Length>,
52    ranges: [ViewportRange; 2],
53    horizontal: OnceCell<OffsetBinding>,
54    vertical: OnceCell<OffsetBinding>,
55}
56
57#[derive(Default)]
58struct MotionProperties {
59    phase: Cell<ViewportMotion>,
60    dragging: Property<bool>,
61    flicking: Property<bool>,
62    moving: Property<bool>,
63    overshoot: [RangeMetric; 2],
64    returning: Cell<[bool; 2]>,
65    rebounding: Property<bool>,
66}
67
68#[derive(Default)]
69struct ViewportRange {
70    position: RangeMetric,
71    size: RangeMetric,
72}
73
74/// Keep the latest layout sample and allocate a dependency only when it is read.
75#[derive(Default)]
76struct RangeMetric {
77    sample: Cell<f64>,
78    observed: OnceCell<Box<Property<f64>>>,
79}
80
81impl RangeMetric {
82    fn get(&self) -> f64 {
83        self.observed
84            .get_or_init(Default::default)
85            .get(|| self.sample.get())
86    }
87
88    fn publish(&self, value: f64) {
89        self.sample.set(value);
90        if let Some(property) = self.observed.get() {
91            property.set_if_changed(value);
92        }
93    }
94}
95
96struct OffsetBinding {
97    read: Box<dyn Fn() -> Length>,
98    write: Box<dyn Fn(Length)>,
99}
100
101impl PartialEq for ViewportHandle {
102    fn eq(&self, other: &Self) -> bool {
103        Rc::ptr_eq(&self.0, &other.0)
104    }
105}
106
107impl fmt::Debug for ViewportHandle {
108    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
109        formatter
110            .debug_struct("ViewportHandle")
111            .finish_non_exhaustive()
112    }
113}
114
115impl ViewportHandle {
116    #[doc(hidden)]
117    pub fn identity(&self) -> usize {
118        Rc::as_ptr(&self.0) as usize
119    }
120
121    #[doc(hidden)]
122    pub fn with_scroll_notifications() -> Self {
123        Self(Rc::new(ViewportProperties {
124            scroll_notifications: true,
125            ..ViewportProperties::default()
126        }))
127    }
128
129    #[doc(hidden)]
130    pub fn for_flickable(scroll_notifications: bool) -> Self {
131        Self(Rc::new(ViewportProperties {
132            scroll_notifications,
133            motion: Some(Box::default()),
134            ..ViewportProperties::default()
135        }))
136    }
137
138    pub fn dragging(&self) -> bool {
139        self.0
140            .motion
141            .as_ref()
142            .is_some_and(|state| state.dragging.get(|| false))
143    }
144    pub fn flicking(&self) -> bool {
145        self.0
146            .motion
147            .as_ref()
148            .is_some_and(|state| state.flicking.get(|| false))
149    }
150    pub fn moving(&self) -> bool {
151        self.0
152            .motion
153            .as_ref()
154            .is_some_and(|state| state.moving.get(|| false))
155    }
156
157    pub fn rebounding(&self) -> bool {
158        self.0
159            .motion
160            .as_ref()
161            .is_some_and(|state| state.rebounding.get(|| false))
162    }
163
164    pub fn horizontal_overshoot(&self) -> Length {
165        self.overshoot(Orientation::Horizontal)
166    }
167    pub fn vertical_overshoot(&self) -> Length {
168        self.overshoot(Orientation::Vertical)
169    }
170
171    fn overshoot(&self, axis: Orientation) -> Length {
172        Length(self.0.motion.as_ref().map_or(0.0, |state| {
173            state.overshoot[usize::from(axis == Orientation::Vertical)].get()
174        }))
175    }
176
177    #[doc(hidden)]
178    pub fn observes_motion(&self) -> bool {
179        self.0.motion.is_some()
180    }
181
182    #[doc(hidden)]
183    pub fn publish_motion(&self, motion: ViewportMotion) {
184        if let Some(state) = &self.0.motion {
185            state.phase.set(motion);
186            state
187                .dragging
188                .set_if_changed(motion == ViewportMotion::Dragging);
189            state
190                .flicking
191                .set_if_changed(motion == ViewportMotion::Flicking);
192            state.moving.set_if_changed(
193                motion != ViewportMotion::Idle || state.returning.get().contains(&true),
194            );
195        }
196    }
197
198    #[doc(hidden)]
199    pub fn publish_overshoot(&self, axis: Orientation, value: f32, returning: bool) {
200        if let Some(state) = &self.0.motion {
201            let index = usize::from(axis == Orientation::Vertical);
202            state.overshoot[index].publish(f64::from(value));
203            let mut phases = state.returning.get();
204            phases[index] = returning;
205            state.returning.set(phases);
206            let rebounding = phases.contains(&true);
207            state.rebounding.set_if_changed(rebounding);
208            state
209                .moving
210                .set_if_changed(state.phase.get() != ViewportMotion::Idle || rebounding);
211        }
212    }
213
214    #[doc(hidden)]
215    pub fn observes_user_scroll(&self) -> bool {
216        self.0.scroll_notifications
217    }
218
219    fn offset_binding(&self, axis: Orientation) -> &OnceCell<OffsetBinding> {
220        match axis {
221            Orientation::Horizontal => &self.0.horizontal,
222            Orientation::Vertical => &self.0.vertical,
223        }
224    }
225
226    #[doc(hidden)]
227    pub fn bind_offset(
228        &self,
229        axis: Orientation,
230        read: impl Fn() -> Length + 'static,
231        write: impl Fn(Length) + 'static,
232    ) {
233        let binding = OffsetBinding {
234            read: Box::new(read),
235            write: Box::new(write),
236        };
237        assert!(
238            self.offset_binding(axis).set(binding).is_ok(),
239            "viewport offset already bound"
240        );
241    }
242
243    #[doc(hidden)]
244    pub fn has_bound_offset(&self, axis: Orientation) -> bool {
245        self.offset_binding(axis).get().is_some()
246    }
247
248    #[doc(hidden)]
249    pub fn bound_offset(&self, axis: Orientation) -> Option<f32> {
250        let binding = self.offset_binding(axis).get()?;
251        Some((-(binding.read)().0).max(0.0).min(f64::from(f32::MAX)) as f32)
252    }
253
254    #[doc(hidden)]
255    pub fn write_bound_offset(&self, axis: Orientation, offset: f32) {
256        if let Some(binding) = self.offset_binding(axis).get() {
257            (binding.write)(Length(-f64::from(offset)));
258        }
259    }
260
261    pub fn content_x(&self) -> Length {
262        self.0.content_x.get(Length::default)
263    }
264    pub fn content_y(&self) -> Length {
265        self.0.content_y.get(Length::default)
266    }
267    pub fn visible_width(&self) -> Length {
268        self.0.visible_width.get(Length::default)
269    }
270    pub fn visible_height(&self) -> Length {
271        self.0.visible_height.get(Length::default)
272    }
273
274    fn range(&self, axis: Orientation) -> &ViewportRange {
275        &self.0.ranges[usize::from(axis == Orientation::Vertical)]
276    }
277
278    pub fn scroll_position(&self, axis: Orientation) -> f64 {
279        self.range(axis).position.get()
280    }
281
282    pub fn scroll_size(&self, axis: Orientation) -> f64 {
283        self.range(axis).size.get()
284    }
285
286    #[doc(hidden)]
287    pub fn publish_scroll_range(&self, axis: Orientation, offset: f32, page: f32, maximum: f32) {
288        let page = f64::from(page);
289        let extent = page + f64::from(maximum);
290        let (position, size) =
291            if page > 0.0 && maximum >= 0.0 && extent.is_finite() && offset.is_finite() {
292                let size = page / extent;
293                ((f64::from(offset) / extent).clamp(0.0, 1.0 - size), size)
294            } else {
295                (0.0, 0.0)
296            };
297        let range = self.range(axis);
298        range.position.publish(position);
299        range.size.publish(size);
300    }
301
302    #[doc(hidden)]
303    pub fn publish(&self, x: Length, y: Length, width: Length, height: Length) {
304        self.0.content_x.set_if_changed(x);
305        self.0.content_y.set_if_changed(y);
306        self.0.visible_width.set_if_changed(width);
307        self.0.visible_height.set_if_changed(height);
308    }
309
310    pub fn request(&self, action: ScrollAction) {
311        ACTIVE.with(|active| {
312            if let Some(requests) = &*active.borrow() {
313                requests.0.borrow_mut().push(ScrollRequest {
314                    target: self.clone(),
315                    action,
316                });
317            }
318        });
319    }
320}
321
322pub struct ScrollRequest {
323    pub target: ViewportHandle,
324    pub action: ScrollAction,
325}
326
327/// Commands are resolved against the window's newly prepared scene.
328#[derive(Clone, Default)]
329pub struct ScrollRequests(Rc<RefCell<Vec<ScrollRequest>>>);
330
331thread_local! {
332    static ACTIVE: RefCell<Option<ScrollRequests>> = const { RefCell::new(None) };
333}
334
335pub struct ScrollContext(Option<ScrollRequests>);
336
337impl ScrollRequests {
338    pub fn enter(&self) -> ScrollContext {
339        ScrollContext(ACTIVE.with(|active| active.replace(Some(self.clone()))))
340    }
341
342    pub fn drain(&self) -> Vec<ScrollRequest> {
343        std::mem::take(&mut *self.0.borrow_mut())
344    }
345
346    pub fn is_empty(&self) -> bool {
347        self.0.borrow().is_empty()
348    }
349}
350
351impl Drop for ScrollContext {
352    fn drop(&mut self) {
353        ACTIVE.with(|active| active.replace(self.0.take()));
354    }
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360
361    #[test]
362    fn moving_binding_remains_cached_across_drag_to_flick_transition() {
363        let viewport = ViewportHandle::for_flickable(false);
364        let moving = Property::default();
365        let dragging = Property::default();
366        viewport.publish_motion(ViewportMotion::Dragging);
367        assert!(moving.get(|| viewport.moving()));
368        assert!(dragging.get(|| viewport.dragging()));
369        viewport.publish_motion(ViewportMotion::Flicking);
370        assert!(!moving.is_dirty());
371        assert!(dragging.is_dirty());
372        assert!(viewport.flicking());
373        viewport.publish_motion(ViewportMotion::Idle);
374        assert!(moving.is_dirty());
375        assert!(!moving.get(|| viewport.moving()));
376    }
377
378    #[test]
379    fn scroll_range_invalidates_only_the_changed_axis_and_metric() {
380        let viewport = ViewportHandle::default();
381        viewport.publish_scroll_range(Orientation::Horizontal, 0.0, 100.0, 100.0);
382        assert!(
383            viewport
384                .range(Orientation::Horizontal)
385                .size
386                .observed
387                .get()
388                .is_none()
389        );
390        let size = Property::default();
391        let position = Property::default();
392        let read_size = || viewport.scroll_size(Orientation::Horizontal);
393        let read_position = || viewport.scroll_position(Orientation::Horizontal);
394        assert_eq!(size.get(read_size), 0.5);
395        assert_eq!(position.get(read_position), 0.0);
396
397        viewport.publish_scroll_range(Orientation::Vertical, 30.0, 20.0, 80.0);
398        assert!(
399            viewport
400                .range(Orientation::Vertical)
401                .position
402                .observed
403                .get()
404                .is_none()
405        );
406        assert!(!position.is_dirty());
407        assert!(!size.is_dirty());
408        viewport.publish_scroll_range(Orientation::Horizontal, 50.0, 100.0, 100.0);
409        assert!(position.is_dirty());
410        assert!(!size.is_dirty());
411        assert_eq!(position.get(read_position), 0.25);
412
413        viewport.publish_scroll_range(Orientation::Horizontal, 50.0, 100.0, 100.0);
414        assert!(!position.is_dirty());
415        viewport.publish_scroll_range(Orientation::Horizontal, 0.0, 0.0, 0.0);
416        assert!(position.is_dirty());
417        assert!(size.is_dirty());
418        assert_eq!(size.get(read_size), 0.0);
419    }
420}