1
//! Gesture and drag manager for multi-frame gestures and drag operations.
2
//!
3
//! Collects input samples, detects drags, double-clicks, long presses, swipes,
4
//! pinch/rotate gestures, and manages drag state for nodes, windows, and file drops.
5
//!
6
//! ## Unified Drag System
7
//!
8
//! This module uses the `DragContext` from `azul_core::drag` to provide a unified
9
//! interface for all drag operations:
10
//! - Text selection drag
11
//! - Scrollbar thumb drag
12
//! - Node drag-and-drop
13
//! - Window drag/resize
14
//! - File drop from OS
15

            
16
use alloc::vec::Vec;
17
#[cfg(feature = "std")]
18
use std::sync::atomic::{AtomicU64, Ordering};
19

            
20
use azul_core::{
21
    dom::{DomId, NodeId},
22
    drag::{ActiveDragType, DragContext, DragData},
23
    geom::{LogicalPosition, LogicalSize, PhysicalPositionI32},
24
    hit_test::HitTest,
25
    task::{Duration as CoreDuration, Instant as CoreInstant},
26
    window::WindowPosition,
27
};
28
use azul_css::{impl_option, impl_option_inner, AzString};
29

            
30
#[cfg(feature = "std")]
31
static NEXT_EVENT_ID: AtomicU64 = AtomicU64::new(1);
32

            
33
/// Allocate a new unique event ID
34
#[cfg(feature = "std")]
35
2491
pub fn allocate_event_id() -> u64 {
36
2491
    NEXT_EVENT_ID.fetch_add(1, Ordering::Relaxed)
37
2491
}
38

            
39
/// Allocate a new unique event ID (no_std fallback: returns 0)
40
#[cfg(not(feature = "std"))]
41
pub fn allocate_event_id() -> u64 {
42
    0
43
}
44

            
45
/// Helper function to convert `CoreDuration` to milliseconds
46
///
47
/// `CoreDuration` is an enum with System (`std::time::Duration`) and Tick variants.
48
/// Both go through `CoreDuration::as_millis_u64`, which converts ticks at the
49
/// nominal frame rate.
50
///
51
/// The Tick arm used to return the raw tick count and carried a WARNING that it
52
/// "assumes 1 tick = 1 ms ... will silently produce wrong timing on platforms
53
/// with a different tick resolution". A tick is a FRAME, so that assumption was
54
/// wrong by a factor of ~16 on every platform, and gesture thresholds
55
/// (double-click, long-press) read the result as milliseconds.
56
58
const fn duration_to_millis(duration: CoreDuration) -> u64 {
57
58
    duration.as_millis_u64()
58
58
}
59

            
60
/// Maximum number of input samples to keep in memory
61
///
62
/// This prevents unbounded memory growth during long drags.
63
/// Older samples beyond this limit are automatically discarded.
64
pub const MAX_SAMPLES_PER_SESSION: usize = 1000;
65

            
66
/// Default timeout for clearing old gesture samples (milliseconds)
67
///
68
/// Samples older than this are automatically removed to prevent
69
/// memory leaks and stale gesture detection.
70
pub const DEFAULT_SAMPLE_TIMEOUT_MS: u64 = 2000;
71

            
72
/// Number of samples to drain at once when the session exceeds `MAX_SAMPLES_PER_SESSION`.
73
///
74
/// Batch draining avoids per-sample overhead on every new sample.
75
const DRAIN_BATCH_SIZE: usize = 100;
76

            
77
/// MWA-B4: button-state bitfield recorded for touch-contact samples.
78
///
79
/// A finger on the surface = primary contact, mirroring `BUTTON_STATE_LEFT` in
80
/// the dll's mouse path so drag heuristics treat touch like a held button.
81
pub const TOUCH_CONTACT_BUTTON_STATE: u8 = 0x01;
82

            
83
/// Configuration for gesture detection thresholds
84
#[derive(Debug, Clone, Copy, PartialEq)]
85
pub struct GestureDetectionConfig {
86
    /// Minimum distance (pixels) to consider movement a drag, not a click
87
    pub drag_distance_threshold: f32,
88
    /// Maximum time between clicks for double-click detection (milliseconds)
89
    pub double_click_time_threshold_ms: u64,
90
    /// Maximum distance between clicks for double-click detection (pixels)
91
    pub double_click_distance_threshold: f32,
92
    /// Minimum time to hold button for long-press detection (milliseconds)
93
    pub long_press_time_threshold_ms: u64,
94
    /// Maximum distance to move while holding for long-press (pixels)
95
    pub long_press_distance_threshold: f32,
96
    /// Minimum samples needed to detect a gesture
97
    pub min_samples_for_gesture: usize,
98
    /// Minimum velocity for swipe detection (pixels per second)
99
    pub swipe_velocity_threshold: f32,
100
    /// Minimum scale change for pinch detection (e.g., 0.1 = 10% change)
101
    pub pinch_scale_threshold: f32,
102
    /// Minimum rotation angle for rotation detection (radians)
103
    pub rotation_angle_threshold: f32,
104
    /// How often to clear old samples (milliseconds)
105
    pub sample_cleanup_interval_ms: u64,
106
}
107

            
108
impl Default for GestureDetectionConfig {
109
7707
    fn default() -> Self {
110
7707
        Self {
111
7707
            drag_distance_threshold: 5.0,
112
7707
            double_click_time_threshold_ms: 500,
113
7707
            double_click_distance_threshold: 5.0,
114
7707
            long_press_time_threshold_ms: 500,
115
7707
            long_press_distance_threshold: 10.0,
116
7707
            min_samples_for_gesture: 2,
117
7707
            swipe_velocity_threshold: 500.0, // 500 px/s
118
7707
            pinch_scale_threshold: 0.1,      // 10% scale change
119
7707
            rotation_angle_threshold: 0.1,   // ~5.7 degrees in radians
120
7707
            sample_cleanup_interval_ms: DEFAULT_SAMPLE_TIMEOUT_MS,
121
7707
        }
122
7707
    }
123
}
124

            
125
/// Single input sample with position and timestamp.
126
///
127
/// `#[repr(C)]` because it crosses the C ABI through
128
/// `CallbackInfo::get_last_input_sample`. Field order is by DECREASING
129
/// ALIGNMENT, not by topic - `repr(C)` lays it out literally, and the
130
/// topical order cost 8 bytes of padding per sample, which the api checker
131
/// refuses to proceed on. It is deliberately NOT `Copy`, unlike
132
/// `PenState` beside it: `timestamp` is an `Instant`, which on a `std` build
133
/// owns a boxed platform clock reading with a destructor.
134
#[derive(Debug, Clone, PartialEq)]
135
#[repr(C)]
136
pub struct InputSample {
137
    /// Timestamp when this sample was recorded (from `ExternalSystemCallbacks`).
138
    ///
139
    /// Spelled as the real type and not through this module's `CoreInstant`
140
    /// alias: the codegen reads the field's written type verbatim, so an alias
141
    /// here produces an `AzCoreInstant` in the C header that does not exist.
142
    pub timestamp: azul_core::task::Instant,
143
    /// Unique, monotonic event ID for ordering (atomic counter)
144
    pub event_id: u64,
145
    /// Position in logical coordinates (window-local, Y=0 at top of window)
146
    pub position: LogicalPosition,
147
    /// Position in virtual screen coordinates (Y=0 at top of primary monitor).
148
    ///
149
    /// Computed as `window_position + position` at the time the sample is recorded.
150
    /// This is stable during window drags because `window_pos + cursor_local`
151
    /// always equals the true screen position, even when the window moves.
152
    ///
153
    /// All coordinates are in logical pixels (HiDPI-independent).
154
    /// On Wayland, this is an estimate (compositor does not expose global position).
155
    pub screen_position: LogicalPosition,
156
    /// Pen/stylus tilt angles in degrees.
157
    /// Range: typically -90.0 to 90.0, both zero = perpendicular.
158
    ///
159
    /// A NAMED struct rather than a `(f32, f32)`, because a tuple has no C
160
    /// representation and this whole sample was unreachable from a binding
161
    /// while it carried two. `PenTilt` is not a new type invented for that -
162
    /// it already existed and `PenState::tilt` beside it already used it, so
163
    /// the tuple here was the odd one out; the conversion that used to happen
164
    /// one level down (`PenTilt { x_tilt: tilt.0, .. }`) simply moved up.
165
    pub tilt: crate::callbacks::PenTilt,
166
    /// Touch contact extent in logical pixels. Zero for mouse input.
167
    ///
168
    /// `LogicalSize` for the same C-representation reason as `tilt`, and it
169
    /// reuses an existing type rather than adding one because a width/height
170
    /// pair in logical pixels IS a logical size. Not `TouchPoint`, which
171
    /// models the same physical thing but as a major/minor ellipse plus an id,
172
    /// a position and a force this sample already carries separately.
173
    pub touch_radius: LogicalSize,
174
    /// Pen/stylus pressure (0.0 to 1.0, 0.5 = default for mouse)
175
    pub pressure: f32,
176
    /// Mouse button state (bitfield: 0x01 = left, 0x02 = right, 0x04 = middle)
177
    pub button_state: u8,
178
}
179

            
180
/// Rotary-encoder units to RADIANS, given the device's own resolution
181
/// (9c-i-a).
182
///
183
/// `InputDevice.MotionRange.getResolution()` is documented as "the number of
184
/// units per millimeter, or per RADIAN for rotational axes", and Android's
185
/// `AXIS_SCROLL` on a `SOURCE_ROTARY_ENCODER` is a rotational axis - so the
186
/// conversion constant comes from the hardware rather than from a guess. That
187
/// matters because watch crowns differ by detent count and gearing, so no
188
/// single constant could be right for more than one of them.
189
///
190
/// # Unknown stays unknown
191
///
192
/// `getResolution` reports `0` when the driver gave none, which many do.
193
/// Dividing by it yields an infinity, and substituting a plausible number puts
194
/// a FABRICATED angle in a field whose entire value is being trustworthy - so
195
/// this answers `0.0`, which is what `DialState::delta_rad` already means on a
196
/// platform that does not measure an angle.
197
///
198
/// Lives here, beside `DialState`, rather than in the Android shell: that file
199
/// is `cfg`-gated to a target this machine never runs tests on, and a division
200
/// with a zero and a NaN case is exactly what wants a test.
201
#[must_use]
202
8
pub fn rotary_units_to_radians(scroll: f32, resolution: f32) -> f32 {
203
8
    if resolution.is_finite() && resolution > 0.0 && scroll.is_finite() {
204
2
        scroll / resolution
205
    } else {
206
6
        0.0
207
    }
208
8
}
209

            
210
impl_option!(
211
    InputSample,
212
    OptionInputSample,
213
    copy = false,
214
    [Debug, Clone, PartialEq]
215
);
216

            
217
/// A sequence of input samples forming one button press session
218
/// One non-primary seat's pen (9b-ii-b-i-b): the same three fields the
219
/// primary keeps on the manager, plus its own report-rate estimate.
220
#[derive(Debug, Clone, Copy, PartialEq, Default)]
221
pub struct SeatPen {
222
    pub state: Option<PenState>,
223
    pub previous: Option<PenState>,
224
    pub event_pending: bool,
225
    pub last_sample_nanos: Option<u64>,
226
    pub rate_ema_hz: f32,
227
}
228

            
229
#[derive(Debug, Clone, PartialEq)]
230
pub struct InputSession {
231
    /// All recorded samples for this session
232
    pub samples: Vec<InputSample>,
233
    /// Whether this session has ended (button released)
234
    pub ended: bool,
235
    /// Session ID for tracking (incremental counter)
236
    pub session_id: u64,
237
    /// Window position at the time this session started (mouse-down).
238
    /// Used by titlebar drag callbacks to compute new window position.
239
    pub window_position_at_start: WindowPosition,
240
    /// WHOSE session this is (9b-ii-b-i): the pointer SEAT that pressed.
241
    /// `PRIMARY_POINTER_SEAT` (0) for the mouse and for touches - the
242
    /// primary seat's own pointers - so every detector that answers "the
243
    /// current session" answers for the primary and is never hijacked by a
244
    /// second cursor's press; a seat's sessions are read through the
245
    /// `*_for(seat_id)` detectors.
246
    pub seat_id: u64,
247
}
248

            
249
impl InputSession {
250
    /// Create a new input session
251
89
    fn new(session_id: u64, first_sample: InputSample, window_position: WindowPosition) -> Self {
252
89
        Self {
253
89
            samples: vec![first_sample],
254
89
            ended: false,
255
89
            session_id,
256
89
            window_position_at_start: window_position,
257
89
            seat_id: azul_core::window::PRIMARY_POINTER_SEAT,
258
89
        }
259
89
    }
260

            
261
    /// Get the first sample in this session
262
    #[must_use]
263
126
    pub fn first_sample(&self) -> Option<&InputSample> {
264
126
        self.samples.first()
265
126
    }
266

            
267
    /// Get the last sample in this session
268
    #[must_use]
269
98
    pub fn last_sample(&self) -> Option<&InputSample> {
270
98
        self.samples.last()
271
98
    }
272

            
273
    /// Get the duration of this session (first to last sample)
274
    #[must_use]
275
28
    pub fn duration_ms(&self) -> Option<u64> {
276
28
        let first = self.first_sample()?;
277
27
        let last = self.last_sample()?;
278
27
        let duration = last.timestamp.duration_since(&first.timestamp);
279
27
        Some(duration_to_millis(duration))
280
28
    }
281

            
282
    /// Get the total distance traveled in this session
283
    #[must_use]
284
23
    pub fn total_distance(&self) -> f32 {
285
23
        if self.samples.len() < 2 {
286
2
            return 0.0;
287
21
        }
288

            
289
21
        let mut total = 0.0;
290
22
        for i in 1..self.samples.len() {
291
22
            let prev = &self.samples[i - 1];
292
22
            let curr = &self.samples[i];
293
22
            let dx = curr.position.x - prev.position.x;
294
22
            let dy = curr.position.y - prev.position.y;
295
22
            total += dx.hypot(dy);
296
22
        }
297
21
        total
298
23
    }
299

            
300
    /// Get the straight-line distance from first to last sample
301
    #[must_use]
302
21
    pub fn direct_distance(&self) -> Option<f32> {
303
21
        let first = self.first_sample()?;
304
20
        let last = self.last_sample()?;
305
20
        let dx = last.position.x - first.position.x;
306
20
        let dy = last.position.y - first.position.y;
307
20
        Some(dx.hypot(dy))
308
21
    }
309
}
310

            
311
/// Result of drag detection analysis
312
#[derive(Debug, Clone, Copy, PartialEq)]
313
pub struct DetectedDrag {
314
    /// Position where drag started
315
    pub start_position: LogicalPosition,
316
    /// Current/end position of drag
317
    pub current_position: LogicalPosition,
318
    /// Direct distance dragged (straight line, pixels)
319
    pub direct_distance: f32,
320
    /// Total distance dragged (following path, pixels)
321
    pub total_distance: f32,
322
    /// Duration of the drag (milliseconds)
323
    pub duration_ms: u64,
324
    /// Number of position samples recorded
325
    pub sample_count: usize,
326
    /// Session ID this drag belongs to
327
    pub session_id: u64,
328
}
329

            
330
/// Result of long-press detection
331
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
332
#[repr(C)]
333
pub struct DetectedLongPress {
334
    /// Position where long press is happening
335
    pub position: LogicalPosition,
336
    /// How long the button has been held (milliseconds)
337
    pub duration_ms: u64,
338
    /// Whether the callback has already been invoked for this long press
339
    pub callback_invoked: bool,
340
    /// Session ID this long press belongs to
341
    pub session_id: u64,
342
}
343

            
344
/// Primary direction of a gesture
345
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
346
#[repr(C)]
347
pub enum GestureDirection {
348
    Up,
349
    Down,
350
    Left,
351
    Right,
352
}
353

            
354
impl_option!(
355
    GestureDirection,
356
    OptionGestureDirection,
357
    [Debug, Clone, Copy, PartialEq, Eq]
358
);
359
impl_option!(
360
    DetectedPinch,
361
    OptionDetectedPinch,
362
    [Debug, Clone, Copy, PartialEq]
363
);
364
impl_option!(
365
    DetectedRotation,
366
    OptionDetectedRotation,
367
    [Debug, Clone, Copy, PartialEq]
368
);
369
impl_option!(
370
    DetectedLongPress,
371
    OptionDetectedLongPress,
372
    [Debug, Clone, Copy, PartialEq, Eq]
373
);
374

            
375
/// Result of pinch gesture detection
376
#[derive(Debug, Clone, Copy, PartialEq)]
377
#[repr(C)]
378
pub struct DetectedPinch {
379
    /// Scale factor (< 1.0 for pinch in, > 1.0 for pinch out)
380
    pub scale: f32,
381
    /// Center point of the pinch gesture
382
    pub center: LogicalPosition,
383
    /// Initial distance between touch points
384
    pub initial_distance: f32,
385
    /// Current distance between touch points
386
    pub current_distance: f32,
387
    /// Duration of pinch (milliseconds)
388
    pub duration_ms: u64,
389
}
390

            
391
/// Result of rotation gesture detection
392
#[derive(Debug, Clone, Copy, PartialEq)]
393
#[repr(C)]
394
pub struct DetectedRotation {
395
    /// Rotation angle in radians (positive = clockwise)
396
    pub angle_radians: f32,
397
    /// Center point of rotation
398
    pub center: LogicalPosition,
399
    /// Duration of rotation (milliseconds)
400
    pub duration_ms: u64,
401
}
402

            
403
/// State of pen/stylus input
404
#[derive(Debug, Clone, Copy, PartialEq)]
405
#[repr(C)]
406
pub struct PenState {
407
    /// Current pen position
408
    pub position: LogicalPosition,
409
    /// Current pressure (0.0 to 1.0)
410
    pub pressure: f32,
411
    /// Current tilt angles (`x_tilt`, `y_tilt`) in degrees
412
    pub tilt: crate::callbacks::PenTilt,
413
    /// Whether pen is in contact with surface
414
    pub in_contact: bool,
415
    /// Whether pen is inverted (eraser mode)
416
    pub is_eraser: bool,
417
    /// Whether barrel button is pressed
418
    pub barrel_button_pressed: bool,
419
    /// Unique identifier for this pen device
420
    pub device_id: u64,
421
    /// Tangential / cylinder pressure (0.0 to 1.0). Wacom Air Brush wheel,
422
    /// Surface Slim Pen 2 secondary axis. `0.0` means "not reported".
423
    /// Maps to W3C `PointerEvent.tangentialPressure`.
424
    pub tangential_pressure: f32,
425
    /// Barrel roll angle in radians (–π to π). Wacom Art Pen rotation,
426
    /// Surface Pen barrel-roll axis. `0.0` means "not reported" (devices
427
    /// that do report it sweep through the full range as the user rolls
428
    /// the pen — the resting state isn't necessarily zero, so callers
429
    /// should compare deltas, not absolute values).
430
    /// Maps to W3C `PointerEvent.twist` (in radians, not degrees).
431
    pub barrel_roll_rad: f32,
432
    /// Per-tool identity for hand-held pens that report it (Wintab GUID,
433
    /// Apple Pencil session id, S-Pen serial). `0` means "not reported".
434
    /// Distinct from `device_id` so callers can both identify the
435
    /// hardware (`device_id`) *and* which tip / lead / button cluster is
436
    /// in use (`tool_id`).
437
    pub tool_id: u32,
438
    /// MEASURED report rate of this tool in Hz - an exponential moving
439
    /// average of the interval between pen samples, because no platform
440
    /// protocol carries the nominal rate (tablet-v2, XI2 and Wintab all
441
    /// omit it). `0.0` until two samples arrive in the current proximity
442
    /// session; re-converges within ~10 packets after proximity-in. Apps
443
    /// use it to size smoothing windows and interpolation ("this pen
444
    /// reports at 133Hz, the display at 60Hz").
445
    pub report_rate_hz: f32,
446
    /// Distance from the surface while hovering, normalized 0.0-1.0 against
447
    /// the tool's OWN sensing range. `0.0` = touching, or not reported.
448
    ///
449
    /// The scale is the device's, not millimetres: Wayland's `distance` is a
450
    /// 16-bit fraction of maximum range and Win32 reports only in/out of
451
    /// range at all. So it is a value to compare against itself over time — a
452
    /// brush preview that grows as the pen approaches — not one to measure
453
    /// with. Check `in_contact` first; a hovering pen has `pressure == 0.0`
454
    /// and a touching one has `hover_distance == 0.0`.
455
    pub hover_distance: f32,
456
    /// Which tool of the tablet this is. `Unknown` where the platform does
457
    /// not classify, which is most of them outside Wayland.
458
    pub tool_kind: TabletToolKind,
459
}
460

            
461
impl_option!(PenState, OptionPenState, [Debug, Clone, Copy, PartialEq]);
462

            
463
impl Default for PenState {
464
    fn default() -> Self {
465
        Self {
466
            position: LogicalPosition::zero(),
467
            pressure: 0.0,
468
            tilt: crate::callbacks::PenTilt {
469
                x_tilt: 0.0,
470
                y_tilt: 0.0,
471
            },
472
            in_contact: false,
473
            is_eraser: false,
474
            barrel_button_pressed: false,
475
            device_id: 0,
476
            tangential_pressure: 0.0,
477
            barrel_roll_rad: 0.0,
478
            tool_id: 0,
479
            report_rate_hz: 0.0,
480
            hover_distance: 0.0,
481
            tool_kind: TabletToolKind::Unknown,
482
        }
483
    }
484
}
485

            
486
/// State of a tablet **pad** — the tablet body's own hardware controls,
487
/// distinct from the pen ([`PenState`] already covers eraser / barrel button /
488
/// barrel roll / tilt / pressure).
489
///
490
/// Named for the hardware class, not a vendor: the protocol behind it is
491
/// `zwp_tablet_pad_v2` on Wayland and `XInput2` valuators on X11, and Huion,
492
/// XP-Pen, Gaomon and Apple's own tablets all report through it.
493
///
494
/// Populated by the platform
495
/// backend (`dll/src/desktop/extra/wacom_pad/`: Wintab on Windows,
496
/// libwacom+libinput on Linux, the driver's `NSEvent` tablet events on macOS).
497
#[derive(Debug, Clone, Copy, PartialEq)]
498
#[repr(C)]
499
pub struct TabletPadState {
500
    // Field order is by DECREASING ALIGNMENT. `device_id` is a u64 and has to
501
    // lead, or `#[repr(C)]` pads to align it after the u32s; the two bools go
502
    // last for the same reason. ~8 bytes per instance.
503
    /// Tablet device id (to distinguish pads on multi-tablet setups).
504
    pub device_id: u64,
505
    /// `ExpressKey` bitset — bit `n` set ⇔ hardware button `n` is held (up to
506
    /// 32). Read via [`TabletPadState::express_key`].
507
    pub express_keys: u32,
508
    /// Touch-ring / touch-strip absolute position, `0.0`–`1.0`. Only
509
    /// meaningful while [`TabletPadState::touch_ring_active`] is `true`.
510
    pub touch_ring: f32,
511
    /// Touch-STRIP absolute position, `0.0`-`1.0`. Only meaningful while
512
    /// [`TabletPadState::strip_active`] is `true`.
513
    ///
514
    /// A strip is not a ring: Intuos Pro bodies have both, and a pad that has
515
    /// one usually does not have the other. Folding them into a single field
516
    /// would make a strip look like a ring stuck at one angle.
517
    pub strip: f32,
518
    /// Dial rotation since the last frame, in radians. `0.0` = no motion.
519
    ///
520
    /// From `zwp_tablet_pad_dial_v2`, which both Linux backends already bind.
521
    /// A DELTA rather than a position because a dial has no endstops — it is
522
    /// the same primitive as a Surface Dial or a Wear crown, which is why
523
    /// this is also the field a future `DialState` would read.
524
    pub dial_delta: f32,
525
    /// Which mode the pad's button group is in. Wacom pads multiplex their
526
    /// `ExpressKeys` across modes, and the ring LEDs show which is active, so
527
    /// the same physical key means different things per mode.
528
    pub mode: u32,
529
    /// How many modes the group has. `0` = the pad does not multiplex.
530
    pub mode_count: u32,
531
    /// Whether a finger is currently on the touch-ring / touch-strip.
532
    pub touch_ring_active: bool,
533
    /// Whether a finger is currently on the touch-strip.
534
    pub strip_active: bool,
535
}
536

            
537
impl_option!(
538
    TabletPadState,
539
    OptionTabletPadState,
540
    [Debug, Clone, Copy, PartialEq]
541
);
542

            
543
impl Default for TabletPadState {
544
35
    fn default() -> Self {
545
35
        Self {
546
35
            express_keys: 0,
547
35
            touch_ring: 0.0,
548
35
            touch_ring_active: false,
549
35
            device_id: 0,
550
35
            strip: 0.0,
551
35
            strip_active: false,
552
35
            dial_delta: 0.0,
553
35
            mode: 0,
554
35
            mode_count: 0,
555
35
        }
556
35
    }
557
}
558

            
559
impl TabletPadState {
560
    /// Whether `ExpressKey` `index` (0-based, < 32) is currently held.
561
    #[must_use]
562
1072
    pub const fn express_key(&self, index: u32) -> bool {
563
1072
        index < 32 && (self.express_keys & (1u32 << index)) != 0
564
1072
    }
565
}
566

            
567
/// [`TabletDeviceInfo::capabilities`]: the device reports pressure.
568
pub const TABLET_CAP_PRESSURE: u32 = 1;
569
/// [`TabletDeviceInfo::capabilities`]: the device reports tilt.
570
pub const TABLET_CAP_TILT: u32 = 2;
571
/// [`TabletDeviceInfo::capabilities`]: the device reports barrel rotation.
572
pub const TABLET_CAP_ROTATION: u32 = 4;
573
/// [`TabletDeviceInfo::capabilities`]: airbrush wheel / tangential pressure.
574
pub const TABLET_CAP_SLIDER: u32 = 8;
575
/// [`TabletDeviceInfo::capabilities`]: a relative wheel on the tool.
576
pub const TABLET_CAP_WHEEL: u32 = 16;
577
/// [`TabletDeviceInfo::capabilities`]: a pad touch-ring or touch-strip.
578
pub const TABLET_CAP_TOUCHRING: u32 = 32;
579

            
580
/// What kind of input device a [`TabletDeviceInfo`] describes.
581
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
582
#[repr(C)]
583
pub enum TabletToolKind {
584
    /// The pen tip.
585
    Stylus,
586
    /// The inverted / eraser end (X11: a device of its own; Wayland: a tool
587
    /// whose type is `eraser`).
588
    Eraser,
589
    /// The tablet's pad: `ExpressKeys` plus touch-ring / strip.
590
    Pad,
591
    /// A touch surface (tablet touch or touchscreen).
592
    Touch,
593
    /// Recognised as tablet-adjacent, kind unknown.
594
    Unknown,
595
    /// A brush tool. APPENDED at the end for ABI stability.
596
    ///
597
    /// These five complete the `zwp_tablet_tool_v2` vocabulary, which is the
598
    /// richest of the platform sets — macOS `NSPointingDeviceType` and Qt's
599
    /// `PointerType` are both subsets of it. Widening this enum rather than
600
    /// adding a parallel `PenToolType` keeps one name for one concept: an app
601
    /// that switches on the tool it is holding should not have to ask which
602
    /// API told it.
603
    Brush,
604
    /// A pencil tool.
605
    Pencil,
606
    /// An airbrush — the tool whose `slider` axis becomes
607
    /// `PenState.tangential_pressure`.
608
    Airbrush,
609
    /// A tablet mouse / puck: rides on the tablet surface, reports absolute
610
    /// position, and is NOT the system pointer.
611
    Mouse,
612
    /// A lens cursor — a puck with crosshairs, for tracing.
613
    Lens,
614
}
615

            
616
/// Identity and capabilities of one tablet input device — the `xinput list`
617
/// level of information: enough for an app to tell the user WHICH tablet is
618
/// in use, offer a device picker, or configure a custom mapping.
619
///
620
/// Produced by the platform backends (X11: `XIQueryDevice` plus the
621
/// `Device Product ID` / `Device Node` properties; Wayland: the
622
/// `zwp_tablet_v2` descriptive events). A field the backend cannot know is
623
/// zero / empty rather than guessed — Wayland, for example, does not report
624
/// a physical size.
625
#[derive(Debug, Clone, PartialEq)]
626
#[repr(C)]
627
pub struct TabletDeviceInfo {
628
    /// Driver-reported device name (X11: the slave device's name, e.g.
629
    /// "Wacom One Pen Display 13 Pen stylus"; Wayland: the tablet's name).
630
    pub name: AzString,
631
    /// Human-readable vendor ("Wacom", "Huion", ...) resolved from
632
    /// `vendor_id` via [`tablet_usb_vendor_name`]; empty when unknown.
633
    pub vendor_name: AzString,
634
    /// Kernel device node (`/dev/input/event..`) where known, else empty.
635
    pub path: AzString,
636
    /// The id [`PenState::device_id`] / [`TabletPadState::device_id`] report
637
    /// on the same backend, so live state can be matched to an entry here.
638
    pub device_id: u64,
639
    /// USB vendor id (0 = unknown).
640
    pub vendor_id: u32,
641
    /// USB product id (0 = unknown).
642
    pub product_id: u32,
643
    /// What this device is.
644
    pub kind: TabletToolKind,
645
    /// `TABLET_CAP_*` bitset.
646
    pub capabilities: u32,
647
    /// The driver's RAW pressure maximum (X11: the valuator range; Wayland:
648
    /// 65535). [`PenState::pressure`] is already normalized to 0..=1 — this
649
    /// is diagnostic, for apps that build their own curves.
650
    pub pressure_max: f32,
651
    /// Active-area width in millimeters, 0.0 = unknown. On X11 this comes
652
    /// from the `Abs X` valuator's range and resolution (units per meter).
653
    pub physical_width_mm: f32,
654
    /// Active-area height in millimeters, 0.0 = unknown.
655
    pub physical_height_mm: f32,
656
    /// Number of buttons the device reports (a pad: its `ExpressKeys`).
657
    pub num_buttons: u32,
658
}
659

            
660
impl_option!(
661
    TabletDeviceInfo,
662
    OptionTabletDeviceInfo,
663
    copy = false,
664
    [Debug, Clone, PartialEq]
665
);
666
impl_option!(
667
    TabletToolKind,
668
    OptionTabletToolKind,
669
    [Debug, Clone, Copy, PartialEq]
670
);
671
azul_css::impl_vec!(
672
    TabletDeviceInfo,
673
    TabletDeviceInfoVec,
674
    TabletDeviceInfoVecDestructor,
675
    TabletDeviceInfoVecDestructorType,
676
    TabletDeviceInfoVecSlice,
677
    OptionTabletDeviceInfo
678
);
679
azul_css::impl_vec_debug!(TabletDeviceInfo, TabletDeviceInfoVec);
680
azul_css::impl_vec_clone!(
681
    TabletDeviceInfo,
682
    TabletDeviceInfoVec,
683
    TabletDeviceInfoVecDestructor
684
);
685
azul_css::impl_vec_partialeq!(TabletDeviceInfo, TabletDeviceInfoVec);
686

            
687
/// Resolve the well-known graphics-tablet USB vendor ids to a display name.
688
/// Empty for a vendor not in the table — show the hex id instead, never a
689
/// guess.
690
#[must_use]
691
pub const fn tablet_usb_vendor_name(vendor_id: u32) -> &'static str {
692
    match vendor_id {
693
        0x056a => "Wacom",
694
        0x256c => "Huion",
695
        0x28bd => "XP-Pen",
696
        0x5543 => "UC-Logic",
697
        0x04f3 => "ELAN",
698
        0x045e => "Microsoft",
699
        0x05ac => "Apple",
700
        0x04e8 => "Samsung",
701
        _ => "",
702
    }
