use core::time::Duration;
use crcbl_core::input::ContactId;
use glam::{UVec2, Vec2};
use crate::tree::{Direction, InputMode, NavInput};
use crate::widget::{ButtonState, PointerInput, UiState, WidgetId};
#[cfg(test)]
mod device_tests;
mod nav;
mod touch;
use nav::{GridLink, GridShape};
pub use touch::{LONG_PRESS, LONG_PRESS_SLOP};
use touch::{Touch, TouchEnd};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CellGrid {
pub origin: Vec2,
pub cell: Vec2,
pub columns: u32,
pub rows: u32,
pub id_base: WidgetId,
pub window: Option<GridWindow>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GridWindow {
pub first: UVec2,
pub size: UVec2,
}
impl CellGrid {
fn shown(&self) -> GridWindow {
self.window.unwrap_or(GridWindow {
first: UVec2::ZERO,
size: UVec2::new(self.columns, self.rows),
})
}
#[must_use]
pub fn cell_bounds(&self, cell: UVec2) -> (Vec2, Vec2) {
let from_first = cell.as_ivec2() - self.shown().first.as_ivec2();
let at = self.origin + from_first.as_vec2() * self.cell;
(at, at + self.cell)
}
#[must_use]
pub fn cell_at(&self, pos: Vec2) -> Option<UVec2> {
if !pos.is_finite() || !self.cell.is_finite() || self.cell.cmple(Vec2::ZERO).any() {
return None;
}
let local = (pos - self.origin) / self.cell;
if local.x < 0.0 || local.y < 0.0 {
return None;
}
let local = local.floor().as_uvec2();
let shown = self.shown();
if local.cmpge(shown.size).any() {
return None;
}
let cell = shown.first.saturating_add(local);
(cell.x < self.columns && cell.y < self.rows).then_some(cell)
}
#[must_use]
pub fn shows(&self, cell: UVec2) -> bool {
let shown = self.shown();
cell.x < self.columns
&& cell.y < self.rows
&& cell.cmpge(shown.first).all()
&& (cell - shown.first).cmplt(shown.size).all()
}
#[must_use]
pub fn id_of(&self, cell: UVec2) -> WidgetId {
self.id_base
+ WidgetId::from(cell.y) * WidgetId::from(self.columns)
+ WidgetId::from(cell.x)
}
#[must_use]
pub fn cell_of(&self, id: WidgetId) -> Option<UVec2> {
let index = id.checked_sub(self.id_base)?;
let columns = WidgetId::from(self.columns);
if columns == 0 {
return None;
}
let x = u32::try_from(index % columns).ok()?;
let y = u32::try_from(index / columns).ok()?;
(y < self.rows).then_some(UVec2::new(x, y))
}
pub fn cells(&self) -> impl Iterator<Item = UVec2> {
let columns = self.columns;
(0..self.rows).flat_map(move |y| (0..columns).map(move |x| UVec2::new(x, y)))
}
pub fn visible_cells(&self) -> impl Iterator<Item = UVec2> + '_ {
self.cells().filter(|&cell| self.shows(cell))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GridCell {
pub grid: WidgetId,
pub cell: UVec2,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Grip<P> {
pub payload: P,
pub origin: UVec2,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Hand {
Pointer(WidgetId),
Cursor,
Touch(ContactId),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Held<P> {
payload: P,
from: GridCell,
hand: Hand,
grab: UVec2,
changed: bool,
}
impl<P> Held<P> {
#[must_use]
pub fn payload(&self) -> &P {
&self.payload
}
pub fn payload_mut(&mut self) -> &mut P {
self.changed = true;
&mut self.payload
}
#[must_use]
pub fn changed(&self) -> bool {
self.changed
}
#[must_use]
pub fn from(&self) -> GridCell {
self.from
}
#[must_use]
pub fn hand(&self) -> Hand {
self.hand
}
#[must_use]
pub fn grab(&self) -> UVec2 {
self.grab
}
pub fn refit(&mut self, size: UVec2) {
self.grab = self.grab.min(size.saturating_sub(UVec2::ONE));
}
pub fn turn_quarter(&mut self, size_before: UVec2) {
self.refit(size_before);
let (column, row) = (self.grab.x, self.grab.y);
self.grab = UVec2::new(size_before.y.saturating_sub(1) - row, column);
self.changed = true;
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DropTarget {
pub at: GridCell,
pub origin: UVec2,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Dropped<P> {
pub payload: P,
pub from: GridCell,
pub to: DropTarget,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Released<P> {
pub payload: P,
pub from: GridCell,
pub over: Option<GridCell>,
pub target: Option<DropTarget>,
pub accepted: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum DropFeedback {
#[default]
None,
Accepting,
Refusing,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct QuickAction(pub u16);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QuickMove<P> {
pub action: QuickAction,
pub payload: P,
pub from: GridCell,
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct DragInput {
pub pointer: PointerInput,
pub nav: NavInput,
pub quick: Option<QuickAction>,
pub dt: Duration,
}
#[derive(Debug, Clone, PartialEq)]
pub struct GridDrag<P> {
held: Option<Held<P>>,
carry_cell: Vec2,
focus: Option<GridCell>,
layout: Vec<GridShape>,
seen: Vec<GridShape>,
links: Vec<GridLink>,
touch: Option<Touch>,
}
impl<P> Default for GridDrag<P> {
fn default() -> Self {
Self::new()
}
}
impl<P> GridDrag<P> {
#[must_use]
pub const fn new() -> Self {
Self {
held: None,
carry_cell: Vec2::ZERO,
focus: None,
layout: Vec::new(),
seen: Vec::new(),
links: Vec::new(),
touch: None,
}
}
#[must_use]
pub fn held(&self) -> Option<&Held<P>> {
self.held.as_ref()
}
pub fn held_mut(&mut self) -> Option<&mut Held<P>> {
self.held.as_mut()
}
#[must_use]
pub fn focus(&self) -> Option<GridCell> {
self.focus
}
pub fn link(&mut self, from: &CellGrid, toward: Direction, to: &CellGrid) {
let link = GridLink {
from: from.id_base,
toward,
to: to.id_base,
};
match self
.links
.iter_mut()
.find(|kept| kept.from == link.from && kept.toward == toward)
{
Some(kept) => *kept = link,
None => self.links.push(link),
}
}
pub fn cancel(&mut self) {
self.held = None;
self.touch = None;
}
pub fn frame<'a>(&'a mut self, ui: &'a mut UiState, pointer: PointerInput) -> DragFrame<'a, P> {
self.frame_with(
ui,
DragInput {
pointer,
..DragInput::default()
},
)
}
pub fn frame_with<'a>(&'a mut self, ui: &'a mut UiState, input: DragInput) -> DragFrame<'a, P> {
let captured = ui.active();
if self.held.as_ref().is_some_and(
|held| matches!(held.hand, Hand::Pointer(widget) if captured != Some(widget)),
) {
self.held = None;
}
core::mem::swap(&mut self.layout, &mut self.seen);
self.seen.clear();
let (nav, quick) = self.steer(input.nav, input.quick);
let ripe = self.held.is_none()
&& self
.touch
.as_mut()
.is_some_and(|touch| touch.ripen(input.dt));
DragFrame {
drag: self,
ui,
pointer: input.pointer,
nav,
quick,
ripe,
captured,
released: None,
took_hold: false,
hand: None,
quick_move: None,
}
}
fn steer(
&mut self,
nav: NavInput,
quick: Option<QuickAction>,
) -> (NavInput, Option<QuickAction>) {
if !self.layout.is_empty()
&& let Some(focus) = self.focus
&& !self.layout.iter().any(|shape| shape.holds(focus))
{
self.focus = None;
}
let Some(focus) = self.focus else {
if nav.direction.is_some() || nav.accept || quick.is_some() {
self.focus = self.layout.iter().find_map(GridShape::landing);
}
let landed = NavInput {
direction: None,
accept: false,
..nav
};
return (landed, None);
};
if let Some(direction) = nav.direction {
self.focus = Some(nav::step(&self.layout, &self.links, focus, direction));
}
(nav, quick)
}
}
#[derive(Debug)]
pub struct DragFrame<'a, P> {
drag: &'a mut GridDrag<P>,
ui: &'a mut UiState,
pointer: PointerInput,
nav: NavInput,
quick: Option<QuickAction>,
ripe: bool,
captured: Option<WidgetId>,
released: Option<ReleaseSpot>,
took_hold: bool,
hand: Option<HandSpot>,
quick_move: Option<QuickMove<P>>,
}
#[derive(Debug, Clone, Copy)]
struct ReleaseSpot {
over: GridCell,
target: Option<DropTarget>,
accepted: bool,
}
#[derive(Debug, Clone, Copy)]
struct HandSpot {
at: Vec2,
cell: Vec2,
drop: DropFeedback,
}
impl<P> DragFrame<'_, P> {
pub fn grid(
&mut self,
grid: &CellGrid,
source: impl FnOnce(UVec2) -> Option<Grip<P>>,
can_accept: impl FnOnce(&P, &DropTarget) -> bool,
) -> GridResponse {
self.drag.seen.push(GridShape::of(grid));
let pointer = self.pointer;
let over = grid.cell_at(pointer.pos);
let mut response = GridResponse {
hovered: over,
..GridResponse::default()
};
let pressed = self.ui.active().and_then(|id| grid.cell_of(id));
for cell in over
.into_iter()
.chain(pressed.filter(|cell| over != Some(*cell)))
{
let hovered = over == Some(cell);
let (state, _clicked) =
self.ui
.interact(grid.id_of(cell), hovered, pointer.down, pointer.released);
match state {
ButtonState::Pressed => response.pressed = Some(cell),
ButtonState::Hovered => response.lit = Some(cell),
ButtonState::Idle => {}
}
}
self.take_hold(grid, source);
let focus = self
.drag
.focus
.filter(|focus| focus.grid == grid.id_base)
.map(|focus| focus.cell);
let carried_by = self.drag.held.as_ref().map(|held| held.hand);
if self.nav.mode == InputMode::Navigation || carried_by == Some(Hand::Cursor) {
response.focused = focus;
}
let Some(held) = self.drag.held.as_ref() else {
return response;
};
let (under, letting_go) = match held.hand {
Hand::Pointer(_) => (Some(pointer.pos), pointer.released),
Hand::Cursor => (
focus.map(|cell| {
let (min, max) = grid.cell_bounds(cell);
(min + max) * 0.5
}),
self.nav.accept && !self.nav.back && !self.took_hold,
),
Hand::Touch(_) => (
self.drag.touch.map(|touch| touch.at),
self.drag
.touch
.is_some_and(|touch| touch.end == Some(TouchEnd::Lifted)),
),
};
let cell = match held.hand {
Hand::Cursor => focus,
Hand::Pointer(_) | Hand::Touch(_) => under.and_then(|at| grid.cell_at(at)),
};
let (Some(at_px), Some(cell)) = (under, cell) else {
return response;
};
let at = GridCell {
grid: grid.id_base,
cell,
};
response.drop_at = Some(cell);
if at == held.from && !held.changed {
if letting_go {
self.note_release(ReleaseSpot {
over: at,
target: None,
accepted: false,
});
}
self.note_hand(at_px, grid.cell, DropFeedback::None);
return response;
}
let target = cell
.checked_sub(held.grab)
.map(|origin| DropTarget { at, origin });
let accepted = target.is_some_and(|target| can_accept(&held.payload, &target));
if letting_go {
self.note_release(ReleaseSpot {
over: at,
target,
accepted,
});
}
response.drop = if accepted {
DropFeedback::Accepting
} else {
DropFeedback::Refusing
};
self.note_hand(at_px, grid.cell, response.drop);
response
}
fn take_hold(&mut self, grid: &CellGrid, source: impl FnOnce(UVec2) -> Option<Grip<P>>) {
if self.drag.held.is_some() {
return;
}
let at = |cell| GridCell {
grid: grid.id_base,
cell,
};
let focus = self
.drag
.focus
.filter(|focus| focus.grid == grid.id_base)
.map(|focus| focus.cell);
let latched = self
.ui
.active()
.filter(|_| self.captured.is_none() && self.pointer.down)
.and_then(|id| Some((id, grid.cell_of(id)?)));
let (cell, hand) = if let Some((id, cell)) = latched {
self.drag.focus = Some(at(cell));
(cell, Hand::Pointer(id))
} else if let Some(cell) = focus.filter(|_| self.nav.accept) {
(cell, Hand::Cursor)
} else if let (Some(cell), Some(action)) = (focus, self.quick) {
self.quick_move = source(cell).map(|grip| QuickMove {
action,
payload: grip.payload,
from: at(cell),
});
return;
} else if let Some(touch) = self.drag.touch.filter(|_| self.ripe)
&& let Some(cell) = grid.cell_at(touch.at)
{
(cell, Hand::Touch(touch.contact))
} else {
return;
};
let Some(grip) = source(cell) else {
return;
};
let Some(grab) = cell.checked_sub(grip.origin) else {
return;
};
self.drag.held = Some(Held {
payload: grip.payload,
from: at(cell),
hand,
grab,
changed: false,
});
self.drag.carry_cell = grid.cell;
self.took_hold = true;
}
fn note_release(&mut self, spot: ReleaseSpot) {
if spot.accepted || !self.released.is_some_and(|kept| kept.accepted) {
self.released = Some(spot);
}
}
fn note_hand(&mut self, at: Vec2, cell: Vec2, drop: DropFeedback) {
let kept_accepting = self
.hand
.is_some_and(|kept| kept.drop == DropFeedback::Accepting);
if drop == DropFeedback::Accepting || !kept_accepting {
self.hand = Some(HandSpot { at, cell, drop });
}
}
fn ends(&self) -> bool {
let Some(held) = self.drag.held.as_ref() else {
return false;
};
match held.hand {
Hand::Pointer(widget) => self.pointer.released || self.ui.active() != Some(widget),
Hand::Cursor => {
self.nav.back || self.drag.focus.is_none() || (self.nav.accept && !self.took_hold)
}
Hand::Touch(contact) => self
.drag
.touch
.is_none_or(|touch| touch.contact != contact || touch.end.is_some()),
}
}
#[must_use]
pub fn ghost(&self) -> Option<Ghost> {
let held = self.drag.held.as_ref()?;
if self.ends() {
return None;
}
let spot = match (self.hand, held.hand) {
(Some(spot), _) => spot,
(None, Hand::Cursor) => return None,
(None, Hand::Pointer(_)) => HandSpot {
at: self.pointer.pos,
cell: self.drag.carry_cell,
drop: DropFeedback::None,
},
(None, Hand::Touch(_)) => HandSpot {
at: self.drag.touch?.at,
cell: self.drag.carry_cell,
drop: DropFeedback::None,
},
};
Some(Ghost {
origin: spot.at - (held.grab.as_vec2() + 0.5) * spot.cell,
cell: spot.cell,
drop: spot.drop,
})
}
pub fn take_quick_move(&mut self) -> Option<QuickMove<P>> {
self.quick_move.take()
}
pub fn finish(self) -> Option<Dropped<P>> {
let released = self.release()?;
let to = released.target.filter(|_| released.accepted)?;
Some(Dropped {
payload: released.payload,
from: released.from,
to,
})
}
pub fn release(self) -> Option<Released<P>> {
if self.ripe && self.drag.held.is_none() {
self.drag.touch = None;
}
if !self.ends() {
return None;
}
let held = self.drag.held.take()?;
if matches!(held.hand, Hand::Touch(_)) {
self.drag.touch = None;
}
let spot = self.released;
Some(Released {
payload: held.payload,
from: held.from,
over: spot.map(|spot| spot.over),
target: spot.and_then(|spot| spot.target),
accepted: spot.is_some_and(|spot| spot.accepted),
})
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Ghost {
pub origin: Vec2,
pub cell: Vec2,
pub drop: DropFeedback,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct GridResponse {
pub hovered: Option<UVec2>,
pressed: Option<UVec2>,
lit: Option<UVec2>,
focused: Option<UVec2>,
drop_at: Option<UVec2>,
drop: DropFeedback,
}
impl GridResponse {
#[must_use]
pub fn cell(&self, cell: UVec2) -> CellResponse {
let state = if self.pressed == Some(cell) {
ButtonState::Pressed
} else if self.lit == Some(cell) {
ButtonState::Hovered
} else {
ButtonState::Idle
};
let drop = if self.drop_at == Some(cell) {
self.drop
} else {
DropFeedback::None
};
CellResponse {
state,
drop,
focused: self.focused == Some(cell),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CellResponse {
pub state: ButtonState,
pub drop: DropFeedback,
pub focused: bool,
}
#[cfg(test)]
mod tests;