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