703
}
704

            
705
/// Manager for multi-frame gestures and drag operations
706
///
707
/// This collects raw input samples and analyzes them to detect gestures.
708
/// Designed for testability and clear separation of input collection
709
/// vs. detection.
710
///
711
/// ## Unified Drag System
712
///
713
/// The manager now uses `DragContext` to unify all drag types:
714
/// - `active_drag`: The unified drag context (replaces individual drag states)
715
#[derive(Debug, Clone, PartialEq)]
716
// The bools are INDEPENDENT latches (per-input-source armed/pending state), not
717
// the states of one machine; an enum would make illegal combinations of them
718
// unrepresentable that are in fact legal.
719
#[allow(clippy::struct_excessive_bools)]
720
pub struct GestureAndDragManager {
721
    /// Configuration for gesture detection
722
    pub config: GestureDetectionConfig,
723
    /// All recorded input sessions (multiple button press sequences)
724
    pub input_sessions: Vec<InputSession>,
725
    /// **NEW**: Unified drag context for all drag types
726
    pub active_drag: Option<DragContext>,
727
    /// The node the CURRENT drag GESTURE began on (the press target),
728
    /// resolved once at `DragStart` and held for the whole gesture. `Drag` /
729
    /// `DragStart` / `DragEnd` fire on THIS node, not on whatever the cursor
730
    /// is over now (W3C: those three target the drag source; only
731
    /// DragEnter/Over/Leave/Drop follow the cursor). Without it a drag whose
732
    /// cursor leaves the dragged element stops receiving Drag events — the
733
    /// "the drag suddenly stops" desync. Remapped across DOM rebuilds,
734
    /// cleared when the button releases / the gesture ends.
735
    drag_source_node: azul_core::dom::OptionDomNodeId,
736
    /// Current pen/stylus state
737
    pub pen_state: Option<PenState>,
738
    /// Pen state as of the previous determine-events pass (for diffing pen events).
739
    pub previous_pen_state: Option<PenState>,
740
    /// Set when pen state changed; gates one pen-event diff (cleared by the event loop).
741
    pub pen_event_pending: bool,
742
    /// Pen slots of the NON-primary seats (9b-ii-b-i-b): a Wayland tablet is
743
    /// per `wl_seat` and an X11 stylus is a slave of one master pointer, so
744
    /// a second seat's stylus is a second pen, not an overwrite of the
745
    /// first. The primary seat keeps the three fields above.
746
    pub seat_pens: alloc::collections::btree_map::BTreeMap<u64, SeatPen>,
747
    /// Force Touch stage from the last `pressureChangeWithEvent:`. 0 none,
748
    /// 1 a normal click, 2 a force click. macOS-only; 0 elsewhere.
749
    pub trackpad_pressure_stage: i32,
750
    /// Most recent rotary-control rotation. `None` until a dial reports.
751
    pub dial_state: Option<DialState>,
752
    /// `true` when the dial reported a rotation this pass, cleared by the dll
753
    /// after the event is collected. Without a pending flag the provider would
754
    /// have to diff, and two equal deltas in a row are two turns.
755
    pending_dial_rotate: bool,
756
    /// `true` on the press EDGE of a clickable dial (a level would re-fire
757
    /// every frame while held).
758
    pending_dial_click: bool,
759
    /// A pen barrel squeeze awaiting dispatch (Apple Pencil Pro).
760
    pub pending_pen_squeeze: bool,
761
    /// A pen barrel double-tap awaiting dispatch (Apple Pencil 2+).
762
    pub pending_pen_double_tap: bool,
763
    /// Monotonic nanos of the previous pen sample (rate measurement);
764
    /// cleared on proximity-out so a gap never reads as a slow rate.
765
    pub last_pen_sample_nanos: Option<u64>,
766
    /// The EMA behind [`PenState::report_rate_hz`].
767
    pub pen_rate_ema_hz: f32,
768
    /// Latest Wacom tablet-pad state (`ExpressKeys` + touch-ring), or `None`
769
    /// until a pad backend delivers one.
770
    pub pad_state: Option<TabletPadState>,
771
    /// Enumerated tablet input devices (see [`TabletDeviceInfo`]), set by the
772
    /// platform backend at window init / device hotplug. Empty = none found.
773
    pub tablet_devices: Vec<TabletDeviceInfo>,
774
    /// Session IDs where long press callback has been invoked
775
    long_press_callbacks_invoked: Vec<u64>,
776
    /// Counter for generating unique session IDs
777
    next_session_id: u64,
778
    /// Native-platform gesture override slot.
779
    ///
780
    /// Platforms with first-class gesture recognizers (iOS `UIKit`,
781
    /// Android `GestureDetector` + `ScaleGestureDetector`, macOS
782
    /// `NSGestureRecognizer`) inject pre-detected gestures here via
783
    /// [`GestureAndDragManager::inject_native_gesture`]. The
784
    /// `detect_*` methods consult this slot before running their
785
    /// in-process heuristics, so callbacks observe consistent results
786
    /// regardless of the detection source.
787
    ///
788
    /// Cleared automatically at the start of every new input recording
789
    /// cycle so a single OS event doesn't keep firing.
790
    pub native_gesture: Option<NativeGestureEvent>,
791
    /// MWA-B4: OS touch id → session id. Desktop touch events previously
792
    /// only filled the window's `touch_state`, so no touch ever became an
793
    /// input session and `detect_pinch` / `detect_rotation` (which need two
794
    /// concurrent sessions) were structurally dead on Windows/X11/Wayland.
795
    /// The shells call [`touch_down`](Self::touch_down) /
796
    /// [`touch_move`](Self::touch_move) / [`touch_up`](Self::touch_up); each
797
    /// finger gets its own session (two fingers = two live sessions).
798
    touch_sessions: alloc::collections::btree_map::BTreeMap<u64, u64>,
799
    /// Seat id -> the session its pressed button owns (9b-ii-b-i); the
800
    /// per-seat twin of `touch_sessions`.
801
    seat_sessions: alloc::collections::btree_map::BTreeMap<u64, u64>,
802
}
803

            
804
/// Gesture detected by a platform-native recognizer.
805
///
806
/// Platform backends construct one of these in their gesture-recognizer
807
/// callbacks (iOS `UIKit`, Android `GestureDetector`, macOS
808
/// `NSGestureRecognizer`) and hand it to
809
/// [`GestureAndDragManager::inject_native_gesture`]. The in-process
810
/// `detect_*` methods then return the native result, sidestepping their
811
/// fallback heuristics. On platforms with poor native gesture support
812
/// (X11 / Wayland touch, headless), backends never inject and the
813
/// in-process detector remains authoritative.
814
#[derive(Debug, Clone, Copy, PartialEq)]
815
#[repr(C, u8)]
816
pub enum NativeGestureEvent {
817
    /// Single tap / double-click detected natively.
818
    DoubleClick,
819
    /// Long-press detected natively (iOS `UILongPressGestureRecognizer`,
820
    /// Android `GestureDetector.OnGestureListener::onLongPress`).
821
    LongPress(DetectedLongPress),
822
    /// Swipe detected natively (iOS `UISwipeGestureRecognizer`,
823
    /// Android `GestureDetector.OnGestureListener::onFling`).
824
    Swipe(GestureDirection),
825
    /// Pinch detected natively (iOS `UIPinchGestureRecognizer`,
826
    /// Android `ScaleGestureDetector`, macOS magnification gesture).
827
    Pinch(DetectedPinch),
828
    /// Rotation detected natively (iOS `UIRotationGestureRecognizer`,
829
    /// macOS rotation gesture).
830
    Rotation(DetectedRotation),
831
}
832

            
833
impl Default for GestureAndDragManager {
834
1
    fn default() -> Self {
835
1
        Self::new()
836
1
    }
837
}
838

            
839
impl GestureAndDragManager {
840
    /// (`input_sessions`, `long_press_callbacks_invoked`). Used by
841
    /// `AZ_E2E_TEST` to watch for unbounded growth.
842
    #[must_use]
843
7
    pub const fn debug_counts(&self) -> (usize, usize) {
844
7
        (
845
7
            self.input_sessions.len(),
846
7
            self.long_press_callbacks_invoked.len(),
847
7
        )
848
7
    }
849

            
850
    /// Create a new gesture and drag manager
851
    #[must_use]
852
7707
    pub fn new() -> Self {
853
7707
        Self {
854
7707
            config: GestureDetectionConfig::default(),
855
7707
            input_sessions: Vec::new(),
856
7707
            next_session_id: 1,
857
7707
            active_drag: None,
858
7707
            drag_source_node: azul_core::dom::OptionDomNodeId::None,
859
7707

            
860
7707
            pen_state: None,
861
7707
            previous_pen_state: None,
862
7707
            pen_event_pending: false,
863
7707
            trackpad_pressure_stage: 0,
864
7707
            dial_state: None,
865
7707
            pending_dial_rotate: false,
866
7707
            pending_dial_click: false,
867
7707
            pending_pen_squeeze: false,
868
7707
            pending_pen_double_tap: false,
869
7707
            last_pen_sample_nanos: None,
870
7707
            pen_rate_ema_hz: 0.0,
871
7707
            pad_state: None,
872
7707
            tablet_devices: Vec::new(),
873
7707
            long_press_callbacks_invoked: Vec::new(),
874
7707
            native_gesture: None,
875
7707
            touch_sessions: alloc::collections::btree_map::BTreeMap::new(),
876
7707
            seat_sessions: alloc::collections::btree_map::BTreeMap::new(),
877
7707
            seat_pens: alloc::collections::btree_map::BTreeMap::new(),
878
7707
        }
879
7707
    }
880

            
881
    /// Inject a native gesture-recognizer result, overriding the
882
    /// in-process detector for the current event frame. Called by the
883
    /// iOS / Android / macOS platform backend from their gesture
884
    /// recognizer callbacks. The override is read once by the next
885
    /// `detect_*` call.
886
    /// Record a Force Touch pressure sample from a pressure-sensitive
887
    /// trackpad (macOS `pressureChangeWithEvent:`).
888
    ///
889
    /// Folded into `PenState` because it is the same quantity a stylus
890
    /// reports — an app reads it through `get_pen_pressure()` either way —
891
    /// but with `is_eraser` and the barrel flags off, since a trackpad has
892
    /// neither. `stage` rides alongside as the discrete detent count, which is
893
    /// what separates a deliberate force click from merely pressing hard.
894
    pub fn update_trackpad_pressure(
895
        &mut self,
896
        position: LogicalPosition,
897
        pressure: f32,
898
        stage: i32,
899
    ) {
900
        self.previous_pen_state = self.pen_state;
901
        let mut state = self.pen_state.unwrap_or_default();
902
        state.position = position;
903
        state.pressure = pressure;
904
        state.in_contact = stage > 0;
905
        state.is_eraser = false;
906
        state.barrel_button_pressed = false;
907
        self.pen_state = Some(state);
908
        self.trackpad_pressure_stage = stage;
909
        self.pen_event_pending = true;
910
    }
911

            
912
    /// The Force Touch stage most recently reported: 0 none, 1 a normal
913
    /// click, 2 a force click past the second detent.
914
    #[must_use]
915
    pub const fn trackpad_pressure_stage(&self) -> i32 {
916
        self.trackpad_pressure_stage
917
    }
918

            
919
27
    pub const fn inject_native_gesture(&mut self, gesture: NativeGestureEvent) {
920
27
        self.native_gesture = Some(gesture);
921
27
    }
922

            
923
    /// Clear any pending native-gesture override. Called by the event
924
    /// loop after each frame's detections have been consumed so a
925
    /// stale OS gesture doesn't keep firing.
926
145
    pub const fn clear_native_gesture(&mut self) {
927
145
        self.native_gesture = None;
928
145
    }
929

            
930
    /// Create with custom configuration
931
    #[must_use]
932
1
    pub fn with_config(config: GestureDetectionConfig) -> Self {
933
1
        Self {
934
1
            config,
935
1
            ..Self::new()
936
1
        }
937
1
    }
938

            
939
    // Input Recording Methods (called from event loop / system timer)
940

            
941
    /// Start a new input session (mouse button pressed down)
942
    ///
943
    /// This begins recording samples for gesture detection.
944
    /// Call this when receiving mouse button down event.
945
    ///
946
    /// `window_position` is the current OS window position at the time of mouse-down.
947
    /// It is stored so that drag callbacks can compute the new window position.
948
    ///
949
    /// Returns the session ID for this new session.
950
87
    pub fn start_input_session(
951
87
        &mut self,
952
87
        position: LogicalPosition,
953
87
        timestamp: CoreInstant,
954
87
        button_state: u8,
955
87
        window_position: WindowPosition,
956
87
        screen_position: LogicalPosition,
957
87
    ) -> u64 {
958
87
        self.start_input_session_with_pen(
959
87
            position,
960
87
            timestamp,
961
87
            button_state,
962
87
            allocate_event_id(),
963
            0.5,        // default pressure for mouse
964
87
            (0.0, 0.0), // no tilt for mouse
965
87
            (0.0, 0.0), // no touch radius for mouse
966
87
            window_position,
967
87
            screen_position,
968
        )
969
87
    }
970

            
971
    /// Start a new input session with pen/touch data
972
88
    pub fn start_input_session_with_pen(
973
88
        &mut self,
974
88
        position: LogicalPosition,
975
88
        timestamp: CoreInstant,
976
88
        button_state: u8,
977
88
        event_id: u64,
978
88
        pressure: f32,
979
88
        tilt: (f32, f32),
980
88
        touch_radius: (f32, f32),
981
88
        window_position: WindowPosition,
982
88
        screen_position: LogicalPosition,
983
88
    ) -> u64 {
984
        // Clear old ended sessions, but keep the most recent ended session
985
        // for double-click detection. detect_double_click() needs two ended
986
        // sessions to compare timing and distance.
987
88
        let last_ended_idx = self.input_sessions.iter().rposition(|s| s.ended);
988
88
        let mut idx = 0usize;
989
88
        self.input_sessions.retain(|session| {
990
31
            let keep = !session.ended || Some(idx) == last_ended_idx;
991
31
            idx += 1;
992
31
            keep
993
31
        });
994

            
995
88
        let session_id = self.next_session_id;
996
88
        self.next_session_id += 1;
997

            
998
88
        let sample = InputSample {
999
88
            position,
88
            screen_position,
88
            timestamp,
88
            button_state,
88
            event_id,
88
            pressure,
88
            tilt: tilt.into(),
88
            touch_radius: LogicalSize::new(touch_radius.0, touch_radius.1),
88
        };
88
        let session = InputSession::new(session_id, sample, window_position);
88
        self.input_sessions.push(session);
88
        session_id
88
    }
    /// 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.
1233
    pub fn record_input_sample(
1233
        &mut self,
1233
        position: LogicalPosition,
1233
        timestamp: CoreInstant,
1233
        button_state: u8,
1233
        screen_position: LogicalPosition,
1233
    ) -> bool {
1233
        self.record_input_sample_with_pen(
1233
            position,
1233
            timestamp,
1233
            button_state,
1233
            allocate_event_id(),
            0.5,        // default pressure for mouse
1233
            (0.0, 0.0), // no tilt for mouse
1233
            (0.0, 0.0), // no touch radius for mouse
1233
            screen_position,
        )
1233
    }
    /// Record an input sample with pen/touch data
1234
    pub fn record_input_sample_with_pen(
1234
        &mut self,
1234
        position: LogicalPosition,
1234
        timestamp: CoreInstant,
1234
        button_state: u8,
1234
        event_id: u64,
1234
        pressure: f32,
1234
        tilt: (f32, f32),
1234
        touch_radius: (f32, f32),
1234
        screen_position: LogicalPosition,
1234
    ) -> bool {
1234
        let Some(session) = self.last_primary_session_mut() else {
1
            return false;
        };
1233
        if session.ended {
1
            return false;
1232
        }
        // Enforce max samples limit
1232
        if session.samples.len() >= MAX_SAMPLES_PER_SESSION {
3
            // Remove oldest samples, keeping the most recent ones
3
            let remove_count = session.samples.len() - MAX_SAMPLES_PER_SESSION + DRAIN_BATCH_SIZE;
3
            session.samples.drain(0..remove_count);
1229
        }
1232
        session.samples.push(InputSample {
1232
            position,
1232
            screen_position,
1232
            timestamp,
1232
            button_state,
1232
            event_id,
1232
            pressure,
1232
            tilt: tilt.into(),
1232
            touch_radius: LogicalSize::new(touch_radius.0, touch_radius.1),
1232
        });
1232
        true
1234
    }
    /// 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.
19
    pub fn end_current_session(&mut self) {
19
        if let Some(session) = self.last_primary_session_mut() {
18
            session.ended = true;
18
        }
19
    }
    // --- Per-touch-id input sessions (MWA-B4) ---
    /// A finger made contact: open a dedicated session for `touch_id`.
33
    pub fn touch_down(
33
        &mut self,
33
        touch_id: u64,
33
        position: LogicalPosition,
33
        timestamp: CoreInstant,
33
        window_position: WindowPosition,
33
        screen_position: LogicalPosition,
33
    ) {
33
        let session_id = self.start_input_session(
33
            position,
33
            timestamp,
            TOUCH_CONTACT_BUTTON_STATE,
33
            window_position,
33
            screen_position,
        );
33
        self.touch_sessions.insert(touch_id, session_id);
33
    }
    /// 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.
1168
    pub fn touch_move(
1168
        &mut self,
1168
        touch_id: u64,
1168
        position: LogicalPosition,
1168
        timestamp: CoreInstant,
1168
        screen_position: LogicalPosition,
1168
    ) -> bool {
1168
        let Some(session_id) = self.touch_sessions.get(&touch_id).copied() else {
3
            return false;
        };
1165
        self.record_sample_for_session(session_id, position, timestamp, screen_position)
1168
    }
    /// A finger lifted (or the OS cancelled the touch): final sample + end
    /// the session and drop the id mapping.
4
    pub fn touch_up(
4
        &mut self,
4
        touch_id: u64,
4
        position: LogicalPosition,
4
        timestamp: CoreInstant,
4
        screen_position: LogicalPosition,
4
    ) {
4
        let Some(session_id) = self.touch_sessions.remove(&touch_id) else {
1
            return;
        };
3
        let _ = self.record_sample_for_session(session_id, position, timestamp, screen_position);
3
        if let Some(session) = self
3
            .input_sessions
3
            .iter_mut()
4
            .find(|s| s.session_id == session_id)
3
        {
3
            session.ended = true;
3
        }
4
    }
    /// The OS cancelled the whole touch sequence (e.g. the compositor took
    /// the gesture over): end every touch session and drop the id map.
2
    pub fn touch_cancel_all(&mut self) {
2
        let ids: Vec<u64> = self.touch_sessions.values().copied().collect();
2
        self.touch_sessions.clear();
5
        for session_id in ids {
3
            if let Some(session) = self
3
                .input_sessions
3
                .iter_mut()
6
                .find(|s| s.session_id == session_id)
3
            {
3
                session.ended = true;
3
            }
        }
2
    }
    /// 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).
1172
    fn record_sample_for_session(
1172
        &mut self,
1172
        session_id: u64,
1172
        position: LogicalPosition,
1172
        timestamp: CoreInstant,
1172
        screen_position: LogicalPosition,
1172
    ) -> bool {
1172
        let Some(session) = self
1172
            .input_sessions
1172
            .iter_mut()
1179
            .find(|s| s.session_id == session_id)
        else {
3
            return false;
        };
1169
        if session.ended {
1
            return false;
1168
        }
1168
        if session.samples.len() >= MAX_SAMPLES_PER_SESSION {
2
            let remove_count = session.samples.len() - MAX_SAMPLES_PER_SESSION + DRAIN_BATCH_SIZE;
2
            session.samples.drain(0..remove_count);
1166
        }
1168
        session.samples.push(InputSample {
1168
            position,
1168
            screen_position,
1168
            timestamp,
1168
            button_state: TOUCH_CONTACT_BUTTON_STATE,
1168
            event_id: allocate_event_id(),
1168
            pressure: 0.5,
1168
            tilt: crate::callbacks::PenTilt {
1168
                x_tilt: 0.0,
1168
                y_tilt: 0.0,
1168
            },
1168
            touch_radius: LogicalSize::zero(),
1168
        });
1168
        true
1172
    }
    /// 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)]
3
    pub fn clear_old_sessions(&mut self, current_time: CoreInstant) {
4
        self.input_sessions.retain(|session| {
4
            if let Some(last_sample) = session.last_sample() {
3
                let duration = current_time.duration_since(&last_sample.timestamp);
3
                let age_ms = duration_to_millis(duration);
3
                age_ms < self.config.sample_cleanup_interval_ms
            } else {
1
                false
            }
4
        });
        // Also clear long press callback tracking for removed sessions
3
        let valid_session_ids: Vec<u64> =
3
            self.input_sessions.iter().map(|s| s.session_id).collect();
3
        self.long_press_callbacks_invoked
3
            .retain(|id| valid_session_ids.contains(id));
3
    }
    /// Clear all input sessions
    ///
    /// Call this when you want to reset all gesture detection state.
3
    pub fn clear_all_sessions(&mut self) {
3
        self.input_sessions.clear();
3
        self.long_press_callbacks_invoked.clear();
3
    }
    /// 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.
22
    pub fn update_pen_state(
22
        &mut self,
22
        position: LogicalPosition,
22
        pressure: f32,
22
        tilt: (f32, f32),
22
        in_contact: bool,
22
        is_eraser: bool,
22
        barrel_button_pressed: bool,
22
        device_id: u64,
22
    ) {
22
        self.update_pen_state_full(
22
            position,
22
            pressure,
22
            tilt,
22
            in_contact,
22
            is_eraser,
22
            barrel_button_pressed,
22
            device_id,
            0.0,
            0.0,
            0,
        );
22
    }
    /// Update pen/stylus state including the extended axes (W3C
    /// `PointerEvent.tangentialPressure` + `twist`) and per-tool id.
23
    pub fn update_pen_state_full(
23
        &mut self,
23
        position: LogicalPosition,
23
        pressure: f32,
23
        tilt: (f32, f32),
23
        in_contact: bool,
23
        is_eraser: bool,
23
        barrel_button_pressed: bool,
23
        device_id: u64,
23
        tangential_pressure: f32,
23
        barrel_roll_rad: f32,
23
        tool_id: u32,
23
    ) {
        // 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.
23
        let now = crate::probe::monotonic_now_nanos();
23
        if let Some(prev) = self.last_pen_sample_nanos {
5
            let dt_s = now.saturating_sub(prev) as f32 / 1e9;
5
            if dt_s > 0.0 && dt_s < 1.0 {
5
                let inst = 1.0 / dt_s.max(1e-4);
5
                self.pen_rate_ema_hz = if self.pen_rate_ema_hz > 0.0 {
1
                    self.pen_rate_ema_hz * 0.9 + inst * 0.1
                } else {
4
                    inst
                };
            } else {
                self.pen_rate_ema_hz = 0.0;
            }
18
        }
23
        self.last_pen_sample_nanos = Some(now);
23
        self.previous_pen_state = self.pen_state;
        self.pen_state = Some(PenState {
23
            position,
23
            pressure,
23
            tilt: crate::callbacks::PenTilt {
23
                x_tilt: tilt.0,
23
                y_tilt: tilt.1,
23
            },
23
            in_contact,
23
            is_eraser,
23
            barrel_button_pressed,
23
            device_id,
23
            tangential_pressure,
23
            barrel_roll_rad,
23
            tool_id,
23
            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.
23
            hover_distance: self.pen_state.map_or(0.0, |p| p.hover_distance),
23
            tool_kind: self
23
                .pen_state
23
                .map_or(TabletToolKind::Unknown, |p| p.tool_kind),
        });
23
        self.pen_event_pending = true;
23
    }
    /// 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) {
        if let Some(ref mut p) = self.pen_state {
            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.
4
    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.
4
        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.
4
        self.pending_dial_click = state.pressed && !self.dial_state.is_some_and(|d| d.pressed);
4
        self.dial_state = Some(state);
4
    }
    /// Clear the dial's pending events. The dll calls this after the pass has
    /// collected them, exactly as it does for the other providers.
3
    pub const fn clear_pending_dial(&mut self) {
3
        self.pending_dial_rotate = false;
3
        self.pending_dial_click = false;
3
    }
    /// The most recent dial rotation, if any dial has reported.
    #[must_use]
    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;
        } else {
            self.pending_pen_double_tap = true;
        }
        self.pen_event_pending = 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`.
    #[must_use]
180
    pub const fn peek_pen_barrel_gestures(&self) -> (bool, bool) {
180
        (self.pending_pen_squeeze, self.pending_pen_double_tap)
180
    }
    /// 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)
3
    pub const fn clear_pen_state(&mut self) {
3
        self.previous_pen_state = self.pen_state;
3
        self.pen_state = None;
3
        self.pen_event_pending = true;
        // Proximity ended: the next session measures afresh.
3
        self.last_pen_sample_nanos = None;
3
        self.pen_rate_ema_hz = 0.0;
3
    }
    /// Get current pen state (read-only)
    #[must_use]
209
    pub const fn get_pen_state(&self) -> Option<&PenState> {
209
        self.pen_state.as_ref()
209
    }
    /// Get the previous pen state (for event diffing).
    #[must_use]
11
    pub const fn get_previous_pen_state(&self) -> Option<&PenState> {
11
        self.previous_pen_state.as_ref()
11
    }
    /// Clear the pen-event-pending flag (called by the event loop after a pass).
146
    pub fn clear_pen_event_pending(&mut self) {
146
        self.pen_event_pending = false;
        // The seats' flags share the primary's lifecycle: one clear per
        // event pass (9b-ii-b-i-b).
146
        for pen in self.seat_pens.values_mut() {
            pen.event_pending = false;
        }
146
    }
    // --- 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(
        &mut self,
        seat_id: u64,
        position: LogicalPosition,
        pressure: f32,
        tilt: (f32, f32),
        in_contact: bool,
        is_eraser: bool,
        barrel_button_pressed: bool,
        device_id: u64,
        tangential_pressure: f32,
        barrel_roll_rad: f32,
        tool_id: u32,
    ) {
        if seat_id == azul_core::window::PRIMARY_POINTER_SEAT {
            self.update_pen_state_full(
                position,
                pressure,
                tilt,
                in_contact,
                is_eraser,
                barrel_button_pressed,
                device_id,
                tangential_pressure,
                barrel_roll_rad,
                tool_id,
            );
            return;
        }
        let now = crate::probe::monotonic_now_nanos();
        let pen = self.seat_pens.entry(seat_id).or_default();
        if let Some(prev) = pen.last_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);
                pen.rate_ema_hz = if pen.rate_ema_hz > 0.0 {
                    pen.rate_ema_hz * 0.9 + inst * 0.1
                } else {
                    inst
                };
            } else {
                pen.rate_ema_hz = 0.0;
            }
        }
        pen.last_sample_nanos = Some(now);
        pen.previous = pen.state;
        pen.state = Some(PenState {
            position,
            pressure,
            tilt: crate::callbacks::PenTilt {
                x_tilt: tilt.0,
                y_tilt: tilt.1,
            },
            in_contact,
            is_eraser,
            barrel_button_pressed,
            device_id,
            tangential_pressure,
            barrel_roll_rad,
            tool_id,
            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) {
        if seat_id == azul_core::window::PRIMARY_POINTER_SEAT {
            self.clear_pen_state();
            return;
        }
        if let Some(pen) = self.seat_pens.get_mut(&seat_id) {
            if pen.state.is_some() {
                pen.previous = pen.state;
                pen.state = None;
                pen.event_pending = true;
            }
            pen.last_sample_nanos = None;
            pen.rate_ema_hz = 0.0;
        }
    }
    pub fn set_pen_hover_distance_for(&mut self, seat_id: u64, distance: f32) {
        if seat_id == azul_core::window::PRIMARY_POINTER_SEAT {
            self.set_pen_hover_distance(distance);
            return;
        }
        if let Some(p) = self
            .seat_pens
            .get_mut(&seat_id)
            .and_then(|pen| pen.state.as_mut())
        {
            p.hover_distance = distance;
        }
    }
    pub fn set_pen_tool_kind_for(&mut self, seat_id: u64, kind: TabletToolKind) {
        if seat_id == azul_core::window::PRIMARY_POINTER_SEAT {
            self.set_pen_tool_kind(kind);
            return;
        }
        if let Some(p) = self
            .seat_pens
            .get_mut(&seat_id)
            .and_then(|pen| pen.state.as_mut())
        {
            p.tool_kind = kind;
        }
    }
    /// One seat's current pen, the primary's for seat 0.
    #[must_use]
    pub fn pen_state_for(&self, seat_id: u64) -> Option<&PenState> {
        if seat_id == azul_core::window::PRIMARY_POINTER_SEAT {
            self.pen_state.as_ref()
        } else {
            self.seat_pens
                .get(&seat_id)
                .and_then(|pen| pen.state.as_ref())
        }
    }
    /// The non-primary seats' pen slots - what the event pass diffs.
180
    pub fn seat_pen_diffs(&self) -> impl Iterator<Item = (u64, &SeatPen)> {
180
        self.seat_pens.iter().map(|(id, pen)| (*id, pen))
180
    }
    /// Set the latest Wacom tablet-pad state (called by the pad backend).
1
    pub const fn update_pad_state(&mut self, pad: TabletPadState) {
1
        self.pad_state = Some(pad);
1
    }
    /// The latest tablet-pad state, or `None` if no pad backend delivered one.
    #[must_use]
5
    pub const fn get_pad_state(&self) -> Option<&TabletPadState> {
5
        self.pad_state.as_ref()
5
    }
    /// Clear the tablet-pad state (pad disconnected / proximity left).
2
    pub const fn clear_pad_state(&mut self) {
2
        self.pad_state = None;
2
    }
    /// 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).
    #[must_use]
    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.
    #[must_use]
196
    pub fn detect_drag(&self) -> Option<DetectedDrag> {
196
        self.detect_drag_for(azul_core::window::PRIMARY_POINTER_SEAT)
196
    }
    /// `detect_drag` over ONE seat's current session (9b-ii-b-i).
    #[must_use]
196
    pub fn detect_drag_for(&self, seat_id: u64) -> Option<DetectedDrag> {
196
        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).
17
        if session.ended {
3
            return None;
14
        }
14
        if session.samples.len() < self.config.min_samples_for_gesture {
2
            return None;
12
        }
12
        let direct_distance = session.direct_distance()?;
12
        if direct_distance >= self.config.drag_distance_threshold {
8
            let first = session.first_sample()?;
8
            let last = session.last_sample()?;
            Some(DetectedDrag {
8
                start_position: first.position,
8
                current_position: last.position,
8
                direct_distance,
8
                total_distance: session.total_distance(),
8
                duration_ms: session.duration_ms()?,
8
                sample_count: session.samples.len(),
8
                session_id: session.session_id,
            })
        } else {
4
            None
        }
196
    }
    /// Detect if current input represents a long press
    ///
    /// Returns Some(DetectedLongPress) if button has been held long enough
    /// without moving much.
    #[must_use]
189
    pub fn detect_long_press(&self) -> Option<DetectedLongPress> {
23
        if let Some(NativeGestureEvent::LongPress(lp)) = self.native_gesture {
3
            return Some(lp);
186
        }
186
        self.detect_long_press_for(azul_core::window::PRIMARY_POINTER_SEAT)
189
    }
    /// `detect_long_press` over ONE seat's current session (9b-ii-b-i).
    #[must_use]
220
    pub fn detect_long_press_for(&self, seat_id: u64) -> Option<DetectedLongPress> {
220
        let session = self.current_session_for(seat_id)?;
9
        if session.ended {
4
            return None; // Can't be long press if button already released
5
        }
5
        let duration_ms = session.duration_ms()?;
5
        if duration_ms < self.config.long_press_time_threshold_ms {
1
            return None;
4
        }
4
        let distance = session.direct_distance()?;
4
        if distance <= self.config.long_press_distance_threshold {
3
            let first = session.first_sample()?;
3
            let callback_invoked = self
3
                .long_press_callbacks_invoked
3
                .contains(&session.session_id);
3
            Some(DetectedLongPress {
3
                position: first.position,
3
                duration_ms,
3
                callback_invoked,
3
                session_id: session.session_id,
3
            })
        } else {
1
            None
        }
220
    }
    /// 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.
3
    pub fn mark_current_long_press_invoked(&mut self) {
3
        if let Some(id) = self.get_current_session().map(|s| s.session_id) {
2
            self.mark_long_press_callback_invoked(id);
2
        }
3
    }
204
    pub fn mark_long_press_callback_invoked(&mut self, session_id: u64) {
204
        if !self.long_press_callbacks_invoked.contains(&session_id) {
6
            self.long_press_callbacks_invoked.push(session_id);
198
        }
204
    }
    /// 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.
    #[must_use]
204
    pub const fn has_injected_double_click(&self) -> bool {
202
        matches!(self.native_gesture, Some(NativeGestureEvent::DoubleClick))
204
    }
    /// 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).
    #[must_use]
24
    pub fn detect_double_click(&self) -> bool {
24
        if self.has_injected_double_click() {
1
            return true;
23
        }
23
        self.detect_double_click_for(azul_core::window::PRIMARY_POINTER_SEAT)
24
    }
    /// `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.
    #[must_use]
