use core::time::Duration;
use crcbl_core::input::{ContactId, TouchPhase};
use glam::Vec2;
use super::{GridDrag, Hand};
pub const LONG_PRESS: Duration = Duration::from_millis(500);
pub const LONG_PRESS_SLOP: f32 = 10.0;
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct Touch {
pub(super) contact: ContactId,
pub(super) at: Vec2,
from: Vec2,
held_for: Duration,
pub(super) end: Option<TouchEnd>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum TouchEnd {
Lifted,
Cancelled,
}
impl Touch {
pub(super) fn ripen(&mut self, dt: Duration) -> bool {
self.held_for = self.held_for.saturating_add(dt);
self.end.is_none() && self.held_for >= LONG_PRESS
}
}
impl<P> GridDrag<P> {
pub fn touch(&mut self, contact: ContactId, phase: TouchPhase, at: Vec2) -> bool {
let carrying = self
.held
.as_ref()
.is_some_and(|held| held.hand == Hand::Touch(contact));
let followed = self.touch.as_mut().filter(|touch| touch.contact == contact);
match (phase, followed) {
(TouchPhase::Began, _) => {
if self.touch.is_some() || self.held.is_some() {
return false;
}
self.touch = Some(Touch {
contact,
at,
from: at,
held_for: Duration::ZERO,
end: None,
});
}
(_, None) => return false,
(TouchPhase::Moved, Some(touch)) => {
touch.at = at;
if !carrying && at.distance(touch.from) > LONG_PRESS_SLOP {
self.touch = None;
return false;
}
}
(TouchPhase::Ended | TouchPhase::Cancelled, Some(touch)) => {
touch.at = at;
if carrying {
touch.end = Some(if phase == TouchPhase::Ended {
TouchEnd::Lifted
} else {
TouchEnd::Cancelled
});
} else {
self.touch = None;
}
}
}
true
}
}