Skip to main content

sim_logic/application/input/
scroll.rs

1//! Bounded wheel deltas and frame-only, event-ordered pointer scrolling.
2
3use std::{error::Error, fmt};
4
5use super::{Action, ActionEdge, PointerSample};
6
7/// Units preserved from the input device; no line-to-pixel conversion is implied.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9pub enum ScrollUnit {
10    /// Fractional wheel lines, independent from display scaling.
11    Lines,
12    /// Logical screen pixels, converted from physical pixels by the desktop adapter.
13    Pixels,
14}
15
16/// One finite wheel displacement with explicit units and no duration scaling.
17///
18/// Positive X scrolls right and positive Y scrolls up. Platform scrolling
19/// preferences are preserved; applications choose their own zoom or pan policy.
20/// The runtime never combines separate events or invents a pixels-per-line ratio.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub struct ScrollDelta {
23    unit: ScrollUnit,
24    bits: [u64; 2],
25}
26
27impl ScrollDelta {
28    /// Inclusive absolute limit of each event's coordinates in its declared units.
29    pub const MAX_DISPLACEMENT: f64 = 1_000_000.0;
30
31    /// Validates fractional line displacements without changing their units.
32    pub fn lines(x: f64, y: f64) -> Result<Self, ScrollDeltaError> {
33        Self::new(ScrollUnit::Lines, x, y)
34    }
35
36    /// Validates logical-pixel displacements, not physical pixels or world units.
37    pub fn pixels(x: f64, y: f64) -> Result<Self, ScrollDeltaError> {
38        Self::new(ScrollUnit::Pixels, x, y)
39    }
40
41    fn new(unit: ScrollUnit, x: f64, y: f64) -> Result<Self, ScrollDeltaError> {
42        if !x.is_finite() || !y.is_finite() {
43            return Err(ScrollDeltaError::NonFinite);
44        }
45        if x.abs() > Self::MAX_DISPLACEMENT || y.abs() > Self::MAX_DISPLACEMENT {
46            return Err(ScrollDeltaError::OutOfRange);
47        }
48        Ok(Self {
49            unit,
50            bits: [canonical_bits(x), canonical_bits(y)],
51        })
52    }
53
54    /// Returns the original line or logical-pixel units.
55    pub const fn unit(self) -> ScrollUnit {
56        self.unit
57    }
58
59    /// Horizontal displacement, positive to the right.
60    pub const fn x(self) -> f64 {
61        f64::from_bits(self.bits[0])
62    }
63
64    /// Vertical displacement, positive upward.
65    pub const fn y(self) -> f64 {
66        f64::from_bits(self.bits[1])
67    }
68}
69
70fn canonical_bits(value: f64) -> u64 {
71    if value == 0.0 { 0 } else { value.to_bits() }
72}
73
74/// A wheel coordinate was rejected before it could enter an input batch.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum ScrollDeltaError {
77    /// A coordinate was NaN or infinite.
78    NonFinite,
79    /// A coordinate exceeded [`ScrollDelta::MAX_DISPLACEMENT`].
80    OutOfRange,
81}
82
83impl fmt::Display for ScrollDeltaError {
84    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
85        formatter.write_str(match self {
86            Self::NonFinite => "wheel displacement must be finite",
87            Self::OutOfRange => "wheel displacement exceeds the per-event limit",
88        })
89    }
90}
91
92impl Error for ScrollDeltaError {}
93
94/// One frame-only wheel occurrence and the pointer known when it arrived.
95///
96/// No binding or transition token is required. These events are not retained
97/// for fixed ticks or replayed into replacement worlds. A focus-loss boundary
98/// discards every wheel occurrence in that accepted frame, before and after it.
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
100pub struct PointerScrollEvent {
101    pub(super) delta: ScrollDelta,
102    pub(super) pointer: Option<PointerSample>,
103    pub(super) ordinal: usize,
104}
105
106impl PointerScrollEvent {
107    /// Returns this event's displacement, including its original units.
108    pub const fn delta(self) -> ScrollDelta {
109        self.delta
110    }
111
112    /// Returns the event-time logical position, or None before motion or after
113    /// pointer leave/capture. Later pointer movement cannot change this sample.
114    pub const fn pointer(self) -> Option<PointerSample> {
115        self.pointer
116    }
117}
118
119/// Ordered frame input for interactions that combine clicks and wheel scrolling.
120///
121/// Continuous absolute motion still lives in [`super::FrameInput::pointer`];
122/// mouse actions and wheel events retain their own event-time pointer samples.
123/// This iterator view allocates no additional event buffer or transition tokens.
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
125pub enum FrameInputEvent<A: Action> {
126    /// A bound button edge, including synthesized cancellation releases.
127    Action(ActionEdge<A>),
128    /// An unbound, frame-only wheel occurrence.
129    Scroll(PointerScrollEvent),
130}
131
132pub(super) fn ordered_events<A: Action>(
133    edges: &[ActionEdge<A>],
134    scrolls: &[PointerScrollEvent],
135) -> impl Iterator<Item = FrameInputEvent<A>> {
136    let mut edges = edges.iter().copied().peekable();
137    let mut scrolls = scrolls.iter().copied().peekable();
138    std::iter::from_fn(move || match (edges.peek(), scrolls.peek()) {
139        (Some(edge), Some(scroll)) if edge.ordinal <= scroll.ordinal => {
140            edges.next().map(FrameInputEvent::Action)
141        }
142        (Some(_), Some(_)) | (None, Some(_)) => scrolls.next().map(FrameInputEvent::Scroll),
143        (Some(_), None) => edges.next().map(FrameInputEvent::Action),
144        (None, None) => None,
145    })
146}