use std::{error::Error, fmt};
use super::{Action, ActionEdge, PointerSample};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ScrollUnit {
Lines,
Pixels,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ScrollDelta {
unit: ScrollUnit,
bits: [u64; 2],
}
impl ScrollDelta {
pub const MAX_DISPLACEMENT: f64 = 1_000_000.0;
pub fn lines(x: f64, y: f64) -> Result<Self, ScrollDeltaError> {
Self::new(ScrollUnit::Lines, x, y)
}
pub fn pixels(x: f64, y: f64) -> Result<Self, ScrollDeltaError> {
Self::new(ScrollUnit::Pixels, x, y)
}
fn new(unit: ScrollUnit, x: f64, y: f64) -> Result<Self, ScrollDeltaError> {
if !x.is_finite() || !y.is_finite() {
return Err(ScrollDeltaError::NonFinite);
}
if x.abs() > Self::MAX_DISPLACEMENT || y.abs() > Self::MAX_DISPLACEMENT {
return Err(ScrollDeltaError::OutOfRange);
}
Ok(Self {
unit,
bits: [canonical_bits(x), canonical_bits(y)],
})
}
pub const fn unit(self) -> ScrollUnit {
self.unit
}
pub const fn x(self) -> f64 {
f64::from_bits(self.bits[0])
}
pub const fn y(self) -> f64 {
f64::from_bits(self.bits[1])
}
}
fn canonical_bits(value: f64) -> u64 {
if value == 0.0 { 0 } else { value.to_bits() }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScrollDeltaError {
NonFinite,
OutOfRange,
}
impl fmt::Display for ScrollDeltaError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::NonFinite => "wheel displacement must be finite",
Self::OutOfRange => "wheel displacement exceeds the per-event limit",
})
}
}
impl Error for ScrollDeltaError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PointerScrollEvent {
pub(super) delta: ScrollDelta,
pub(super) pointer: Option<PointerSample>,
pub(super) ordinal: usize,
}
impl PointerScrollEvent {
pub const fn delta(self) -> ScrollDelta {
self.delta
}
pub const fn pointer(self) -> Option<PointerSample> {
self.pointer
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FrameInputEvent<A: Action> {
Action(ActionEdge<A>),
Scroll(PointerScrollEvent),
}
pub(super) fn ordered_events<A: Action>(
edges: &[ActionEdge<A>],
scrolls: &[PointerScrollEvent],
) -> impl Iterator<Item = FrameInputEvent<A>> {
let mut edges = edges.iter().copied().peekable();
let mut scrolls = scrolls.iter().copied().peekable();
std::iter::from_fn(move || match (edges.peek(), scrolls.peek()) {
(Some(edge), Some(scroll)) if edge.ordinal <= scroll.ordinal => {
edges.next().map(FrameInputEvent::Action)
}
(Some(_), Some(_)) | (None, Some(_)) => scrolls.next().map(FrameInputEvent::Scroll),
(Some(_), None) => edges.next().map(FrameInputEvent::Action),
(None, None) => None,
})
}