Lines
77.95 %
Functions
47.98 %
Branches
100 %
//! Gesture and drag manager for multi-frame gestures and drag operations.
//!
//! Collects input samples, detects drags, double-clicks, long presses, swipes,
//! pinch/rotate gestures, and manages drag state for nodes, windows, and file drops.
//! ## Unified Drag System
//! This module uses the `DragContext` from `azul_core::drag` to provide a unified
//! interface for all drag operations:
//! - Text selection drag
//! - Scrollbar thumb drag
//! - Node drag-and-drop
//! - Window drag/resize
//! - File drop from OS
use alloc::vec::Vec;
#[cfg(feature = "std")]
use std::sync::atomic::{AtomicU64, Ordering};
use azul_core::{
dom::{DomId, NodeId},
drag::{ActiveDragType, DragContext, DragData},
geom::{LogicalPosition, LogicalSize, PhysicalPositionI32},
hit_test::HitTest,
task::{Duration as CoreDuration, Instant as CoreInstant},
window::WindowPosition,
};
use azul_css::{impl_option, impl_option_inner, AzString};
static NEXT_EVENT_ID: AtomicU64 = AtomicU64::new(1);
/// Allocate a new unique event ID
pub fn allocate_event_id() -> u64 {
NEXT_EVENT_ID.fetch_add(1, Ordering::Relaxed)
}
/// Allocate a new unique event ID (no_std fallback: returns 0)
#[cfg(not(feature = "std"))]
0
/// Helper function to convert `CoreDuration` to milliseconds
///
/// `CoreDuration` is an enum with System (`std::time::Duration`) and Tick variants.
/// Both go through `CoreDuration::as_millis_u64`, which converts ticks at the
/// nominal frame rate.
/// The Tick arm used to return the raw tick count and carried a WARNING that it
/// "assumes 1 tick = 1 ms ... will silently produce wrong timing on platforms
/// with a different tick resolution". A tick is a FRAME, so that assumption was
/// wrong by a factor of ~16 on every platform, and gesture thresholds
/// (double-click, long-press) read the result as milliseconds.
const fn duration_to_millis(duration: CoreDuration) -> u64 {
duration.as_millis_u64()
/// Maximum number of input samples to keep in memory
/// This prevents unbounded memory growth during long drags.
/// Older samples beyond this limit are automatically discarded.
pub const MAX_SAMPLES_PER_SESSION: usize = 1000;
/// Default timeout for clearing old gesture samples (milliseconds)
/// Samples older than this are automatically removed to prevent
/// memory leaks and stale gesture detection.
pub const DEFAULT_SAMPLE_TIMEOUT_MS: u64 = 2000;
/// Number of samples to drain at once when the session exceeds `MAX_SAMPLES_PER_SESSION`.
/// Batch draining avoids per-sample overhead on every new sample.
const DRAIN_BATCH_SIZE: usize = 100;
/// MWA-B4: button-state bitfield recorded for touch-contact samples.
/// A finger on the surface = primary contact, mirroring `BUTTON_STATE_LEFT` in
/// the dll's mouse path so drag heuristics treat touch like a held button.
pub const TOUCH_CONTACT_BUTTON_STATE: u8 = 0x01;
/// Configuration for gesture detection thresholds
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GestureDetectionConfig {
/// Minimum distance (pixels) to consider movement a drag, not a click
pub drag_distance_threshold: f32,
/// Maximum time between clicks for double-click detection (milliseconds)
pub double_click_time_threshold_ms: u64,
/// Maximum distance between clicks for double-click detection (pixels)
pub double_click_distance_threshold: f32,
/// Minimum time to hold button for long-press detection (milliseconds)
pub long_press_time_threshold_ms: u64,
/// Maximum distance to move while holding for long-press (pixels)
pub long_press_distance_threshold: f32,
/// Minimum samples needed to detect a gesture
pub min_samples_for_gesture: usize,
/// Minimum velocity for swipe detection (pixels per second)
pub swipe_velocity_threshold: f32,
/// Minimum scale change for pinch detection (e.g., 0.1 = 10% change)
pub pinch_scale_threshold: f32,
/// Minimum rotation angle for rotation detection (radians)
pub rotation_angle_threshold: f32,
/// How often to clear old samples (milliseconds)
pub sample_cleanup_interval_ms: u64,
impl Default for GestureDetectionConfig {
fn default() -> Self {
Self {
drag_distance_threshold: 5.0,
double_click_time_threshold_ms: 500,
double_click_distance_threshold: 5.0,
long_press_time_threshold_ms: 500,
long_press_distance_threshold: 10.0,
min_samples_for_gesture: 2,
swipe_velocity_threshold: 500.0, // 500 px/s
pinch_scale_threshold: 0.1, // 10% scale change
rotation_angle_threshold: 0.1, // ~5.7 degrees in radians
sample_cleanup_interval_ms: DEFAULT_SAMPLE_TIMEOUT_MS,
/// Single input sample with position and timestamp.
/// `#[repr(C)]` because it crosses the C ABI through
/// `CallbackInfo::get_last_input_sample`. Field order is by DECREASING
/// ALIGNMENT, not by topic - `repr(C)` lays it out literally, and the
/// topical order cost 8 bytes of padding per sample, which the api checker
/// refuses to proceed on. It is deliberately NOT `Copy`, unlike
/// `PenState` beside it: `timestamp` is an `Instant`, which on a `std` build
/// owns a boxed platform clock reading with a destructor.
#[derive(Debug, Clone, PartialEq)]
#[repr(C)]
pub struct InputSample {
/// Timestamp when this sample was recorded (from `ExternalSystemCallbacks`).
/// Spelled as the real type and not through this module's `CoreInstant`
/// alias: the codegen reads the field's written type verbatim, so an alias
/// here produces an `AzCoreInstant` in the C header that does not exist.
pub timestamp: azul_core::task::Instant,
/// Unique, monotonic event ID for ordering (atomic counter)
pub event_id: u64,
/// Position in logical coordinates (window-local, Y=0 at top of window)
pub position: LogicalPosition,
/// Position in virtual screen coordinates (Y=0 at top of primary monitor).
/// Computed as `window_position + position` at the time the sample is recorded.
/// This is stable during window drags because `window_pos + cursor_local`
/// always equals the true screen position, even when the window moves.
/// All coordinates are in logical pixels (HiDPI-independent).
/// On Wayland, this is an estimate (compositor does not expose global position).
pub screen_position: LogicalPosition,
/// Pen/stylus tilt angles in degrees.
/// Range: typically -90.0 to 90.0, both zero = perpendicular.
/// A NAMED struct rather than a `(f32, f32)`, because a tuple has no C
/// representation and this whole sample was unreachable from a binding
/// while it carried two. `PenTilt` is not a new type invented for that -
/// it already existed and `PenState::tilt` beside it already used it, so
/// the tuple here was the odd one out; the conversion that used to happen
/// one level down (`PenTilt { x_tilt: tilt.0, .. }`) simply moved up.
pub tilt: crate::callbacks::PenTilt,
/// Touch contact extent in logical pixels. Zero for mouse input.
/// `LogicalSize` for the same C-representation reason as `tilt`, and it
/// reuses an existing type rather than adding one because a width/height
/// pair in logical pixels IS a logical size. Not `TouchPoint`, which
/// models the same physical thing but as a major/minor ellipse plus an id,
/// a position and a force this sample already carries separately.
pub touch_radius: LogicalSize,
/// Pen/stylus pressure (0.0 to 1.0, 0.5 = default for mouse)
pub pressure: f32,
/// Mouse button state (bitfield: 0x01 = left, 0x02 = right, 0x04 = middle)
pub button_state: u8,
/// Rotary-encoder units to RADIANS, given the device's own resolution
/// (9c-i-a).
/// `InputDevice.MotionRange.getResolution()` is documented as "the number of
/// units per millimeter, or per RADIAN for rotational axes", and Android's
/// `AXIS_SCROLL` on a `SOURCE_ROTARY_ENCODER` is a rotational axis - so the
/// conversion constant comes from the hardware rather than from a guess. That
/// matters because watch crowns differ by detent count and gearing, so no
/// single constant could be right for more than one of them.
/// # Unknown stays unknown
/// `getResolution` reports `0` when the driver gave none, which many do.
/// Dividing by it yields an infinity, and substituting a plausible number puts
/// a FABRICATED angle in a field whose entire value is being trustworthy - so
/// this answers `0.0`, which is what `DialState::delta_rad` already means on a
/// platform that does not measure an angle.
/// Lives here, beside `DialState`, rather than in the Android shell: that file
/// is `cfg`-gated to a target this machine never runs tests on, and a division
/// with a zero and a NaN case is exactly what wants a test.
#[must_use]
pub fn rotary_units_to_radians(scroll: f32, resolution: f32) -> f32 {
if resolution.is_finite() && resolution > 0.0 && scroll.is_finite() {
scroll / resolution
} else {
0.0
impl_option!(
InputSample,
OptionInputSample,
copy = false,
[Debug, Clone, PartialEq]
);
/// A sequence of input samples forming one button press session
/// One non-primary seat's pen (9b-ii-b-i-b): the same three fields the
/// primary keeps on the manager, plus its own report-rate estimate.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct SeatPen {
pub state: Option<PenState>,
pub previous: Option<PenState>,
pub event_pending: bool,
pub last_sample_nanos: Option<u64>,
pub rate_ema_hz: f32,
pub struct InputSession {
/// All recorded samples for this session
pub samples: Vec<InputSample>,
/// Whether this session has ended (button released)
pub ended: bool,
/// Session ID for tracking (incremental counter)
pub session_id: u64,
/// Window position at the time this session started (mouse-down).
/// Used by titlebar drag callbacks to compute new window position.
pub window_position_at_start: WindowPosition,
/// WHOSE session this is (9b-ii-b-i): the pointer SEAT that pressed.
/// `PRIMARY_POINTER_SEAT` (0) for the mouse and for touches - the
/// primary seat's own pointers - so every detector that answers "the
/// current session" answers for the primary and is never hijacked by a
/// second cursor's press; a seat's sessions are read through the
/// `*_for(seat_id)` detectors.
pub seat_id: u64,
impl InputSession {
/// Create a new input session
fn new(session_id: u64, first_sample: InputSample, window_position: WindowPosition) -> Self {
samples: vec![first_sample],
ended: false,
session_id,
window_position_at_start: window_position,
seat_id: azul_core::window::PRIMARY_POINTER_SEAT,
/// Get the first sample in this session
pub fn first_sample(&self) -> Option<&InputSample> {
self.samples.first()
/// Get the last sample in this session
pub fn last_sample(&self) -> Option<&InputSample> {
self.samples.last()
/// Get the duration of this session (first to last sample)
pub fn duration_ms(&self) -> Option<u64> {
let first = self.first_sample()?;
let last = self.last_sample()?;
let duration = last.timestamp.duration_since(&first.timestamp);
Some(duration_to_millis(duration))
/// Get the total distance traveled in this session
pub fn total_distance(&self) -> f32 {
if self.samples.len() < 2 {
return 0.0;
let mut total = 0.0;
for i in 1..self.samples.len() {
let prev = &self.samples[i - 1];
let curr = &self.samples[i];
let dx = curr.position.x - prev.position.x;
let dy = curr.position.y - prev.position.y;
total += dx.hypot(dy);
total
/// Get the straight-line distance from first to last sample
pub fn direct_distance(&self) -> Option<f32> {
let dx = last.position.x - first.position.x;
let dy = last.position.y - first.position.y;
Some(dx.hypot(dy))
/// Result of drag detection analysis
pub struct DetectedDrag {
/// Position where drag started
pub start_position: LogicalPosition,
/// Current/end position of drag
pub current_position: LogicalPosition,
/// Direct distance dragged (straight line, pixels)
pub direct_distance: f32,
/// Total distance dragged (following path, pixels)
pub total_distance: f32,
/// Duration of the drag (milliseconds)
pub duration_ms: u64,
/// Number of position samples recorded
pub sample_count: usize,
/// Session ID this drag belongs to
/// Result of long-press detection
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DetectedLongPress {
/// Position where long press is happening
/// How long the button has been held (milliseconds)
/// Whether the callback has already been invoked for this long press
pub callback_invoked: bool,
/// Session ID this long press belongs to
/// Primary direction of a gesture
pub enum GestureDirection {
Up,
Down,
Left,
Right,
GestureDirection,
OptionGestureDirection,
[Debug, Clone, Copy, PartialEq, Eq]
DetectedPinch,
OptionDetectedPinch,
[Debug, Clone, Copy, PartialEq]
DetectedRotation,
OptionDetectedRotation,
DetectedLongPress,
OptionDetectedLongPress,
/// Result of pinch gesture detection
pub struct DetectedPinch {
/// Scale factor (< 1.0 for pinch in, > 1.0 for pinch out)
pub scale: f32,
/// Center point of the pinch gesture
pub center: LogicalPosition,
/// Initial distance between touch points
pub initial_distance: f32,
/// Current distance between touch points
pub current_distance: f32,
/// Duration of pinch (milliseconds)
/// Result of rotation gesture detection
pub struct DetectedRotation {
/// Rotation angle in radians (positive = clockwise)
pub angle_radians: f32,
/// Center point of rotation
/// Duration of rotation (milliseconds)
/// State of pen/stylus input
pub struct PenState {
/// Current pen position
/// Current pressure (0.0 to 1.0)
/// Current tilt angles (`x_tilt`, `y_tilt`) in degrees
/// Whether pen is in contact with surface
pub in_contact: bool,
/// Whether pen is inverted (eraser mode)
pub is_eraser: bool,
/// Whether barrel button is pressed
pub barrel_button_pressed: bool,
/// Unique identifier for this pen device
pub device_id: u64,
/// Tangential / cylinder pressure (0.0 to 1.0). Wacom Air Brush wheel,
/// Surface Slim Pen 2 secondary axis. `0.0` means "not reported".
/// Maps to W3C `PointerEvent.tangentialPressure`.
pub tangential_pressure: f32,
/// Barrel roll angle in radians (–π to π). Wacom Art Pen rotation,
/// Surface Pen barrel-roll axis. `0.0` means "not reported" (devices
/// that do report it sweep through the full range as the user rolls
/// the pen — the resting state isn't necessarily zero, so callers
/// should compare deltas, not absolute values).
/// Maps to W3C `PointerEvent.twist` (in radians, not degrees).
pub barrel_roll_rad: f32,
/// Per-tool identity for hand-held pens that report it (Wintab GUID,
/// Apple Pencil session id, S-Pen serial). `0` means "not reported".
/// Distinct from `device_id` so callers can both identify the
/// hardware (`device_id`) *and* which tip / lead / button cluster is
/// in use (`tool_id`).
pub tool_id: u32,
/// MEASURED report rate of this tool in Hz - an exponential moving
/// average of the interval between pen samples, because no platform
/// protocol carries the nominal rate (tablet-v2, XI2 and Wintab all
/// omit it). `0.0` until two samples arrive in the current proximity
/// session; re-converges within ~10 packets after proximity-in. Apps
/// use it to size smoothing windows and interpolation ("this pen
/// reports at 133Hz, the display at 60Hz").
pub report_rate_hz: f32,
/// Distance from the surface while hovering, normalized 0.0-1.0 against
/// the tool's OWN sensing range. `0.0` = touching, or not reported.
/// The scale is the device's, not millimetres: Wayland's `distance` is a
/// 16-bit fraction of maximum range and Win32 reports only in/out of
/// range at all. So it is a value to compare against itself over time — a
/// brush preview that grows as the pen approaches — not one to measure
/// with. Check `in_contact` first; a hovering pen has `pressure == 0.0`
/// and a touching one has `hover_distance == 0.0`.
pub hover_distance: f32,
/// Which tool of the tablet this is. `Unknown` where the platform does
/// not classify, which is most of them outside Wayland.
pub tool_kind: TabletToolKind,
impl_option!(PenState, OptionPenState, [Debug, Clone, Copy, PartialEq]);
impl Default for PenState {
position: LogicalPosition::zero(),
pressure: 0.0,
tilt: crate::callbacks::PenTilt {
x_tilt: 0.0,
y_tilt: 0.0,
},
in_contact: false,
is_eraser: false,
barrel_button_pressed: false,
device_id: 0,
tangential_pressure: 0.0,
barrel_roll_rad: 0.0,
tool_id: 0,
report_rate_hz: 0.0,
hover_distance: 0.0,
tool_kind: TabletToolKind::Unknown,
/// State of a tablet **pad** — the tablet body's own hardware controls,
/// distinct from the pen ([`PenState`] already covers eraser / barrel button /
/// barrel roll / tilt / pressure).
/// Named for the hardware class, not a vendor: the protocol behind it is
/// `zwp_tablet_pad_v2` on Wayland and `XInput2` valuators on X11, and Huion,
/// XP-Pen, Gaomon and Apple's own tablets all report through it.
/// Populated by the platform
/// backend (`dll/src/desktop/extra/wacom_pad/`: Wintab on Windows,
/// libwacom+libinput on Linux, the driver's `NSEvent` tablet events on macOS).
pub struct TabletPadState {
// Field order is by DECREASING ALIGNMENT. `device_id` is a u64 and has to
// lead, or `#[repr(C)]` pads to align it after the u32s; the two bools go
// last for the same reason. ~8 bytes per instance.
/// Tablet device id (to distinguish pads on multi-tablet setups).
/// `ExpressKey` bitset — bit `n` set ⇔ hardware button `n` is held (up to
/// 32). Read via [`TabletPadState::express_key`].
pub express_keys: u32,
/// Touch-ring / touch-strip absolute position, `0.0`–`1.0`. Only
/// meaningful while [`TabletPadState::touch_ring_active`] is `true`.
pub touch_ring: f32,
/// Touch-STRIP absolute position, `0.0`-`1.0`. Only meaningful while
/// [`TabletPadState::strip_active`] is `true`.
/// A strip is not a ring: Intuos Pro bodies have both, and a pad that has
/// one usually does not have the other. Folding them into a single field
/// would make a strip look like a ring stuck at one angle.
pub strip: f32,
/// Dial rotation since the last frame, in radians. `0.0` = no motion.
/// From `zwp_tablet_pad_dial_v2`, which both Linux backends already bind.
/// A DELTA rather than a position because a dial has no endstops — it is
/// the same primitive as a Surface Dial or a Wear crown, which is why
/// this is also the field a future `DialState` would read.
pub dial_delta: f32,
/// Which mode the pad's button group is in. Wacom pads multiplex their
/// `ExpressKeys` across modes, and the ring LEDs show which is active, so
/// the same physical key means different things per mode.
pub mode: u32,
/// How many modes the group has. `0` = the pad does not multiplex.
pub mode_count: u32,
/// Whether a finger is currently on the touch-ring / touch-strip.
pub touch_ring_active: bool,
/// Whether a finger is currently on the touch-strip.
pub strip_active: bool,
TabletPadState,
OptionTabletPadState,
impl Default for TabletPadState {
express_keys: 0,
touch_ring: 0.0,
touch_ring_active: false,
strip: 0.0,
strip_active: false,
dial_delta: 0.0,
mode: 0,
mode_count: 0,
impl TabletPadState {
/// Whether `ExpressKey` `index` (0-based, < 32) is currently held.
pub const fn express_key(&self, index: u32) -> bool {
index < 32 && (self.express_keys & (1u32 << index)) != 0
/// [`TabletDeviceInfo::capabilities`]: the device reports pressure.
pub const TABLET_CAP_PRESSURE: u32 = 1;
/// [`TabletDeviceInfo::capabilities`]: the device reports tilt.
pub const TABLET_CAP_TILT: u32 = 2;
/// [`TabletDeviceInfo::capabilities`]: the device reports barrel rotation.
pub const TABLET_CAP_ROTATION: u32 = 4;
/// [`TabletDeviceInfo::capabilities`]: airbrush wheel / tangential pressure.
pub const TABLET_CAP_SLIDER: u32 = 8;
/// [`TabletDeviceInfo::capabilities`]: a relative wheel on the tool.
pub const TABLET_CAP_WHEEL: u32 = 16;
/// [`TabletDeviceInfo::capabilities`]: a pad touch-ring or touch-strip.
pub const TABLET_CAP_TOUCHRING: u32 = 32;
/// What kind of input device a [`TabletDeviceInfo`] describes.
pub enum TabletToolKind {
/// The pen tip.
Stylus,
/// The inverted / eraser end (X11: a device of its own; Wayland: a tool
/// whose type is `eraser`).
Eraser,
/// The tablet's pad: `ExpressKeys` plus touch-ring / strip.
Pad,
/// A touch surface (tablet touch or touchscreen).
Touch,
/// Recognised as tablet-adjacent, kind unknown.
Unknown,
/// A brush tool. APPENDED at the end for ABI stability.
/// These five complete the `zwp_tablet_tool_v2` vocabulary, which is the
/// richest of the platform sets — macOS `NSPointingDeviceType` and Qt's
/// `PointerType` are both subsets of it. Widening this enum rather than
/// adding a parallel `PenToolType` keeps one name for one concept: an app
/// that switches on the tool it is holding should not have to ask which
/// API told it.
Brush,
/// A pencil tool.
Pencil,
/// An airbrush — the tool whose `slider` axis becomes
/// `PenState.tangential_pressure`.
Airbrush,
/// A tablet mouse / puck: rides on the tablet surface, reports absolute
/// position, and is NOT the system pointer.
Mouse,
/// A lens cursor — a puck with crosshairs, for tracing.
Lens,
/// Identity and capabilities of one tablet input device — the `xinput list`
/// level of information: enough for an app to tell the user WHICH tablet is
/// in use, offer a device picker, or configure a custom mapping.
/// Produced by the platform backends (X11: `XIQueryDevice` plus the
/// `Device Product ID` / `Device Node` properties; Wayland: the
/// `zwp_tablet_v2` descriptive events). A field the backend cannot know is
/// zero / empty rather than guessed — Wayland, for example, does not report
/// a physical size.
pub struct TabletDeviceInfo {
/// Driver-reported device name (X11: the slave device's name, e.g.
/// "Wacom One Pen Display 13 Pen stylus"; Wayland: the tablet's name).
pub name: AzString,
/// Human-readable vendor ("Wacom", "Huion", ...) resolved from
/// `vendor_id` via [`tablet_usb_vendor_name`]; empty when unknown.
pub vendor_name: AzString,
/// Kernel device node (`/dev/input/event..`) where known, else empty.
pub path: AzString,
/// The id [`PenState::device_id`] / [`TabletPadState::device_id`] report
/// on the same backend, so live state can be matched to an entry here.
/// USB vendor id (0 = unknown).
pub vendor_id: u32,
/// USB product id (0 = unknown).
pub product_id: u32,
/// What this device is.
pub kind: TabletToolKind,
/// `TABLET_CAP_*` bitset.
pub capabilities: u32,
/// The driver's RAW pressure maximum (X11: the valuator range; Wayland:
/// 65535). [`PenState::pressure`] is already normalized to 0..=1 — this
/// is diagnostic, for apps that build their own curves.
pub pressure_max: f32,
/// Active-area width in millimeters, 0.0 = unknown. On X11 this comes
/// from the `Abs X` valuator's range and resolution (units per meter).
pub physical_width_mm: f32,
/// Active-area height in millimeters, 0.0 = unknown.
pub physical_height_mm: f32,
/// Number of buttons the device reports (a pad: its `ExpressKeys`).
pub num_buttons: u32,
TabletDeviceInfo,
OptionTabletDeviceInfo,
TabletToolKind,
OptionTabletToolKind,
azul_css::impl_vec!(
TabletDeviceInfoVec,
TabletDeviceInfoVecDestructor,
TabletDeviceInfoVecDestructorType,
TabletDeviceInfoVecSlice,
OptionTabletDeviceInfo
azul_css::impl_vec_debug!(TabletDeviceInfo, TabletDeviceInfoVec);
azul_css::impl_vec_clone!(
TabletDeviceInfoVecDestructor
azul_css::impl_vec_partialeq!(TabletDeviceInfo, TabletDeviceInfoVec);
/// Resolve the well-known graphics-tablet USB vendor ids to a display name.
/// Empty for a vendor not in the table — show the hex id instead, never a
/// guess.
pub const fn tablet_usb_vendor_name(vendor_id: u32) -> &'static str {
match vendor_id {
0x056a => "Wacom",
0x256c => "Huion",
0x28bd => "XP-Pen",
0x5543 => "UC-Logic",
0x04f3 => "ELAN",
0x045e => "Microsoft",
0x05ac => "Apple",
0x04e8 => "Samsung",
_ => "",
/// Manager for multi-frame gestures and drag operations
/// This collects raw input samples and analyzes them to detect gestures.
/// Designed for testability and clear separation of input collection
/// vs. detection.
/// ## Unified Drag System
/// The manager now uses `DragContext` to unify all drag types:
/// - `active_drag`: The unified drag context (replaces individual drag states)
// The bools are INDEPENDENT latches (per-input-source armed/pending state), not
// the states of one machine; an enum would make illegal combinations of them
// unrepresentable that are in fact legal.
#[allow(clippy::struct_excessive_bools)]
pub struct GestureAndDragManager {
/// Configuration for gesture detection
pub config: GestureDetectionConfig,
/// All recorded input sessions (multiple button press sequences)
pub input_sessions: Vec<InputSession>,
/// **NEW**: Unified drag context for all drag types
pub active_drag: Option<DragContext>,
/// The node the CURRENT drag GESTURE began on (the press target),
/// resolved once at `DragStart` and held for the whole gesture. `Drag` /
/// `DragStart` / `DragEnd` fire on THIS node, not on whatever the cursor
/// is over now (W3C: those three target the drag source; only
/// DragEnter/Over/Leave/Drop follow the cursor). Without it a drag whose
/// cursor leaves the dragged element stops receiving Drag events — the
/// "the drag suddenly stops" desync. Remapped across DOM rebuilds,
/// cleared when the button releases / the gesture ends.
drag_source_node: azul_core::dom::OptionDomNodeId,
/// Current pen/stylus state
pub pen_state: Option<PenState>,
/// Pen state as of the previous determine-events pass (for diffing pen events).
pub previous_pen_state: Option<PenState>,
/// Set when pen state changed; gates one pen-event diff (cleared by the event loop).
pub pen_event_pending: bool,
/// Pen slots of the NON-primary seats (9b-ii-b-i-b): a Wayland tablet is
/// per `wl_seat` and an X11 stylus is a slave of one master pointer, so
/// a second seat's stylus is a second pen, not an overwrite of the
/// first. The primary seat keeps the three fields above.
pub seat_pens: alloc::collections::btree_map::BTreeMap<u64, SeatPen>,
/// Force Touch stage from the last `pressureChangeWithEvent:`. 0 none,
/// 1 a normal click, 2 a force click. macOS-only; 0 elsewhere.
pub trackpad_pressure_stage: i32,
/// Most recent rotary-control rotation. `None` until a dial reports.
pub dial_state: Option<DialState>,
/// `true` when the dial reported a rotation this pass, cleared by the dll
/// after the event is collected. Without a pending flag the provider would
/// have to diff, and two equal deltas in a row are two turns.
pending_dial_rotate: bool,
/// `true` on the press EDGE of a clickable dial (a level would re-fire
/// every frame while held).
pending_dial_click: bool,
/// A pen barrel squeeze awaiting dispatch (Apple Pencil Pro).
pub pending_pen_squeeze: bool,
/// A pen barrel double-tap awaiting dispatch (Apple Pencil 2+).
pub pending_pen_double_tap: bool,
/// Monotonic nanos of the previous pen sample (rate measurement);
/// cleared on proximity-out so a gap never reads as a slow rate.
pub last_pen_sample_nanos: Option<u64>,
/// The EMA behind [`PenState::report_rate_hz`].
pub pen_rate_ema_hz: f32,
/// Latest Wacom tablet-pad state (`ExpressKeys` + touch-ring), or `None`
/// until a pad backend delivers one.
pub pad_state: Option<TabletPadState>,
/// Enumerated tablet input devices (see [`TabletDeviceInfo`]), set by the
/// platform backend at window init / device hotplug. Empty = none found.
pub tablet_devices: Vec<TabletDeviceInfo>,
/// Session IDs where long press callback has been invoked
long_press_callbacks_invoked: Vec<u64>,
/// Counter for generating unique session IDs
next_session_id: u64,
/// Native-platform gesture override slot.
/// Platforms with first-class gesture recognizers (iOS `UIKit`,
/// Android `GestureDetector` + `ScaleGestureDetector`, macOS
/// `NSGestureRecognizer`) inject pre-detected gestures here via
/// [`GestureAndDragManager::inject_native_gesture`]. The
/// `detect_*` methods consult this slot before running their
/// in-process heuristics, so callbacks observe consistent results
/// regardless of the detection source.
/// Cleared automatically at the start of every new input recording
/// cycle so a single OS event doesn't keep firing.
pub native_gesture: Option<NativeGestureEvent>,
/// MWA-B4: OS touch id → session id. Desktop touch events previously
/// only filled the window's `touch_state`, so no touch ever became an
/// input session and `detect_pinch` / `detect_rotation` (which need two
/// concurrent sessions) were structurally dead on Windows/X11/Wayland.
/// The shells call [`touch_down`](Self::touch_down) /
/// [`touch_move`](Self::touch_move) / [`touch_up`](Self::touch_up); each
/// finger gets its own session (two fingers = two live sessions).
touch_sessions: alloc::collections::btree_map::BTreeMap<u64, u64>,
/// Seat id -> the session its pressed button owns (9b-ii-b-i); the
/// per-seat twin of `touch_sessions`.
seat_sessions: alloc::collections::btree_map::BTreeMap<u64, u64>,
/// Gesture detected by a platform-native recognizer.
/// Platform backends construct one of these in their gesture-recognizer
/// callbacks (iOS `UIKit`, Android `GestureDetector`, macOS
/// `NSGestureRecognizer`) and hand it to
/// [`GestureAndDragManager::inject_native_gesture`]. The in-process
/// `detect_*` methods then return the native result, sidestepping their
/// fallback heuristics. On platforms with poor native gesture support
/// (X11 / Wayland touch, headless), backends never inject and the
/// in-process detector remains authoritative.
#[repr(C, u8)]
pub enum NativeGestureEvent {
/// Single tap / double-click detected natively.
DoubleClick,
/// Long-press detected natively (iOS `UILongPressGestureRecognizer`,
/// Android `GestureDetector.OnGestureListener::onLongPress`).
LongPress(DetectedLongPress),
/// Swipe detected natively (iOS `UISwipeGestureRecognizer`,
/// Android `GestureDetector.OnGestureListener::onFling`).
Swipe(GestureDirection),
/// Pinch detected natively (iOS `UIPinchGestureRecognizer`,
/// Android `ScaleGestureDetector`, macOS magnification gesture).
Pinch(DetectedPinch),
/// Rotation detected natively (iOS `UIRotationGestureRecognizer`,
/// macOS rotation gesture).
Rotation(DetectedRotation),
impl Default for GestureAndDragManager {
Self::new()
impl GestureAndDragManager {
/// (`input_sessions`, `long_press_callbacks_invoked`). Used by
/// `AZ_E2E_TEST` to watch for unbounded growth.
pub const fn debug_counts(&self) -> (usize, usize) {
(
self.input_sessions.len(),
self.long_press_callbacks_invoked.len(),
)
/// Create a new gesture and drag manager
pub fn new() -> Self {
config: GestureDetectionConfig::default(),
input_sessions: Vec::new(),
next_session_id: 1,
active_drag: None,
drag_source_node: azul_core::dom::OptionDomNodeId::None,
pen_state: None,
previous_pen_state: None,
pen_event_pending: false,
trackpad_pressure_stage: 0,
dial_state: None,
pending_dial_rotate: false,
pending_dial_click: false,
pending_pen_squeeze: false,
pending_pen_double_tap: false,
last_pen_sample_nanos: None,
pen_rate_ema_hz: 0.0,
pad_state: None,
tablet_devices: Vec::new(),
long_press_callbacks_invoked: Vec::new(),
native_gesture: None,
touch_sessions: alloc::collections::btree_map::BTreeMap::new(),
seat_sessions: alloc::collections::btree_map::BTreeMap::new(),
seat_pens: alloc::collections::btree_map::BTreeMap::new(),
/// Inject a native gesture-recognizer result, overriding the
/// in-process detector for the current event frame. Called by the
/// iOS / Android / macOS platform backend from their gesture
/// recognizer callbacks. The override is read once by the next
/// `detect_*` call.
/// Record a Force Touch pressure sample from a pressure-sensitive
/// trackpad (macOS `pressureChangeWithEvent:`).
/// Folded into `PenState` because it is the same quantity a stylus
/// reports — an app reads it through `get_pen_pressure()` either way —
/// but with `is_eraser` and the barrel flags off, since a trackpad has
/// neither. `stage` rides alongside as the discrete detent count, which is
/// what separates a deliberate force click from merely pressing hard.
pub fn update_trackpad_pressure(
&mut self,
position: LogicalPosition,
pressure: f32,
stage: i32,
) {
self.previous_pen_state = self.pen_state;
let mut state = self.pen_state.unwrap_or_default();
state.position = position;
state.pressure = pressure;
state.in_contact = stage > 0;
state.is_eraser = false;
state.barrel_button_pressed = false;
self.pen_state = Some(state);
self.trackpad_pressure_stage = stage;
self.pen_event_pending = true;
/// The Force Touch stage most recently reported: 0 none, 1 a normal
/// click, 2 a force click past the second detent.
pub const fn trackpad_pressure_stage(&self) -> i32 {
self.trackpad_pressure_stage
pub const fn inject_native_gesture(&mut self, gesture: NativeGestureEvent) {
self.native_gesture = Some(gesture);
/// Clear any pending native-gesture override. Called by the event
/// loop after each frame's detections have been consumed so a
/// stale OS gesture doesn't keep firing.
pub const fn clear_native_gesture(&mut self) {
self.native_gesture = None;
/// Create with custom configuration
pub fn with_config(config: GestureDetectionConfig) -> Self {
config,
..Self::new()
// Input Recording Methods (called from event loop / system timer)
/// Start a new input session (mouse button pressed down)
/// This begins recording samples for gesture detection.
/// Call this when receiving mouse button down event.
/// `window_position` is the current OS window position at the time of mouse-down.
/// It is stored so that drag callbacks can compute the new window position.
/// Returns the session ID for this new session.
pub fn start_input_session(
timestamp: CoreInstant,
button_state: u8,
window_position: WindowPosition,
screen_position: LogicalPosition,
) -> u64 {
self.start_input_session_with_pen(
position,
timestamp,
button_state,
allocate_event_id(),
0.5, // default pressure for mouse
(0.0, 0.0), // no tilt for mouse
(0.0, 0.0), // no touch radius for mouse
window_position,
screen_position,
/// Start a new input session with pen/touch data
pub fn start_input_session_with_pen(
event_id: u64,
tilt: (f32, f32),
touch_radius: (f32, f32),
// Clear old ended sessions, but keep the most recent ended session
// for double-click detection. detect_double_click() needs two ended
// sessions to compare timing and distance.
let last_ended_idx = self.input_sessions.iter().rposition(|s| s.ended);
let mut idx = 0usize;
self.input_sessions.retain(|session| {
let keep = !session.ended || Some(idx) == last_ended_idx;
idx += 1;
keep
});
let session_id = self.next_session_id;
self.next_session_id += 1;
let sample = InputSample {
event_id,
pressure,
tilt: tilt.into(),
touch_radius: LogicalSize::new(touch_radius.0, touch_radius.1),
let session = InputSession::new(session_id, sample, window_position);
self.input_sessions.push(session);
session_id
/// Record an input sample to the current session
/// Call this on every mouse move event while button is pressed,
/// and also periodically from a system timer to track long presses.
/// Returns true if sample was recorded, false if no active session.
pub fn record_input_sample(
) -> bool {
self.record_input_sample_with_pen(
/// Record an input sample with pen/touch data
pub fn record_input_sample_with_pen(
let Some(session) = self.last_primary_session_mut() else {
return false;
if session.ended {
// Enforce max samples limit
if session.samples.len() >= MAX_SAMPLES_PER_SESSION {
// Remove oldest samples, keeping the most recent ones
let remove_count = session.samples.len() - MAX_SAMPLES_PER_SESSION + DRAIN_BATCH_SIZE;
session.samples.drain(0..remove_count);
session.samples.push(InputSample {
true
/// End the current input session (mouse button released)
/// Call this when receiving mouse button up event.
/// The session is kept for analysis but marked as ended.
pub fn end_current_session(&mut self) {
if let Some(session) = self.last_primary_session_mut() {
session.ended = true;
// --- Per-touch-id input sessions (MWA-B4) ---
/// A finger made contact: open a dedicated session for `touch_id`.
pub fn touch_down(
touch_id: u64,
let session_id = self.start_input_session(
TOUCH_CONTACT_BUTTON_STATE,
self.touch_sessions.insert(touch_id, session_id);
/// A finger moved: record into ITS OWN session — never `last_mut()`,
/// two concurrent fingers must not interleave into one session (that
/// would corrupt both the drag heuristics and pinch/rotate distances).
/// Returns `true` if a sample was recorded.
pub fn touch_move(
let Some(session_id) = self.touch_sessions.get(&touch_id).copied() else {
self.record_sample_for_session(session_id, position, timestamp, screen_position)
/// A finger lifted (or the OS cancelled the touch): final sample + end
/// the session and drop the id mapping.
pub fn touch_up(
let Some(session_id) = self.touch_sessions.remove(&touch_id) else {
return;
let _ = self.record_sample_for_session(session_id, position, timestamp, screen_position);
if let Some(session) = self
.input_sessions
.iter_mut()
.find(|s| s.session_id == session_id)
{
/// The OS cancelled the whole touch sequence (e.g. the compositor took
/// the gesture over): end every touch session and drop the id map.
pub fn touch_cancel_all(&mut self) {
let ids: Vec<u64> = self.touch_sessions.values().copied().collect();
self.touch_sessions.clear();
for session_id in ids {
/// Record a sample into the session with `session_id` (MWA-B4 helper —
/// the by-id sibling of `record_input_sample_with_pen`, which only ever
/// writes to the LAST session).
fn record_sample_for_session(
session_id: u64,
let Some(session) = self
else {
button_state: TOUCH_CONTACT_BUTTON_STATE,
event_id: allocate_event_id(),
pressure: 0.5,
touch_radius: LogicalSize::zero(),
/// Clear old input sessions that have timed out
/// Call this periodically (e.g., every frame) to prevent memory leaks.
/// Sessions older than `config.sample_cleanup_interval_ms` are removed.
// CoreInstant is a ref-counted FFI clock handle threaded through the event loop by value;
// &-converting would cascade through the loop call chain and across all dll backends.
#[allow(clippy::needless_pass_by_value)]
pub fn clear_old_sessions(&mut self, current_time: CoreInstant) {
if let Some(last_sample) = session.last_sample() {
let duration = current_time.duration_since(&last_sample.timestamp);
let age_ms = duration_to_millis(duration);
age_ms < self.config.sample_cleanup_interval_ms
false
// Also clear long press callback tracking for removed sessions
let valid_session_ids: Vec<u64> =
self.input_sessions.iter().map(|s| s.session_id).collect();
self.long_press_callbacks_invoked
.retain(|id| valid_session_ids.contains(id));
/// Clear all input sessions
/// Call this when you want to reset all gesture detection state.
pub fn clear_all_sessions(&mut self) {
self.input_sessions.clear();
self.long_press_callbacks_invoked.clear();
/// Update pen/stylus state
/// Call this when receiving pen events from the platform. The
/// extended fields (`tangential_pressure`, `barrel_roll_rad`,
/// `tool_id`) default to `0` — pass [`update_pen_state_full`] when
/// the platform reports them.
pub fn update_pen_state(
in_contact: bool,
is_eraser: bool,
barrel_button_pressed: bool,
device_id: u64,
self.update_pen_state_full(
tilt,
in_contact,
is_eraser,
barrel_button_pressed,
device_id,
0.0,
0,
/// Update pen/stylus state including the extended axes (W3C
/// `PointerEvent.tangentialPressure` + `twist`) and per-tool id.
pub fn update_pen_state_full(
tangential_pressure: f32,
barrel_roll_rad: f32,
tool_id: u32,
// Report-rate measurement: EMA over the inter-sample interval on the
// shared monotonic clock. A gap over one second (left and re-entered
// proximity without a proximity-out, app stall) restarts the
// estimate instead of averaging in a bogus slow sample.
let now = crate::probe::monotonic_now_nanos();
if let Some(prev) = self.last_pen_sample_nanos {
let dt_s = now.saturating_sub(prev) as f32 / 1e9;
if dt_s > 0.0 && dt_s < 1.0 {
let inst = 1.0 / dt_s.max(1e-4);
self.pen_rate_ema_hz = if self.pen_rate_ema_hz > 0.0 {
self.pen_rate_ema_hz * 0.9 + inst * 0.1
inst
self.pen_rate_ema_hz = 0.0;
self.last_pen_sample_nanos = Some(now);
self.pen_state = Some(PenState {
x_tilt: tilt.0,
y_tilt: tilt.1,
tangential_pressure,
barrel_roll_rad,
tool_id,
report_rate_hz: self.pen_rate_ema_hz,
// Carried forward: the backends report hover distance and tool
// kind on their own events (Wayland `distance`, `tool_type`),
// not on the motion frame this builds, so overwriting them here
// would clear them on every sample.
hover_distance: self.pen_state.map_or(0.0, |p| p.hover_distance),
tool_kind: self
.pen_state
.map_or(TabletToolKind::Unknown, |p| p.tool_kind),
/// Record the hover distance reported while a tool is in proximity.
/// Separate from `update_pen_state_full` because the backends send it on
/// its own event — Wayland `zwp_tablet_tool_v2.distance` arrives between
/// motion frames — so folding it into the motion path would mean either
/// dropping it or inventing a motion sample to carry it.
pub const fn set_pen_hover_distance(&mut self, distance: f32) {
if let Some(ref mut p) = self.pen_state {
p.hover_distance = distance;
/// Record which tool of the tablet is in use.
/// Announced once per tool at proximity-in, not per sample, which is why
/// it is a setter rather than a parameter.
pub const fn set_pen_tool_kind(&mut self, kind: TabletToolKind) {
p.tool_kind = kind;
/// Record a dial rotation.
/// Called by whichever backend owns the dial — the Wayland tablet pad
/// today, a `RadialController` or a crown later. The manager keeps the
/// most recent frame rather than accumulating: a delta belongs to the
/// frame that reported it, and an app that misses a frame wants the next
/// rotation, not a stale sum.
pub fn update_dial_state(&mut self, state: DialState) {
// A rotation belongs to the frame that reported it, so the EVENT is
// armed per update rather than derived from a diff: two identical
// deltas in a row are two turns, not one.
self.pending_dial_rotate = state.delta_rad != 0.0 || state.detent_count != 0.0;
// The CLICK is an edge — a dial reports `pressed` as a level, and
// arming on the level would fire once per frame for as long as it is
// held. Same rule the gamepad's press edges use.
self.pending_dial_click = state.pressed && !self.dial_state.is_some_and(|d| d.pressed);
self.dial_state = Some(state);
/// Clear the dial's pending events. The dll calls this after the pass has
/// collected them, exactly as it does for the other providers.
pub const fn clear_pending_dial(&mut self) {
self.pending_dial_rotate = false;
self.pending_dial_click = false;
/// The most recent dial rotation, if any dial has reported.
pub const fn get_dial_state(&self) -> Option<DialState> {
self.dial_state
/// Record a pen barrel gesture — a squeeze or a double-tap.
/// Latched rather than dispatched directly because these arrive on their
/// own `UIKit` channel, outside the touch stream, so there is no pen sample
/// to attach them to. The event-determination pass drains the latch and
/// emits `PenSqueeze` / `PenDoubleTap`.
pub const fn note_pen_barrel_gesture(&mut self, is_squeeze: bool) {
if is_squeeze {
self.pending_pen_squeeze = true;
self.pending_pen_double_tap = true;
/// Read the pen barrel gestures without consuming them — event
/// determination takes `&self`, so the drain happens in the shell's
/// clear-pending block alongside `clear_pen_event_pending`.
pub const fn peek_pen_barrel_gestures(&self) -> (bool, bool) {
(self.pending_pen_squeeze, self.pending_pen_double_tap)
/// Drain the pen barrel gestures recorded since the last pass, as
/// `(squeeze, double_tap)`.
pub fn take_pen_barrel_gestures(&mut self) -> (bool, bool) {
core::mem::take(&mut self.pending_pen_squeeze),
core::mem::take(&mut self.pending_pen_double_tap),
/// Clear pen state (when pen leaves proximity)
pub const fn clear_pen_state(&mut self) {
self.pen_state = None;
// Proximity ended: the next session measures afresh.
self.last_pen_sample_nanos = None;
/// Get current pen state (read-only)
pub const fn get_pen_state(&self) -> Option<&PenState> {
self.pen_state.as_ref()
/// Get the previous pen state (for event diffing).
pub const fn get_previous_pen_state(&self) -> Option<&PenState> {
self.previous_pen_state.as_ref()
/// Clear the pen-event-pending flag (called by the event loop after a pass).
pub fn clear_pen_event_pending(&mut self) {
self.pen_event_pending = false;
// The seats' flags share the primary's lifecycle: one clear per
// event pass (9b-ii-b-i-b).
for pen in self.seat_pens.values_mut() {
pen.event_pending = false;
// --- Per-SEAT pens (9b-ii-b-i-b) ---
//
// `*_for(seat_id, ..)` route to the primary's own fields for seat 0 and
// to `seat_pens` otherwise, so a producer that knows its seat calls one
// API and the primary path is unchanged.
#[allow(clippy::too_many_arguments)]
pub fn update_pen_state_full_for(
seat_id: u64,
if seat_id == azul_core::window::PRIMARY_POINTER_SEAT {
let pen = self.seat_pens.entry(seat_id).or_default();
if let Some(prev) = pen.last_sample_nanos {
pen.rate_ema_hz = if pen.rate_ema_hz > 0.0 {
pen.rate_ema_hz * 0.9 + inst * 0.1
pen.rate_ema_hz = 0.0;
pen.last_sample_nanos = Some(now);
pen.previous = pen.state;
pen.state = Some(PenState {
report_rate_hz: pen.rate_ema_hz,
hover_distance: pen.state.map_or(0.0, |p| p.hover_distance),
tool_kind: pen.state.map_or(TabletToolKind::Unknown, |p| p.tool_kind),
pen.event_pending = true;
pub fn clear_pen_state_for(&mut self, seat_id: u64) {
self.clear_pen_state();
if let Some(pen) = self.seat_pens.get_mut(&seat_id) {
if pen.state.is_some() {
pen.state = None;
pen.last_sample_nanos = None;
pub fn set_pen_hover_distance_for(&mut self, seat_id: u64, distance: f32) {
self.set_pen_hover_distance(distance);
if let Some(p) = self
.seat_pens
.get_mut(&seat_id)
.and_then(|pen| pen.state.as_mut())
pub fn set_pen_tool_kind_for(&mut self, seat_id: u64, kind: TabletToolKind) {
self.set_pen_tool_kind(kind);
/// One seat's current pen, the primary's for seat 0.
pub fn pen_state_for(&self, seat_id: u64) -> Option<&PenState> {
self.seat_pens
.get(&seat_id)
.and_then(|pen| pen.state.as_ref())
/// The non-primary seats' pen slots - what the event pass diffs.
pub fn seat_pen_diffs(&self) -> impl Iterator<Item = (u64, &SeatPen)> {
self.seat_pens.iter().map(|(id, pen)| (*id, pen))
/// Set the latest Wacom tablet-pad state (called by the pad backend).
pub const fn update_pad_state(&mut self, pad: TabletPadState) {
self.pad_state = Some(pad);
/// The latest tablet-pad state, or `None` if no pad backend delivered one.
pub const fn get_pad_state(&self) -> Option<&TabletPadState> {
self.pad_state.as_ref()
/// Clear the tablet-pad state (pad disconnected / proximity left).
pub const fn clear_pad_state(&mut self) {
self.pad_state = None;
/// Replace the enumerated tablet-device list. Called by the platform
/// backend at window init and on device hotplug.
pub fn set_tablet_devices(&mut self, devices: Vec<TabletDeviceInfo>) {
self.tablet_devices = devices;
/// The enumerated tablet devices (empty when the backend found none, or
/// none exist).
pub fn get_tablet_devices(&self) -> &[TabletDeviceInfo] {
&self.tablet_devices
// Gesture Detection Methods (query state without mutation)
/// Detect if current input represents a drag gesture
/// Returns Some(DetectedDrag) if a drag is detected based on distance threshold.
pub fn detect_drag(&self) -> Option<DetectedDrag> {
self.detect_drag_for(azul_core::window::PRIMARY_POINTER_SEAT)
/// `detect_drag` over ONE seat's current session (9b-ii-b-i).
pub fn detect_drag_for(&self, seat_id: u64) -> Option<DetectedDrag> {
let session = self.current_session_for(seat_id)?;
// A released button ended the session; the samples stay for velocity
// queries, but they are no longer a drag. Without this every pass
// after `DragEnd` re-detected the finished drag and re-fired
// `DragStart` (the tear-off drag on a popup began again on the very
// mouse-up that ended it).
return None;
if session.samples.len() < self.config.min_samples_for_gesture {
let direct_distance = session.direct_distance()?;
if direct_distance >= self.config.drag_distance_threshold {
let first = session.first_sample()?;
let last = session.last_sample()?;
Some(DetectedDrag {
start_position: first.position,
current_position: last.position,
direct_distance,
total_distance: session.total_distance(),
duration_ms: session.duration_ms()?,
sample_count: session.samples.len(),
session_id: session.session_id,
})
None
/// Detect if current input represents a long press
/// Returns Some(DetectedLongPress) if button has been held long enough
/// without moving much.
pub fn detect_long_press(&self) -> Option<DetectedLongPress> {
if let Some(NativeGestureEvent::LongPress(lp)) = self.native_gesture {
return Some(lp);
self.detect_long_press_for(azul_core::window::PRIMARY_POINTER_SEAT)
/// `detect_long_press` over ONE seat's current session (9b-ii-b-i).
pub fn detect_long_press_for(&self, seat_id: u64) -> Option<DetectedLongPress> {
return None; // Can't be long press if button already released
let duration_ms = session.duration_ms()?;
if duration_ms < self.config.long_press_time_threshold_ms {
let distance = session.direct_distance()?;
if distance <= self.config.long_press_distance_threshold {
let callback_invoked = self
.long_press_callbacks_invoked
.contains(&session.session_id);
Some(DetectedLongPress {
position: first.position,
duration_ms,
callback_invoked,
/// Mark long press callback as invoked for a session
/// Call this after invoking the long press callback to prevent
/// repeated invocations.
/// MWA-B12: mark the CURRENT session's long-press as delivered. The
/// event pass calls this right after emitting `EventType::LongPress` —
/// nothing ever called `mark_long_press_callback_invoked`, so `LongPress`
/// re-fired on every subsequent pass of the same hold.
pub fn mark_current_long_press_invoked(&mut self) {
if let Some(id) = self.get_current_session().map(|s| s.session_id) {
self.mark_long_press_callback_invoked(id);
pub fn mark_long_press_callback_invoked(&mut self, session_id: u64) {
if !self.long_press_callbacks_invoked.contains(&session_id) {
self.long_press_callbacks_invoked.push(session_id);
/// Did the PLATFORM report a double-click (as opposed to this manager
/// inferring one from the session history)?
/// The injected gesture is CONSUMED — the event loop clears the latch at
/// the end of the pass that saw it — whereas [`Self::detect_double_click`]
/// is a pure predicate over the session history that stays true until the
/// next press. Event *determination* has to tell those two apart, because
/// only the injected one may fire without a mouse-release edge.
pub const fn has_injected_double_click(&self) -> bool {
matches!(self.native_gesture, Some(NativeGestureEvent::DoubleClick))
/// Detect if last two sessions form a double-click.
/// Returns true if timing and distance match double-click criteria.
/// PURE PREDICATE, deliberately: `CallbackInfo::was_double_clicked` asks it
/// during dispatch, so it must still answer `true` after the event that
/// carried the double-click was raised. Nothing here is consumed — the two
/// ended sessions stay the newest pair until the next press — so a CALLER
/// that turns this into an event owes it an edge of its own (see
/// `determine_all_events`, which only raises `DoubleClick` on the release
/// that completes the gesture).
pub fn detect_double_click(&self) -> bool {
if self.has_injected_double_click() {
return true;
self.detect_double_click_for(azul_core::window::PRIMARY_POINTER_SEAT)
/// `detect_double_click` over ONE seat's sessions (9b-ii-b-i): the two
/// most recent presses of that seat, and no other seat's.
pub fn detect_double_click_for(&self, seat_id: u64) -> bool {
let sessions: Vec<&InputSession> = self.sessions_of(seat_id).collect();
if sessions.len() < 2 {
let prev_session = sessions[sessions.len() - 2];
let last_session = sessions[sessions.len() - 1];
// Both sessions must have ended (button released)
if !prev_session.ended || !last_session.ended {
let prev_first = prev_session.first_sample();
let last_first = last_session.first_sample();
let (Some(prev_first), Some(last_first)) = (prev_first, last_first) else {
let duration = last_first.timestamp.duration_since(&prev_first.timestamp);
let time_delta_ms = duration_to_millis(duration);
if time_delta_ms > self.config.double_click_time_threshold_ms {
let dx = last_first.position.x - prev_first.position.x;
let dy = last_first.position.y - prev_first.position.y;
let distance = dx.hypot(dy);
distance < self.config.double_click_distance_threshold
/// Detect click count (1=single, 2=double, 3=triple) by examining
/// the recent ended sessions. Uses only timestamps and positions
/// from the session history, so the result is fully deterministic
/// for any given sequence of `InputSession`s (easy to unit-test
/// with synthetic `CoreInstant`/`CoreDuration` values).
pub fn detect_click_count(&self) -> u32 {
self.detect_click_count_for(azul_core::window::PRIMARY_POINTER_SEAT)
/// `detect_click_count` over ONE seat's sessions (9b-ii-b-i).
pub fn detect_click_count_for(&self, seat_id: u64) -> u32 {
let n = sessions.len();
if n == 0 {
return 1;
// We need at least 2 ended sessions for double-click,
// 3 ended sessions for triple-click.
// Walk backwards from the most recent ended session and count
// how many consecutive clicks fall within the time+distance
// thresholds.
// Collect the last up-to-3 click sessions (most-recent first). The
// click IN PROGRESS counts: `detect_click_count` runs on mouse-DOWN,
// which has already started a new (still-live) session for THIS click,
// so a double-click's second press sees `[click1(ended),
// click2(LIVE)]` — the live one is the current click and must be
// counted. Only EARLIER clicks have to be ended.
let mut recent: Vec<&InputSession> = Vec::new();
for s in sessions.iter().rev() {
if !s.ended && !recent.is_empty() {
break;
recent.push(*s);
if recent.len() >= 3 {
if recent.is_empty() {
// recent[0] = most recent ended session
// recent[1] = previous ended session (if any)
// recent[2] = one before that (if any)
let mut count = 1u32;
for i in 0..recent.len() - 1 {
let later = recent[i];
let earlier = recent[i + 1];
let Some(later_start) = later.first_sample() else {
let Some(earlier_start) = earlier.first_sample() else {
let duration = later_start
.timestamp
.duration_since(&earlier_start.timestamp);
let dx = later_start.position.x - earlier_start.position.x;
let dy = later_start.position.y - earlier_start.position.y;
if distance >= self.config.double_click_distance_threshold {
count += 1;
// Cap at 3 (triple-click selects paragraph, beyond that cycles back)
if count > 3 {
1
count
/// Get the primary direction of current drag.
pub fn get_drag_direction(&self) -> Option<GestureDirection> {
let session = self.get_current_session()?;
let direction = match (dx.abs() > dy.abs(), dx > 0.0, dy > 0.0) {
(true, true, _) => GestureDirection::Right,
(true, false, _) => GestureDirection::Left,
(false, _, true) => GestureDirection::Down,
(false, _, false) => GestureDirection::Up,
Some(direction)
/// Get average velocity of current gesture (pixels per second)
#[allow(clippy::cast_precision_loss)] // bounded layout/render numeric cast
pub fn get_gesture_velocity(&self) -> Option<f32> {
if session.samples.len() < 2 {
let total_distance = session.total_distance();
if duration_ms == 0 {
let duration_secs = duration_ms as f32 / 1000.0;
Some(total_distance / duration_secs)
/// Check if current gesture is a swipe (fast directional movement).
pub fn is_swipe(&self) -> bool {
self.get_gesture_velocity()
.is_some_and(|v| v >= self.config.swipe_velocity_threshold)
/// Detect swipe with specific direction
/// Returns Some(dir) if gesture is a fast swipe in a clear direction
pub fn detect_swipe_direction(&self) -> Option<GestureDirection> {
if let Some(NativeGestureEvent::Swipe(d)) = self.native_gesture {
return Some(d);
// Must be a fast swipe first
if !self.is_swipe() {
// Get direction
self.get_drag_direction()
/// Detect pinch gesture (two-touch zoom in/out)
/// Returns Some if two touch points are active and distance is changing
/// significantly. Scale < 1.0 = pinch in, scale > 1.0 = pinch out.
#[allow(clippy::similar_names)] // domain-standard coordinate/geometry/short-lived names
pub fn detect_pinch(&self) -> Option<DetectedPinch> {
if let Some(NativeGestureEvent::Pinch(p)) = self.native_gesture {
return Some(p);
// Need at least two active sessions for pinch
if self.input_sessions.len() < 2 {
// Get last two sessions (most recent touches)
let session1 = &self.input_sessions[self.input_sessions.len() - 2];
let session2 = &self.input_sessions[self.input_sessions.len() - 1];
// A pinch is a TWO-finger gesture: both contacts must be concurrently
// active. A desktop mouse produces *sequential* sessions (the previous one
// is `ended` on button-up before the next begins), so without this guard a
// stale ended session (e.g. a prior click on a button) pairs with the
// current drag and is misread as a pinch — the map zooms on a plain click.
if session1.ended || session2.ended {
// Both must have samples
let first1 = session1.first_sample()?;
let first2 = session2.first_sample()?;
let last1 = session1.last_sample()?;
let last2 = session2.last_sample()?;
// Calculate initial distance between touches
let dx_initial = first2.position.x - first1.position.x;
let dy_initial = first2.position.y - first1.position.y;
let initial_distance = dx_initial.hypot(dy_initial);
// Calculate current distance
let dx_current = last2.position.x - last1.position.x;
let dy_current = last2.position.y - last1.position.y;
let current_distance = dx_current.hypot(dy_current);
// Avoid division by zero
if initial_distance < 1.0 {
// Calculate scale factor
let scale = current_distance / initial_distance;
// Check if scale change is significant (threshold from config)
let scale_threshold = 1.0 + self.config.pinch_scale_threshold;
if scale > 1.0 / scale_threshold && scale < scale_threshold {
return None; // Change too small
// Calculate center point
let center = LogicalPosition {
x: f32::midpoint(last1.position.x, last2.position.x),
y: f32::midpoint(last1.position.y, last2.position.y),
// Calculate duration
let duration = last1.timestamp.duration_since(&first1.timestamp);
let duration_ms = duration_to_millis(duration);
Some(DetectedPinch {
scale,
center,
initial_distance,
current_distance,
/// Detect rotation gesture (two-touch rotate)
/// Returns Some if two touch points are rotating around center.
/// Positive angle = clockwise, negative = counterclockwise.
pub fn detect_rotation(&self) -> Option<DetectedRotation> {
const PI: f32 = core::f32::consts::PI;
if let Some(NativeGestureEvent::Rotation(r)) = self.native_gesture {
return Some(r);
// Need at least two active sessions
// Get last two sessions
// Two-finger rotation requires both contacts concurrently active; a desktop
// mouse yields sequential sessions, so a stale ended session must not pair
// with the current one (see detect_pinch).
// Calculate center (average of both touches)
// Calculate initial angle between touches
let initial_angle = dy_initial.atan2(dx_initial);
// Calculate current angle
let current_angle = dy_current.atan2(dx_current);
// Calculate angle difference (normalized to -π to π)
let mut angle_diff = current_angle - initial_angle;
// Normalize angle to -π to π range
#[allow(clippy::while_float)]
// intentional bounded float loop (angle-wrap / pixel-step); an integer counter would be
// artificial
while angle_diff > PI {
angle_diff -= 2.0 * PI;
while angle_diff < -PI {
angle_diff += 2.0 * PI;
// Check if rotation is significant (threshold from config)
if angle_diff.abs() < self.config.rotation_angle_threshold {
Some(DetectedRotation {
angle_radians: angle_diff,
/// Get the current active input session (if any)
pub fn get_current_session(&self) -> Option<&InputSession> {
self.last_primary_session()
/// Every session of one seat, oldest first (9b-ii-b-i).
pub fn sessions_of(&self, seat_id: u64) -> impl Iterator<Item = &InputSession> {
self.input_sessions
.iter()
.filter(move |s| s.seat_id == seat_id)
/// The most recent session of one seat, ended or not.
pub fn current_session_for(&self, seat_id: u64) -> Option<&InputSession> {
.rev()
.find(|s| s.seat_id == seat_id)
/// The most recent PRIMARY session - what every "current session" reader
/// means, and never a second seat's (9b-ii-b-i).
fn last_primary_session(&self) -> Option<&InputSession> {
self.current_session_for(azul_core::window::PRIMARY_POINTER_SEAT)
fn last_primary_session_mut(&mut self) -> Option<&mut InputSession> {
.find(|s| s.seat_id == azul_core::window::PRIMARY_POINTER_SEAT)
// --- Per-SEAT input sessions (9b-ii-b-i) ---
// The per-seat twin of the touch API: a second cursor's press opens a
// session owned by that seat, its moves feed it, its release ends it.
// Fed by the shell from the window-state diff of `pointer_seats`, so
// every backend that publishes a seat gets its gestures without its own
// wiring.
pub fn seat_down(
if let Some(s) = self
s.seat_id = seat_id;
self.seat_sessions.insert(seat_id, session_id);
pub fn seat_move(
let Some(session_id) = self.seat_sessions.get(&seat_id).copied() else {
pub fn seat_up(
let Some(session_id) = self.seat_sessions.remove(&seat_id) else {
/// Whether one seat's current session has become a DRAG: not ended and
/// moved past the drag threshold.
pub fn seat_drag_active(&self, seat_id: u64) -> bool {
self.detect_drag_for(seat_id).is_some()
/// Whether one seat's current session crossed the drag threshold with
/// its LAST sample - the pure edge `DragStart` fires on, computed from
/// the samples so the event pass needs no mutable latch.
pub fn seat_drag_started_now(&self, seat_id: u64) -> bool {
let Some(session) = self.current_session_for(seat_id) else {
if session.ended || session.samples.len() < self.config.min_samples_for_gesture {
let Some(first) = session.first_sample() else {
let dist = |sample: &InputSample| {
let dx = sample.position.x - first.position.x;
let dy = sample.position.y - first.position.y;
dx.hypot(dy)
let n = session.samples.len();
if dist(&session.samples[n - 1]) < self.config.drag_distance_threshold {
n < 2 || dist(&session.samples[n - 2]) < self.config.drag_distance_threshold
/// Whether one seat's most recent session - which has just ended - had
/// been a drag, so its release is a `DragEnd`.
pub fn seat_drag_just_ended(&self, seat_id: u64) -> bool {
session.ended
&& session
.direct_distance()
.is_some_and(|d| d >= self.config.drag_distance_threshold)
/// Get current mouse position from latest sample
pub fn get_current_mouse_position(&self) -> Option<LogicalPosition> {
self.get_current_session()
.and_then(|s| s.last_sample())
.map(|sample| sample.position)
/// Get the drag delta (current mouse position minus mouse-down position)
/// from the current input session.
/// Returns `None` if there is no active session or not enough samples.
pub fn get_drag_delta(&self) -> Option<(f32, f32)> {
Some((
last.position.x - first.position.x,
last.position.y - first.position.y,
))
/// Get the drag delta in **screen-absolute** coordinates.
/// Unlike `get_drag_delta()` which uses window-local coordinates (and therefore
/// oscillates during window drags due to the window moving under the cursor),
/// this method uses screen-absolute positions that are stable regardless of
/// window movement.
/// **Use this for window dragging (titlebar drag).**
/// Use `get_drag_delta()` for in-window operations (node drag-and-drop, etc.).
pub fn get_drag_delta_screen(&self) -> Option<(f32, f32)> {
last.screen_position.x - first.screen_position.x,
last.screen_position.y - first.screen_position.y,
/// Get the **incremental** (frame-to-frame) drag delta in screen coordinates.
/// Returns `(dx, dy)` where `dx = last_screen.x - previous_screen.x` and
/// `dy = last_screen.y - previous_screen.y`.
/// Unlike `get_drag_delta_screen()` which returns the *total* delta since drag
/// start, this returns only the delta since the previous sample. This is used
/// by `titlebar_drag` to apply position changes incrementally:
/// ```text
/// new_pos = current_window_pos + incremental_delta
/// ```
/// This approach is more robust than `initial_pos + total_delta` because it
/// automatically handles external window position changes (DPI change, OS
/// clamping, compositor resize) that would make `initial_pos` stale.
/// Returns `None` if there is no active session or fewer than 2 samples.
pub fn get_drag_delta_screen_incremental(&self) -> Option<(f32, f32)> {
let len = session.samples.len();
if len < 2 {
let prev = &session.samples[len - 2];
let last = &session.samples[len - 1];
last.screen_position.x - prev.screen_position.x,
last.screen_position.y - prev.screen_position.y,
/// Get the window position that was stored when the current input session
/// started (i.e. on mouse-down). Titlebar drag callbacks use this
/// together with `get_drag_delta_screen()` to compute the new window position.
pub fn get_window_position_at_session_start(&self) -> Option<WindowPosition> {
Some(session.window_position_at_start)
// ========================================================================
// UNIFIED DRAG CONTEXT API (NEW)
/// Get the active drag context (if any)
pub const fn get_drag_context(&self) -> Option<&DragContext> {
self.active_drag.as_ref()
/// Get the active drag context mutably (if any)
pub const fn get_drag_context_mut(&mut self) -> Option<&mut DragContext> {
self.active_drag.as_mut()
// NOTE: text-selection and scrollbar-thumb drags do NOT flow through this
// manager's `active_drag`. Text selection is driven by `MultiCursorState`
// (managers/selection.rs) and scrollbar dragging by `ScrollbarDragState`
// (window.rs, set in common/event.rs). The former `activate_text_selection_drag`
// / `activate_scrollbar_drag` constructors here were dead duplicates of those
// paths (zero callers) and were removed.
/// Activate a node drag-and-drop
/// Record the node a drag gesture started on (the press target). The dll
/// resolves it once when the first `DragStart` fires. See the field doc.
pub const fn set_drag_source_node(&mut self, node: azul_core::dom::DomNodeId) {
self.drag_source_node = azul_core::dom::OptionDomNodeId::Some(node);
/// The node the current drag gesture began on, if a drag is active
/// (`None` once the button releases, so a stale source is never reused).
pub fn drag_source_node(&self) -> Option<azul_core::dom::DomNodeId> {
if self.active_drag.is_some() {
self.drag_source_node.into_option()
pub fn activate_node_drag(
dom_id: DomId,
node_id: NodeId,
drag_data: DragData,
_start_hit_test: Option<HitTest>,
if let Some(detected) = self.detect_drag() {
self.active_drag = Some(DragContext::node_drag(
dom_id,
node_id,
detected.start_position,
drag_data,
detected.session_id,
));
/// Activate a window move drag (titlebar)
pub fn activate_window_drag(
initial_window_position: WindowPosition,
self.active_drag = Some(DragContext::window_move(
initial_window_position,
// NOTE: OS file drops are tracked by `FileDropManager` (managers/file_drop.rs),
// not by this manager's `active_drag`. The former `start_file_drop` constructor
// here was a dead duplicate (zero callers) and was removed.
/// Update positions for active drag (call on mouse move)
pub const fn update_active_drag_positions(&mut self, position: LogicalPosition) {
if let Some(ref mut drag) = self.active_drag {
drag.update_position(position);
/// Update drop target for node or file drag
pub fn update_drop_target(&mut self, target: Option<azul_core::dom::DomNodeId>) {
match &mut drag.drag_type {
ActiveDragType::Node(ref mut node_drag) => {
node_drag.current_drop_target = target.into();
ActiveDragType::FileDrop(ref mut file_drop) => {
file_drop.drop_target = target.into();
_ => {}
/// End the current drag and return the context
pub const fn end_drag(&mut self) -> Option<DragContext> {
self.active_drag.take()
/// Cancel the current drag
pub fn cancel_drag(&mut self) {
drag.cancelled = true;
self.active_drag = None;
self.drag_source_node = azul_core::dom::OptionDomNodeId::None;
// QUERY METHODS
/// Check if any drag operation is in progress
pub const fn is_dragging(&self) -> bool {
self.active_drag.is_some()
/// Check if a text selection drag is active
pub fn is_text_selection_dragging(&self) -> bool {
self.active_drag
.as_ref()
.is_some_and(DragContext::is_text_selection)
/// Check if a scrollbar thumb drag is active
pub fn is_scrollbar_dragging(&self) -> bool {
.is_some_and(DragContext::is_scrollbar_thumb)
/// Check if a node drag is active
pub fn is_node_drag_active(&self) -> bool {
.is_some_and(DragContext::is_node_drag)
/// Check if a specific node is being dragged
pub fn is_node_dragging(&self, dom_id: DomId, node_id: NodeId) -> bool {
self.active_drag.as_ref().is_some_and(|d| {
d.as_node_drag()
.is_some_and(|node_drag| node_drag.dom_id == dom_id && node_drag.node_id == node_id)
/// Check if window drag is active
pub fn is_window_dragging(&self) -> bool {
.is_some_and(DragContext::is_window_move)
/// Check if file drop is active
pub fn is_file_dropping(&self) -> bool {
.is_some_and(DragContext::is_file_drop)
/// Get number of active input sessions
pub const fn session_count(&self) -> usize {
self.input_sessions.len()
/// Get current session ID (if any)
pub fn current_session_id(&self) -> Option<u64> {
self.get_current_session().map(|s| s.session_id)
// WINDOW DRAG HELPER METHODS
/// Calculate window position delta from current drag state
/// Returns (`delta_x`, `delta_y`) to apply to window position.
/// Returns None if no window drag is active or drag hasn't moved.
#[allow(clippy::cast_possible_truncation)] // bounded layout/render numeric cast
pub fn get_window_drag_delta(&self) -> Option<(i32, i32)> {
let drag = self.active_drag.as_ref()?.as_window_move()?;
let delta_x = drag.current_position.x - drag.start_position.x;
let delta_y = drag.current_position.y - drag.start_position.y;
match drag.initial_window_position {
WindowPosition::Initialized(_initial_pos) => Some((delta_x as i32, delta_y as i32)),
_ => None,
/// Get the new window position based on current drag
/// Returns the absolute window position to set.
pub fn get_window_position_from_drag(&self) -> Option<WindowPosition> {
WindowPosition::Initialized(initial_pos) => {
Some(WindowPosition::Initialized(PhysicalPositionI32::new(
initial_pos.x + delta_x as i32,
initial_pos.y + delta_y as i32,
)))
/// Calculate the new scroll offset for scrollbar thumb drag
pub fn get_scrollbar_scroll_offset(&self) -> Option<f32> {
.as_ref()?
.calculate_scrollbar_scroll_offset()
impl crate::managers::NodeIdRemap for GestureAndDragManager {
/// Remap `NodeIds` in the active drag context after DOM reconciliation.
/// When the DOM is regenerated during an active drag, `NodeIds` change.
/// If a critical `NodeId` was unmounted, the drag is cancelled (an active
/// drag whose source node no longer exists cannot be completed).
fn remap_node_ids(&mut self, dom_id: DomId, map: &crate::managers::NodeIdMap) {
if !drag.remap_node_ids(dom_id, map.as_btree_map()) {
// Critical node removed — cancel the drag
// The drag SOURCE follows its node; an unmounted source ends the
// gesture's targeting (Drag events fall back to the hover node).
if let azul_core::dom::OptionDomNodeId::Some(src) = self.drag_source_node {
if src.dom == dom_id {
self.drag_source_node = src
.node
.into_crate_internal()
.and_then(|n| map.resolve(n))
.map_or(azul_core::dom::OptionDomNodeId::None, |n| {
azul_core::dom::OptionDomNodeId::Some(azul_core::dom::DomNodeId {
dom: src.dom,
node: azul_core::styled_dom::NodeHierarchyItemId::from_crate_internal(
Some(n),
),
#[cfg(test)]
mod touch_session_tests {
use azul_core::task::{Instant as TestInstant, SystemTick};
use super::*;
/// A timestamp `n` MILLISECONDS from the origin.
/// This used to build `Tick(n)` while every caller named its argument
/// `hold_ms` / `gap_ms`. That was harmless only while a tick was assumed to
/// be one millisecond; once `duration_to_millis` started converting ticks at
/// the real frame rate (~16.67 ms), every gesture threshold in this module —
/// double-click window, long-press time, swipe velocity — was being compared
/// against a duration 16x longer than the test meant, and six tests failed.
/// These tests are about gesture SEMANTICS, not about the tick/ms constant,
/// so they express time in the same unit the thresholds use.
/// `duration_to_millis_*` still pins the conversion itself.
fn ts(n: u64) -> CoreInstant {
// `Instant::System` wraps a real std Instant, so "n ms from the origin"
// needs a STABLE origin — a fresh `now()` per call would make ts(0) and
// ts(20) differ by however long the test took, not by 20 ms. One
// process-wide base keeps every difference exact.
use std::sync::OnceLock;
static BASE: OnceLock<std::time::Instant> = OnceLock::new();
let base = *BASE.get_or_init(std::time::Instant::now);
(base + core::time::Duration::from_millis(n)).into()
fn pos(x: f32, y: f32) -> LogicalPosition {
LogicalPosition { x, y }
#[test]
fn two_fingers_open_two_concurrent_sessions() {
let mut m = GestureAndDragManager::new();
m.touch_down(
1,
pos(100.0, 100.0),
ts(0),
WindowPosition::Uninitialized,
2,
pos(200.0, 100.0),
ts(1),
assert_eq!(m.input_sessions.len(), 2);
assert!(!m.input_sessions[0].ended);
assert!(!m.input_sessions[1].ended);
fn moves_land_in_the_correct_session_not_the_last_one() {
// Move finger 1 — the FIRST session must receive the sample even
// though session 2 is the most recent (record_input_sample would
// have corrupted session 2 here).
assert!(m.touch_move(1, pos(90.0, 100.0), ts(2), pos(90.0, 100.0)));
assert_eq!(
m.input_sessions[0].samples.len(),
"finger 1 session grew"
m.input_sessions[1].samples.len(),
"finger 2 session untouched"
fn spread_gesture_is_detected_as_pinch_out() {
// Spread: initial distance 100 → current distance 200.
m.touch_move(1, pos(50.0, 100.0), ts(2), pos(50.0, 100.0));
m.touch_move(2, pos(250.0, 100.0), ts(3), pos(250.0, 100.0));
let pinch = m
.detect_pinch()
.expect("two concurrent touch sessions must yield a pinch");
assert!(
pinch.scale > 1.5,
"spread must read as pinch-out (scale {}), initial {} current {}",
pinch.scale,
pinch.initial_distance,
pinch.current_distance
fn touch_up_ends_only_its_own_session() {
m.touch_up(1, pos(100.0, 100.0), ts(2), pos(100.0, 100.0));
assert!(m.input_sessions[0].ended);
// Further moves for the lifted finger are ignored.
assert!(!m.touch_move(1, pos(0.0, 0.0), ts(3), pos(0.0, 0.0)));
#[allow(clippy::float_cmp, clippy::unreadable_literal)]
mod autotest_generated {
drag::ScrollbarAxis,
geom::PhysicalPositionI32,
styled_dom::NodeHierarchyItemId,
task::{SystemTick, SystemTickDiff, SystemTimeDiff},
// ---------------------------------------------------------------- helpers
/// Tick-based instant: 1 tick == 1 ms for `duration_to_millis`.
/// A timestamp `n` MILLISECONDS from the origin — see the note on the other
/// `ts` in this file.
/// A sample with window-local == screen position (the common mouse case).
fn sample(x: f32, y: f32, tick: u64) -> InputSample {
InputSample {
position: pos(x, y),
screen_position: pos(x, y),
timestamp: ts(tick),
button_state: 0x01,
event_id: 0,
/// A synthetic *ended* session — the only way to build a >2-click history,
/// because `start_input_session` prunes all but the newest ended session.
fn ended_session(session_id: u64, samples: Vec<InputSample>) -> InputSession {
InputSession {
samples,
ended: true,
window_position_at_start: WindowPosition::Uninitialized,
/// Press at `from`, move to `to`, `hold_ms` apart — a session that
/// `detect_drag` will accept (distance permitting).
fn dragging_manager(
from: LogicalPosition,
to: LogicalPosition,
hold_ms: u64,
) -> GestureAndDragManager {
m.start_input_session(from, ts(0), 0x01, WindowPosition::Uninitialized, from);
let recorded = m.record_input_sample(to, ts(hold_ms), 0x01, to);
assert!(recorded);
m
// ------------------------------------------------- duration_to_millis (private)
fn duration_to_millis_tick_zero_and_max_do_not_panic() {
duration_to_millis(CoreDuration::Tick(SystemTickDiff { tick_diff: 0 })),
duration_to_millis(CoreDuration::Tick(SystemTickDiff {
tick_diff: u64::MAX
})),
u64::MAX
/// A tick is a FRAME, so it converts at the nominal frame rate. Returning the
/// raw tick count made every gesture threshold read a 16x-too-small number of
/// milliseconds — a 60-frame hold looked like 60ms, well under any
/// long-press threshold.
fn duration_to_millis_converts_ticks_at_the_nominal_frame_rate() {
duration_to_millis(CoreDuration::Tick(SystemTickDiff { tick_diff: 60 })),
1_000
duration_to_millis(CoreDuration::Tick(SystemTickDiff { tick_diff: 30 })),
500
duration_to_millis(CoreDuration::Tick(SystemTickDiff { tick_diff: 1 })),
16
fn duration_to_millis_system_zero_and_sub_millisecond_floor() {
duration_to_millis(CoreDuration::System(SystemTimeDiff { secs: 0, nanos: 0 })),
// 999_999 ns is under a millisecond => floors to 0, never rounds up.
duration_to_millis(CoreDuration::System(SystemTimeDiff {
secs: 0,
nanos: 999_999
secs: 2,
nanos: 500_000_000
2500
fn duration_to_millis_system_max_truncates_instead_of_panicking() {
// as_millis() is u128 and would be MAX*1000+999; the `as u64` cast
// truncates rather than panicking or saturating. Lock the exact value
// so a change to saturating semantics is caught.
let d = CoreDuration::System(SystemTimeDiff {
secs: u64::MAX,
nanos: 999_999_999,
let expected = ((u64::MAX as u128) * 1000 + 999) as u64;
assert_eq!(duration_to_millis(d), expected);
// ------------------------------------------------- TabletPadState::express_key
fn express_key_out_of_range_index_is_false_not_a_shift_overflow() {
// 1u32 << 32 would panic in debug; the `index < 32` guard must short-circuit.
let pad = TabletPadState {
express_keys: u32::MAX,
// Pad controls this site does not set; growing the struct
// must not break every construction of it.
..Default::default()
assert!(pad.express_key(31));
assert!(!pad.express_key(32));
assert!(!pad.express_key(33));
assert!(!pad.express_key(u32::MAX));
fn express_key_default_pad_has_no_keys_held() {
let pad = TabletPadState::default();
for i in 0..40u32 {
!pad.express_key(i),
"bit {i} must be unset on a default pad"
fn express_key_bitset_round_trips_every_bit() {
for bit in 0..32u32 {
express_keys: 1u32 << bit,
for probe in 0..32u32 {
pad.express_key(probe),
probe == bit,
"encode bit {bit} -> decode probe {probe}"
// ------------------------------------------------- InputSession
fn input_session_new_holds_its_construction_invariants() {
let s = InputSession::new(
u64::MAX,
sample(1.0, 2.0, 7),
WindowPosition::Initialized(PhysicalPositionI32::new(-5, 9)),
assert_eq!(s.session_id, u64::MAX);
assert!(!s.ended);
assert_eq!(s.samples.len(), 1);
assert_eq!(s.first_sample(), s.last_sample());
s.window_position_at_start,
WindowPosition::Initialized(PhysicalPositionI32::new(-5, 9))
assert_eq!(s.total_distance(), 0.0);
assert_eq!(s.direct_distance(), Some(0.0));
assert_eq!(s.duration_ms(), Some(0));
fn empty_session_getters_return_none_instead_of_panicking() {
let s = InputSession {
samples: Vec::new(),
session_id: 0,
assert!(s.first_sample().is_none());
assert!(s.last_sample().is_none());
assert!(s.duration_ms().is_none());
assert!(s.direct_distance().is_none());
fn duration_ms_saturates_to_zero_when_time_runs_backwards() {
// last sample is *earlier* than the first (reordered / skewed clock).
samples: vec![sample(0.0, 0.0, 900), sample(0.0, 0.0, 100)],
session_id: 1,
fn duration_ms_with_mismatched_instant_kinds_is_zero() {
// Both variants are named EXPLICITLY. This used to lean on `sample()`
// happening to produce a Tick, so when `ts()` moved to System the
// "mismatch" quietly became System-vs-System and the test asserted
// nothing — it measured 4997 ms and expected 0. An invariant about
// mismatched kinds must construct both kinds itself.
let mut first = sample(0.0, 0.0, 0);
first.timestamp = CoreInstant::now(); // System variant
let mut last = sample(0.0, 0.0, 5_000);
last.timestamp = CoreInstant::Tick(SystemTick::new(5_000)); // Tick variant
samples: vec![first, last],
fn total_distance_sums_the_path_while_direct_distance_is_the_chord() {
samples: vec![
sample(0.0, 0.0, 0),
sample(3.0, 0.0, 1),
sample(3.0, 4.0, 2),
],
assert_eq!(s.total_distance(), 7.0);
assert_eq!(s.direct_distance(), Some(5.0));
fn distances_with_nan_coordinates_are_nan_and_do_not_panic() {
samples: vec![sample(0.0, 0.0, 0), sample(f32::NAN, f32::NAN, 1)],
assert!(s.total_distance().is_nan());
assert!(s.direct_distance().is_some_and(f32::is_nan));
fn distances_at_f32_extremes_saturate_to_infinity_instead_of_panicking() {
sample(-f32::MAX, -f32::MAX, 0),
sample(f32::MAX, f32::MAX, 1),
assert!(s.total_distance().is_infinite());
assert!(s.direct_distance().is_some_and(f32::is_infinite));
// ------------------------------------------------- construction
fn new_manager_is_inert_and_every_detector_is_quiet() {
let m = GestureAndDragManager::new();
assert_eq!(m.session_count(), 0);
assert_eq!(m.debug_counts(), (0, 0));
assert!(m.current_session_id().is_none());
assert!(m.get_current_session().is_none());
assert!(m.get_current_mouse_position().is_none());
assert!(m.get_pen_state().is_none());
assert!(m.get_previous_pen_state().is_none());
assert!(m.get_pad_state().is_none());
assert!(m.get_drag_context().is_none());
assert!(m.detect_drag().is_none());
assert!(m.detect_long_press().is_none());
assert!(!m.detect_double_click());
assert!(m.get_drag_direction().is_none());
assert!(m.get_gesture_velocity().is_none());
assert!(!m.is_swipe());
assert!(m.detect_swipe_direction().is_none());
assert!(m.detect_pinch().is_none());
assert!(m.detect_rotation().is_none());
assert!(m.get_drag_delta().is_none());
assert!(m.get_drag_delta_screen().is_none());
assert!(m.get_drag_delta_screen_incremental().is_none());
assert!(m.get_window_position_at_session_start().is_none());
assert!(m.get_window_drag_delta().is_none());
assert!(m.get_window_position_from_drag().is_none());
assert!(m.get_scrollbar_scroll_offset().is_none());
assert!(!m.is_dragging());
assert!(!m.is_text_selection_dragging());
assert!(!m.is_scrollbar_dragging());
assert!(!m.is_node_drag_active());
assert!(!m.is_window_dragging());
assert!(!m.is_file_dropping());
assert!(!m.is_node_dragging(DomId::ROOT_ID, NodeId::ZERO));
// Documented default for "no history at all".
assert_eq!(m.detect_click_count(), 1);
assert_eq!(m, GestureAndDragManager::default());
fn with_config_keeps_extreme_thresholds_verbatim_and_still_starts_at_session_1() {
let cfg = GestureDetectionConfig {
drag_distance_threshold: f32::NAN,
double_click_time_threshold_ms: u64::MAX,
double_click_distance_threshold: f32::INFINITY,
long_press_time_threshold_ms: 0,
long_press_distance_threshold: -1.0,
min_samples_for_gesture: usize::MAX,
swipe_velocity_threshold: 0.0,
pinch_scale_threshold: f32::MAX,
rotation_angle_threshold: -0.0,
sample_cleanup_interval_ms: 0,
let mut m = GestureAndDragManager::with_config(cfg);
assert!(m.config.drag_distance_threshold.is_nan());
assert_eq!(m.config.double_click_time_threshold_ms, u64::MAX);
assert_eq!(m.config.min_samples_for_gesture, usize::MAX);
let id = m.start_input_session(
pos(0.0, 0.0),
0x01,
assert_eq!(id, 1, "with_config must not disturb the session counter");
// min_samples_for_gesture == usize::MAX can never be reached => no drag.
// ------------------------------------------------- session recording
fn session_ids_are_monotonic_starting_at_one() {
for expected in 1..=5u64 {
ts(expected),
assert_eq!(id, expected);
assert_eq!(m.current_session_id(), Some(expected));
m.end_current_session();
fn session_id_counter_at_the_u64_boundary_does_not_overflow() {
m.next_session_id = u64::MAX - 1;
0xFF,
assert_eq!(id, u64::MAX - 1);
assert_eq!(m.next_session_id, u64::MAX);
fn recording_without_or_after_a_session_returns_false() {
assert!(!m.record_input_sample(pos(1.0, 1.0), ts(1), 0x01, pos(1.0, 1.0)));
m.start_input_session(
assert!(m.record_input_sample(pos(1.0, 1.0), ts(1), 0x01, pos(1.0, 1.0)));
assert!(!m.record_input_sample(pos(2.0, 2.0), ts(2), 0x01, pos(2.0, 2.0)));
// Ending twice is idempotent, and ending nothing must not panic.
m.clear_all_sessions();
fn sample_count_stays_bounded_by_max_samples_per_session() {
for i in 1..=(MAX_SAMPLES_PER_SESSION as u64 + 200) {
assert!(m.record_input_sample(pos(i as f32, 0.0), ts(i), 0x01, pos(i as f32, 0.0)));
m.get_current_session().unwrap().samples.len() <= MAX_SAMPLES_PER_SESSION,
"sample buffer grew past MAX_SAMPLES_PER_SESSION at i={i}"
// The newest sample always survives the drain.
let last = m.get_current_mouse_position().unwrap();
assert_eq!(last.x, (MAX_SAMPLES_PER_SESSION + 200) as f32);
fn pen_samples_accept_nan_inf_and_extreme_values() {
let id = m.start_input_session_with_pen(
pos(f32::NAN, f32::INFINITY),
f32::NAN,
(f32::INFINITY, f32::NEG_INFINITY),
(-f32::MAX, f32::MAX),
pos(f32::NEG_INFINITY, f32::NAN),
assert_eq!(id, 1);
assert!(m.record_input_sample_with_pen(
ts(u64::MAX),
0x00,
-1.0e30,
(f32::NAN, f32::NAN),
let session = m.get_current_session().unwrap();
assert_eq!(session.samples.len(), 2);
let first = session.first_sample().unwrap();
assert!(first.pressure.is_nan());
assert!(first.tilt.x_tilt.is_infinite());
assert_eq!(first.button_state, 0xFF);
assert_eq!(first.event_id, u64::MAX);
// ts(u64::MAX) - ts(0) fits: duration_since is a saturating u64 sub.
assert_eq!(session.duration_ms(), Some(u64::MAX));
// NaN/inf coordinates must not make any detector panic. `hypot(NaN, inf)`
// is `+inf` per IEEE-754, so this DOES read as a drag — but only with a
// non-finite distance, never a plausible-looking finite one.
assert!(m
.detect_drag()
.is_none_or(|d| !d.direct_distance.is_finite()));
assert!(m.get_drag_direction().is_some());
fn starting_a_session_prunes_all_but_the_newest_ended_session() {
for tick in [0u64, 10, 20] {
ts(tick),
// Bounded growth: never more than "one ended + one live" session.
assert_eq!(m.session_count(), 2);
assert_eq!(m.input_sessions[0].session_id, 2);
assert_eq!(m.input_sessions[1].session_id, 3);
// KNOWN LIMITATION: because the history is pruned to a single ended
// session, a genuine triple-click through the public API can only ever
// report 2. detect_click_count()'s triple-click arm is unreachable here.
assert_eq!(m.detect_click_count(), 2);
// ------------------------------------------------- touch sessions
fn touch_ids_at_zero_and_u64_max_are_tracked_independently() {
pos(50.0, 0.0),
assert!(m.touch_move(0, pos(1.0, 1.0), ts(2), pos(1.0, 1.0)));
assert!(m.touch_move(u64::MAX, pos(60.0, 0.0), ts(3), pos(60.0, 0.0)));
assert_eq!(m.input_sessions[0].samples.len(), 2);
assert_eq!(m.input_sessions[1].samples.len(), 2);
m.touch_up(0, pos(1.0, 1.0), ts(4), pos(1.0, 1.0));
fn touch_events_for_unknown_ids_are_ignored_without_panicking() {
assert!(!m.touch_move(42, pos(0.0, 0.0), ts(0), pos(0.0, 0.0)));
m.touch_up(42, pos(0.0, 0.0), ts(1), pos(0.0, 0.0));
m.touch_cancel_all(); // nothing to cancel
fn a_repeated_touch_down_for_the_same_id_rebinds_to_the_newest_session() {
7,
pos(9.0, 9.0),
assert_eq!(m.touch_sessions.len(), 1, "the id map must not grow");
assert_eq!(m.touch_sessions.get(&7).copied(), Some(2));
// touch_up ends only the session the id currently maps to; the orphaned
// first session stays open until clear_old_sessions() reaps it.
m.touch_up(7, pos(9.0, 9.0), ts(2), pos(9.0, 9.0));
assert!(m.input_sessions[1].ended);
assert!(m.touch_sessions.is_empty());
fn touch_cancel_all_ends_every_finger_and_empties_the_id_map() {
for id in 0..3u64 {
id,
pos(id as f32 * 10.0, 0.0),
ts(id),
m.touch_cancel_all();
assert!(m.input_sessions.iter().all(|s| s.ended));
assert!(!m.touch_move(1, pos(0.0, 0.0), ts(9), pos(0.0, 0.0)));
fn touch_moves_after_clear_all_sessions_are_dropped_not_resurrected() {
// The id->session map still holds a dangling entry, but the by-id
// lookup finds no session, so nothing is recorded and nothing panics.
assert!(!m.touch_move(1, pos(5.0, 5.0), ts(1), pos(5.0, 5.0)));
fn record_sample_for_session_rejects_unknown_and_ended_sessions() {
assert!(!m.record_sample_for_session(u64::MAX, pos(0.0, 0.0), ts(0), pos(0.0, 0.0)));
assert!(m.record_sample_for_session(id, pos(1.0, 0.0), ts(1), pos(1.0, 0.0)));
assert!(!m.record_sample_for_session(0, pos(1.0, 0.0), ts(1), pos(1.0, 0.0)));
assert!(!m.record_sample_for_session(id, pos(2.0, 0.0), ts(2), pos(2.0, 0.0)));
fn record_sample_for_session_is_also_bounded_by_max_samples() {
for i in 1..=(MAX_SAMPLES_PER_SESSION as u64 + 150) {
assert!(m.touch_move(1, pos(i as f32, 0.0), ts(i), pos(i as f32, 0.0)));
assert!(m.input_sessions[0].samples.len() <= MAX_SAMPLES_PER_SESSION);
// ------------------------------------------------- cleanup
fn clear_old_sessions_reaps_stale_sessions_and_their_long_press_ids() {
let old = m.start_input_session(
m.mark_long_press_callback_invoked(old);
let fresh = m.start_input_session(
ts(10_000),
m.mark_long_press_callback_invoked(fresh);
assert_eq!(m.debug_counts(), (2, 2));
// Now is 10_050 ticks: `old` is 10s stale (> 2000ms), `fresh` is 50ms old.
m.clear_old_sessions(ts(10_050));
assert_eq!(m.session_count(), 1);
assert_eq!(m.current_session_id(), Some(fresh));
m.debug_counts(),
(1, 1),
"long-press bookkeeping must not grow unboundedly"
fn clear_old_sessions_drops_sessions_that_have_no_samples() {
m.input_sessions.push(InputSession {
session_id: 99,
m.clear_old_sessions(ts(0));
fn clear_old_sessions_with_a_backwards_clock_keeps_everything() {
ts(5_000),
// `now` is *before* the sample: duration_since saturates to 0 => age 0.
fn clear_all_sessions_resets_both_counters() {
m.mark_current_long_press_invoked();
assert_eq!(m.debug_counts(), (1, 1));
fn long_press_invocation_marks_are_deduplicated() {
for _ in 0..100 {
m.mark_long_press_callback_invoked(u64::MAX);
m.mark_long_press_callback_invoked(0);
assert_eq!(m.debug_counts(), (0, 2));
// Marking without a session is a no-op, not a panic.
// ------------------------------------------------- drag / long-press detection
fn detect_drag_fires_exactly_at_the_distance_threshold() {
// hypot(3, 4) == 5.0 == drag_distance_threshold => `>=` must fire.
let m = dragging_manager(pos(0.0, 0.0), pos(3.0, 4.0), 20);
let drag = m
.expect("distance == threshold must be a drag");
assert_eq!(drag.direct_distance, 5.0);
assert_eq!(drag.total_distance, 5.0);
assert_eq!(drag.sample_count, 2);
assert_eq!(drag.duration_ms, 20);
assert_eq!(drag.session_id, 1);
assert_eq!(drag.start_position, pos(0.0, 0.0));
assert_eq!(drag.current_position, pos(3.0, 4.0));
// Just below the threshold: no drag.
let m = dragging_manager(pos(0.0, 0.0), pos(4.9, 0.0), 20);
fn detect_drag_with_nan_movement_returns_none() {
let m = dragging_manager(pos(0.0, 0.0), pos(f32::NAN, f32::NAN), 20);
m.detect_drag().is_none(),
"NaN distance is never >= threshold"
fn detect_drag_needs_min_samples_for_gesture() {
pos(500.0, 500.0),
assert!(m.detect_drag().is_none(), "one sample is not a gesture");
fn detect_long_press_honours_time_and_distance_thresholds() {
// Held 500ms (== threshold) without moving => long press.
let m = dragging_manager(pos(10.0, 10.0), pos(10.0, 10.0), 500);
let lp = m.detect_long_press().expect("500ms hold is a long press");
assert_eq!(lp.duration_ms, 500);
assert_eq!(lp.position, pos(10.0, 10.0));
assert!(!lp.callback_invoked);
assert_eq!(lp.session_id, 1);
// One ms short => not yet.
let m = dragging_manager(pos(10.0, 10.0), pos(10.0, 10.0), 499);
// Long enough but moved too far (> 10px).
let m = dragging_manager(pos(0.0, 0.0), pos(11.0, 0.0), 800);
fn detect_long_press_stops_at_button_up_and_after_being_marked() {
let mut m = dragging_manager(pos(10.0, 10.0), pos(10.0, 10.0), 600);
assert!(m.detect_long_press().is_some());
let lp = m.detect_long_press().expect("still held");
lp.callback_invoked,
"a marked long press must report callback_invoked"
m.detect_long_press().is_none(),
"a released button cannot be a long press"
// ------------------------------------------------- click counting
fn detect_double_click_checks_both_timing_and_distance() {
m.input_sessions = vec![
ended_session(1, vec![sample(10.0, 10.0, 0)]),
ended_session(2, vec![sample(11.0, 11.0, 100)]),
];
assert!(m.detect_double_click());
// Too slow (501ms > 500ms).
m.input_sessions[1].samples[0].timestamp = ts(501);
// Fast, but too far apart (>= 5px).
m.input_sessions[1].samples[0].timestamp = ts(100);
m.input_sessions[1].samples[0].position = pos(100.0, 10.0);
// Fast and close, but the second click is still held down.
m.input_sessions[1].samples[0].position = pos(11.0, 11.0);
m.input_sessions[1].ended = false;
fn detect_double_click_needs_two_sessions() {
m.input_sessions = vec![ended_session(1, vec![sample(0.0, 0.0, 0)])];
fn detect_click_count_counts_up_to_three_and_stops_at_the_first_gap() {
// Three ended clicks, each 100ms apart at (nearly) the same point.
ended_session(2, vec![sample(10.0, 11.0, 100)]),
ended_session(3, vec![sample(11.0, 10.0, 200)]),
assert_eq!(m.detect_click_count(), 3);
// Break the middle gap in *time*: only the newest pair counts.
m.input_sessions[2].samples[0].timestamp = ts(900);
// A backwards clock does NOT break the chain: duration_since saturates
// to 0, which reads as "no gap at all" => the click still counts.
m.input_sessions[2].samples[0].timestamp = ts(200);
m.input_sessions[0].samples[0].timestamp = ts(u64::MAX);
// Break the oldest gap in *distance*.
m.input_sessions[0].samples[0].timestamp = ts(0);
m.input_sessions[0].samples[0].position = pos(500.0, 500.0);
fn detect_click_count_ignores_live_sessions_and_defaults_to_one() {
// Only a live (un-ended) session => nothing to count => 1.
assert_eq!(GestureAndDragManager::new().detect_click_count(), 1);
fn detect_click_count_with_empty_sample_vec_does_not_panic() {
ended_session(1, Vec::new()),
ended_session(2, vec![sample(0.0, 0.0, 10)]),
// ------------------------------------------------- direction / velocity / swipe
fn drag_direction_is_deterministic_for_stationary_and_nan_input() {
// No movement at all: dx == dy == 0 => documented fallback is Up.
let m = dragging_manager(pos(5.0, 5.0), pos(5.0, 5.0), 10);
assert_eq!(m.get_drag_direction(), Some(GestureDirection::Up));
// NaN deltas compare false everywhere => same deterministic fallback.
let m = dragging_manager(pos(0.0, 0.0), pos(f32::NAN, f32::NAN), 10);
fn drag_direction_picks_the_dominant_axis() {
let cases = [
(pos(100.0, 1.0), GestureDirection::Right),
(pos(-100.0, 1.0), GestureDirection::Left),
(pos(1.0, 100.0), GestureDirection::Down),
(pos(1.0, -100.0), GestureDirection::Up),
// Perfect diagonal: |dx| > |dy| is false => vertical wins.
(pos(50.0, 50.0), GestureDirection::Down),
for (to, expected) in cases {
let m = dragging_manager(pos(0.0, 0.0), to, 10);
m.get_drag_direction(),
Some(expected),
"drag to ({}, {})",
to.x,
to.y
fn gesture_velocity_returns_none_instead_of_dividing_by_zero() {
// Two samples with the SAME timestamp => duration 0 => no velocity.
let m = dragging_manager(pos(0.0, 0.0), pos(100.0, 0.0), 0);
// A single sample is not enough either.
fn swipe_needs_velocity_above_the_configured_threshold() {
// 60px in 100ms == 600 px/s > 500 px/s.
let fast = dragging_manager(pos(0.0, 0.0), pos(60.0, 0.0), 100);
assert!(fast.get_gesture_velocity().unwrap() > 500.0);
assert!(fast.is_swipe());
assert_eq!(fast.detect_swipe_direction(), Some(GestureDirection::Right));
// 40px in 100ms == 400 px/s < 500 px/s.
let slow = dragging_manager(pos(0.0, 0.0), pos(0.0, -40.0), 100);
assert!(!slow.is_swipe());
assert!(slow.detect_swipe_direction().is_none());
fn gesture_velocity_with_infinite_travel_saturates_to_infinity() {
let m = dragging_manager(pos(-f32::MAX, 0.0), pos(f32::MAX, 0.0), 1);
let v = m.get_gesture_velocity().expect("two samples, 1ms apart");
assert!(v.is_infinite(), "expected saturation to +inf, got {v}");
assert!(m.is_swipe());
// ------------------------------------------------- pinch / rotation
fn pinch_and_rotation_ignore_sequential_mouse_sessions() {
// Click, release, then press-and-drag: two sessions, but the first is
// ended — this must NOT be read as a two-finger gesture.
pos(200.0, 0.0),
ts(10),
m.record_input_sample(pos(400.0, 0.0), ts(20), 0x01, pos(400.0, 0.0));
m.detect_pinch().is_none(),
"an ended session is not a finger"
fn pinch_returns_none_when_the_fingers_start_on_top_of_each_other() {
pos(100.5, 100.0),
// initial_distance 0.5 < 1.0 => division guard returns None.
m.touch_move(1, pos(0.0, 100.0), ts(2), pos(0.0, 100.0));
fn pinch_below_the_scale_threshold_is_not_reported() {
// 100px -> 105px is a 5% change; the threshold is 10%.
m.touch_move(2, pos(205.0, 100.0), ts(2), pos(205.0, 100.0));
fn pinch_in_reports_a_scale_below_one() {
m.touch_move(1, pos(50.0, 0.0), ts(10), pos(50.0, 0.0));
m.touch_move(2, pos(150.0, 0.0), ts(11), pos(150.0, 0.0));
let p = m.detect_pinch().expect("200px -> 100px is a pinch in");
assert_eq!(p.initial_distance, 200.0);
assert_eq!(p.current_distance, 100.0);
assert_eq!(p.scale, 0.5);
assert_eq!(p.center, pos(100.0, 0.0));
assert_eq!(p.duration_ms, 10);
fn pinch_with_infinite_coordinates_saturates_instead_of_panicking() {
pos(10.0, 0.0),
// The spread overflows f32: MAX - (-MAX) == +inf.
m.touch_move(1, pos(-f32::MAX, 0.0), ts(2), pos(-f32::MAX, 0.0));
m.touch_move(2, pos(f32::MAX, 0.0), ts(3), pos(f32::MAX, 0.0));
let p = m
.expect("an overflowing spread is still a pinch");
!p.scale.is_finite(),
"expected a saturated (non-finite) scale, got {}",
p.scale
assert!(!p.scale.is_nan());
fn pinch_and_rotation_with_nan_coordinates_never_panic() {
pos(f32::NAN, f32::NAN),
// Whatever the detectors decide, they must not produce a *finite*
// (i.e. plausible-looking but garbage) scale or angle from NaN input.
assert!(m.detect_pinch().is_none_or(|p| !p.scale.is_finite()));
.detect_rotation()
.is_none_or(|r| !r.angle_radians.is_finite()));
fn rotation_normalisation_terminates_for_extreme_coordinates() {
// The angle-wrap `while` loops must not spin: atan2 is bounded to
// [-PI, PI], so angle_diff can never be infinite.
pos(-f32::MAX, -f32::MAX),
pos(f32::MAX, f32::MAX),
m.touch_move(2, pos(-f32::MAX, f32::MAX), ts(2), pos(0.0, 0.0));
let r = m.detect_rotation();
assert!(r.is_none_or(|r| r.angle_radians.abs() <= core::f32::consts::PI + 1.0e-4));
fn rotation_reports_the_signed_angle_between_the_two_fingers() {
// Finger 2 swings from +x (angle 0) to +y (angle PI/2) around finger 1.
m.touch_move(2, pos(0.0, 10.0), ts(50), pos(0.0, 10.0));
let r = m.detect_rotation().expect("a quarter turn is a rotation");
(r.angle_radians - core::f32::consts::FRAC_PI_2).abs() < 1.0e-4,
"expected ~PI/2, got {}",
r.angle_radians
assert_eq!(r.center, pos(0.0, 5.0));
fn rotation_below_the_angle_threshold_is_not_reported() {
pos(1000.0, 0.0),
// ~0.05 rad, under the 0.1 rad threshold.
m.touch_move(2, pos(1000.0, 50.0), ts(2), pos(1000.0, 50.0));
// ------------------------------------------------- native gesture override
fn injected_native_gestures_win_over_the_in_process_detector() {
m.inject_native_gesture(NativeGestureEvent::DoubleClick);
assert!(m.detect_double_click(), "no sessions, but the OS said so");
m.clear_native_gesture();
let lp = DetectedLongPress {
position: pos(3.0, 4.0),
duration_ms: u64::MAX,
callback_invoked: true,
session_id: u64::MAX,
m.inject_native_gesture(NativeGestureEvent::LongPress(lp));
assert_eq!(m.detect_long_press(), Some(lp));
m.inject_native_gesture(NativeGestureEvent::Swipe(GestureDirection::Left));
assert_eq!(m.detect_swipe_direction(), Some(GestureDirection::Left));
!m.is_swipe(),
"is_swipe() is velocity-only and ignores the native override"
let pinch = DetectedPinch {
scale: f32::INFINITY,
center: pos(0.0, 0.0),
initial_distance: 0.0,
current_distance: f32::NAN,
duration_ms: 0,
m.inject_native_gesture(NativeGestureEvent::Pinch(pinch));
let got = m.detect_pinch().expect("native pinch is passed through");
assert!(got.scale.is_infinite());
let rot = DetectedRotation {
angle_radians: -core::f32::consts::PI,
center: pos(1.0, 1.0),
duration_ms: 7,
m.inject_native_gesture(NativeGestureEvent::Rotation(rot));
assert_eq!(m.detect_rotation(), Some(rot));
// ------------------------------------------------- pen / pad state
fn pen_state_stores_extremes_verbatim_and_tracks_the_previous_state() {
m.update_pen_state(
pos(1.0, 2.0),
true,
assert!(m.pen_event_pending);
let pen = *m.get_pen_state().expect("pen state was just set");
assert!(pen.pressure.is_nan());
assert!(pen.tilt.x_tilt.is_infinite());
assert!(pen.tilt.y_tilt.is_infinite());
assert!(pen.in_contact && pen.is_eraser && pen.barrel_button_pressed);
assert_eq!(pen.device_id, u64::MAX);
// The short form must zero the extended axes.
assert_eq!(pen.tangential_pressure, 0.0);
assert_eq!(pen.barrel_roll_rad, 0.0);
assert_eq!(pen.tool_id, 0);
m.clear_pen_event_pending();
assert!(!m.pen_event_pending);
m.update_pen_state_full(
1.0,
(0.0, 0.0),
false,
-f32::MAX,
u32::MAX,
let prev = *m.get_previous_pen_state().expect("previous pen state kept");
assert_eq!(prev.device_id, u64::MAX);
let now = *m.get_pen_state().unwrap();
assert!(now.tangential_pressure.is_nan());
assert_eq!(now.barrel_roll_rad, -f32::MAX);
assert_eq!(now.tool_id, u32::MAX);
m.clear_pen_state();
m.get_previous_pen_state().map(|p| p.tool_id),
Some(u32::MAX)
// Clearing twice must not panic and must not resurrect a state.
fn pad_state_round_trips_and_clears() {
m.update_pad_state(TabletPadState {
express_keys: 0b1010,
touch_ring: f32::NAN,
touch_ring_active: true,
device_id: u64::MAX,
let pad = *m.get_pad_state().expect("pad state was just set");
assert!(!pad.express_key(0));
assert!(pad.express_key(1));
assert!(!pad.express_key(2));
assert!(pad.express_key(3));
assert!(pad.touch_ring.is_nan());
assert_eq!(pad.device_id, u64::MAX);
m.clear_pad_state();
// ------------------------------------------------- drag deltas
fn drag_deltas_use_window_local_and_screen_coordinates_independently() {
pos(10.0, 10.0),
WindowPosition::Initialized(PhysicalPositionI32::new(100, 100)),
pos(110.0, 110.0),
// One sample: totals exist, but there is no *incremental* delta yet.
assert_eq!(m.get_drag_delta(), Some((0.0, 0.0)));
assert_eq!(m.get_drag_delta_screen(), Some((0.0, 0.0)));
m.record_input_sample(pos(15.0, 10.0), ts(10), 0x01, pos(120.0, 130.0));
m.record_input_sample(pos(20.0, 10.0), ts(20), 0x01, pos(125.0, 132.0));
assert_eq!(m.get_drag_delta(), Some((10.0, 0.0)));
assert_eq!(m.get_drag_delta_screen(), Some((15.0, 22.0)));
assert_eq!(m.get_drag_delta_screen_incremental(), Some((5.0, 2.0)));
m.get_window_position_at_session_start(),
100, 100
assert_eq!(m.get_current_mouse_position(), Some(pos(20.0, 10.0)));
fn drag_deltas_at_f32_extremes_stay_finite_or_saturate() {
let m = dragging_manager(pos(-f32::MAX, -f32::MAX), pos(f32::MAX, f32::MAX), 5);
let (dx, dy) = m.get_drag_delta().expect("two samples");
assert!(dx.is_infinite() && dy.is_infinite());
let (sx, sy) = m.get_drag_delta_screen().expect("two samples");
assert!(sx.is_infinite() && sy.is_infinite());
// ------------------------------------------------- unified drag context
fn activating_a_node_drag_without_a_detected_drag_is_a_no_op() {
// No session at all.
m.activate_node_drag(DomId::ROOT_ID, NodeId::new(1), DragData::new(), None);
// A session that has not moved far enough to be a drag.
let mut m = dragging_manager(pos(0.0, 0.0), pos(1.0, 1.0), 10);
m.activate_window_drag(WindowPosition::Uninitialized, None);
fn node_drag_context_tracks_its_own_node_and_drop_target() {
let mut m = dragging_manager(pos(0.0, 0.0), pos(100.0, 0.0), 10);
let mut data = DragData::new();
data.set_text("payload");
m.activate_node_drag(DomId::ROOT_ID, NodeId::new(4), data, None);
assert!(m.is_dragging());
assert!(m.is_node_drag_active());
assert!(m.is_node_dragging(DomId::ROOT_ID, NodeId::new(4)));
assert!(!m.is_node_dragging(DomId::ROOT_ID, NodeId::new(5)));
assert!(!m.is_node_dragging(DomId { inner: 7 }, NodeId::new(4)));
m.update_active_drag_positions(pos(42.0, -7.0));
m.get_drag_context().unwrap().current_position(),
pos(42.0, -7.0)
m.update_drop_target(Some(azul_core::dom::DomNodeId {
dom: DomId::ROOT_ID,
node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(9))),
}));
let nd = m
.get_drag_context()
.and_then(DragContext::as_node_drag)
.expect("node drag");
nd.current_drop_target
.into_option()
.and_then(|t| t.node.into_crate_internal()),
Some(NodeId::new(9))
assert_eq!(nd.drag_data.get_data("text/plain"), Some(&b"payload"[..]));
// Clearing the target back to None must work too.
m.update_drop_target(None);
.unwrap()
.current_drop_target
.is_none());
let ctx = m.end_drag().expect("the drag context is returned");
assert_eq!(ctx.session_id, 1);
assert!(m.end_drag().is_none());
fn drop_target_updates_without_a_drag_do_not_panic() {
m.update_active_drag_positions(pos(f32::NAN, f32::INFINITY));
m.cancel_drag();
assert!(m.get_drag_context_mut().is_none());
fn a_text_selection_drag_is_not_a_node_drag() {
m.active_drag = Some(DragContext::text_selection(
DomId::ROOT_ID,
NodeId::new(2),
11,
assert!(m.is_text_selection_dragging());
// update_drop_target must leave a text-selection drag untouched.
// ------------------------------------------------- window drag maths
fn window_dragging_manager(initial: WindowPosition) -> GestureAndDragManager {
m.activate_window_drag(initial, None);
assert!(m.is_window_dragging());
fn window_drag_delta_needs_an_initialized_window_position() {
let m = window_dragging_manager(WindowPosition::Uninitialized);
fn window_drag_delta_is_measured_from_the_drag_start() {
let mut m = window_dragging_manager(WindowPosition::Initialized(PhysicalPositionI32::new(
10, 20,
)));
m.update_active_drag_positions(pos(30.5, -20.9));
// start_position is the drag's start (0,0) => delta truncates toward zero.
assert_eq!(m.get_window_drag_delta(), Some((30, -20)));
m.get_window_position_from_drag(),
Some(WindowPosition::Initialized(PhysicalPositionI32::new(40, 0)))
fn window_drag_delta_saturates_the_float_to_int_cast() {
let mut m =
window_dragging_manager(WindowPosition::Initialized(PhysicalPositionI32::new(0, 0)));
m.update_active_drag_positions(pos(f32::MAX, -f32::MAX));
m.get_window_drag_delta(),
Some((i32::MAX, i32::MIN)),
"float->int casts must saturate, not wrap or trap"
i32::MAX,
i32::MIN
fn window_drag_delta_with_nan_position_is_zero_not_a_trap() {
window_dragging_manager(WindowPosition::Initialized(PhysicalPositionI32::new(3, 4)));
m.update_active_drag_positions(pos(f32::NAN, f32::NAN));
// `NaN as i32` is defined as 0 in Rust.
assert_eq!(m.get_window_drag_delta(), Some((0, 0)));
Some(WindowPosition::Initialized(PhysicalPositionI32::new(3, 4)))
fn window_position_from_drag_at_the_i32_extremes_does_not_overflow() {
// i32::MAX window origin dragged fully negative: MAX + MIN == -1.
m.update_active_drag_positions(pos(-f32::MAX, -f32::MAX));
-1, -1
// ------------------------------------------------- scrollbar drag maths
fn scrollbar_manager(
start_offset: f32,
track: f32,
content: f32,
viewport: f32,
m.active_drag = Some(DragContext::scrollbar_thumb(
NodeId::new(1),
ScrollbarAxis::Vertical,
start_offset,
track,
content,
viewport,
fn scrollbar_offset_scales_the_mouse_delta_and_clamps_to_the_range() {
let mut m = scrollbar_manager(0.0, 100.0, 1000.0, 100.0);
assert!(m.is_scrollbar_dragging());
assert_eq!(m.get_scrollbar_scroll_offset(), Some(0.0));
// thumb = 10px, scrollable track = 90px, scrollable range = 900px.
m.update_active_drag_positions(pos(0.0, 45.0));
let half = m.get_scrollbar_scroll_offset().expect("scrollbar drag");
assert!((half - 450.0).abs() < 0.5, "expected ~450, got {half}");
// Way past the end of the track: clamped to the scrollable range.
m.update_active_drag_positions(pos(0.0, 1.0e9));
assert_eq!(m.get_scrollbar_scroll_offset(), Some(900.0));
// Dragged backwards past the start: clamped to 0.
m.update_active_drag_positions(pos(0.0, -1.0e9));
fn scrollbar_offset_with_nothing_to_scroll_returns_the_start_offset() {
// content <= viewport => scrollable range <= 0.
let mut m = scrollbar_manager(42.0, 100.0, 50.0, 100.0);
m.update_active_drag_positions(pos(0.0, 500.0));
assert_eq!(m.get_scrollbar_scroll_offset(), Some(42.0));
// A zero-length track cannot be scrolled either.
let mut m = scrollbar_manager(7.0, 0.0, 1000.0, 100.0);
assert_eq!(m.get_scrollbar_scroll_offset(), Some(7.0));
fn scrollbar_offset_with_a_nan_mouse_position_does_not_panic() {
let v = m.get_scrollbar_scroll_offset();
v.is_some_and(f32::is_nan),
"a NaN mouse position must propagate as NaN, not panic: {v:?}"
// ------------------------------------------------- event ids
fn allocate_event_id_is_strictly_monotonic() {
let a = allocate_event_id();
let b = allocate_event_id();
let c = allocate_event_id();
assert!(a < b && b < c, "ids must increase: {a} {b} {c}");
fn allocate_event_id_is_zero_without_std() {
assert_eq!(allocate_event_id(), 0);
fn recorded_samples_get_distinct_event_ids() {
m.record_input_sample(pos(1.0, 0.0), ts(1), 0x01, pos(1.0, 0.0));
let s = m.get_current_session().unwrap();
assert_ne!(s.samples[0].event_id, s.samples[1].event_id);
assert!(s.samples[0].event_id < s.samples[1].event_id);
/// One rotary control — a dial, wheel or crown.
/// Four platforms converged on the same primitive independently: Microsoft's
/// `RadialController` (the Surface Dial), Wayland's `zwp_tablet_pad_dial_v2`,
/// Android's `SOURCE_ROTARY_ENCODER` (a Wear crown) and the Apple Digital
/// Crown. One type covers all four because they agree on what a dial is.
/// Rotation is a DELTA, not a position, and that is the defining property: a
/// dial has no endstops, so there is no absolute angle to report and no
/// meaningful zero to return to. An app integrates the deltas into whatever
/// value it is controlling.
pub struct DialState {
/// Which dial, when a device has more than one. `0` = unidentified.
/// Rotation since the last frame, in radians. Positive is clockwise.
pub delta_rad: f32,
/// Detents crossed since the last frame, for a dial with physical
/// clicks. `0.0` on a smooth dial. Fractional on a high-resolution one,
/// for the same reason `axis_value120` is.
pub detent_count: f32,
/// Whether the dial is currently pressed. Surface Dial and most crowns
/// click; a tablet pad dial usually does not.
pub pressed: bool,
/// Where the dial sits on screen, when it is ON the screen.
/// Only the Surface Dial on a Surface Studio reports this — the device is
/// physically placed on the display and the OS gives its contact point, so
/// an app can draw a radial menu around it. `None` everywhere else,
/// including for the same Dial used off-screen.
pub contact_position: azul_core::geom::OptionLogicalPosition,
impl_option!(DialState, OptionDialState, [Debug, Clone, Copy, PartialEq]);
/// Yields `DialRotate` / `DialClick` for the dial.
/// `DialState` has been readable through `CallbackInfo::get_dial_state()`
/// since the type landed, and there was no event to subscribe to — so an app
/// could only POLL it from an unrelated callback that happened to run. This is
/// the producer that makes the filters reachable.
/// Both are WINDOW-scoped (`DomNodeId::ROOT`). Only a Surface Dial placed on a
/// Surface Studio's display reports a contact point; every other dial — a
/// tablet pad's, a Wear crown, a Digital Crown — is used off-screen, so there
/// is no node under it and the window is the only honest target. The Hover
/// filters still receive it by propagation from the root.
impl azul_core::events::EventProvider for GestureAndDragManager {
fn get_pending_events(
&self,
timestamp: azul_core::task::Instant,
) -> Vec<azul_core::events::SyntheticEvent> {
dom::DomNodeId,
events::{EventData, EventSource, EventType, SyntheticEvent},
let mut events = Vec::new();
if self.pending_dial_rotate {
events.push(SyntheticEvent::new(
EventType::DialRotate,
EventSource::User,
DomNodeId::ROOT,
timestamp.clone(),
// The payload is read through `CallbackInfo::get_dial_state()`,
// the accessor that already existed — the same convention the
// gamepad uses rather than duplicating the state into the event.
EventData::None,
if self.pending_dial_click {
EventType::DialClick,
events
mod dial_event_tests {
/// A rotation arms an event; a repeated PRESS does not.
/// The click is an EDGE. A dial reports `pressed` as a level, so arming on the
/// level would emit `DialClick` once per frame for as long as it is held —
/// the same trap the gamepad's press edges avoid.
fn a_held_dial_click_does_not_re_fire() {
use azul_core::events::{EventProvider, EventType};
use super::{DialState, GestureAndDragManager};
let ts = || azul_core::task::Instant::Tick(azul_core::task::SystemTick::new(0));
let dial = |delta: f32, pressed: bool| DialState {
device_id: 1,
delta_rad: delta,
detent_count: 0.0,
pressed,
contact_position: azul_core::geom::OptionLogicalPosition::None,
let kinds = |m: &GestureAndDragManager| {
m.get_pending_events(ts())
.map(|e| e.event_type)
.collect::<Vec<_>>()
m.update_dial_state(dial(0.5, true));
assert_eq!(kinds(&m), vec![EventType::DialRotate, EventType::DialClick]);
// Still held, still turning: the rotation repeats, the click does not.
m.clear_pending_dial();
kinds(&m),
vec![EventType::DialRotate],
"a HELD dial must not re-fire DialClick",
// Released and pressed again: a new edge.
m.update_dial_state(dial(0.0, false));
assert!(kinds(&m).is_empty(), "no rotation and no press is no event");
m.update_dial_state(dial(0.0, true));
assert_eq!(kinds(&m), vec![EventType::DialClick]);
mod rotary_units_tests {
use super::rotary_units_to_radians;
/// A device reporting 20 units per radian, turned by a quarter turn.
fn a_reported_resolution_converts_units_to_radians() {
let quarter_turn = core::f32::consts::FRAC_PI_2;
let scroll = quarter_turn * 20.0;
let got = rotary_units_to_radians(scroll, 20.0);
assert!((got - quarter_turn).abs() < 1e-5, "got {got}");
// Direction survives: a crown turns both ways.
assert!(rotary_units_to_radians(-10.0, 20.0) < 0.0);
/// THE TRAP. `getResolution` returns 0 when the driver reported none, and
/// many do; dividing gives an infinity that would travel all the way into
/// an app's rotation maths.
fn an_unknown_resolution_answers_zero_rather_than_infinity() {
for bad in [0.0, -1.0, f32::NAN, f32::INFINITY] {
let got = rotary_units_to_radians(10.0, bad);
got, 0.0,
"resolution {bad} must answer 0.0, the value that means \"not measured\", got \
{got}"
assert!(got.is_finite());
/// A nonsense SAMPLE is guarded too: an infinity here would come straight
/// from the platform, and it must not become an infinite angle.
fn a_nonfinite_sample_answers_zero() {
assert_eq!(rotary_units_to_radians(f32::NAN, 20.0), 0.0);
assert_eq!(rotary_units_to_radians(f32::INFINITY, 20.0), 0.0);