32
    pub fn detect_double_click_for(&self, seat_id: u64) -> bool {
32
        let sessions: Vec<&InputSession> = self.sessions_of(seat_id).collect();
32
        if sessions.len() < 2 {
26
            return false;
6
        }
6
        let prev_session = sessions[sessions.len() - 2];
6
        let last_session = sessions[sessions.len() - 1];
        // Both sessions must have ended (button released)
6
        if !prev_session.ended || !last_session.ended {
1
            return false;
5
        }
5
        let prev_first = prev_session.first_sample();
5
        let last_first = last_session.first_sample();
5
        let (Some(prev_first), Some(last_first)) = (prev_first, last_first) else {
1
            return false;
        };
4
        let duration = last_first.timestamp.duration_since(&prev_first.timestamp);
4
        let time_delta_ms = duration_to_millis(duration);
4
        if time_delta_ms > self.config.double_click_time_threshold_ms {
1
            return false;
3
        }
3
        let dx = last_first.position.x - prev_first.position.x;
3
        let dy = last_first.position.y - prev_first.position.y;
3
        let distance = dx.hypot(dy);
3
        distance < self.config.double_click_distance_threshold
32
    }
    /// 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).
    #[must_use]
341
    pub fn detect_click_count(&self) -> u32 {
341
        self.detect_click_count_for(azul_core::window::PRIMARY_POINTER_SEAT)
341
    }
    /// `detect_click_count` over ONE seat's sessions (9b-ii-b-i).
    #[must_use]
