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