Skip to main content

xrack_runtime/
viewport.rs

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