341
    pub fn detect_click_count_for(&self, seat_id: u64) -> u32 {
341
        let sessions: Vec<&InputSession> = self.sessions_of(seat_id).collect();
341
        let n = sessions.len();
341
        if n == 0 {
334
            return 1;
7
        }
        // 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.
7
        let mut recent: Vec<&InputSession> = Vec::new();
17
        for s in sessions.iter().rev() {
17
            if !s.ended && !recent.is_empty() {
                break;
17
            }
17
            recent.push(*s);
17
            if recent.len() >= 3 {
4
                break;
13
            }
        }
7
        if recent.is_empty() {
            return 1;
7
        }
        // recent[0] = most recent ended session
        // recent[1] = previous ended session (if any)
        // recent[2] = one before that (if any)
7
        let mut count = 1u32;
9
        for i in 0..recent.len() - 1 {
9
            let later = recent[i];
9
            let earlier = recent[i + 1];
9
            let Some(later_start) = later.first_sample() else {
                break;
            };
9
            let Some(earlier_start) = earlier.first_sample() else {
1
                break;
            };
8
            let duration = later_start
8
                .timestamp
8
                .duration_since(&earlier_start.timestamp);
8
            let time_delta_ms = duration_to_millis(duration);
8
            if time_delta_ms > self.config.double_click_time_threshold_ms {
1
                break;
7
            }
7
            let dx = later_start.position.x - earlier_start.position.x;
7
            let dy = later_start.position.y - earlier_start.position.y;
7
            let distance = dx.hypot(dy);
7
            if distance >= self.config.double_click_distance_threshold {
1
                break;
6
            }
6
            count += 1;
        }
        // Cap at 3 (triple-click selects paragraph, beyond that cycles back)
7
        if count > 3 {
            1
        } else {
7
            count
        }
341
    }
    /// Get the primary direction of current drag.
    #[must_use]
