Skip to main content

xrack_runtime/
viewport.rs

1use crate::{Length, ListModel, Orientation, Property, RowKey, Value};
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/// Method names used by the XR viewport operations.
59#[derive(Clone, Copy, Debug)]
60#[doc(hidden)]
61pub enum ScrollCommandMethod {
62    To,
63    Index,
64    Column,
65    Cell,
66    SourceIndex,
67    SourceCell,
68    CancelFlick,
69    ReturnToBounds,
70}
71
72impl ScrollCommandMethod {
73    pub fn parse(name: &str) -> Option<Self> {
74        Some(match name {
75            "scroll-to" => Self::To,
76            "position-view-at-index" | "position-view-at-row" => Self::Index,
77            "position-view-at-column" => Self::Column,
78            "position-view-at-cell" => Self::Cell,
79            "position-view-at-source-index" => Self::SourceIndex,
80            "position-view-at-source-cell" => Self::SourceCell,
81            "cancel-flick" => Self::CancelFlick,
82            "return-to-bounds" => Self::ReturnToBounds,
83            _ => return None,
84        })
85    }
86
87    pub fn uses_source_row(self) -> bool {
88        matches!(self, Self::SourceIndex | Self::SourceCell)
89    }
90
91    pub fn command(self, operands: &[Value]) -> Option<ScrollCommand> {
92        use Value::{Int, Length, ScrollAlignment};
93        let action = match (self, operands) {
94            (Self::CancelFlick, []) => ScrollAction::CancelFlick,
95            (Self::ReturnToBounds, []) => ScrollAction::ReturnToBounds,
96            (Self::To, &[Length(x), Length(y)]) => ScrollAction::To { x, y },
97            (Self::Index, &[Int(index), ScrollAlignment(alignment)]) => {
98                ScrollAction::ToIndex { index, alignment }
99            }
100            (Self::Column, &[Int(column), ScrollAlignment(alignment)]) => {
101                ScrollAction::ToColumn { column, alignment }
102            }
103            (
104                Self::Cell,
105                &[
106                    Int(row),
107                    Int(column),
108                    ScrollAlignment(horizontal),
109                    ScrollAlignment(vertical),
110                ],
111            ) => ScrollAction::ToCell {
112                row,
113                column,
114                horizontal,
115                vertical,
116            },
117            (Self::SourceIndex, &[Int(row), ScrollAlignment(alignment)]) => {
118                return Some(ScrollCommand::Source(row, SourceScroll::Row(alignment)));
119            }
120            (
121                Self::SourceCell,
122                &[
123                    Int(row),
124                    Int(column),
125                    ScrollAlignment(horizontal),
126                    ScrollAlignment(vertical),
127                ],
128            ) => {
129                return Some(ScrollCommand::Source(
130                    row,
131                    SourceScroll::Cell {
132                        column,
133                        horizontal,
134                        vertical,
135                    },
136                ));
137            }
138            _ => return None,
139        };
140        Some(ScrollCommand::Direct(action))
141    }
142}
143
144#[doc(hidden)]
145pub enum ScrollCommand {
146    Direct(ScrollAction),
147    Source(i64, SourceScroll),
148}
149
150impl ScrollCommand {
151    pub fn try_resolve<E>(
152        self,
153        key_at: impl FnOnce(usize) -> Result<Option<RowKey>, E>,
154    ) -> Result<Option<ScrollAction>, E> {
155        match self {
156            Self::Direct(action) => Ok(Some(action)),
157            Self::Source(row, command) => command.try_resolve(row, key_at),
158        }
159    }
160
161    pub fn resolve(self, key_at: impl FnOnce(usize) -> Option<RowKey>) -> Option<ScrollAction> {
162        self.try_resolve(|index| Ok::<_, std::convert::Infallible>(key_at(index)))
163            .unwrap_or_else(|error| match error {})
164    }
165}
166
167/// Source positions are converted to stable row keys when the command is queued.
168#[derive(Clone, Copy)]
169#[doc(hidden)]
170pub enum SourceScroll {
171    Row(ScrollAlignment),
172    Cell {
173        column: i64,
174        horizontal: ScrollAlignment,
175        vertical: ScrollAlignment,
176    },
177}
178
179impl SourceScroll {
180    pub fn try_resolve<E>(
181        self,
182        row: i64,
183        key_at: impl FnOnce(usize) -> Result<Option<RowKey>, E>,
184    ) -> Result<Option<ScrollAction>, E> {
185        let Ok(source_index) = usize::try_from(row) else {
186            return Ok(None);
187        };
188        if matches!(self, Self::Cell { column, .. } if usize::try_from(column).is_err()) {
189            return Ok(None);
190        }
191        let Some(key) = key_at(source_index)? else {
192            return Ok(None);
193        };
194        Ok(Some(match self {
195            Self::Row(alignment) => ScrollAction::ToRowKey {
196                key,
197                source_index,
198                alignment,
199            },
200            Self::Cell {
201                column,
202                horizontal,
203                vertical,
204            } => ScrollAction::ToCellAtRowKey {
205                key,
206                source_index,
207                column,
208                horizontal,
209                vertical,
210            },
211        }))
212    }
213
214    pub fn resolve<M: ListModel>(
215        self,
216        row: i64,
217        model: impl FnOnce() -> Rc<M>,
218    ) -> Option<ScrollAction> {
219        self.try_resolve(row, |index| {
220            let model = model();
221            Ok::<_, std::convert::Infallible>(model.key_at(index))
222        })
223        .unwrap_or_else(|error| match error {})
224    }
225}
226
227#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
228pub enum ViewportMotion {
229    #[default]
230    Idle,
231    Dragging,
232    Flicking,
233}
234
235/// A viewport's stable identity and reactive geometry, owned by its component instance.
236#[derive(Clone, Default)]
237pub struct ViewportHandle(Rc<ViewportProperties>);
238
239#[derive(Default)]
240struct ViewportProperties {
241    scroll_notifications: bool,
242    motion: Option<Box<MotionProperties>>,
243    content_x: Property<Length>,
244    content_y: Property<Length>,
245    visible_width: Property<Length>,
246    visible_height: Property<Length>,
247    ranges: [ViewportRange; 2],
248    horizontal: OnceCell<OffsetBinding>,
249    vertical: OnceCell<OffsetBinding>,
250}
251
252#[derive(Default)]
253struct MotionProperties {
254    phase: Cell<ViewportMotion>,
255    dragging: Property<bool>,
256    flicking: Property<bool>,
257    moving: Property<bool>,
258    overshoot: [RangeMetric; 2],
259    returning: Cell<[bool; 2]>,
260    rebounding: Property<bool>,
261}
262
263#[derive(Default)]
264struct ViewportRange {
265    position: RangeMetric,
266    size: RangeMetric,
267}
268
269/// Keep the latest layout sample and allocate a dependency only when it is read.
270#[derive(Default)]
271struct RangeMetric {
272    sample: Cell<f64>,
273    observed: OnceCell<Box<Property<f64>>>,
274}
275
276impl RangeMetric {
277    fn get(&self) -> f64 {
278        self.observed
279            .get_or_init(Default::default)
280            .get(|| self.sample.get())
281    }
282
283    fn publish(&self, value: f64) {
284        self.sample.set(value);
285        if let Some(property) = self.observed.get() {
286            property.set_if_changed(value);
287        }
288    }
289}
290
291struct OffsetBinding {
292    read: Box<dyn Fn() -> Length>,
293    write: Box<dyn Fn(Length)>,
294}
295
296impl PartialEq for ViewportHandle {
297    fn eq(&self, other: &Self) -> bool {
298        Rc::ptr_eq(&self.0, &other.0)
299    }
300}
301
302impl fmt::Debug for ViewportHandle {
303    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
304        formatter
305            .debug_struct("ViewportHandle")
306            .finish_non_exhaustive()
307    }
308}
309
310impl ViewportHandle {
311    #[doc(hidden)]
312    pub fn identity(&self) -> usize {
313        Rc::as_ptr(&self.0) as usize
314    }
315
316    #[doc(hidden)]
317    pub fn with_scroll_notifications() -> Self {
318        Self(Rc::new(ViewportProperties {
319            scroll_notifications: true,
320            ..ViewportProperties::default()
321        }))
322    }
323
324    #[doc(hidden)]
325    pub fn for_flickable(scroll_notifications: bool) -> Self {
326        Self(Rc::new(ViewportProperties {
327            scroll_notifications,
328            motion: Some(Box::default()),
329            ..ViewportProperties::default()
330        }))
331    }
332
333    pub fn dragging(&self) -> bool {
334        self.0
335            .motion
336            .as_ref()
337            .is_some_and(|state| state.dragging.get(|| false))
338    }
339    pub fn flicking(&self) -> bool {
340        self.0
341            .motion
342            .as_ref()
343            .is_some_and(|state| state.flicking.get(|| false))
344    }
345    pub fn moving(&self) -> bool {
346        self.0
347            .motion
348            .as_ref()
349            .is_some_and(|state| state.moving.get(|| false))
350    }
351
352    pub fn rebounding(&self) -> bool {
353        self.0
354            .motion
355            .as_ref()
356            .is_some_and(|state| state.rebounding.get(|| false))
357    }
358
359    pub fn horizontal_overshoot(&self) -> Length {
360        self.overshoot(Orientation::Horizontal)
361    }
362    pub fn vertical_overshoot(&self) -> Length {
363        self.overshoot(Orientation::Vertical)
364    }
365
366    fn overshoot(&self, axis: Orientation) -> Length {
367        Length(self.0.motion.as_ref().map_or(0.0, |state| {
368            state.overshoot[usize::from(axis == Orientation::Vertical)].get()
369        }))
370    }
371
372    #[doc(hidden)]
373    pub fn observes_motion(&self) -> bool {
374        self.0.motion.is_some()
375    }
376
377    #[doc(hidden)]
378    pub fn publish_motion(&self, motion: ViewportMotion) {
379        if let Some(state) = &self.0.motion {
380            state.phase.set(motion);
381            state
382                .dragging
383                .set_if_changed(motion == ViewportMotion::Dragging);
384            state
385                .flicking
386                .set_if_changed(motion == ViewportMotion::Flicking);
387            state.moving.set_if_changed(
388                motion != ViewportMotion::Idle || state.returning.get().contains(&true),
389            );
390        }
391    }
392
393    #[doc(hidden)]
394    pub fn publish_overshoot(&self, axis: Orientation, value: f32, returning: bool) {
395        if let Some(state) = &self.0.motion {
396            let index = usize::from(axis == Orientation::Vertical);
397            state.overshoot[index].publish(f64::from(value));
398            let mut phases = state.returning.get();
399            phases[index] = returning;
400            state.returning.set(phases);
401            let rebounding = phases.contains(&true);
402            state.rebounding.set_if_changed(rebounding);
403            state
404                .moving
405                .set_if_changed(state.phase.get() != ViewportMotion::Idle || rebounding);
406        }
407    }
408
409    #[doc(hidden)]
410    pub fn observes_user_scroll(&self) -> bool {
411        self.0.scroll_notifications
412    }
413
414    fn offset_binding(&self, axis: Orientation) -> &OnceCell<OffsetBinding> {
415        match axis {
416            Orientation::Horizontal => &self.0.horizontal,
417            Orientation::Vertical => &self.0.vertical,
418        }
419    }
420
421    #[doc(hidden)]
422    pub fn bind_offset(
423        &self,
424        axis: Orientation,
425        read: impl Fn() -> Length + 'static,
426        write: impl Fn(Length) + 'static,
427    ) {
428        let binding = OffsetBinding {
429            read: Box::new(read),
430            write: Box::new(write),
431        };
432        assert!(
433            self.offset_binding(axis).set(binding).is_ok(),
434            "viewport offset already bound"
435        );
436    }
437
438    #[doc(hidden)]
439    pub fn has_bound_offset(&self, axis: Orientation) -> bool {
440        self.offset_binding(axis).get().is_some()
441    }
442
443    #[doc(hidden)]
444    pub fn bound_offset(&self, axis: Orientation) -> Option<f32> {
445        let binding = self.offset_binding(axis).get()?;
446        Some((-(binding.read)().0).max(0.0).min(f64::from(f32::MAX)) as f32)
447    }
448
449    #[doc(hidden)]
450    pub fn write_bound_offset(&self, axis: Orientation, offset: f32) {
451        if let Some(binding) = self.offset_binding(axis).get() {
452            (binding.write)(Length(-f64::from(offset)));
453        }
454    }
455
456    pub fn content_x(&self) -> Length {
457        self.0.content_x.get(Length::default)
458    }
459    pub fn content_y(&self) -> Length {
460        self.0.content_y.get(Length::default)
461    }
462    pub fn visible_width(&self) -> Length {
463        self.0.visible_width.get(Length::default)
464    }
465    pub fn visible_height(&self) -> Length {
466        self.0.visible_height.get(Length::default)
467    }
468
469    fn range(&self, axis: Orientation) -> &ViewportRange {
470        &self.0.ranges[usize::from(axis == Orientation::Vertical)]
471    }
472
473    pub fn scroll_position(&self, axis: Orientation) -> f64 {
474        self.range(axis).position.get()
475    }
476
477    pub fn scroll_size(&self, axis: Orientation) -> f64 {
478        self.range(axis).size.get()
479    }
480
481    #[doc(hidden)]
482    pub fn publish_scroll_range(&self, axis: Orientation, offset: f32, page: f32, maximum: f32) {
483        let page = f64::from(page);
484        let extent = page + f64::from(maximum);
485        let (position, size) =
486            if page > 0.0 && maximum >= 0.0 && extent.is_finite() && offset.is_finite() {
487                let size = page / extent;
488                ((f64::from(offset) / extent).clamp(0.0, 1.0 - size), size)
489            } else {
490                (0.0, 0.0)
491            };
492        let range = self.range(axis);
493        range.position.publish(position);
494        range.size.publish(size);
495    }
496
497    #[doc(hidden)]
498    pub fn publish(&self, x: Length, y: Length, width: Length, height: Length) {
499        self.0.content_x.set_if_changed(x);
500        self.0.content_y.set_if_changed(y);
501        self.0.visible_width.set_if_changed(width);
502        self.0.visible_height.set_if_changed(height);
503    }
504
505    pub fn request(&self, action: ScrollAction) {
506        ACTIVE.with(|active| {
507            if let Some(requests) = &*active.borrow() {
508                requests.0.borrow_mut().push(ScrollRequest {
509                    target: self.clone(),
510                    action,
511                });
512            }
513        });
514    }
515}
516
517pub struct ScrollRequest {
518    pub target: ViewportHandle,
519    pub action: ScrollAction,
520}
521
522/// Commands are resolved against the window's newly prepared scene.
523#[derive(Clone, Default)]
524pub struct ScrollRequests(Rc<RefCell<Vec<ScrollRequest>>>);
525
526thread_local! {
527    static ACTIVE: RefCell<Option<ScrollRequests>> = const { RefCell::new(None) };
528}
529
530pub struct ScrollContext(Option<ScrollRequests>);
531
532impl ScrollRequests {
533    pub fn enter(&self) -> ScrollContext {
534        ScrollContext(ACTIVE.with(|active| active.replace(Some(self.clone()))))
535    }
536
537    pub fn drain(&self) -> Vec<ScrollRequest> {
538        std::mem::take(&mut *self.0.borrow_mut())
539    }
540
541    pub fn is_empty(&self) -> bool {
542        self.0.borrow().is_empty()
543    }
544}
545
546impl Drop for ScrollContext {
547    fn drop(&mut self) {
548        ACTIVE.with(|active| active.replace(self.0.take()));
549    }
550}
551
552#[cfg(test)]
553mod tests {
554    use super::*;
555
556    #[test]
557    fn moving_binding_remains_cached_across_drag_to_flick_transition() {
558        let viewport = ViewportHandle::for_flickable(false);
559        let moving = Property::default();
560        let dragging = Property::default();
561        viewport.publish_motion(ViewportMotion::Dragging);
562        assert!(moving.get(|| viewport.moving()));
563        assert!(dragging.get(|| viewport.dragging()));
564        viewport.publish_motion(ViewportMotion::Flicking);
565        assert!(!moving.is_dirty());
566        assert!(dragging.is_dirty());
567        assert!(viewport.flicking());
568        viewport.publish_motion(ViewportMotion::Idle);
569        assert!(moving.is_dirty());
570        assert!(!moving.get(|| viewport.moving()));
571    }
572
573    #[test]
574    fn scroll_range_invalidates_only_the_changed_axis_and_metric() {
575        let viewport = ViewportHandle::default();
576        viewport.publish_scroll_range(Orientation::Horizontal, 0.0, 100.0, 100.0);
577        assert!(
578            viewport
579                .range(Orientation::Horizontal)
580                .size
581                .observed
582                .get()
583                .is_none()
584        );
585        let size = Property::default();
586        let position = Property::default();
587        let read_size = || viewport.scroll_size(Orientation::Horizontal);
588        let read_position = || viewport.scroll_position(Orientation::Horizontal);
589        assert_eq!(size.get(read_size), 0.5);
590        assert_eq!(position.get(read_position), 0.0);
591
592        viewport.publish_scroll_range(Orientation::Vertical, 30.0, 20.0, 80.0);
593        assert!(
594            viewport
595                .range(Orientation::Vertical)
596                .position
597                .observed
598                .get()
599                .is_none()
600        );
601        assert!(!position.is_dirty());
602        assert!(!size.is_dirty());
603        viewport.publish_scroll_range(Orientation::Horizontal, 50.0, 100.0, 100.0);
604        assert!(position.is_dirty());
605        assert!(!size.is_dirty());
606        assert_eq!(position.get(read_position), 0.25);
607
608        viewport.publish_scroll_range(Orientation::Horizontal, 50.0, 100.0, 100.0);
609        assert!(!position.is_dirty());
610        viewport.publish_scroll_range(Orientation::Horizontal, 0.0, 0.0, 0.0);
611        assert!(position.is_dirty());
612        assert!(size.is_dirty());
613        assert_eq!(size.get(read_size), 0.0);
614    }
615}