10
    pub fn get_drag_direction(&self) -> Option<GestureDirection> {
10
        let session = self.get_current_session()?;
9
        let first = session.first_sample()?;
9
        let last = session.last_sample()?;
9
        let dx = last.position.x - first.position.x;
9
        let dy = last.position.y - first.position.y;
9
        let direction = match (dx.abs() > dy.abs(), dx > 0.0, dy > 0.0) {
2
            (true, true, _) => GestureDirection::Right,
1
            (true, false, _) => GestureDirection::Left,
2
            (false, _, true) => GestureDirection::Down,
4
            (false, _, false) => GestureDirection::Up,
        };
9
        Some(direction)
10
    }
    /// Get average velocity of current gesture (pixels per second)
    #[allow(clippy::cast_precision_loss)] // bounded layout/render numeric cast
    #[must_use]
192
    pub fn get_gesture_velocity(&self) -> Option<f32> {
192
        let session = self.get_current_session()?;
14
        if session.samples.len() < 2 {
4
            return None;
10
        }
10
        let total_distance = session.total_distance();
10
        let duration_ms = session.duration_ms()?;
10
        if duration_ms == 0 {
3
            return None;
7
        }
7
        let duration_secs = duration_ms as f32 / 1000.0;
7
        Some(total_distance / duration_secs)
192
    }
    /// Check if current gesture is a swipe (fast directional movement).
    #[must_use]
187
    pub fn is_swipe(&self) -> bool {
187
        self.get_gesture_velocity()
187
            .is_some_and(|v| v >= self.config.swipe_velocity_threshold)
187
    }
    /// Detect swipe with specific direction
    ///
    /// Returns Some(dir) if gesture is a fast swipe in a clear direction
    #[must_use]
186
    pub fn detect_swipe_direction(&self) -> Option<GestureDirection> {
23
        if let Some(NativeGestureEvent::Swipe(d)) = self.native_gesture {
5
            return Some(d);
181
        }
        // Must be a fast swipe first
181
        if !self.is_swipe() {
180
            return None;
1
        }
        // Get direction
1
        self.get_drag_direction()
186
    }
    /// 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
    #[must_use]
195
    pub fn detect_pinch(&self) -> Option<DetectedPinch> {
23
        if let Some(NativeGestureEvent::Pinch(p)) = self.native_gesture {
9
            return Some(p);
186
        }
        // Need at least two active sessions for pinch
186
        if self.input_sessions.len() < 2 {
176
            return None;
10
        }
        // Get last two sessions (most recent touches)
10
        let session1 = &self.input_sessions[self.input_sessions.len() - 2];
10
        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.
10
        if session1.ended || session2.ended {
4
            return None;
6
        }
        // Both must have samples
6
        let first1 = session1.first_sample()?;
6
        let first2 = session2.first_sample()?;
6
        let last1 = session1.last_sample()?;
6
        let last2 = session2.last_sample()?;
        // Calculate initial distance between touches
6
        let dx_initial = first2.position.x - first1.position.x;
6
        let dy_initial = first2.position.y - first1.position.y;
6
        let initial_distance = dx_initial.hypot(dy_initial);
        // Calculate current distance
6
        let dx_current = last2.position.x - last1.position.x;
6
        let dy_current = last2.position.y - last1.position.y;
6
        let current_distance = dx_current.hypot(dy_current);
        // Avoid division by zero
6
        if initial_distance < 1.0 {
1
            return None;
5
        }
        // Calculate scale factor
5
        let scale = current_distance / initial_distance;
        // Check if scale change is significant (threshold from config)
5
        let scale_threshold = 1.0 + self.config.pinch_scale_threshold;
5
        if scale > 1.0 / scale_threshold && scale < scale_threshold {
1
            return None; // Change too small
4
        }
        // Calculate center point
4
        let center = LogicalPosition {
4
            x: f32::midpoint(last1.position.x, last2.position.x),
4
            y: f32::midpoint(last1.position.y, last2.position.y),
4
        };
        // Calculate duration
4
        let duration = last1.timestamp.duration_since(&first1.timestamp);
4
        let duration_ms = duration_to_millis(duration);
4
        Some(DetectedPinch {
4
            scale,
4
            center,
4
            initial_distance,
4
            current_distance,
4
            duration_ms,
4
        })
195
    }
    /// Detect rotation gesture (two-touch rotate)
    ///
    /// Returns Some if two touch points are rotating around center.
    /// Positive angle = clockwise, negative = counterclockwise.
    #[allow(clippy::similar_names)] // domain-standard coordinate/geometry/short-lived names
    #[must_use]
188
    pub fn detect_rotation(&self) -> Option<DetectedRotation> {
        const PI: f32 = core::f32::consts::PI;
23
        if let Some(NativeGestureEvent::Rotation(r)) = self.native_gesture {
8
            return Some(r);
180
        }
        // Need at least two active sessions
180
        if self.input_sessions.len() < 2 {
172
            return None;
8
        }
        // Get last two sessions
8
        let session1 = &self.input_sessions[self.input_sessions.len() - 2];
8
        let session2 = &self.input_sessions[self.input_sessions.len() - 1];
        // 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).
8
        if session1.ended || session2.ended {
4
            return None;
4
        }
        // Both must have samples
4
        let first1 = session1.first_sample()?;
4
        let first2 = session2.first_sample()?;
4
        let last1 = session1.last_sample()?;
4
        let last2 = session2.last_sample()?;
        // Calculate center (average of both touches)
4
        let center = LogicalPosition {
4
            x: f32::midpoint(last1.position.x, last2.position.x),
4
            y: f32::midpoint(last1.position.y, last2.position.y),
4
        };
        // Calculate initial angle between touches
4
        let dx_initial = first2.position.x - first1.position.x;
4
        let dy_initial = first2.position.y - first1.position.y;
4
        let initial_angle = dy_initial.atan2(dx_initial);
        // Calculate current angle
4
        let dx_current = last2.position.x - last1.position.x;
4
        let dy_current = last2.position.y - last1.position.y;
4
        let current_angle = dy_current.atan2(dx_current);
        // Calculate angle difference (normalized to -π to π)
4
        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
4
        while angle_diff > PI {
            angle_diff -= 2.0 * PI;
        }
        #[allow(clippy::while_float)]
        // intentional bounded float loop (angle-wrap / pixel-step); an integer counter would be
        // artificial
4
        while angle_diff < -PI {
            angle_diff += 2.0 * PI;
        }
        // Check if rotation is significant (threshold from config)
4
        if angle_diff.abs() < self.config.rotation_angle_threshold {
1
            return None;
3
        }
        // Calculate duration
3
        let duration = last1.timestamp.duration_since(&first1.timestamp);
3
        let duration_ms = duration_to_millis(duration);
3
        Some(DetectedRotation {
3
            angle_radians: angle_diff,
3
            center,
3
            duration_ms,
3
        })
188
    }
    /// Get the current active input session (if any)
    #[must_use]
1441
    pub fn get_current_session(&self) -> Option<&InputSession> {
1441
        self.last_primary_session()
1441
    }
    /// Every session of one seat, oldest first (9b-ii-b-i).
373
    pub fn sessions_of(&self, seat_id: u64) -> impl Iterator<Item = &InputSession> {
373
        self.input_sessions
373
            .iter()
383
            .filter(move |s| s.seat_id == seat_id)
373
    }
    /// The most recent session of one seat, ended or not.
    #[must_use]
1900
    pub fn current_session_for(&self, seat_id: u64) -> Option<&InputSession> {
1900
        self.input_sessions
1900
            .iter()
1900
            .rev()
1900
            .find(|s| s.seat_id == seat_id)
1900
    }
    /// The most recent PRIMARY session - what every "current session" reader
    /// means, and never a second seat's (9b-ii-b-i).
1441
    fn last_primary_session(&self) -> Option<&InputSession> {
1441
        self.current_session_for(azul_core::window::PRIMARY_POINTER_SEAT)
1441
    }
1253
    fn last_primary_session_mut(&mut self) -> Option<&mut InputSession> {
1253
        self.input_sessions
1253
            .iter_mut()
1253
            .rev()
1253
            .find(|s| s.seat_id == azul_core::window::PRIMARY_POINTER_SEAT)
1253
    }
    // --- 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(
        &mut self,
        seat_id: u64,
        position: LogicalPosition,
        timestamp: CoreInstant,
        button_state: u8,
        window_position: WindowPosition,
        screen_position: LogicalPosition,
    ) {
        let session_id = self.start_input_session(
            position,
            timestamp,
            button_state,
            window_position,
            screen_position,
        );
        if let Some(s) = self
            .input_sessions
            .iter_mut()
            .find(|s| s.session_id == session_id)
        {
            s.seat_id = seat_id;
        }
        self.seat_sessions.insert(seat_id, session_id);
    }
    pub fn seat_move(
        &mut self,
        seat_id: u64,
        position: LogicalPosition,
        timestamp: CoreInstant,
        screen_position: LogicalPosition,
    ) -> bool {
        let Some(session_id) = self.seat_sessions.get(&seat_id).copied() else {
            return false;
        };
        self.record_sample_for_session(session_id, position, timestamp, screen_position)
    }
    pub fn seat_up(
        &mut self,
        seat_id: u64,
        position: LogicalPosition,
        timestamp: CoreInstant,
        screen_position: LogicalPosition,
    ) {
        let Some(session_id) = self.seat_sessions.remove(&seat_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)
        {
            session.ended = true;
        }
    }
    /// Whether one seat's current session has become a DRAG: not ended and
    /// moved past the drag threshold.
    #[must_use]
    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.
    #[must_use]
34
    pub fn seat_drag_started_now(&self, seat_id: u64) -> bool {
34
        let Some(session) = self.current_session_for(seat_id) else {
34
            return false;
        };
        if session.ended || session.samples.len() < self.config.min_samples_for_gesture {
            return false;
        }
        let Some(first) = session.first_sample() else {
            return false;
        };
        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 {
            return false;
        }
        n < 2 || dist(&session.samples[n - 2]) < self.config.drag_distance_threshold
34
    }
    /// Whether one seat's most recent session - which has just ended - had
    /// been a drag, so its release is a `DragEnd`.
    #[must_use]
9
    pub fn seat_drag_just_ended(&self, seat_id: u64) -> bool {
9
        let Some(session) = self.current_session_for(seat_id) else {
9
            return false;
        };
        session.ended
            && session
                .direct_distance()
                .is_some_and(|d| d >= self.config.drag_distance_threshold)
9
    }
    /// Get current mouse position from latest sample
    #[must_use]
3
    pub fn get_current_mouse_position(&self) -> Option<LogicalPosition> {
3
        self.get_current_session()
3
            .and_then(|s| s.last_sample())
3
            .map(|sample| sample.position)
3
    }
    /// 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.
    #[must_use]
5
    pub fn get_drag_delta(&self) -> Option<(f32, f32)> {
5
        let session = self.get_current_session()?;
3
        let first = session.first_sample()?;
3
        let last = session.last_sample()?;
3
        Some((
3
            last.position.x - first.position.x,
3
            last.position.y - first.position.y,
3
        ))
5
    }
    /// 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.).
    ///
    /// Returns `None` if there is no active session or not enough samples.
    #[must_use]
5
    pub fn get_drag_delta_screen(&self) -> Option<(f32, f32)> {
5
        let session = self.get_current_session()?;
3
        let first = session.first_sample()?;
3
        let last = session.last_sample()?;
3
        Some((
3
            last.screen_position.x - first.screen_position.x,
3
            last.screen_position.y - first.screen_position.y,
3
        ))
5
    }
    /// 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.
    #[must_use]
10
    pub fn get_drag_delta_screen_incremental(&self) -> Option<(f32, f32)> {
10
        let session = self.get_current_session()?;
2
        let len = session.samples.len();
2
        if len < 2 {
1
            return None;
1
        }
1
        let prev = &session.samples[len - 2];
1
        let last = &session.samples[len - 1];
1
        Some((
1
            last.screen_position.x - prev.screen_position.x,
1
            last.screen_position.y - prev.screen_position.y,
1
        ))
10
    }
    /// 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.
    #[must_use]
2
    pub fn get_window_position_at_session_start(&self) -> Option<WindowPosition> {
2
        let session = self.get_current_session()?;
1
        Some(session.window_position_at_start)
2
    }
    // ========================================================================
    // UNIFIED DRAG CONTEXT API (NEW)
    // ========================================================================
    /// Get the active drag context (if any)
    #[must_use]
8
    pub const fn get_drag_context(&self) -> Option<&DragContext> {
8
        self.active_drag.as_ref()
8
    }
    /// Get the active drag context mutably (if any)
1
    pub const fn get_drag_context_mut(&mut self) -> Option<&mut DragContext> {
1
        self.active_drag.as_mut()
1
    }
    // 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.
2
    pub const fn set_drag_source_node(&mut self, node: azul_core::dom::DomNodeId) {
2
        self.drag_source_node = azul_core::dom::OptionDomNodeId::Some(node);
2
    }
    /// 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).
    #[must_use]
182
    pub fn drag_source_node(&self) -> Option<azul_core::dom::DomNodeId> {
182
        if self.active_drag.is_some() {
3
            self.drag_source_node.into_option()
        } else {
179
            None
        }
182
    }
3
    pub fn activate_node_drag(
3
        &mut self,
3
        dom_id: DomId,
3
        node_id: NodeId,
3
        drag_data: DragData,
3
        _start_hit_test: Option<HitTest>,
3
    ) {
3
        if let Some(detected) = self.detect_drag() {
1
            self.active_drag = Some(DragContext::node_drag(
1
                dom_id,
1
                node_id,
1
                detected.start_position,
1
                drag_data,
1
                detected.session_id,
1
            ));
2
        }
3
    }
    /// Activate a window move drag (titlebar)
6
    pub fn activate_window_drag(
6
        &mut self,
6
        initial_window_position: WindowPosition,
6
        _start_hit_test: Option<HitTest>,
6
    ) {
6
        if let Some(detected) = self.detect_drag() {
5
            self.active_drag = Some(DragContext::window_move(
5
                detected.start_position,
5
                initial_window_position,
5
                detected.session_id,
5
            ));
5
        }
6
    }
    // 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)
12
    pub const fn update_active_drag_positions(&mut self, position: LogicalPosition) {
12
        if let Some(ref mut drag) = self.active_drag {
11
            drag.update_position(position);
11
        }
12
    }
    /// Update drop target for node or file drag
4
    pub fn update_drop_target(&mut self, target: Option<azul_core::dom::DomNodeId>) {
4
        if let Some(ref mut drag) = self.active_drag {
3
            match &mut drag.drag_type {
2
                ActiveDragType::Node(ref mut node_drag) => {
2
                    node_drag.current_drop_target = target.into();
2
                }
                ActiveDragType::FileDrop(ref mut file_drop) => {
                    file_drop.drop_target = target.into();
                }
1
                _ => {}
            }
1
        }
4
    }
    /// End the current drag and return the context
2
    pub const fn end_drag(&mut self) -> Option<DragContext> {
2
        self.active_drag.take()
2
    }
    /// Cancel the current drag
2
    pub fn cancel_drag(&mut self) {
2
        if let Some(ref mut drag) = self.active_drag {
1
            drag.cancelled = true;
1
        }
2
        self.active_drag = None;
2
        self.drag_source_node = azul_core::dom::OptionDomNodeId::None;
2
    }
    // ========================================================================
    // QUERY METHODS
    // ========================================================================
    /// Check if any drag operation is in progress
    #[must_use]
368
    pub const fn is_dragging(&self) -> bool {
368
        self.active_drag.is_some()
368
    }
    /// Check if a text selection drag is active
    #[must_use]
5
    pub fn is_text_selection_dragging(&self) -> bool {
5
        self.active_drag
5
            .as_ref()
5
            .is_some_and(DragContext::is_text_selection)
5
    }
    /// Check if a scrollbar thumb drag is active
    #[must_use]
3
    pub fn is_scrollbar_dragging(&self) -> bool {
3
        self.active_drag
3
            .as_ref()
3
            .is_some_and(DragContext::is_scrollbar_thumb)
3
    }
    /// Check if a node drag is active
    #[must_use]
190
    pub fn is_node_drag_active(&self) -> bool {
190
        self.active_drag
190
            .as_ref()
190
            .is_some_and(DragContext::is_node_drag)
190
    }
    /// Check if a specific node is being dragged
    #[must_use]
6
    pub fn is_node_dragging(&self, dom_id: DomId, node_id: NodeId) -> bool {
6
        self.active_drag.as_ref().is_some_and(|d| {
5
            d.as_node_drag()
5
                .is_some_and(|node_drag| node_drag.dom_id == dom_id && node_drag.node_id == node_id)
5
        })
6
    }
    /// Check if window drag is active
    #[must_use]
8
    pub fn is_window_dragging(&self) -> bool {
8
        self.active_drag
8
            .as_ref()
8
            .is_some_and(DragContext::is_window_move)
8
    }
    /// Check if file drop is active
    #[must_use]
4
    pub fn is_file_dropping(&self) -> bool {
4
        self.active_drag
4
            .as_ref()
4
            .is_some_and(DragContext::is_file_drop)
4
    }
    /// Get number of active input sessions
    #[must_use]
12
    pub const fn session_count(&self) -> usize {
12
        self.input_sessions.len()
12
    }
    /// Get current session ID (if any)
    #[must_use]
7
    pub fn current_session_id(&self) -> Option<u64> {
7
        self.get_current_session().map(|s| s.session_id)
7
    }
    // ========================================================================
    // 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
    #[must_use]
6
    pub fn get_window_drag_delta(&self) -> Option<(i32, i32)> {
6
        let drag = self.active_drag.as_ref()?.as_window_move()?;
4
        let delta_x = drag.current_position.x - drag.start_position.x;
4
        let delta_y = drag.current_position.y - drag.start_position.y;
4
        match drag.initial_window_position {
3
            WindowPosition::Initialized(_initial_pos) => Some((delta_x as i32, delta_y as i32)),
1
            _ => None,
        }
6
    }
    /// Get the new window position based on current drag
    ///
    /// Returns the absolute window position to set.
    #[allow(clippy::cast_possible_truncation)] // bounded layout/render numeric cast
    #[must_use]
6
    pub fn get_window_position_from_drag(&self) -> Option<WindowPosition> {
6
        let drag = self.active_drag.as_ref()?.as_window_move()?;
5
        let delta_x = drag.current_position.x - drag.start_position.x;
5
        let delta_y = drag.current_position.y - drag.start_position.y;
5
        match drag.initial_window_position {
4
            WindowPosition::Initialized(initial_pos) => {
4
                Some(WindowPosition::Initialized(PhysicalPositionI32::new(
4
                    initial_pos.x + delta_x as i32,
4
                    initial_pos.y + delta_y as i32,
4
                )))
            }
1
            _ => None,
        }
6
    }
    /// Calculate the new scroll offset for scrollbar thumb drag
    #[must_use]
9
    pub fn get_scrollbar_scroll_offset(&self) -> Option<f32> {
9
        self.active_drag
9
            .as_ref()?
8
            .calculate_scrollbar_scroll_offset()
9
    }
}
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).
448
    fn remap_node_ids(&mut self, dom_id: DomId, map: &crate::managers::NodeIdMap) {
448
        if let Some(ref mut drag) = self.active_drag {
2
            if !drag.remap_node_ids(dom_id, map.as_btree_map()) {
1
                // Critical node removed — cancel the drag
1
                drag.cancelled = true;
1
                self.active_drag = None;
1
            }
446
        }
        // The drag SOURCE follows its node; an unmounted source ends the
        // gesture's targeting (Drag events fall back to the hover node).
448
        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),
                            ),
                        })
                    });
            }
448
        }
448
    }
}
#[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.
13
    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();
13
        let base = *BASE.get_or_init(std::time::Instant::now);
13
        (base + core::time::Duration::from_millis(n)).into()
13
    }
26
    fn pos(x: f32, y: f32) -> LogicalPosition {
26
        LogicalPosition { x, y }
26
    }
    #[test]
1
    fn two_fingers_open_two_concurrent_sessions() {
1
        let mut m = GestureAndDragManager::new();
1
        m.touch_down(
            1,
1
            pos(100.0, 100.0),
1
            ts(0),
1
            WindowPosition::Uninitialized,
1
            pos(100.0, 100.0),
        );
1
        m.touch_down(
            2,
1
            pos(200.0, 100.0),
1
            ts(1),
1
            WindowPosition::Uninitialized,
1
            pos(200.0, 100.0),
        );
1
        assert_eq!(m.input_sessions.len(), 2);
1
        assert!(!m.input_sessions[0].ended);
1
        assert!(!m.input_sessions[1].ended);
1
    }
    #[test]
1
    fn moves_land_in_the_correct_session_not_the_last_one() {
1
        let mut m = GestureAndDragManager::new();
1
        m.touch_down(
            1,
1
            pos(100.0, 100.0),
1
            ts(0),
1
            WindowPosition::Uninitialized,
1
            pos(100.0, 100.0),
        );
1
        m.touch_down(
            2,
1
            pos(200.0, 100.0),
1
            ts(1),
1
            WindowPosition::Uninitialized,
1
            pos(200.0, 100.0),
        );
        // 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).
1
        assert!(m.touch_move(1, pos(90.0, 100.0), ts(2), pos(90.0, 100.0)));
1
        assert_eq!(
1
            m.input_sessions[0].samples.len(),
            2,
            "finger 1 session grew"
        );
1
        assert_eq!(
1
            m.input_sessions[1].samples.len(),
            1,
            "finger 2 session untouched"
        );
1
    }
    #[test]
1
    fn spread_gesture_is_detected_as_pinch_out() {
1
        let mut m = GestureAndDragManager::new();
1
        m.touch_down(
            1,
1
            pos(100.0, 100.0),
1
            ts(0),
1
            WindowPosition::Uninitialized,
1
            pos(100.0, 100.0),
        );
1
        m.touch_down(
            2,
1
            pos(200.0, 100.0),
1
            ts(1),
1
            WindowPosition::Uninitialized,
1
            pos(200.0, 100.0),
        );
        // Spread: initial distance 100 → current distance 200.
1
        m.touch_move(1, pos(50.0, 100.0), ts(2), pos(50.0, 100.0));
1
        m.touch_move(2, pos(250.0, 100.0), ts(3), pos(250.0, 100.0));
1
        let pinch = m
1
            .detect_pinch()
1
            .expect("two concurrent touch sessions must yield a pinch");
1
        assert!(
1
            pinch.scale > 1.5,
            "spread must read as pinch-out (scale {}), initial {} current {}",
            pinch.scale,
            pinch.initial_distance,
            pinch.current_distance
        );
1
    }
    #[test]
1
    fn touch_up_ends_only_its_own_session() {
1
        let mut m = GestureAndDragManager::new();
1
        m.touch_down(
            1,
1
            pos(100.0, 100.0),
1
            ts(0),
1
            WindowPosition::Uninitialized,
1
            pos(100.0, 100.0),
        );
1
        m.touch_down(
            2,
1
            pos(200.0, 100.0),
1
            ts(1),
1
            WindowPosition::Uninitialized,
1
            pos(200.0, 100.0),
        );
1
        m.touch_up(1, pos(100.0, 100.0), ts(2), pos(100.0, 100.0));
1
        assert!(m.input_sessions[0].ended);
1
        assert!(!m.input_sessions[1].ended);
        // Further moves for the lifted finger are ignored.
1
        assert!(!m.touch_move(1, pos(0.0, 0.0), ts(3), pos(0.0, 0.0)));
1
    }
}
#[cfg(test)]
#[allow(clippy::float_cmp, clippy::unreadable_literal)]
mod autotest_generated {
    use azul_core::{
        drag::ScrollbarAxis,
        geom::PhysicalPositionI32,
        styled_dom::NodeHierarchyItemId,
        task::{SystemTick, SystemTickDiff, SystemTimeDiff},
    };
    use super::*;
    // ---------------------------------------------------------------- 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.
    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 }
    }
    /// 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,
            pressure: 0.5,
            tilt: crate::callbacks::PenTilt {
                x_tilt: 0.0,
                y_tilt: 0.0,
            },
            touch_radius: LogicalSize::zero(),
        }
    }
    /// 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,
            session_id,
            window_position_at_start: WindowPosition::Uninitialized,
            seat_id: azul_core::window::PRIMARY_POINTER_SEAT,
        }
    }
    /// 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 {
        let mut m = GestureAndDragManager::new();
        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)
    #[test]
    fn duration_to_millis_tick_zero_and_max_do_not_panic() {
        assert_eq!(
            duration_to_millis(CoreDuration::Tick(SystemTickDiff { tick_diff: 0 })),
            0
        );
        assert_eq!(
            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.
    #[test]
    fn duration_to_millis_converts_ticks_at_the_nominal_frame_rate() {
        assert_eq!(
            duration_to_millis(CoreDuration::Tick(SystemTickDiff { tick_diff: 60 })),
            1_000
        );
        assert_eq!(
            duration_to_millis(CoreDuration::Tick(SystemTickDiff { tick_diff: 30 })),
            500
        );
        assert_eq!(
            duration_to_millis(CoreDuration::Tick(SystemTickDiff { tick_diff: 1 })),
            16
        );
    }
    #[cfg(feature = "std")]
    #[test]
    fn duration_to_millis_system_zero_and_sub_millisecond_floor() {
        assert_eq!(
            duration_to_millis(CoreDuration::System(SystemTimeDiff { secs: 0, nanos: 0 })),
            0
        );
        // 999_999 ns is under a millisecond => floors to 0, never rounds up.
        assert_eq!(
            duration_to_millis(CoreDuration::System(SystemTimeDiff {
                secs: 0,
                nanos: 999_999
            })),
            0
        );
        assert_eq!(
            duration_to_millis(CoreDuration::System(SystemTimeDiff {
                secs: 2,
                nanos: 500_000_000
            })),
            2500
        );
    }
    #[cfg(feature = "std")]
    #[test]
    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
    #[test]
    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,
            touch_ring: 0.0,
            touch_ring_active: false,
            device_id: 0,
            // 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));
    }
    #[test]
    fn express_key_default_pad_has_no_keys_held() {
        let pad = TabletPadState::default();
        for i in 0..40u32 {
            assert!(
                !pad.express_key(i),
                "bit {i} must be unset on a default pad"
            );
        }
    }
    #[test]
    fn express_key_bitset_round_trips_every_bit() {
        for bit in 0..32u32 {
            let pad = TabletPadState {
                express_keys: 1u32 << bit,
                touch_ring: 0.0,
                touch_ring_active: false,
                device_id: 0,
                // Pad controls this site does not set; growing the struct
                // must not break every construction of it.
                ..Default::default()
            };
            for probe in 0..32u32 {
                assert_eq!(
                    pad.express_key(probe),
                    probe == bit,
                    "encode bit {bit} -> decode probe {probe}"
                );
            }
        }
    }
    // ------------------------------------------------- InputSession
    #[test]
    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());
        assert_eq!(
            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));
    }
    #[test]
    fn empty_session_getters_return_none_instead_of_panicking() {
        let s = InputSession {
            samples: Vec::new(),
            ended: false,
            session_id: 0,
            window_position_at_start: WindowPosition::Uninitialized,
            seat_id: azul_core::window::PRIMARY_POINTER_SEAT,
        };
        assert!(s.first_sample().is_none());
        assert!(s.last_sample().is_none());
        assert!(s.duration_ms().is_none());
        assert!(s.direct_distance().is_none());
        assert_eq!(s.total_distance(), 0.0);
    }
    #[test]
    fn duration_ms_saturates_to_zero_when_time_runs_backwards() {
        // last sample is *earlier* than the first (reordered / skewed clock).
        let s = InputSession {
            samples: vec![sample(0.0, 0.0, 900), sample(0.0, 0.0, 100)],
            ended: false,
            session_id: 1,
            window_position_at_start: WindowPosition::Uninitialized,
            seat_id: azul_core::window::PRIMARY_POINTER_SEAT,
        };
        assert_eq!(s.duration_ms(), Some(0));
    }
    #[cfg(feature = "std")]
    #[test]
    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
        let s = InputSession {
            samples: vec![first, last],
            ended: false,
            session_id: 1,
            window_position_at_start: WindowPosition::Uninitialized,
            seat_id: azul_core::window::PRIMARY_POINTER_SEAT,
        };
        assert_eq!(s.duration_ms(), Some(0));
    }
    #[test]
    fn total_distance_sums_the_path_while_direct_distance_is_the_chord() {
        let s = InputSession {
            samples: vec![
                sample(0.0, 0.0, 0),
                sample(3.0, 0.0, 1),
                sample(3.0, 4.0, 2),
            ],
            ended: false,
            session_id: 1,
            window_position_at_start: WindowPosition::Uninitialized,
            seat_id: azul_core::window::PRIMARY_POINTER_SEAT,
        };
        assert_eq!(s.total_distance(), 7.0);
        assert_eq!(s.direct_distance(), Some(5.0));
    }
    #[test]
    fn distances_with_nan_coordinates_are_nan_and_do_not_panic() {
        let s = InputSession {
            samples: vec![sample(0.0, 0.0, 0), sample(f32::NAN, f32::NAN, 1)],
            ended: false,
            session_id: 1,
            window_position_at_start: WindowPosition::Uninitialized,
            seat_id: azul_core::window::PRIMARY_POINTER_SEAT,
        };
        assert!(s.total_distance().is_nan());
        assert!(s.direct_distance().is_some_and(f32::is_nan));
    }
    #[test]
    fn distances_at_f32_extremes_saturate_to_infinity_instead_of_panicking() {
        let s = InputSession {
            samples: vec![
                sample(-f32::MAX, -f32::MAX, 0),
                sample(f32::MAX, f32::MAX, 1),
            ],
            ended: false,
            session_id: 1,
            window_position_at_start: WindowPosition::Uninitialized,
            seat_id: azul_core::window::PRIMARY_POINTER_SEAT,
        };
        assert!(s.total_distance().is_infinite());
        assert!(s.direct_distance().is_some_and(f32::is_infinite));
    }
    // ------------------------------------------------- construction
    #[test]
    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());
    }
    #[test]
    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);
        assert_eq!(m.session_count(), 0);
        let id = m.start_input_session(
            pos(0.0, 0.0),
            ts(0),
            0x01,
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        assert_eq!(id, 1, "with_config must not disturb the session counter");
        // min_samples_for_gesture == usize::MAX can never be reached => no drag.
        assert!(m.detect_drag().is_none());
    }
    // ------------------------------------------------- session recording
    #[test]
    fn session_ids_are_monotonic_starting_at_one() {
        let mut m = GestureAndDragManager::new();
        for expected in 1..=5u64 {
            let id = m.start_input_session(
                pos(0.0, 0.0),
                ts(expected),
                0x01,
                WindowPosition::Uninitialized,
                pos(0.0, 0.0),
            );
            assert_eq!(id, expected);
            assert_eq!(m.current_session_id(), Some(expected));
            m.end_current_session();
        }
    }
    #[test]
    fn session_id_counter_at_the_u64_boundary_does_not_overflow() {
        let mut m = GestureAndDragManager::new();
        m.next_session_id = u64::MAX - 1;
        let id = m.start_input_session(
            pos(0.0, 0.0),
            ts(0),
            0xFF,
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        assert_eq!(id, u64::MAX - 1);
        assert_eq!(m.next_session_id, u64::MAX);
    }
    #[test]
    fn recording_without_or_after_a_session_returns_false() {
        let mut m = GestureAndDragManager::new();
        assert!(!m.record_input_sample(pos(1.0, 1.0), ts(1), 0x01, pos(1.0, 1.0)));
        m.start_input_session(
            pos(0.0, 0.0),
            ts(0),
            0x01,
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        assert!(m.record_input_sample(pos(1.0, 1.0), ts(1), 0x01, pos(1.0, 1.0)));
        m.end_current_session();
        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.end_current_session();
        m.clear_all_sessions();
        m.end_current_session();
        assert_eq!(m.session_count(), 0);
    }
    #[test]
    fn sample_count_stays_bounded_by_max_samples_per_session() {
        let mut m = GestureAndDragManager::new();
        m.start_input_session(
            pos(0.0, 0.0),
            ts(0),
            0x01,
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        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)));
            assert!(
                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);
    }
    #[test]
    fn pen_samples_accept_nan_inf_and_extreme_values() {
        let mut m = GestureAndDragManager::new();
        let id = m.start_input_session_with_pen(
            pos(f32::NAN, f32::INFINITY),
            ts(0),
            0xFF,
            u64::MAX,
            f32::NAN,
            (f32::INFINITY, f32::NEG_INFINITY),
            (-f32::MAX, f32::MAX),
            WindowPosition::Uninitialized,
            pos(f32::NEG_INFINITY, f32::NAN),
        );
        assert_eq!(id, 1);
        assert!(m.record_input_sample_with_pen(
            pos(0.0, 0.0),
            ts(u64::MAX),
            0x00,
            0,
            -1.0e30,
            (f32::NAN, f32::NAN),
            (f32::NAN, f32::NAN),
            pos(0.0, 0.0),
        ));
        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());
    }
    #[test]
    fn starting_a_session_prunes_all_but_the_newest_ended_session() {
        let mut m = GestureAndDragManager::new();
        for tick in [0u64, 10, 20] {
            m.start_input_session(
                pos(0.0, 0.0),
                ts(tick),
                0x01,
                WindowPosition::Uninitialized,
                pos(0.0, 0.0),
            );
            m.end_current_session();
        }
        // 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
    #[test]
    fn touch_ids_at_zero_and_u64_max_are_tracked_independently() {
        let mut m = GestureAndDragManager::new();
        m.touch_down(
            0,
            pos(0.0, 0.0),
            ts(0),
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        m.touch_down(
            u64::MAX,
            pos(50.0, 0.0),
            ts(1),
            WindowPosition::Uninitialized,
            pos(50.0, 0.0),
        );
        assert_eq!(m.session_count(), 2);
        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));
        assert!(m.input_sessions[0].ended);
        assert!(!m.input_sessions[1].ended);
    }
    #[test]
    fn touch_events_for_unknown_ids_are_ignored_without_panicking() {
        let mut m = GestureAndDragManager::new();
        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
        assert_eq!(m.session_count(), 0);
    }
    #[test]
    fn a_repeated_touch_down_for_the_same_id_rebinds_to_the_newest_session() {
        let mut m = GestureAndDragManager::new();
        m.touch_down(
            7,
            pos(0.0, 0.0),
            ts(0),
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        m.touch_down(
            7,
            pos(9.0, 9.0),
            ts(1),
            WindowPosition::Uninitialized,
            pos(9.0, 9.0),
        );
        assert_eq!(m.touch_sessions.len(), 1, "the id map must not grow");
        assert_eq!(m.session_count(), 2);
        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[0].ended);
        assert!(m.input_sessions[1].ended);
        assert!(m.touch_sessions.is_empty());
    }
    #[test]
    fn touch_cancel_all_ends_every_finger_and_empties_the_id_map() {
        let mut m = GestureAndDragManager::new();
        for id in 0..3u64 {
            m.touch_down(
                id,
                pos(id as f32 * 10.0, 0.0),
                ts(id),
                WindowPosition::Uninitialized,
                pos(id as f32 * 10.0, 0.0),
            );
        }
        m.touch_cancel_all();
        assert!(m.touch_sessions.is_empty());
        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)));
    }
    #[test]
    fn touch_moves_after_clear_all_sessions_are_dropped_not_resurrected() {
        let mut m = GestureAndDragManager::new();
        m.touch_down(
            1,
            pos(0.0, 0.0),
            ts(0),
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        m.clear_all_sessions();
        // 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)));
        assert_eq!(m.session_count(), 0);
    }
    #[test]
    fn record_sample_for_session_rejects_unknown_and_ended_sessions() {
        let mut m = GestureAndDragManager::new();
        assert!(!m.record_sample_for_session(u64::MAX, pos(0.0, 0.0), ts(0), pos(0.0, 0.0)));
        let id = m.start_input_session(
            pos(0.0, 0.0),
            ts(0),
            0x01,
            WindowPosition::Uninitialized,
            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)));
        m.end_current_session();
        assert!(!m.record_sample_for_session(id, pos(2.0, 0.0), ts(2), pos(2.0, 0.0)));
        assert_eq!(m.input_sessions[0].samples.len(), 2);
    }
    #[test]
    fn record_sample_for_session_is_also_bounded_by_max_samples() {
        let mut m = GestureAndDragManager::new();
        m.touch_down(
            1,
            pos(0.0, 0.0),
            ts(0),
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        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
    #[test]
    fn clear_old_sessions_reaps_stale_sessions_and_their_long_press_ids() {
        let mut m = GestureAndDragManager::new();
        let old = m.start_input_session(
            pos(0.0, 0.0),
            ts(0),
            0x01,
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        m.end_current_session();
        m.mark_long_press_callback_invoked(old);
        let fresh = m.start_input_session(
            pos(0.0, 0.0),
            ts(10_000),
            0x01,
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        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));
        assert_eq!(
            m.debug_counts(),
            (1, 1),
            "long-press bookkeeping must not grow unboundedly"
        );
    }
    #[test]
    fn clear_old_sessions_drops_sessions_that_have_no_samples() {
        let mut m = GestureAndDragManager::new();
        m.input_sessions.push(InputSession {
            samples: Vec::new(),
            ended: false,
            session_id: 99,
            window_position_at_start: WindowPosition::Uninitialized,
            seat_id: azul_core::window::PRIMARY_POINTER_SEAT,
        });
        m.clear_old_sessions(ts(0));
        assert_eq!(m.session_count(), 0);
    }
    #[test]
    fn clear_old_sessions_with_a_backwards_clock_keeps_everything() {
        let mut m = GestureAndDragManager::new();
        m.start_input_session(
            pos(0.0, 0.0),
            ts(5_000),
            0x01,
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        // `now` is *before* the sample: duration_since saturates to 0 => age 0.
        m.clear_old_sessions(ts(0));
        assert_eq!(m.session_count(), 1);
    }
    #[test]
    fn clear_all_sessions_resets_both_counters() {
        let mut m = GestureAndDragManager::new();
        m.start_input_session(
            pos(0.0, 0.0),
            ts(0),
            0x01,
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        m.mark_current_long_press_invoked();
        assert_eq!(m.debug_counts(), (1, 1));
        m.clear_all_sessions();
        assert_eq!(m.debug_counts(), (0, 0));
        assert!(m.get_current_session().is_none());
    }
    #[test]
    fn long_press_invocation_marks_are_deduplicated() {
        let mut m = GestureAndDragManager::new();
        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.
        m.mark_current_long_press_invoked();
        assert_eq!(m.debug_counts(), (0, 2));
    }
    // ------------------------------------------------- drag / long-press detection
    #[test]
    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
            .detect_drag()
            .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);
        assert!(m.detect_drag().is_none());
    }
    #[test]
    fn detect_drag_with_nan_movement_returns_none() {
        let m = dragging_manager(pos(0.0, 0.0), pos(f32::NAN, f32::NAN), 20);
        assert!(
            m.detect_drag().is_none(),
            "NaN distance is never >= threshold"
        );
    }
    #[test]
    fn detect_drag_needs_min_samples_for_gesture() {
        let mut m = GestureAndDragManager::new();
        m.start_input_session(
            pos(0.0, 0.0),
            ts(0),
            0x01,
            WindowPosition::Uninitialized,
            pos(500.0, 500.0),
        );
        assert!(m.detect_drag().is_none(), "one sample is not a gesture");
    }
    #[test]
    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);
        assert!(m.detect_long_press().is_none());
        // Long enough but moved too far (> 10px).
        let m = dragging_manager(pos(0.0, 0.0), pos(11.0, 0.0), 800);
        assert!(m.detect_long_press().is_none());
    }
    #[test]
    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());
        m.mark_current_long_press_invoked();
        let lp = m.detect_long_press().expect("still held");
        assert!(
            lp.callback_invoked,
            "a marked long press must report callback_invoked"
        );
        m.end_current_session();
        assert!(
            m.detect_long_press().is_none(),
            "a released button cannot be a long press"
        );
    }
    // ------------------------------------------------- click counting
    #[test]
    fn detect_double_click_checks_both_timing_and_distance() {
        let mut m = GestureAndDragManager::new();
        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);
        assert!(!m.detect_double_click());
        // 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);
        assert!(!m.detect_double_click());
        // 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;
        assert!(!m.detect_double_click());
    }
    #[test]
    fn detect_double_click_needs_two_sessions() {
        let mut m = GestureAndDragManager::new();
        m.input_sessions = vec![ended_session(1, vec![sample(0.0, 0.0, 0)])];
        assert!(!m.detect_double_click());
    }
    #[test]
    fn detect_click_count_counts_up_to_three_and_stops_at_the_first_gap() {
        let mut m = GestureAndDragManager::new();
        // Three ended clicks, each 100ms apart at (nearly) the same point.
        m.input_sessions = vec![
            ended_session(1, vec![sample(10.0, 10.0, 0)]),
            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);
        assert_eq!(m.detect_click_count(), 1);
        // 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);
        assert_eq!(m.detect_click_count(), 3);
        // 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);
        assert_eq!(m.detect_click_count(), 2);
    }
    #[test]
    fn detect_click_count_ignores_live_sessions_and_defaults_to_one() {
        let mut m = GestureAndDragManager::new();
        // Only a live (un-ended) session => nothing to count => 1.
        m.start_input_session(
            pos(0.0, 0.0),
            ts(0),
            0x01,
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        assert_eq!(m.detect_click_count(), 1);
        assert_eq!(GestureAndDragManager::new().detect_click_count(), 1);
    }
    #[test]
    fn detect_click_count_with_empty_sample_vec_does_not_panic() {
        let mut m = GestureAndDragManager::new();
        m.input_sessions = vec![
            ended_session(1, Vec::new()),
            ended_session(2, vec![sample(0.0, 0.0, 10)]),
        ];
        assert_eq!(m.detect_click_count(), 1);
        assert!(!m.detect_double_click());
    }
    // ------------------------------------------------- direction / velocity / swipe
    #[test]
    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);
        assert_eq!(m.get_drag_direction(), Some(GestureDirection::Up));
    }
    #[test]
    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);
            assert_eq!(
                m.get_drag_direction(),
                Some(expected),
                "drag to ({}, {})",
                to.x,
                to.y
            );
        }
    }
    #[test]
    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);
        assert!(m.get_gesture_velocity().is_none());
        assert!(!m.is_swipe());
        assert!(m.detect_swipe_direction().is_none());
        // A single sample is not enough either.
        let mut m = GestureAndDragManager::new();
        m.start_input_session(
            pos(0.0, 0.0),
            ts(0),
            0x01,
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        assert!(m.get_gesture_velocity().is_none());
    }
    #[test]
    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());
    }
    #[test]
    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
    #[test]
    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.
        let mut m = GestureAndDragManager::new();
        m.start_input_session(
            pos(0.0, 0.0),
            ts(0),
            0x01,
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        m.end_current_session();
        m.start_input_session(
            pos(200.0, 0.0),
            ts(10),
            0x01,
            WindowPosition::Uninitialized,
            pos(200.0, 0.0),
        );
        m.record_input_sample(pos(400.0, 0.0), ts(20), 0x01, pos(400.0, 0.0));
        assert_eq!(m.session_count(), 2);
        assert!(
            m.detect_pinch().is_none(),
            "an ended session is not a finger"
        );
        assert!(m.detect_rotation().is_none());
    }
    #[test]
    fn pinch_returns_none_when_the_fingers_start_on_top_of_each_other() {
        let mut m = GestureAndDragManager::new();
        m.touch_down(
            1,
            pos(100.0, 100.0),
            ts(0),
            WindowPosition::Uninitialized,
            pos(100.0, 100.0),
        );
        m.touch_down(
            2,
            pos(100.5, 100.0),
            ts(1),
            WindowPosition::Uninitialized,
            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));
        assert!(m.detect_pinch().is_none());
    }
    #[test]
    fn pinch_below_the_scale_threshold_is_not_reported() {
        let mut m = GestureAndDragManager::new();
        m.touch_down(
            1,
            pos(100.0, 100.0),
            ts(0),
            WindowPosition::Uninitialized,
            pos(100.0, 100.0),
        );
        m.touch_down(
            2,
            pos(200.0, 100.0),
            ts(1),
            WindowPosition::Uninitialized,
            pos(200.0, 100.0),
        );
        // 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));
        assert!(m.detect_pinch().is_none());
    }
    #[test]
    fn pinch_in_reports_a_scale_below_one() {
        let mut m = GestureAndDragManager::new();
        m.touch_down(
            1,
            pos(0.0, 0.0),
            ts(0),
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        m.touch_down(
            2,
            pos(200.0, 0.0),
            ts(1),
            WindowPosition::Uninitialized,
            pos(200.0, 0.0),
        );
        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);
    }
    #[test]
    fn pinch_with_infinite_coordinates_saturates_instead_of_panicking() {
        let mut m = GestureAndDragManager::new();
        m.touch_down(
            1,
            pos(0.0, 0.0),
            ts(0),
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        m.touch_down(
            2,
            pos(10.0, 0.0),
            ts(1),
            WindowPosition::Uninitialized,
            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
            .detect_pinch()
            .expect("an overflowing spread is still a pinch");
        assert!(
            !p.scale.is_finite(),
            "expected a saturated (non-finite) scale, got {}",
            p.scale
        );
        assert!(!p.scale.is_nan());
    }
    #[test]
    fn pinch_and_rotation_with_nan_coordinates_never_panic() {
        let mut m = GestureAndDragManager::new();
        m.touch_down(
            1,
            pos(f32::NAN, f32::NAN),
            ts(0),
            WindowPosition::Uninitialized,
            pos(f32::NAN, f32::NAN),
        );
        m.touch_down(
            2,
            pos(200.0, 100.0),
            ts(1),
            WindowPosition::Uninitialized,
            pos(200.0, 100.0),
        );
        // 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()));
        assert!(m
            .detect_rotation()
            .is_none_or(|r| !r.angle_radians.is_finite()));
    }
    #[test]
    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.
        let mut m = GestureAndDragManager::new();
        m.touch_down(
            1,
            pos(-f32::MAX, -f32::MAX),
            ts(0),
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        m.touch_down(
            2,
            pos(f32::MAX, f32::MAX),
            ts(1),
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        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));
    }
    #[test]
    fn rotation_reports_the_signed_angle_between_the_two_fingers() {
        let mut m = GestureAndDragManager::new();
        m.touch_down(
            1,
            pos(0.0, 0.0),
            ts(0),
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        m.touch_down(
            2,
            pos(10.0, 0.0),
            ts(1),
            WindowPosition::Uninitialized,
            pos(10.0, 0.0),
        );
        // 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");
        assert!(
            (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));
    }
    #[test]
    fn rotation_below_the_angle_threshold_is_not_reported() {
        let mut m = GestureAndDragManager::new();
        m.touch_down(
            1,
            pos(0.0, 0.0),
            ts(0),
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        m.touch_down(
            2,
            pos(1000.0, 0.0),
            ts(1),
            WindowPosition::Uninitialized,
            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));
        assert!(m.detect_rotation().is_none());
    }
    // ------------------------------------------------- native gesture override
    #[test]
    fn injected_native_gestures_win_over_the_in_process_detector() {
        let mut m = GestureAndDragManager::new();
        m.inject_native_gesture(NativeGestureEvent::DoubleClick);
        assert!(m.detect_double_click(), "no sessions, but the OS said so");
        m.clear_native_gesture();
        assert!(!m.detect_double_click());
        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));
        assert!(
            !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));
        m.clear_native_gesture();
        assert!(m.detect_long_press().is_none());
        assert!(m.detect_pinch().is_none());
        assert!(m.detect_rotation().is_none());
        assert!(m.detect_swipe_direction().is_none());
    }
    // ------------------------------------------------- pen / pad state
    #[test]
    fn pen_state_stores_extremes_verbatim_and_tracks_the_previous_state() {
        let mut m = GestureAndDragManager::new();
        m.update_pen_state(
            pos(1.0, 2.0),
            f32::NAN,
            (f32::INFINITY, f32::NEG_INFINITY),
            true,
            true,
            true,
            u64::MAX,
        );
        assert!(m.pen_event_pending);
        assert!(m.get_previous_pen_state().is_none());
        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(
            pos(0.0, 0.0),
            1.0,
            (0.0, 0.0),
            false,
            false,
            false,
            0,
            f32::NAN,
            -f32::MAX,
            u32::MAX,
        );
        assert!(m.pen_event_pending);
        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();
        assert!(m.get_pen_state().is_none());
        assert_eq!(
            m.get_previous_pen_state().map(|p| p.tool_id),
            Some(u32::MAX)
        );
        assert!(m.pen_event_pending);
        // Clearing twice must not panic and must not resurrect a state.
        m.clear_pen_state();
        assert!(m.get_pen_state().is_none());
        assert!(m.get_previous_pen_state().is_none());
    }
    #[test]
    fn pad_state_round_trips_and_clears() {
        let mut m = GestureAndDragManager::new();
        assert!(m.get_pad_state().is_none());
        m.update_pad_state(TabletPadState {
            express_keys: 0b1010,
            touch_ring: f32::NAN,
            touch_ring_active: true,
            device_id: u64::MAX,
            // Pad controls this site does not set; growing the struct
            // must not break every construction of it.
            ..Default::default()
        });
        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();
        assert!(m.get_pad_state().is_none());
        m.clear_pad_state();
        assert!(m.get_pad_state().is_none());
    }
    // ------------------------------------------------- drag deltas
    #[test]
    fn drag_deltas_use_window_local_and_screen_coordinates_independently() {
        let mut m = GestureAndDragManager::new();
        m.start_input_session(
            pos(10.0, 10.0),
            ts(0),
            0x01,
            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)));
        assert!(m.get_drag_delta_screen_incremental().is_none());
        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)));
        assert_eq!(
            m.get_window_position_at_session_start(),
            Some(WindowPosition::Initialized(PhysicalPositionI32::new(
                100, 100
            )))
        );
        assert_eq!(m.get_current_mouse_position(), Some(pos(20.0, 10.0)));
    }
    #[test]
    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
    #[test]
    fn activating_a_node_drag_without_a_detected_drag_is_a_no_op() {
        let mut m = GestureAndDragManager::new();
        // No session at all.
        m.activate_node_drag(DomId::ROOT_ID, NodeId::new(1), DragData::new(), None);
        assert!(!m.is_dragging());
        // 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_node_drag(DomId::ROOT_ID, NodeId::new(1), DragData::new(), None);
        assert!(!m.is_node_drag_active());
        m.activate_window_drag(WindowPosition::Uninitialized, None);
        assert!(!m.is_window_dragging());
    }
    #[test]
    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)));
        assert!(!m.is_window_dragging());
        assert!(!m.is_file_dropping());
        assert!(!m.is_text_selection_dragging());
        assert!(!m.is_scrollbar_dragging());
        assert!(m.get_window_drag_delta().is_none());
        assert!(m.get_scrollbar_scroll_offset().is_none());
        m.update_active_drag_positions(pos(42.0, -7.0));
        assert_eq!(
            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");
        assert_eq!(
            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);
        assert!(m
            .get_drag_context()
            .and_then(DragContext::as_node_drag)
            .unwrap()
            .current_drop_target
            .into_option()
            .is_none());
        assert!(m.is_node_drag_active());
        let ctx = m.end_drag().expect("the drag context is returned");
        assert_eq!(ctx.session_id, 1);
        assert!(!m.is_dragging());
        assert!(m.end_drag().is_none());
    }
    #[test]
    fn drop_target_updates_without_a_drag_do_not_panic() {
        let mut m = GestureAndDragManager::new();
        m.update_drop_target(None);
        m.update_active_drag_positions(pos(f32::NAN, f32::INFINITY));
        m.cancel_drag();
        assert!(!m.is_dragging());
        assert!(m.get_drag_context_mut().is_none());
    }
    #[test]
    fn a_text_selection_drag_is_not_a_node_drag() {
        let mut m = GestureAndDragManager::new();
        m.active_drag = Some(DragContext::text_selection(
            DomId::ROOT_ID,
            NodeId::new(2),
            pos(0.0, 0.0),
            11,
        ));
        assert!(m.is_text_selection_dragging());
        assert!(!m.is_node_drag_active());
        // update_drop_target must leave a text-selection drag untouched.
        m.update_drop_target(None);
        assert!(m.is_text_selection_dragging());
        m.cancel_drag();
        assert!(!m.is_dragging());
        assert!(!m.is_text_selection_dragging());
    }
    // ------------------------------------------------- window drag maths
    fn window_dragging_manager(initial: WindowPosition) -> GestureAndDragManager {
        let mut m = dragging_manager(pos(0.0, 0.0), pos(100.0, 0.0), 10);
        m.activate_window_drag(initial, None);
        assert!(m.is_window_dragging());
        m
    }
    #[test]
    fn window_drag_delta_needs_an_initialized_window_position() {
        let m = window_dragging_manager(WindowPosition::Uninitialized);
        assert!(m.get_window_drag_delta().is_none());
        assert!(m.get_window_position_from_drag().is_none());
    }
    #[test]
    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)));
        assert_eq!(
            m.get_window_position_from_drag(),
            Some(WindowPosition::Initialized(PhysicalPositionI32::new(40, 0)))
        );
    }
    #[test]
    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));
        assert_eq!(
            m.get_window_drag_delta(),
            Some((i32::MAX, i32::MIN)),
            "float->int casts must saturate, not wrap or trap"
        );
        assert_eq!(
            m.get_window_position_from_drag(),
            Some(WindowPosition::Initialized(PhysicalPositionI32::new(
                i32::MAX,
                i32::MIN
            )))
        );
    }
    #[test]
    fn window_drag_delta_with_nan_position_is_zero_not_a_trap() {
        let mut m =
            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)));
        assert_eq!(
            m.get_window_position_from_drag(),
            Some(WindowPosition::Initialized(PhysicalPositionI32::new(3, 4)))
        );
    }
    #[test]
    fn window_position_from_drag_at_the_i32_extremes_does_not_overflow() {
        // i32::MAX window origin dragged fully negative: MAX + MIN == -1.
        let mut m = window_dragging_manager(WindowPosition::Initialized(PhysicalPositionI32::new(
            i32::MAX,
            i32::MAX,
        )));
        m.update_active_drag_positions(pos(-f32::MAX, -f32::MAX));
        assert_eq!(
            m.get_window_position_from_drag(),
            Some(WindowPosition::Initialized(PhysicalPositionI32::new(
                -1, -1
            )))
        );
    }
    // ------------------------------------------------- scrollbar drag maths
    fn scrollbar_manager(
        start_offset: f32,
        track: f32,
        content: f32,
        viewport: f32,
    ) -> GestureAndDragManager {
        let mut m = GestureAndDragManager::new();
        m.active_drag = Some(DragContext::scrollbar_thumb(
            DomId::ROOT_ID,
            NodeId::new(1),
            ScrollbarAxis::Vertical,
            pos(0.0, 0.0),
            start_offset,
            track,
            content,
            viewport,
            1,
        ));
        m
    }
    #[test]
    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));
        assert_eq!(m.get_scrollbar_scroll_offset(), Some(0.0));
    }
    #[test]
    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);
        m.update_active_drag_positions(pos(0.0, 500.0));
        assert_eq!(m.get_scrollbar_scroll_offset(), Some(7.0));
    }
    #[test]
    fn scrollbar_offset_with_a_nan_mouse_position_does_not_panic() {
        let mut m = scrollbar_manager(0.0, 100.0, 1000.0, 100.0);
        m.update_active_drag_positions(pos(f32::NAN, f32::NAN));
        let v = m.get_scrollbar_scroll_offset();
        assert!(
            v.is_some_and(f32::is_nan),
            "a NaN mouse position must propagate as NaN, not panic: {v:?}"
        );
    }
    // ------------------------------------------------- event ids
    #[cfg(feature = "std")]
    #[test]
    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}");
    }
    #[cfg(not(feature = "std"))]
    #[test]
    fn allocate_event_id_is_zero_without_std() {
        assert_eq!(allocate_event_id(), 0);
    }
    #[cfg(feature = "std")]
    #[test]
    fn recorded_samples_get_distinct_event_ids() {
        let mut m = GestureAndDragManager::new();
        m.start_input_session(
            pos(0.0, 0.0),
            ts(0),
            0x01,
            WindowPosition::Uninitialized,
            pos(0.0, 0.0),
        );
        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.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[repr(C)]
pub struct DialState {
    /// Which dial, when a device has more than one. `0` = unidentified.
    pub device_id: u64,
    /// 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 {
4
    fn get_pending_events(
4
        &self,
4
        timestamp: azul_core::task::Instant,
4
    ) -> Vec<azul_core::events::SyntheticEvent> {
        use azul_core::{
            dom::DomNodeId,
            events::{EventData, EventSource, EventType, SyntheticEvent},
        };
4
        let mut events = Vec::new();
4
        if self.pending_dial_rotate {
2
            events.push(SyntheticEvent::new(
2
                EventType::DialRotate,
2
                EventSource::User,
2
                DomNodeId::ROOT,
2
                timestamp.clone(),
2
                // The payload is read through `CallbackInfo::get_dial_state()`,
2
                // the accessor that already existed — the same convention the
2
                // gamepad uses rather than duplicating the state into the event.
2
                EventData::None,
2
            ));
2
        }
4
        if self.pending_dial_click {
2
            events.push(SyntheticEvent::new(
2
                EventType::DialClick,
2
                EventSource::User,
2
                DomNodeId::ROOT,
2
                timestamp,
2
                EventData::None,
2
            ));
2
        }
4
        events
4
    }
}
#[cfg(test)]
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.
    #[test]
1
    fn a_held_dial_click_does_not_re_fire() {
        use azul_core::events::{EventProvider, EventType};
        use super::{DialState, GestureAndDragManager};
4
        let ts = || azul_core::task::Instant::Tick(azul_core::task::SystemTick::new(0));
1
        let dial = |delta: f32, pressed: bool| DialState {
            device_id: 1,
4
            delta_rad: delta,
            detent_count: 0.0,
4
            pressed,
4
            contact_position: azul_core::geom::OptionLogicalPosition::None,
4
        };
4
        let kinds = |m: &GestureAndDragManager| {
4
            m.get_pending_events(ts())
4
                .iter()
4
                .map(|e| e.event_type)
4
                .collect::<Vec<_>>()
4
        };
1
        let mut m = GestureAndDragManager::new();
1
        m.update_dial_state(dial(0.5, true));
1
        assert_eq!(kinds(&m), vec![EventType::DialRotate, EventType::DialClick]);
        // Still held, still turning: the rotation repeats, the click does not.
1
        m.clear_pending_dial();
1
        m.update_dial_state(dial(0.5, true));
1
        assert_eq!(
1
            kinds(&m),
1
            vec![EventType::DialRotate],
            "a HELD dial must not re-fire DialClick",
        );
        // Released and pressed again: a new edge.
1
        m.clear_pending_dial();
1
        m.update_dial_state(dial(0.0, false));
1
        assert!(kinds(&m).is_empty(), "no rotation and no press is no event");
1
        m.clear_pending_dial();
1
        m.update_dial_state(dial(0.0, true));
1
        assert_eq!(kinds(&m), vec![EventType::DialClick]);
1
    }
}
#[cfg(test)]
mod rotary_units_tests {
    use super::rotary_units_to_radians;
    /// A device reporting 20 units per radian, turned by a quarter turn.
    #[test]
1
    fn a_reported_resolution_converts_units_to_radians() {
1
        let quarter_turn = core::f32::consts::FRAC_PI_2;
1
        let scroll = quarter_turn * 20.0;
1
        let got = rotary_units_to_radians(scroll, 20.0);
1
        assert!((got - quarter_turn).abs() < 1e-5, "got {got}");
        // Direction survives: a crown turns both ways.
1
        assert!(rotary_units_to_radians(-10.0, 20.0) < 0.0);
1
    }
    /// 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.
    #[test]
1
    fn an_unknown_resolution_answers_zero_rather_than_infinity() {
5
        for bad in [0.0, -1.0, f32::NAN, f32::INFINITY] {
4
            let got = rotary_units_to_radians(10.0, bad);
4
            assert_eq!(
                got, 0.0,
                "resolution {bad} must answer 0.0, the value that means \"not measured\", got \
                 {got}"
            );
4
            assert!(got.is_finite());
        }
1
    }
    /// A nonsense SAMPLE is guarded too: an infinity here would come straight
    /// from the platform, and it must not become an infinite angle.
    #[test]
1
    fn a_nonfinite_sample_answers_zero() {
1
        assert_eq!(rotary_units_to_radians(f32::NAN, 20.0), 0.0);
1
        assert_eq!(rotary_units_to_radians(f32::INFINITY, 20.0), 0.0);
1
    }
}