1
//! Event and callback filtering module
2

            
3
#[cfg(not(feature = "std"))]
4
use alloc::string::{String, ToString};
5
use alloc::{
6
    boxed::Box,
7
    collections::{btree_map::BTreeMap, btree_set::BTreeSet},
8
    vec::Vec,
9
};
10

            
11
use azul_css::AzString;
12

            
13
use crate::{
14
    callbacks::Update,
15
    dom::{DomId, DomNodeId, On},
16
    geom::{LogicalPosition, LogicalRect},
17
    hit_test::{FullHitTest, HitTestItem},
18
    id::NodeId,
19
    styled_dom::{ChangedCssProperty, NodeHierarchyItemId},
20
    task::Instant,
21
    OrderedMap,
22
};
23

            
24
/// Easing functions for smooth scroll animations
25
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26
pub enum EasingFunction {
27
    Linear,
28
    EaseInOut,
29
    EaseOut,
30
    /// Critically-damped spring settle (ledger #28, per the animation
31
    /// design doc): position eases like a spring released toward the
32
    /// target — fast initial pull, asymptote-free exact landing. Evaluated
33
    /// analytically from normalized time (same curve family the scroll
34
    /// physics integrates numerically).
35
    Spring,
36
}
37

            
38
pub type RestyleNodes = BTreeMap<NodeId, Vec<ChangedCssProperty>>;
39
pub type RelayoutNodes = BTreeMap<NodeId, Vec<ChangedCssProperty>>;
40
pub type RelayoutWords = BTreeMap<NodeId, AzString>;
41

            
42
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43
pub struct FocusChange {
44
    pub old: Option<DomNodeId>,
45
    pub new: Option<DomNodeId>,
46
}
47

            
48
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49
pub struct CallbackToCall {
50
    pub node_id: NodeId,
51
    pub hit_test_item: Option<HitTestItem>,
52
    pub event_filter: EventFilter,
53
}
54

            
55
impl CallbackToCall {
56
    #[must_use]
57
1
    pub const fn new(
58
1
        node_id: NodeId,
59
1
        hit_test_item: Option<HitTestItem>,
60
1
        event_filter: EventFilter,
61
1
    ) -> Self {
62
1
        Self {
63
1
            node_id,
64
1
            hit_test_item,
65
1
            event_filter,
66
1
        }
67
1
    }
68

            
69
    /// Build a list of `CallbackToCall` entries for every node hit by the
70
    /// given hit test under the given DOM, tagged with `event_filter`.
71
    /// Returns an empty `Vec` when there is no hit test data for the DOM.
72
    #[must_use]
73
2
    pub fn from_hit_test(
74
2
        hit_test: &FullHitTest,
75
2
        dom_id: DomId,
76
2
        event_filter: EventFilter,
77
2
    ) -> Vec<Self> {
78
2
        let Some(hit) = hit_test.hovered_nodes.get(&dom_id) else {
79
1
            return Vec::new();
80
        };
81
1
        hit.regular_hit_test_nodes
82
1
            .iter()
83
1
            .map(|(node_id, item)| Self {
84
1
                node_id: *node_id,
85
1
                hit_test_item: Some(*item),
86
1
                event_filter,
87
1
            })
88
1
            .collect()
89
2
    }
90
}
91

            
92
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
93
#[must_use = "ProcessEventResult must be used to determine if relayout/repaint is needed"]
94
pub enum ProcessEventResult {
95
    DoNothing = 0,
96
    ShouldReRenderCurrentWindow = 1,
97
    ShouldUpdateDisplayListCurrentWindow = 2,
98
    // GPU transforms changed: do another hit-test and recurse
99
    // until nothing has changed anymore
100
    UpdateHitTesterAndProcessAgain = 3,
101
    // Restyle or runtime edit changed layout-affecting properties:
102
    // re-run layout on the EXISTING StyledDom (no DOM rebuild).
103
    ShouldIncrementalRelayout = 4,
104
    // Full DOM rebuild via user's layout_callback()
105
    ShouldRegenerateDomCurrentWindow = 5,
106
    ShouldRegenerateDomAllWindows = 6,
107
}
108

            
109
impl ProcessEventResult {
110
    #[must_use]
111
7864
    pub const fn order(&self) -> usize {
112
        use self::ProcessEventResult::{
113
            DoNothing, ShouldIncrementalRelayout, ShouldReRenderCurrentWindow,
114
            ShouldRegenerateDomAllWindows, ShouldRegenerateDomCurrentWindow,
115
            ShouldUpdateDisplayListCurrentWindow, UpdateHitTesterAndProcessAgain,
116
        };
117
7864
        match self {
118
3956
            DoNothing => 0,
119
2024
            ShouldReRenderCurrentWindow => 1,
120
494
            ShouldUpdateDisplayListCurrentWindow => 2,
121
92
            UpdateHitTesterAndProcessAgain => 3,
122
186
            ShouldIncrementalRelayout => 4,
123
1014
            ShouldRegenerateDomCurrentWindow => 5,
124
98
            ShouldRegenerateDomAllWindows => 6,
125
        }
126
7864
    }
127
}
128

            
129
impl PartialOrd for ProcessEventResult {
130
3806
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
131
3806
        self.order().partial_cmp(&other.order())
132
3806
    }
133
}
134

            
135
impl Ord for ProcessEventResult {
136
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
137
        self.order().cmp(&other.order())
138
    }
139
}
140

            
141
impl ProcessEventResult {
142
150
    pub fn max_self(self, other: Self) -> Self {
143
150
        self.max(other)
144
150
    }
145
}
146

            
147
/// Tracks the origin of an event for proper handling.
148
///
149
/// This allows the system to distinguish between user input, programmatic
150
/// changes, and synthetic events generated by UI components.
151
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
152
#[repr(C)]
153
pub enum EventSource {
154
    /// Direct user input (mouse, keyboard, touch, gamepad)
155
    User,
156
    /// API call (programmatic scroll, focus change, etc.)
157
    Programmatic,
158
    /// Generated from UI interaction (scrollbar drag, synthetic events)
159
    Synthetic,
160
    /// Generated from lifecycle hooks (mount, unmount, resize)
161
    Lifecycle,
162
}
163

            
164
/// Event propagation phase (similar to DOM Level 2 Events).
165
///
166
/// Events can be intercepted at different phases:
167
/// - **Capture**: Event travels from root down to target (rarely used)
168
/// - **Target**: Event is at the target element
169
/// - **Bubble**: Event travels from target back up to root (most common)
170
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
171
#[repr(C)]
172
#[derive(Default)]
173
pub enum EventPhase {
174
    /// Event travels from root down to target
175
    Capture,
176
    /// Event is at the target element
177
    Target,
178
    /// Event bubbles from target back up to root
179
    #[default]
180
    Bubble,
181
}
182

            
183
/// Mouse button identifier for mouse events.
184
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
185
#[repr(C)]
186
pub enum MouseButton {
187
    Left,
188
    Middle,
189
    Right,
190
    Other(u8),
191
}
192

            
193
/// Scroll delta mode (how scroll deltas should be interpreted).
194
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
195
#[repr(C)]
196
pub enum ScrollDeltaMode {
197
    /// Delta is in pixels
198
    Pixel,
199
    /// Delta is in lines (e.g., 3 lines of text)
200
    Line,
201
    /// Delta is in pages
202
    Page,
203
}
204

            
205
/// Scroll direction for conditional event filtering.
206
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
207
#[repr(C)]
208
pub enum ScrollDirection {
209
    Up,
210
    Down,
211
    Left,
212
    Right,
213
}
214

            
215
// ============================================================================
216
// W3C CSSOM View Module - Scroll Into View Types
217
// ============================================================================
218

            
219
/// W3C-compliant scroll-into-view options
220
///
221
/// These options control how an element is scrolled into view, following
222
/// the CSSOM View Module specification.
223
#[repr(C)]
224
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
225
pub struct ScrollIntoViewOptions {
226
    /// Vertical alignment: start, center, end, nearest (default: nearest)
227
    pub block: ScrollLogicalPosition,
228
    /// Horizontal alignment: start, center, end, nearest (default: nearest)
229
    /// Note: Named `inline_axis` to avoid conflict with C keyword `inline`
230
    pub inline_axis: ScrollLogicalPosition,
231
    /// Animation behavior: auto, instant, smooth (default: auto)
232
    pub behavior: ScrollIntoViewBehavior,
233
}
234

            
235
impl ScrollIntoViewOptions {
236
    /// Create options with "nearest" alignment for both axes
237
    #[must_use]
238
160
    pub const fn nearest() -> Self {
239
160
        Self {
240
160
            block: ScrollLogicalPosition::Nearest,
241
160
            inline_axis: ScrollLogicalPosition::Nearest,
242
160
            behavior: ScrollIntoViewBehavior::Auto,
243
160
        }
244
160
    }
245

            
246
    /// Create options with "center" alignment for both axes
247
    #[must_use]
248
2
    pub const fn center() -> Self {
249
2
        Self {
250
2
            block: ScrollLogicalPosition::Center,
251
2
            inline_axis: ScrollLogicalPosition::Center,
252
2
            behavior: ScrollIntoViewBehavior::Auto,
253
2
        }
254
2
    }
255

            
256
    /// Create options with "start" alignment for both axes
257
    #[must_use]
258
2
    pub const fn start() -> Self {
259
2
        Self {
260
2
            block: ScrollLogicalPosition::Start,
261
2
            inline_axis: ScrollLogicalPosition::Start,
262
2
            behavior: ScrollIntoViewBehavior::Auto,
263
2
        }
264
2
    }
265

            
266
    /// Create options to align the end of the target with the end of the viewport
267
    #[must_use]
268
1
    pub const fn end() -> Self {
269
1
        Self {
270
1
            block: ScrollLogicalPosition::End,
271
1
            inline_axis: ScrollLogicalPosition::End,
272
1
            behavior: ScrollIntoViewBehavior::Auto,
273
1
        }
274
1
    }
275

            
276
    /// Set instant scroll behavior
277
    #[must_use]
278
12
    pub const fn with_instant(mut self) -> Self {
279
12
        self.behavior = ScrollIntoViewBehavior::Instant;
280
12
        self
281
12
    }
282

            
283
    /// Set smooth scroll behavior
284
    #[must_use]
285
12
    pub const fn with_smooth(mut self) -> Self {
286
12
        self.behavior = ScrollIntoViewBehavior::Smooth;
287
12
        self
288
12
    }
289
}
290

            
291
/// Scroll alignment for vertical (block) or horizontal (inline) axis
292
///
293
/// Determines where the target element should be positioned within
294
/// the scroll container's visible area.
295
#[repr(C)]
296
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
297
pub enum ScrollLogicalPosition {
298
    /// Align target's start edge with container's start edge
299
    Start,
300
    /// Center target within container
301
    Center,
302
    /// Align target's end edge with container's end edge
303
    End,
304
    /// Minimum scroll distance to make target fully visible (default)
305
    #[default]
306
    Nearest,
307
}
308

            
309
/// Scroll animation behavior for scrollIntoView API
310
///
311
/// This is distinct from the CSS `scroll-behavior` property, as it also
312
/// supports the `Instant` option which CSS does not have.
313
#[repr(C)]
314
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
315
pub enum ScrollIntoViewBehavior {
316
    /// Respect CSS scroll-behavior property (default)
317
    #[default]
318
    Auto,
319
    /// Immediate jump without animation
320
    Instant,
321
    /// Animated smooth scroll
322
    Smooth,
323
}
324

            
325
/// Reason why a lifecycle event was triggered.
326
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
327
#[repr(C)]
328
pub enum LifecycleReason {
329
    /// First appearance in DOM
330
    InitialMount,
331
    /// Removed and re-added to DOM
332
    Remount,
333
    /// Layout bounds changed
334
    Resize,
335
    /// Props or state changed
336
    Update,
337
    /// Node was removed from DOM
338
    Unmount,
339
    /// A `<transient-window>` was closed by the USER (outside click, Escape),
340
    /// not by the app flipping `open`.
341
    Dismiss,
342
    /// A `<transient-window>` was torn off its anchor into a free toplevel
343
    /// by the user's drag. `current_bounds` is where it went, in the parent.
344
    TearOff,
345
    /// A torn-off `<transient-window>` was docked back (onto its anchor or a
346
    /// drop zone) by the user's drag.
347
    Dock,
348
}
349

            
350
/// Keyboard modifier keys state.
351
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default)]
352
#[repr(C)]
353
pub struct KeyModifiers {
354
    pub shift: bool,
355
    pub ctrl: bool,
356
    pub alt: bool,
357
    pub meta: bool,
358
}
359

            
360
impl KeyModifiers {
361
    #[must_use]
362
21
    pub fn new() -> Self {
363
21
        Self::default()
364
21
    }
365

            
366
    #[must_use]
367
5
    pub const fn with_shift(mut self) -> Self {
368
5
        self.shift = true;
369
5
        self
370
5
    }
371

            
372
    #[must_use]
373
10
    pub const fn with_ctrl(mut self) -> Self {
374
10
        self.ctrl = true;
375
10
        self
376
10
    }
377

            
378
    #[must_use]
379
3
    pub const fn with_alt(mut self) -> Self {
380
3
        self.alt = true;
381
3
        self
382
3
    }
383

            
384
    #[must_use]
385
3
    pub const fn with_meta(mut self) -> Self {
386
3
        self.meta = true;
387
3
        self
388
3
    }
389

            
390
    #[must_use]
391
8
    pub const fn is_empty(&self) -> bool {
392
8
        !self.shift && !self.ctrl && !self.alt && !self.meta
393
8
    }
394
}
395

            
396
/// What kind of device produced a pointer event.
397
///
398
/// The same discriminator the web calls `PointerEvent.pointerType`, GTK calls
399
/// `GdkInputSource` and Qt calls `QInputDevice::DeviceType`. Azul splits Mouse,
400
/// Touch and Pen into separate FILTERS, which is a stronger guarantee than a
401
/// runtime tag — but it cannot express the distinctions WITHIN the pointer
402
/// family, and those matter:
403
///
404
/// - A touchpad and a mouse both arrive as a synthesized pointer. Telling them apart is what lets
405
///   an app know a pinch gesture is possible at all, and whether "scroll" means a wheel detent or a
406
///   continuous drag.
407
/// - A trackball and a trackpoint have their own acceleration and scroll semantics, which is why
408
///   GTK and Android name them separately.
409
/// - A pen reported through the pointer path (a stylus acting as a mouse, the Wayland tablet
410
///   bridge) is not a finger and not a mouse.
411
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
412
#[repr(C)]
413
pub enum PointerSource {
414
    /// The platform did not say.
415
    Unknown,
416
    /// A mouse.
417
    Mouse,
418
    /// An indirect touch surface — a laptop trackpad or a Magic Trackpad.
419
    Touchpad,
420
    /// A trackball.
421
    Trackball,
422
    /// A pointing stick (`ThinkPad` nub).
423
    Trackpoint,
424
    /// A direct touch surface reporting through the pointer path.
425
    Touchscreen,
426
    /// A stylus tip.
427
    Pen,
428
    /// The inverted end of a stylus.
429
    Eraser,
430
}
431

            
432
/// Type-specific event data for mouse events.
433
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
434
#[repr(C)]
435
pub struct MouseEventData {
436
    /// Position of the mouse cursor
437
    pub position: LogicalPosition,
438
    /// Which button was pressed/released
439
    pub button: MouseButton,
440
    /// Bitmask of currently pressed buttons
441
    pub buttons: u8,
442
    /// Modifier keys state
443
    pub modifiers: KeyModifiers,
444
    /// What produced this event. APPENDED for ABI stability.
445
    pub source: PointerSource,
446
    /// Which physical device produced it, or `0` when the platform does not
447
    /// say. APPENDED for ABI stability.
448
    ///
449
    /// Only `PenState`, `GamepadState` and `TabletPadState` carried a device id
450
    /// before, so a mouse event could not say WHICH of two mice moved — and
451
    /// `MouseState` used to be a single global, which is why multi-seat (a
452
    /// kiosk, a shared display, two people on one compositor) was not
453
    /// expressible at all. The state fans out per seat since 9b-ii; this
454
    /// field stays the PHYSICAL device, `seat_id` below says which cursor.
455
    pub device_id: u64,
456
    /// Which pointer SEAT - which independent cursor - produced it. APPENDED
457
    /// (9b-ii). `PRIMARY_POINTER_SEAT` (0) for the ordinary mouse, which is
458
    /// every event on a platform with one cursor; an X11 MPX master id or a
459
    /// Wayland seat otherwise. A callback that receives a non-zero value
460
    /// reads that seat's state through `get_pointer_seat_state`, because
461
    /// `get_current_mouse_state` is the PRIMARY seat by definition.
462
    pub seat_id: u64,
463
}
464

            
465
impl Default for MouseEventData {
466
52
    fn default() -> Self {
467
52
        Self {
468
52
            position: LogicalPosition { x: 0.0, y: 0.0 },
469
52
            button: MouseButton::Left,
470
52
            buttons: 0,
471
52
            modifiers: KeyModifiers::default(),
472
52
            source: PointerSource::Unknown,
473
52
            device_id: 0,
474
52
            seat_id: crate::window::PRIMARY_POINTER_SEAT,
475
52
        }
476
52
    }
477
}
478

            
479
/// Type-specific event data for keyboard events.
480
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
481
pub struct KeyboardEventData {
482
    /// The virtual key code
483
    pub key_code: u32,
484
    /// The character produced (if any)
485
    pub char_code: Option<char>,
486
    /// Modifier keys state
487
    pub modifiers: KeyModifiers,
488
    /// Whether this is a repeat event
489
    pub repeat: bool,
490
    /// Which physical keyboard produced this event, or `0` when the platform
491
    /// does not say. APPENDED for ABI stability.
492
    ///
493
    /// Same reasoning as `MouseEventData::device_id`: with two keyboards
494
    /// attached — a laptop's built-in and an external, or a barcode scanner
495
    /// presenting as a keyboard — nothing could tell their input apart.
496
    pub device_id: u64,
497
    /// Which KEYBOARD SEAT pressed (9b-ii-a-i): `PRIMARY_POINTER_SEAT` for
498
    /// the ordinary keyboard, a seat id for a second person's - the same
499
    /// number their pointer events carry.
500
    pub seat_id: u64,
501
}
502

            
503
impl Default for KeyboardEventData {
504
3427
    fn default() -> Self {
505
3427
        Self {
506
3427
            key_code: 0,
507
3427
            char_code: None,
508
3427
            modifiers: KeyModifiers::default(),
509
3427
            repeat: false,
510
3427
            device_id: 0,
511
3427
            seat_id: crate::window::PRIMARY_POINTER_SEAT,
512
3427
        }
513
3427
    }
514
}
515

            
516
/// Type-specific event data for scroll events.
517
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
518
pub struct ScrollEventData {
519
    /// Scroll delta (dx, dy)
520
    pub delta: LogicalPosition,
521
    /// How the delta should be interpreted
522
    pub delta_mode: ScrollDeltaMode,
523
    /// Which pointer SEAT turned the wheel (9b-ii-b); `PRIMARY_POINTER_SEAT`
524
    /// for the ordinary mouse. A second cursor's wheel scrolls the node under
525
    /// THAT cursor, so the event names the seat the way a mouse event does.
526
    pub seat_id: u64,
527
}
528

            
529
/// Type-specific event data for touch events.
530
#[derive(Debug, Clone, Copy, PartialEq)]
531
pub struct TouchEventData {
532
    /// Touch identifier
533
    pub id: u64,
534
    /// Touch position
535
    pub position: LogicalPosition,
536
    /// Touch force/pressure (0.0 - 1.0)
537
    pub force: f32,
538
    /// The SEAT whose touchscreen this is (9b-ii-a-i-c); ids are per seat.
539
    pub seat_id: u64,
540
}
541

            
542
/// Type-specific event data for clipboard events.
543
#[derive(Debug, Clone, PartialEq, Eq)]
544
pub struct ClipboardEventData {
545
    /// The clipboard content (for paste events)
546
    pub content: Option<String>,
547
}
548

            
549
/// Type-specific event data for lifecycle events.
550
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
551
pub struct LifecycleEventData {
552
    /// Why this lifecycle event was triggered
553
    pub reason: LifecycleReason,
554
    /// Previous layout bounds (for resize events)
555
    pub previous_bounds: Option<LogicalRect>,
556
    /// Current layout bounds
557
    pub current_bounds: LogicalRect,
558
}
559

            
560
/// Type-specific event data for window events.
561
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
562
pub struct WindowEventData {
563
    /// Window size (for resize events)
564
    pub size: Option<LogicalRect>,
565
    /// Window position (for move events)
566
    pub position: Option<LogicalPosition>,
567
}
568

            
569
/// Type-specific event data for text-input (editing) events.
570
///
571
/// Data carried by `EventType::RawMouseMotion`.
572
///
573
/// Raw motion is what a 3D viewport, a map orbit, an infinite-drag number
574
/// scrubber and a first-person camera all need, and it is NOT the difference
575
/// between two cursor positions. Absolute positions have already had the OS
576
/// pointer-acceleration curve applied and are clamped to the screen, so
577
/// differencing them gives accelerated motion that stops dead at the edge of
578
/// the display. These deltas are pre-acceleration and unbounded.
579
/// Where the caret sits INSIDE an open IME preedit.
580
///
581
/// Both offsets are into the preedit string, not into the document: the
582
/// preedit is not committed text and has no position in the document until it
583
/// is. An IME uses this to place its candidate window under the segment being
584
/// edited, and a `begin != end` pair is a SELECTED segment - several IMEs
585
/// (Japanese conversion especially) move a highlighted region through the
586
/// preedit as the user cycles candidates.
587
///
588
/// A named struct rather than the `(usize, usize)` this used to be, because a
589
/// non-empty tuple has no C representation - so the accessor could not be
590
/// exposed at all and no binding could read an IME's caret.
591
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
592
#[repr(C)]
593
pub struct CompositionCursor {
594
    /// Start offset in the preedit, in bytes.
595
    pub begin: usize,
596
    /// End offset. Equal to `begin` for a caret with no selected segment.
597
    pub end: usize,
598
}
599

            
600
azul_css::impl_option!(
601
    CompositionCursor,
602
    OptionCompositionCursor,
603
    [Debug, Copy, Clone, PartialEq, Eq]
604
);
605

            
606
/// `#[repr(C)]` because `CallbackInfo::get_raw_mouse_motion` hands this
607
/// across the C API. Without it the layout is undefined at the boundary and
608
/// the generated bindings read garbage fields.
609
#[derive(Debug, Clone, Copy, PartialEq)]
610
#[repr(C)]
611
pub struct RawMotionEventData {
612
    /// Horizontal motion in the device's own units. NOT logical pixels: a
613
    /// mouse reports counts, whose size depends on its DPI, which is exactly
614
    /// why a sensitivity setting exists.
615
    pub dx: f64,
616
    /// Vertical motion, same units.
617
    pub dy: f64,
618
    /// Which device moved, or `0` when the platform does not say.
619
    pub device_id: u64,
620
}
621

            
622
azul_css::impl_option!(
623
    RawMotionEventData,
624
    OptionRawMotionEventData,
625
    [Debug, Copy, Clone, PartialEq]
626
);
627

            
628
/// Data carried by a `MediaControl` event (9h-i-a-i-a, 9h-i-a-i-b): what the
629
/// platform's media controls asked for.
630
///
631
/// The URI of an `OpenUri` is not repeated here -
632
/// `CallbackInfo::get_media_control_request` carries the whole request.
633
#[derive(Debug, Clone, Copy, PartialEq)]
634
#[repr(C)]
635
pub struct MediaControlEventData {
636
    /// Microseconds; relative for `SeekRelative`, absolute for `SeekAbsolute`.
637
    pub position_us: i64,
638
    pub kind: crate::media_session::MediaControlKind,
639
    /// The requested volume for `SetVolume` (`0.0` silent, `1.0` full), `0.0`
640
    /// for every other kind.
641
    pub volume: f32,
642
}
643

            
644
/// Data carried by a `SystemAudioChange` event (9h-i-a-i-d-i): what the
645
/// system did with the audio the app took over. Also readable through
646
/// `CallbackInfo::get_system_audio_change`.
647
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
648
#[repr(C)]
649
pub struct SystemAudioEventData {
650
    pub change: crate::media_session::SystemAudioChange,
651
}
652

            
653
/// Data carried by the three IME composition events.
654
///
655
/// Every desktop shell already runs a real IME client — Win32 `WM_IME_*` with
656
/// candidate-window positioning, macOS `NSTextInputClient`, Wayland
657
/// `zwp_text_input_v3` preedit/commit, X11 XIM plus the xkb Compose layer —
658
/// and all of it terminated in the engine's text cache. The built-in text
659
/// widgets therefore worked, but an app rendering its own composition (a code
660
/// editor, a terminal, a chat box with inline candidates) had no way to see
661
/// it, because the `Composition*` filters had no event to carry.
662
///
663
/// The shape is the intersection of what the platforms report, which is also
664
/// what W3C `CompositionEvent` and Wayland `preedit_string` agree on.
665
#[derive(Debug, Clone, PartialEq, Eq)]
666
pub struct CompositionEventData {
667
    /// The preedit (composition) text as it currently stands. Empty on
668
    /// `CompositionStart`, and on `CompositionEnd` this is the committed
669
    /// string — W3C defines `compositionend.data` as what was committed, not
670
    /// what was pending.
671
    pub data: String,
672
    /// Byte offset of the selection/caret start within `data`. Wayland sends
673
    /// this directly (`preedit_string(text, cursor_begin, cursor_end)`);
674
    /// Win32 derives it from `GCS_CURSORPOS`; macOS from the `selectedRange`
675
    /// passed to `setMarkedText:selectedRange:replacementRange:`.
676
    pub cursor_begin: usize,
677
    /// Byte offset of the selection/caret end within `data`. Equal to
678
    /// `cursor_begin` for a collapsed caret.
679
    pub cursor_end: usize,
680
    /// The SEAT whose input method this is (9b-ii-a-i-d-ii-c-i); the primary
681
    /// is `PRIMARY_POINTER_SEAT`. The Focus filter delivers a seat's
682
    /// composition to that seat's focused node.
683
    pub seat_id: u64,
684
}
685

            
686
/// Carried by `EventType::Input` events so that text-input callbacks can read
687
/// the edit details directly off the event.
688
///
689
/// This matches how mouse/keyboard/scroll callbacks read their data, instead of
690
/// having to reach into the `TextInputManager`'s pending changeset. The edited
691
/// node is already available via `SyntheticEvent.target`.
692
#[derive(Debug, Clone, PartialEq, Eq)]
693
pub struct TextInputEventData {
694
    /// The text inserted by this edit (empty for pure deletions).
695
    pub inserted_text: String,
696
    /// The text content of the node *before* this edit was applied.
697
    pub old_text: String,
698
}
699

            
700
/// Identifies WHICH pending structural changeset a notification is for.
701
///
702
/// Carried by `EventType::DocumentEdit` events; the app acks with the same
703
/// id via `mark_document_edit_applied`. The full changeset is intentionally
704
/// NOT copied onto the event — it stays single-instance in the window
705
/// (one-pending-changeset model).
706
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
707
pub struct DocumentEditEventData {
708
    /// The commit-handshake id of the recorded changeset.
709
    pub changeset_id: u64,
710
}
711

            
712
/// Union of all possible event data types.
713
#[derive(Debug, Clone, PartialEq)]
714
pub enum EventData {
715
    /// Mouse event data
716
    Mouse(MouseEventData),
717
    /// Keyboard event data
718
    Keyboard(KeyboardEventData),
719
    /// Scroll event data
720
    Scroll(ScrollEventData),
721
    /// Touch event data
722
    Touch(TouchEventData),
723
    /// Clipboard event data
724
    Clipboard(ClipboardEventData),
725
    /// Text-input (editing) event data
726
    TextInput(TextInputEventData),
727
    /// Structural document-edit notification data
728
    DocumentEdit(DocumentEditEventData),
729
    /// Lifecycle event data
730
    Lifecycle(LifecycleEventData),
731
    /// Window event data
732
    Window(WindowEventData),
733
    /// No additional data
734
    None,
735
    /// IME composition data. APPENDED at the end for ABI stability — this is
736
    /// `#[repr(C, u8)]`-adjacent, so a variant inserted in the middle would
737
    /// renumber every discriminant after it.
738
    Composition(CompositionEventData),
739
    /// Raw, pre-acceleration pointer motion. APPENDED at the end.
740
    RawMotion(RawMotionEventData),
741
    /// A media seek (9h-i-a-i-a). APPENDED for ABI stability.
742
    MediaControl(MediaControlEventData),
743
    SystemAudio(SystemAudioEventData),
744
}
745

            
746
/// High-level event type classification.
747
///
748
/// This enum categorizes all possible events that can occur in the UI.
749
/// It extends the existing event system with new event types for
750
/// lifecycle, clipboard, media, and form handling.
751
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
752
#[repr(C)]
753
pub enum EventType {
754
    // Mouse Events
755
    /// Mouse cursor is over the element
756
    MouseOver,
757
    /// Mouse cursor entered the element
758
    MouseEnter,
759
    /// Mouse cursor left the element
760
    MouseLeave,
761
    /// Mouse left the element OR moved to a child element (W3C `mouseout`, bubbles)
762
    MouseOut,
763
    /// Mouse button pressed
764
    MouseDown,
765
    /// Mouse button released
766
    MouseUp,
767
    /// Mouse click (down + up on same element)
768
    Click,
769
    /// Mouse double-click
770
    DoubleClick,
771
    /// Right-click / context menu
772
    ContextMenu,
773

            
774
    // Keyboard Events
775
    /// Key pressed down
776
    KeyDown,
777
    /// Key released
778
    KeyUp,
779
    /// Character input (respects locale/keyboard layout)
780
    KeyPress,
781

            
782
    // IME Composition Events
783
    /// IME composition started
784
    CompositionStart,
785
    /// IME composition updated (intermediate text changed)
786
    CompositionUpdate,
787
    /// IME composition ended (final text committed)
788
    CompositionEnd,
789

            
790
    // Focus Events
791
    /// Element received focus
792
    Focus,
793
    /// Element lost focus
794
    Blur,
795
    /// Focus entered element or its children
796
    FocusIn,
797
    /// Focus left element and its children
798
    FocusOut,
799

            
800
    // Input Events
801
    /// Input value is being changed (fires on every keystroke)
802
    Input,
803
    /// Input value has changed (fires after editing complete)
804
    Change,
805
    /// Form submitted
806
    Submit,
807
    /// Form reset
808
    Reset,
809
    /// Form validation failed
810
    Invalid,
811

            
812
    // Scroll Events
813
    /// Element is being scrolled
814
    Scroll,
815
    /// Scroll started
816
    ScrollStart,
817
    /// Scroll ended
818
    ScrollEnd,
819

            
820
    // Drag Events
821
    /// Drag operation started
822
    DragStart,
823
    /// Element is being dragged
824
    Drag,
825
    /// Drag operation ended
826
    DragEnd,
827
    /// Dragged element entered drop target
828
    DragEnter,
829
    /// Dragged element is over drop target
830
    DragOver,
831
    /// Dragged element left drop target
832
    DragLeave,
833
    /// Element was dropped
834
    Drop,
835

            
836
    // Touch Events
837
    /// Touch started
838
    TouchStart,
839
    /// Touch moved
840
    TouchMove,
841
    /// Touch ended
842
    TouchEnd,
843
    /// Touch cancelled
844
    TouchCancel,
845

            
846
    // Pen / Stylus Events (W3C PointerEvent, pointerType "pen")
847
    /// Pen tip made contact (or pen entered while down)
848
    PenDown,
849
    /// Pen moved (in contact or hovering in range)
850
    PenMove,
851
    /// Pen tip lifted
852
    PenUp,
853
    /// Pen entered hover/sensing range (proximity in)
854
    PenEnter,
855
    /// Pen left hover/sensing range (proximity out)
856
    PenLeave,
857

            
858
    // Gesture Events
859
    /// Long press detected (touch or mouse held down)
860
    LongPress,
861
    /// Swipe gesture to the left
862
    SwipeLeft,
863
    /// Swipe gesture to the right
864
    SwipeRight,
865
    /// Swipe gesture upward
866
    SwipeUp,
867
    /// Swipe gesture downward
868
    SwipeDown,
869
    /// Pinch-in gesture (zoom out)
870
    PinchIn,
871
    /// Pinch-out gesture (zoom in)
872
    PinchOut,
873
    /// Clockwise rotation gesture
874
    RotateClockwise,
875
    /// Counter-clockwise rotation gesture
876
    RotateCounterClockwise,
877

            
878
    // Clipboard Events
879
    /// Content copied to clipboard
880
    Copy,
881
    /// Content cut to clipboard
882
    Cut,
883
    /// Content pasted from clipboard
884
    Paste,
885

            
886
    // Media Events
887
    /// Media playback started
888
    Play,
889
    /// Media playback paused
890
    Pause,
891
    /// Media playback ended
892
    Ended,
893
    /// Media time updated
894
    TimeUpdate,
895
    /// Media volume changed
896
    VolumeChange,
897
    /// Media error occurred
898
    MediaError,
899

            
900
    // Lifecycle Events
901
    /// Component was mounted to the DOM
902
    Mount,
903
    /// Component will be unmounted from the DOM
904
    Unmount,
905
    /// Component was updated
906
    Update,
907
    /// Component layout bounds changed
908
    Resize,
909
    /// A `<transient-window>` was dismissed by the user (outside click or
910
    /// Escape). Fired on the transient node so the app can drop its `open`
911
    /// flag; the surface is already gone by the time this runs.
912
    Dismiss,
913
    /// A `<transient-window>` was torn off by the user's drag and is now a
914
    /// free toplevel. Fired on the transient node; the lifecycle data's
915
    /// `current_bounds` is the toplevel's rect in the parent's coordinates,
916
    /// for apps that persist their palette layout.
917
    TearOff,
918
    /// A torn-off `<transient-window>` was docked back by the user's drag.
919
    Dock,
920

            
921
    // Window Events
922
    /// Window resized
923
    WindowResize,
924
    /// Window moved
925
    WindowMove,
926
    /// Window close requested
927
    WindowClose,
928
    /// The window's frame state changed — minimized, maximized, restored to
929
    /// normal, or entered/left fullscreen.
930
    ///
931
    /// Read the new state from `flags.frame` on the current window state; the
932
    /// event carries no payload of its own because the flag IS the payload and
933
    /// a callback that cares will already be reading window state.
934
    WindowFrameChanged,
935
    /// Window received focus
936
    WindowFocusIn,
937
    /// Window lost focus
938
    WindowFocusOut,
939
    /// System theme changed
940
    ThemeChange,
941
    /// Window DPI/scale factor changed (moved to different monitor)
942
    WindowDpiChanged,
943
    /// Window moved to a different monitor
944
    WindowMonitorChanged,
945

            
946
    // Application Events
947
    /// A monitor/display was connected
948
    MonitorConnected,
949
    /// A monitor/display was disconnected
950
    MonitorDisconnected,
951

            
952
    // File Events
953
    /// File is being hovered
954
    FileHover,
955
    /// File was dropped
956
    FileDrop,
957
    /// File hover cancelled
958
    FileHoverCancel,
959

            
960
    // Hardware input-device Events (P6 sensors / gamepad)
961
    /// A motion-sensor reading (accelerometer / gyroscope / magnetometer)
962
    /// changed. Read the value with `CallbackInfo::get_sensor_reading`.
963
    SensorChanged,
964
    /// A gamepad's buttons / axes changed, or one was (dis)connected. Read it
965
    /// with `CallbackInfo::get_primary_gamepad` / `get_gamepad_state`.
966
    GamepadInput,
967

            
968
    // Geolocation Events (MWA-A1 — synthesized by the capability pump's
969
    // GeolocationManager EventProvider; both filter enums already carried
970
    // the matching variants, only this dispatch type was missing them).
971
    /// A new GPS / network location fix arrived. Read it with
972
    /// `CallbackInfo::get_geolocation_fix`.
973
    GeolocationFix,
974
    /// The native geolocation subscription errored, timed out, or was
975
    /// revoked.
976
    GeolocationError,
977

            
978
    // Async capability outcomes (MWA-A1b — synthesized by the capability
979
    // pump's manager EventProviders so idle apps observe prompt results).
980
    /// A permission's OS-observed state changed (granted / denied /
981
    /// revoked / restricted). Targeted at the capability's most recent
982
    /// subscriber node when known, else the root. Read the new state via
983
    /// `CallbackInfo` permission accessors.
984
    PermissionChanged,
985
    /// A biometric authentication prompt completed. Read the outcome via
986
    /// `CallbackInfo::get_biometric_result`.
987
    BiometricResult,
988
    /// The screen eyedropper started by `CallbackInfo::pick_screen_color`
989
    /// finished - the user picked a pixel, or cancelled. Window-level (the
990
    /// pick is not bound to a node); read the colour via
991
    /// `CallbackInfo::get_picked_screen_color` (`None` = cancelled).
992
    ScreenColorPicked,
993
    /// A keyring store / get / delete operation completed. Read the outcome
994
    /// via `CallbackInfo::get_keyring_result`.
995
    KeyringResult,
996

            
997
    // Structural document editing (C11 — synthesized once per recorded
998
    // changeset by the LayoutWindow's document-edit EventProvider).
999
    /// A STRUCTURAL document edit (Enter split / Backspace merge / wrap /
    /// selection-spanning replace…) was recorded and awaits the app's
    /// apply-and-ack. Fired ONCE per changeset so the app's apply loop is
    /// prompt instead of polling `get_pending_document_edit()` on its next
    /// unrelated callback. The changeset id rides on
    /// `EventData::DocumentEdit`; the full changeset is read via
    /// `CallbackInfo` / `LayoutWindow::get_pending_document_edit()`.
    DocumentEdit,
    /// The text of an editable node CHANGED - fired once per commit, AFTER
    /// the edit is applied (typing, IME commit, deletion, paste, undo/redo:
    /// everything that writes the text overlay).
    ///
    /// `Input` is the `beforeinput` of this pair: it fires BEFORE the
    /// pending insertion is applied so a listener can `prevent_default`,
    /// which means a model that reads `get_unsynced_text_edits` from an
    /// `Input` callback is always one keystroke behind. A listener that
    /// wants the committed text - a word counter, a dirty flag, a live
    /// preview - listens here instead; the edits are already in the sync
    /// channel when this runs. Deletions used to be the only edits notified
    /// post-commit (through a second `Input`); this is the uniform spelling.
    TextChanged,
    /// An input device was attached. APPENDED at the end for ABI stability.
    ///
    /// `ApplicationEventFilter` has carried `DeviceConnected` since it was
    /// introduced, with no `EventType` able to reach it. Hotplug is observable
    /// on every backend — gilrs already reports gamepad arrive/leave through
    /// the capability pump, Wayland has `wl_seat.capabilities` and the
    /// `zwp_tablet_seat_v2` add/remove events, X11 has `XI_HierarchyChanged`,
    /// Win32 has `WM_DEVICECHANGE` — so the filter was the only thing missing.
    DeviceConnected,
    /// An input device was detached. See [`EventType::DeviceConnected`].
    DeviceDisconnected,
    /// The pen barrel was squeezed. APPENDED at the end for ABI stability.
    ///
    /// Apple Pencil Pro's squeeze, surfaced by `UIPencilInteraction`. The
    /// Hover and Window filter variants have existed with no `EventType` able
    /// to reach them.
    PenSqueeze,
    /// The pen was double-tapped on its barrel — Apple Pencil 2 and later,
    /// also `UIPencilInteraction`. See [`EventType::PenSqueeze`].
    PenDoubleTap,
    /// The pen is in range but not touching. Wayland reports it as
    /// `proximity_in` plus `distance`, Win32 as `POINTER_FLAG_INRANGE` without
    /// `POINTER_FLAG_INCONTACT`, Android as `ACTION_HOVER_MOVE` with a stylus
    /// tool type, macOS as an `NSEventSubtype::TabletProximity` subtype on the
    /// ordinary mouse-event path. See [`EventType::PenSqueeze`].
    PenHover,
    /// A component's default action was invoked — Enter/Space on a focused
    /// control, or the accessibility `Default` action. Distinct from `Click`:
    /// that is the pointer spelling, this is the component-level one that
    /// `ComponentEventFilter::DefaultAction` subscribes to.
    DefaultAction,
    /// A component's selection changed. `ComponentEventFilter::Selected` has
    /// existed with no `EventType` and no match arm.
    Selected,
    /// A HID device delivered an input report. APPENDED at the end.
    ///
    /// The escape hatch for devices azul does not model — flight sticks,
    /// wheels, 6-DOF mice, pedals, Stream Decks. Read the bytes via
    /// `CallbackInfo::get_hid_reports`.
    HidReport,
    /// A modifier or lock key changed state. APPENDED at the end.
    ///
    /// Modifiers arrive today only as ordinary key events, so an app tracking
    /// "is Shift down" has to watch every `KeyDown` and `KeyUp` and reconstruct
    /// it — and gets it wrong across a focus loss, because the `KeyUp` for a
    /// modifier released while another window had focus never arrives. This
    /// event carries the resolved state instead.
    ModifiersChanged,
    /// Raw pointer motion, pre-acceleration and unclamped. APPENDED at the
    /// end for ABI stability.
    ///
    /// `MouseState.is_cursor_locked` has existed since the beginning,
    /// documented as "important for applications like games", with no event
    /// carrying a delta behind it — so pointer lock was a flag that did
    /// nothing. This is the event it was waiting for.
    RawMouseMotion,
    /// A dial or rotary encoder turned. APPENDED at the end for ABI stability.
    ///
    /// The Surface Dial, a tablet pad's dial, a Wear crown, an Apple Digital
    /// Crown. `DialState` (rotation, detents, pressed, contact point) has been
    /// readable through `CallbackInfo::get_dial_state()` since the type
    /// landed, with no event to subscribe to — so a dial could only be POLLED
    /// from an unrelated callback that happened to run.
    DialRotate,
    /// A dial with a physical click was pressed. APPENDED at the end.
    DialClick,
    /// The pointer MOVED while over this node. APPENDED at the end.
    ///
    /// W3C `mousemove`. This is the event `MouseOver` used to be: until
    /// now azul had no movement event at all, and `MouseOver` was emitted
    /// on every cursor move - `mousemove` semantics under the `mouseover`
    /// name. `MouseOver` now means what the spec says (the pointer
    /// ENTERED the node) and movement lives here.
    MouseMove,
    /// The platform's media controls asked for a SEEK (9h-i-a-i-a): a desktop
    /// scrubber, a lock-screen slider, `playerctl position`. APPENDED at the
    /// end for ABI stability. Unlike Play/Pause/Next, which arrive as media
    /// KEY events, a seek carries a position - read it with
    /// `CallbackInfo::get_media_control_request`.
    MediaControl,
    /// The pointer lock changed hands (9d-ii-c): the app took or released it,
    /// or the platform ended it - every grab-based backend drops the grab
    /// when the window loses focus, and a Wayland compositor may end a
    /// constraint at any time. Both directions, like the browser's
    /// `pointerlockchange`; read `mouse_state.is_cursor_locked` for which.
    /// Nothing re-takes a lost lock on focus return (USER RULING
    /// 2026-09-03): an app that wants it back asks again from
    /// `WindowFocusReceived`.
    PointerLockChange,
    /// The system did something with the audio the app took over
    /// (9h-i-a-i-d-i): an interruption began or ended, focus was ducked,
    /// granted, or lost. Application-level, at the root; the payload is
    /// `EventData::SystemAudio` and `CallbackInfo::get_system_audio_change`.
    SystemAudioChange,
}
/// Unified event wrapper (similar to React's `SyntheticEvent`).
///
/// All events in the system are wrapped in this structure, providing
/// a consistent interface and enabling event propagation control.
#[derive(Debug, Clone, PartialEq)]
#[allow(clippy::struct_excessive_bools)] // four independent propagation flags — W3C's own model
pub struct SyntheticEvent {
    /// The type of event
    pub event_type: EventType,
    /// Where the event came from
    pub source: EventSource,
    /// Current propagation phase
    pub phase: EventPhase,
    /// Target node that the event was dispatched to
    pub target: DomNodeId,
    /// Current node in the propagation path
    pub current_target: DomNodeId,
    /// Timestamp when event was created
    pub timestamp: Instant,
    /// Type-specific event data
    pub data: EventData,
    /// Whether propagation has been stopped
    pub stopped: bool,
    /// Whether immediate propagation has been stopped
    pub stopped_immediate: bool,
    /// Whether default action has been prevented
    pub prevented_default: bool,
    /// Deliver at the target ONLY — no capture, no bubble.
    ///
    /// Set on the release synthesised for the node that was PRESSED when the
    /// pointer releases somewhere else (press-target capture, see
    /// `HoverManager::apply_press_target_capture`): that node owes a
    /// `MouseUp`, but its ancestors already see the real release through the
    /// hovered node's propagation path and must not see it twice.
    pub at_target_only: bool,
}
impl SyntheticEvent {
    /// Create a new synthetic event.
    ///
    /// # Parameters
    /// - `timestamp`: Current time from `(system_callbacks.get_system_time_fn.cb)()`
    #[must_use]
79974
    pub const fn new(
79974
        event_type: EventType,
79974
        source: EventSource,
79974
        target: DomNodeId,
79974
        timestamp: Instant,
79974
        data: EventData,
79974
    ) -> Self {
79974
        Self {
79974
            event_type,
79974
            source,
79974
            phase: EventPhase::Target,
79974
            target,
79974
            current_target: target,
79974
            timestamp,
79974
            data,
79974
            stopped: false,
79974
            stopped_immediate: false,
79974
            prevented_default: false,
79974
            at_target_only: false,
79974
        }
79974
    }
    /// This event, delivered at its target only (see [`Self::at_target_only`]).
    #[must_use]
34
    pub const fn at_target_only(mut self) -> Self {
34
        self.at_target_only = true;
34
        self
34
    }
    /// Stop event propagation after the current phase completes.
    ///
    /// This prevents the event from reaching handlers in subsequent phases
    /// (e.g., stopping during capture prevents bubble phase).
3
    pub const fn stop_propagation(&mut self) {
3
        self.stopped = true;
3
    }
    /// Stop event propagation immediately.
    ///
    /// This prevents any further handlers from being called, even on the
    /// current target element.
5
    pub const fn stop_immediate_propagation(&mut self) {
5
        self.stopped_immediate = true;
5
        self.stopped = true;
5
    }
    /// Prevent the default action associated with this event.
    ///
    /// For example, prevents form submission on Enter key, or prevents
    /// text selection on drag.
4
    pub const fn prevent_default(&mut self) {
4
        self.prevented_default = true;
4
    }
    /// Check if propagation was stopped.
    #[must_use]
6
    pub const fn is_propagation_stopped(&self) -> bool {
6
        self.stopped
6
    }
    /// Check if immediate propagation was stopped.
    #[must_use]
5
    pub const fn is_immediate_propagation_stopped(&self) -> bool {
5
        self.stopped_immediate
5
    }
    /// Check if default action was prevented.
    #[must_use]
5
    pub const fn is_default_prevented(&self) -> bool {
5
        self.prevented_default
5
    }
}
/// Result of event propagation through DOM tree.
#[derive(Debug, Clone, Default)]
pub struct PropagationResult {
    /// Callbacks that should be invoked, in order
    pub callbacks_to_invoke: Vec<(NodeId, EventFilter)>,
    /// Whether default action should be prevented
    pub default_prevented: bool,
}
/// Get the path from root to target node in the DOM tree.
///
/// This is used for event propagation - we need to know which nodes
/// are ancestors of the target to implement capture/bubble phases.
///
/// Returns nodes in order from root to target (inclusive).
#[must_use]
97
pub fn get_dom_path(
97
    node_hierarchy: &crate::id::NodeHierarchy,
97
    target_node: NodeHierarchyItemId,
97
) -> Vec<NodeId> {
97
    let mut path = Vec::new();
97
    let Some(target_node_id) = target_node.into_crate_internal() else {
2
        return path;
    };
95
    let hier_ref = node_hierarchy.as_ref();
    // Build path from target to root. Bounded by the node count and guarded by a
    // visited-set: a corrupt hierarchy with a parent cycle (or a parent chain
    // longer than the arena) would otherwise loop forever / OOM here, and this
    // runs on every event dispatch.
95
    let node_count = hier_ref.len();
95
    let mut visited: BTreeSet<NodeId> = BTreeSet::new();
95
    let mut current = Some(target_node_id);
5309
    while let Some(node_id) = current {
5216
        if path.len() > node_count || !visited.insert(node_id) {
            // Cycle or overrun detected: stop rather than spin forever.
2
            break;
5214
        }
5214
        path.push(node_id);
5214
        current = hier_ref.get(node_id).and_then(|node| node.parent);
    }
    // Reverse to get root → target order
95
    path.reverse();
95
    path
97
}
/// Propagate event through DOM tree with capture and bubble phases.
///
/// This implements DOM Level 2 event propagation:
/// 1. **Capture Phase**: Event travels from root down to target
/// 2. **Target Phase**: Event is at the target element
/// 3. **Bubble Phase**: Event travels from target back up to root
///
/// The event can be stopped at any point via `stopPropagation()` or
/// `stopImmediatePropagation()`.
///
/// # Panics
///
/// Panics if `path` is empty; it must contain at least the target node.
32
pub fn propagate_event(
32
    event: &mut SyntheticEvent,
32
    node_hierarchy: &crate::id::NodeHierarchy,
32
    callbacks: &BTreeMap<NodeId, Vec<EventFilter>>,
32
) -> PropagationResult {
32
    let path = get_dom_path(node_hierarchy, event.target.node);
32
    if path.is_empty() {
1
        return PropagationResult::default();
31
    }
31
    let ancestors = &path[..path.len().saturating_sub(1)];
31
    let target_node_id = *path.last().unwrap();
31
    let mut result = PropagationResult::default();
    // A captured release (see `SyntheticEvent::at_target_only`) reaches its
    // target and nothing else: the ancestors get the real release through
    // the hovered node's path.
31
    if event.at_target_only {
1
        propagate_target_phase(event, target_node_id, callbacks, &mut result);
1
        result.default_prevented = event.prevented_default;
1
        return result;
30
    }
    // Phase 1: Capture (root → target)
30
    propagate_phase(
30
        event,
30
        ancestors.iter().copied(),
30
        EventPhase::Capture,
30
        callbacks,
30
        &mut result,
    );
    // Phase 2: Target
30
    if !event.stopped {
28
        propagate_target_phase(event, target_node_id, callbacks, &mut result);
28
    }
    // Phase 3: Bubble (target → root) — unless the event type does not bubble.
30
    if !event.stopped && event.event_type.bubbles() {
24
        propagate_phase(
24
            event,
24
            ancestors.iter().rev().copied(),
24
            EventPhase::Bubble,
24
            callbacks,
24
            &mut result,
24
        );
25
    }
30
    result.default_prevented = event.prevented_default;
30
    result
32
}
impl EventType {
    /// Whether the event reaches the target's ANCESTORS in the bubble phase.
    ///
    /// Enter/leave events do not bubble (`W3C` `mouseenter`/`mouseleave`,
    /// `pointerenter`/`pointerleave`): each node that gained or lost hover
    /// gets its OWN event (`event_determination` generates them per node), so
    /// bubbling a child's leave to its parent tells the parent the pointer
    /// left IT while it is still inside — which is how a slider's drag ended
    /// the moment the pointer slid off the thumb, a map pan ended on every
    /// tile crossing, and a split-pane drag ended on its first motion.
    /// `dragenter`/`dragleave` DO bubble in the `W3C` model and keep doing so.
    #[must_use]
34
    pub const fn bubbles(self) -> bool {
26
        !matches!(
34
            self,
            Self::MouseEnter | Self::MouseLeave | Self::PenEnter | Self::PenLeave
        )
34
    }
}
/// Process a single propagation phase (Capture or Bubble)
55
fn propagate_phase(
55
    event: &mut SyntheticEvent,
55
    nodes: impl Iterator<Item = NodeId>,
55
    phase: EventPhase,
55
    callbacks: &BTreeMap<NodeId, Vec<EventFilter>>,
55
    result: &mut PropagationResult,
55
) {
55
    event.phase = phase;
153
    for node_id in nodes {
100
        if event.stopped_immediate || event.stopped {
2
            return;
98
        }
98
        event.current_target = DomNodeId {
98
            dom: event.target.dom,
98
            node: NodeHierarchyItemId::from_crate_internal(Some(node_id)),
98
        };
98
        collect_matching_callbacks(event, node_id, phase, callbacks, result);
    }
55
}
/// Process the target phase
30
fn propagate_target_phase(
30
    event: &mut SyntheticEvent,
30
    target_node_id: NodeId,
30
    callbacks: &BTreeMap<NodeId, Vec<EventFilter>>,
30
    result: &mut PropagationResult,
30
) {
30
    event.phase = EventPhase::Target;
30
    event.current_target = event.target;
30
    collect_matching_callbacks(event, target_node_id, EventPhase::Target, callbacks, result);
30
}
/// Collect callbacks that match the current phase for a node
130
fn collect_matching_callbacks(
130
    event: &SyntheticEvent,
130
    node_id: NodeId,
130
    phase: EventPhase,
130
    callbacks: &BTreeMap<NodeId, Vec<EventFilter>>,
130
    result: &mut PropagationResult,
130
) {
130
    let Some(node_callbacks) = callbacks.get(&node_id) else {
100
        return;
    };
30
    let matching = node_callbacks
30
        .iter()
32
        .take_while(|_| !event.stopped_immediate)
31
        .filter(|filter| matches_filter_phase(**filter, event, phase))
30
        .map(|filter| (node_id, *filter));
30
    result.callbacks_to_invoke.extend(matching);
130
}
// =============================================================================
// DEFAULT ACTIONS (W3C UI Events / HTML5 Activation Behavior)
// =============================================================================
/// Default actions are built-in behaviors that occur in response to events.
///
/// Per W3C DOM Event specification:
/// > A default action is an action that the implementation is expected to take
/// > in response to an event, unless that action is cancelled by the script.
///
/// Examples:
/// - Tab key → move focus to next focusable element
/// - Enter/Space on button → activate (click) the button
/// - Escape → clear focus or close modal
/// - Arrow keys in listbox → move selection
///
/// Default actions are processed AFTER all event callbacks have been invoked,
/// and only if `event.prevent_default()` was NOT called.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C, u8)]
pub enum DefaultAction {
    /// Move focus to the next focusable element (Tab key)
    FocusNext,
    /// Move focus to the previous focusable element (Shift+Tab)
    FocusPrevious,
    /// Move focus to the first focusable element
    FocusFirst,
    /// Move focus to the last focusable element
    FocusLast,
    /// Move focus SPATIALLY — to the nearest focusable element in that
    /// direction, rather than the next one in document order.
    ///
    /// Tab order is a single sequence; a D-pad, a TV remote and spatial
    /// navigation all ask a different question ("what is above this?"), which
    /// `FocusTarget::Directional` already answered and nothing could request.
    ///
    /// NOT bound to the arrow keys: those scroll, and taking them
    /// unconditionally would break every scroll container. That binding waits
    /// on the CSS opt-out (item 9a-i); a D-pad has no such conflict.
    FocusUp,
    FocusDown,
    FocusLeft,
    FocusRight,
    /// Clear focus from the currently focused element (Escape key)
    ClearFocus,
    /// Activate the focused element (Enter/Space on activatable elements)
    /// This generates a synthetic Click event on the target
    ActivateFocusedElement {
        target: DomNodeId,
    },
    /// Submit the form containing the focused element (Enter in form input)
    SubmitForm {
        form_node: DomNodeId,
    },
    /// Close the current modal/dialog (Escape key when modal is open)
    CloseModal {
        modal_node: DomNodeId,
    },
    /// Scroll the focused scrollable container
    ScrollFocusedContainer {
        direction: ScrollDirection,
        amount: ScrollAmount,
    },
    /// Select all text in the focused text input (Ctrl+A / Cmd+A)
    SelectAllText,
    /// Enter in a contenteditable host: record a STRUCTURAL split-block
    /// changeset for the app to apply to its model (azul never mutates the
    /// DOM). Execution = `LayoutWindow::record_structural_default_action`.
    SplitBlockAtCursor {
        target: DomNodeId,
    },
    /// Backspace at block start in a contenteditable host: record a
    /// merge-with-previous-block changeset (same record-only semantics).
    MergeWithPrevious {
        target: DomNodeId,
    },
    /// Delete at block end in a contenteditable host: record a
    /// merge-with-next-block changeset (same record-only semantics).
    MergeWithNext {
        target: DomNodeId,
    },
    /// No default action for this event
    None,
    /// Enter in a PLAIN-TEXT editing context (the editing host's computed
    /// `white-space` preserves newlines: pre / pre-wrap / break-spaces /
    /// pre-line), and Shift+Enter in ANY contenteditable host: insert a
    /// literal `"\n"` through the standard text-input pipeline (which brings
    /// veto, undo, and caret-follow along) instead of recording a structural
    /// block split. APPENDED at the enum tail for ABI stability.
    InsertLineBreakAtCursor {
        target: DomNodeId,
    },
    /// Reset a form to its controls' default values (a `type="reset"` control
    /// was activated). APPENDED at the enum tail for ABI stability.
    ///
    /// The sibling of [`Self::SubmitForm`]: both name the FORM rather than the
    /// control that triggered them, because a reset handler belongs on the
    /// form and the button is an implementation detail of how the user asked.
    ResetForm {
        form_node: DomNodeId,
    },
}
/// Amount to scroll for keyboard-based scrolling
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C)]
pub enum ScrollAmount {
    /// Scroll by one line (arrow keys)
    Line,
    /// Scroll by one page (Page Up/Down)
    Page,
    /// Scroll to start/end (Home/End)
    Document,
}
/// Result of determining what default action should occur for an event.
///
/// This is computed AFTER event dispatch, based on:
/// 1. The event type
/// 2. The target element's type/role
/// 3. Whether `prevent_default()` was called
#[derive(Debug, Clone, Copy)]
#[repr(C)]
pub struct DefaultActionResult {
    /// The default action to perform (if any)
    pub action: DefaultAction,
    /// Whether the action was prevented by a callback
    pub prevented: bool,
}
impl Default for DefaultActionResult {
12
    fn default() -> Self {
12
        Self {
12
            action: DefaultAction::None,
12
            prevented: false,
12
        }
12
    }
}
impl DefaultActionResult {
    /// Create a new result with a specific action
    #[must_use]
91077
    pub const fn new(action: DefaultAction) -> Self {
91077
        Self {
91077
            action,
91077
            prevented: false,
91077
        }
91077
    }
    /// Create a prevented result (callback called `prevent_default`)
    #[must_use]
11894
    pub const fn prevented() -> Self {
11894
        Self {
11894
            action: DefaultAction::None,
11894
            prevented: true,
11894
        }
11894
    }
    /// Check if there's an action to perform
    #[must_use]
32
    pub const fn has_action(&self) -> bool {
32
        !self.prevented && !matches!(self.action, DefaultAction::None)
32
    }
}
/// Trait for elements that have activation behavior (can be "clicked" via keyboard).
///
/// Per HTML5 spec, elements with activation behavior include:
/// - `<button>` elements
/// - `<input type="submit">`, `<input type="button">`, `<input type="reset">`
/// - `<a>` elements with href
/// - `<area>` elements with href
/// - Any element with a click handler (implicit activation)
///
/// When an element with activation behavior is focused and the user presses
/// Enter or Space, a synthetic click event is generated.
pub trait ActivationBehavior {
    /// Returns true if this element can be activated via keyboard (Enter/Space)
    fn has_activation_behavior(&self) -> bool;
    /// Returns true if this element is currently activatable
    /// (e.g., not disabled, not aria-disabled="true")
    fn is_activatable(&self) -> bool;
}
/// Trait to query if a node is focusable for tab navigation
pub trait Focusable {
    /// Returns the tabindex value for this element (-1, 0, or positive)
    fn get_tabindex(&self) -> Option<i32>;
    /// Returns true if this element can receive focus
    fn is_focusable(&self) -> bool;
    /// Returns true if this element should be in the tab order
    fn is_in_tab_order(&self) -> bool {
        self.get_tabindex()
            .map_or_else(|| self.is_naturally_focusable(), |i| i >= 0)
    }
    /// Returns true if this element type is naturally focusable
    /// (button, input, select, textarea, a[href])
    fn is_naturally_focusable(&self) -> bool;
}
/// Check if an event filter matches the given event in the current phase.
///
/// This is used during event propagation to determine which callbacks
/// should be invoked at each phase.
153387
fn matches_filter_phase(
153387
    filter: EventFilter,
153387
    event: &SyntheticEvent,
153387
    current_phase: EventPhase,
153387
) -> bool {
    // azul has no capture-phase listeners (no `addEventListener(…, capture=true)`
    // equivalent): every `EventFilter` is a bubble-phase listener, which by the W3C
    // model fires only in the Target and Bubble phases — never Capture. Without this
    // guard an ancestor node's Hover/Focus callback was collected in BOTH the capture
    // and the bubble walk, so it fired TWICE whenever the hit target was a descendant
    // (e.g. a menubar item, hit via its text child, opened two stacked popups; any
    // button containing a text/child node ran its MouseUp callback twice).
153387
    if matches!(current_phase, EventPhase::Capture) {
21
        return false;
153366
    }
153366
    match filter {
50445
        EventFilter::Hover(hover_filter) => {
50445
            matches_hover_filter(hover_filter, event, current_phase)
        }
36736
        EventFilter::Focus(focus_filter) => {
36736
            matches_focus_filter(focus_filter, event, current_phase)
        }
52818
        EventFilter::Window(window_filter) => {
52818
            matches_window_filter(window_filter, event, current_phase)
        }
6201
        EventFilter::Component(component_filter) => {
6201
            matches_component_filter(component_filter, event, current_phase)
        }
3584
        EventFilter::Application(application_filter) => {
3584
            matches_application_filter(application_filter, event, current_phase)
        }
3582
        EventFilter::External(external_filter) => {
3582
            matches_external_filter(external_filter, event, current_phase)
        }
    }
153387
}
/// Check if a component (lifecycle) filter matches the event.
///
/// Lifecycle events produced by `diff::reconcile_dom` carry the target node in
/// `SyntheticEvent.target`, so dispatchers that bypass `propagate_event` and
/// invoke the target directly also need a way to compare. This predicate is
/// the single source of truth for that comparison; changing it without
/// updating `event_type_to_filters` will de-sync dispatch.
6264
const fn matches_component_filter(
6264
    filter: ComponentEventFilter,
6264
    event: &SyntheticEvent,
6264
    _phase: EventPhase,
6264
) -> bool {
6209
    matches!(
6264
        (filter, &event.event_type),
        (ComponentEventFilter::AfterMount, EventType::Mount)
            | (ComponentEventFilter::BeforeUnmount, EventType::Unmount)
            | (ComponentEventFilter::Updated, EventType::Update)
            | (ComponentEventFilter::NodeResized, EventType::Resize)
            | (ComponentEventFilter::Dismissed, EventType::Dismiss)
            | (ComponentEventFilter::TornOff, EventType::TearOff)
            | (ComponentEventFilter::Docked, EventType::Dock)
            // These two were simply absent from the match. Both filter
            // variants shipped in `ComponentEventFilter`, so a component
            // subscribing to either was collected and then dropped.
            | (ComponentEventFilter::DefaultAction, EventType::DefaultAction)
            | (ComponentEventFilter::Selected, EventType::Selected)
    )
6264
}
/// Check if the event data contains a mouse event with the expected button.
///
/// `MouseButton::Other(BACK)` — the thumb "back" button, button 4 on a mouse
/// and index 3 zero-based, which is the numbering the web and every shell
/// already use (Win32 `XBUTTON1`, X11 button 8, macOS `otherMouseDown:` 3).
pub const MOUSE_BUTTON_BACK: u8 = 3;
/// `MouseButton::Other(FORWARD)` — the thumb "forward" button.
pub const MOUSE_BUTTON_FORWARD: u8 = 4;
/// Bit for the back button in [`MouseState::other_down`].
pub const MOUSE_OTHER_MASK_BACK: u8 = 1 << 0;
/// Bit for the forward button in [`MouseState::other_down`].
pub const MOUSE_OTHER_MASK_FORWARD: u8 = 1 << 1;
532
fn check_mouse_button(data: &EventData, expected: MouseButton) -> bool {
532
    if let EventData::Mouse(mouse_data) = data {
441
        mouse_data.button == expected
    } else {
91
        false
    }
532
}
/// Check if a hover filter matches the event.
// Exhaustive (filter, event-type) truth table: many distinct pairs share the
// `=> true` body. One arm per pair is intentional; merging into giant or-patterns
// would destroy the table's readability/maintainability.
#[allow(clippy::match_same_arms, clippy::too_many_lines)]
50475
fn matches_hover_filter(
50475
    filter: HoverEventFilter,
50475
    event: &SyntheticEvent,
50475
    _phase: EventPhase,
50475
) -> bool {
    use HoverEventFilter::{
        BiometricResult, DoubleClick, Drag, DragEnd, DragEnter, DragLeave, DragOver, DragStart,
        Drop, DroppedFile, GamepadInput, GeolocationError, GeolocationFix, HoveredFile,
        HoveredFileCancelled, KeyringResult, LeftMouseDown, LeftMouseUp, MiddleMouseDown,
        MiddleMouseUp, MouseDown, MouseEnter, MouseLeave, MouseMove, MouseOver, MouseUp,
        PenDoubleTap, PenDown, PenEnter, PenHover, PenLeave, PenMove, PenSqueeze, PenUp,
        PermissionChanged, RightMouseDown, RightMouseUp, ScreenColorPicked, Scroll, ScrollEnd,
        ScrollStart, SensorChanged, TextInput, TouchCancel, TouchEnd, TouchMove, TouchStart,
        VirtualKeyDown, VirtualKeyUp,
    };
50475
    match (filter, &event.event_type) {
56
        (MouseOver, EventType::MouseOver) => true,
22
        (MouseMove, EventType::MouseMove) => true,
38
        (MouseDown, EventType::MouseDown) => true,
33
        (LeftMouseDown, EventType::MouseDown) => check_mouse_button(&event.data, MouseButton::Left),
        (RightMouseDown, EventType::MouseDown) => {
30
            check_mouse_button(&event.data, MouseButton::Right)
        }
        (MiddleMouseDown, EventType::MouseDown) => {
30
            check_mouse_button(&event.data, MouseButton::Middle)
        }
34
        (MouseUp, EventType::MouseUp) => true,
        // KEYBOARD ACTIVATION (Enter / Space on a focused element) dispatches
        // a synthetic `EventType::Click`. Every widget in the toolkit listens
        // on MouseUp / LeftMouseUp - the pointer spelling of "activate" - so
        // without this arm the synthetic event matched NOTHING and Enter /
        // Space silently did nothing on every focusable widget (device
        // report, 2026-08-31). Nothing else in the engine emits
        // `EventType::Click`, so this cannot double-fire a real pointer
        // click: a real click arrives as MouseDown + MouseUp.
        //
        // A keyboard activation counts as a LEFT activation - it carries no
        // button data, so `check_mouse_button` cannot answer for it - which
        // is the W3C activation behaviour Enter and Space implement.
28
        (HoverEventFilter::Click, EventType::Click) => true,
30
        (LeftMouseUp, EventType::MouseUp) => check_mouse_button(&event.data, MouseButton::Left),
29
        (RightMouseUp, EventType::MouseUp) => check_mouse_button(&event.data, MouseButton::Right),
29
        (MiddleMouseUp, EventType::MouseUp) => check_mouse_button(&event.data, MouseButton::Middle),
55
        (MouseEnter, EventType::MouseEnter) => true,
9
        (MouseLeave, EventType::MouseLeave) => true,
7
        (Scroll, EventType::Scroll) => true,
5
        (ScrollStart, EventType::ScrollStart) => true,
5
        (ScrollEnd, EventType::ScrollEnd) => true,
4
        (TextInput, EventType::Input) => true,
        // `KeyPress` (a key that produced a character) and `Change` (a value
        // committed on blur) both plan onto the `TextInput` filter, which is
        // what an app registers for "text arrived here". Planning named that
        // filter and this table then rejected it, so both dispatched to
        // nothing.
4
        (TextInput, EventType::KeyPress) => true,
5
        (TextInput, EventType::Change) => true,
        // A context-menu request is not a `MouseDown`, so the button-payload
        // check on the `RightMouseDown` arm cannot answer for it. Routing it
        // to the same filter means the Menu/Apps key, Shift+F10 and the
        // accessibility `ShowContextMenu` action all reach the handler an app
        // already registered for right-click, without inventing a new filter
        // variant for each spelling of "open the context menu".
4
        (RightMouseDown, EventType::ContextMenu) => true,
24
        (VirtualKeyDown, EventType::KeyDown) => true,
23
        (VirtualKeyUp, EventType::KeyUp) => true,
4
        (HoveredFile, EventType::FileHover) => true,
4
        (DroppedFile, EventType::FileDrop) => true,
4
        (HoveredFileCancelled, EventType::FileHoverCancel) => true,
17
        (TouchStart, EventType::TouchStart) => true,
5
        (TouchMove, EventType::TouchMove) => true,
5
        (TouchEnd, EventType::TouchEnd) => true,
5
        (TouchCancel, EventType::TouchCancel) => true,
5
        (PenDown, EventType::PenDown) => true,
5
        (PenMove, EventType::PenMove) => true,
5
        (PenUp, EventType::PenUp) => true,
6
        (PenEnter, EventType::PenEnter) => true,
6
        (PenLeave, EventType::PenLeave) => true,
4
        (DragStart, EventType::DragStart) => true,
4
        (Drag, EventType::Drag) => true,
4
        (DragEnd, EventType::DragEnd) => true,
4
        (DragEnter, EventType::DragEnter) => true,
4
        (DragOver, EventType::DragOver) => true,
4
        (DragLeave, EventType::DragLeave) => true,
4
        (Drop, EventType::Drop) => true,
4
        (DoubleClick, EventType::DoubleClick) => true,
16
        (SensorChanged, EventType::SensorChanged) => true,
16
        (GamepadInput, EventType::GamepadInput) => true,
4
        (GeolocationFix, EventType::GeolocationFix) => true,
4
        (GeolocationError, EventType::GeolocationError) => true,
4
        (PermissionChanged, EventType::PermissionChanged) => true,
4
        (BiometricResult, EventType::BiometricResult) => true,
4
        (ScreenColorPicked, EventType::ScreenColorPicked) => true,
4
        (KeyringResult, EventType::KeyringResult) => true,
        // Gestures. These filters existed, the detectors produced the events,
        // and this table had no arm for them — a `PinchOut` handler on a map
        // could never fire, whatever the gesture manager saw.
6
        (HoverEventFilter::LongPress, EventType::LongPress) => true,
7
        (HoverEventFilter::SwipeLeft, EventType::SwipeLeft) => true,
6
        (HoverEventFilter::SwipeRight, EventType::SwipeRight) => true,
6
        (HoverEventFilter::SwipeUp, EventType::SwipeUp) => true,
6
        (HoverEventFilter::SwipeDown, EventType::SwipeDown) => true,
7
        (HoverEventFilter::PinchIn, EventType::PinchIn) => true,
6
        (HoverEventFilter::PinchOut, EventType::PinchOut) => true,
7
        (HoverEventFilter::RotateClockwise, EventType::RotateClockwise) => true,
6
        (HoverEventFilter::RotateCounterClockwise, EventType::RotateCounterClockwise) => true,
6
        (HoverEventFilter::MouseOut, EventType::MouseOut) => true,
4
        (HoverEventFilter::FocusIn, EventType::FocusIn) => true,
4
        (HoverEventFilter::FocusOut, EventType::FocusOut) => true,
4
        (HoverEventFilter::CompositionStart, EventType::CompositionStart) => true,
4
        (HoverEventFilter::CompositionUpdate, EventType::CompositionUpdate) => true,
4
        (HoverEventFilter::CompositionEnd, EventType::CompositionEnd) => true,
        // Pen barrel gestures and hover. The filter variants shipped long
        // before any `EventType` existed that could reach them.
2
        (PenSqueeze, EventType::PenSqueeze) => true,
2
        (PenDoubleTap, EventType::PenDoubleTap) => true,
2
        (PenHover, EventType::PenHover) => true,
        // Thumb buttons. Gated on the payload like every other
        // button-specific arm — a payloadless event must not claim a button.
        (HoverEventFilter::BackMouseDown, EventType::MouseDown) => {
            check_mouse_button(&event.data, MouseButton::Other(MOUSE_BUTTON_BACK))
        }
        (HoverEventFilter::BackMouseUp, EventType::MouseUp) => {
            check_mouse_button(&event.data, MouseButton::Other(MOUSE_BUTTON_BACK))
        }
        (HoverEventFilter::ForwardMouseDown, EventType::MouseDown) => {
            check_mouse_button(&event.data, MouseButton::Other(MOUSE_BUTTON_FORWARD))
        }
        (HoverEventFilter::ForwardMouseUp, EventType::MouseUp) => {
            check_mouse_button(&event.data, MouseButton::Other(MOUSE_BUTTON_FORWARD))
        }
4
        (HoverEventFilter::Submit, EventType::Submit) => true,
4
        (HoverEventFilter::Change, EventType::Change) => true,
4
        (HoverEventFilter::Reset, EventType::Reset) => true,
4
        (HoverEventFilter::Invalid, EventType::Invalid) => true,
        // The dial. A NODE-scoped dial event only makes sense for a device
        // that reports a contact point (a Surface Dial ON the display); every
        // other dial reaches the app through the Window filter.
3
        (HoverEventFilter::DialRotate, EventType::DialRotate) => true,
3
        (HoverEventFilter::DialClick, EventType::DialClick) => true,
49701
        _ => false,
    }
50475
}
/// Check if a focus filter matches the event.
// Exhaustive (filter, event-type) truth table — see matches_hover_filter.
#[allow(clippy::match_same_arms)]
36746
fn matches_focus_filter(
36746
    filter: FocusEventFilter,
36746
    event: &SyntheticEvent,
36746
    _phase: EventPhase,
36746
) -> bool {
    use FocusEventFilter::{
        Drag, DragEnd, DragEnter, DragLeave, DragOver, DragStart, Drop, FocusLost, FocusReceived,
        LeftMouseDown, LeftMouseUp, MiddleMouseDown, MiddleMouseUp, MouseDown, MouseEnter,
        MouseLeave, MouseMove, MouseOver, MouseUp, RightMouseDown, RightMouseUp, Scroll, ScrollEnd,
        ScrollStart, TextInput, VirtualKeyDown, VirtualKeyUp,
    };
36746
    match (filter, &event.event_type) {
52
        (MouseOver, EventType::MouseOver) => true,
22
        (MouseMove, EventType::MouseMove) => true,
28
        (MouseDown, EventType::MouseDown) => true,
28
        (LeftMouseDown, EventType::MouseDown) => check_mouse_button(&event.data, MouseButton::Left),
        (RightMouseDown, EventType::MouseDown) => {
27
            check_mouse_button(&event.data, MouseButton::Right)
        }
        (MiddleMouseDown, EventType::MouseDown) => {
27
            check_mouse_button(&event.data, MouseButton::Middle)
        }
29
        (MouseUp, EventType::MouseUp) => true,
30
        (LeftMouseUp, EventType::MouseUp) => check_mouse_button(&event.data, MouseButton::Left),
28
        (RightMouseUp, EventType::MouseUp) => check_mouse_button(&event.data, MouseButton::Right),
28
        (MiddleMouseUp, EventType::MouseUp) => check_mouse_button(&event.data, MouseButton::Middle),
53
        (MouseEnter, EventType::MouseEnter) => true,
7
        (MouseLeave, EventType::MouseLeave) => true,
6
        (Scroll, EventType::Scroll) => true,
5
        (ScrollStart, EventType::ScrollStart) => true,
5
        (ScrollEnd, EventType::ScrollEnd) => true,
4
        (TextInput, EventType::Input) => true,
5
        (FocusEventFilter::DocumentEdit, EventType::DocumentEdit) => true,
4
        (FocusEventFilter::TextChanged, EventType::TextChanged) => true,
24
        (VirtualKeyDown, EventType::KeyDown) => true,
23
        (VirtualKeyUp, EventType::KeyUp) => true,
29
        (FocusReceived, EventType::Focus) => true,
16
        (FocusLost, EventType::Blur) => true,
4
        (DragStart, EventType::DragStart) => true,
4
        (Drag, EventType::Drag) => true,
4
        (DragEnd, EventType::DragEnd) => true,
4
        (DragEnter, EventType::DragEnter) => true,
4
        (DragOver, EventType::DragOver) => true,
4
        (DragLeave, EventType::DragLeave) => true,
4
        (Drop, EventType::Drop) => true,
        // MWA-C-clipboard: W3C clipboard events on the focused element
        // (qualified paths — `use FocusEventFilter::Copy` would shadow the
        // `Copy` trait in this scope).
4
        (FocusEventFilter::Copy, EventType::Copy) => true,
4
        (FocusEventFilter::Cut, EventType::Cut) => true,
4
        (FocusEventFilter::Paste, EventType::Paste) => true,
        // Gestures — same gap as the hover table.
6
        (FocusEventFilter::LongPress, EventType::LongPress) => true,
7
        (FocusEventFilter::SwipeLeft, EventType::SwipeLeft) => true,
6
        (FocusEventFilter::SwipeRight, EventType::SwipeRight) => true,
6
        (FocusEventFilter::SwipeUp, EventType::SwipeUp) => true,
6
        (FocusEventFilter::SwipeDown, EventType::SwipeDown) => true,
7
        (FocusEventFilter::PinchIn, EventType::PinchIn) => true,
6
        (FocusEventFilter::PinchOut, EventType::PinchOut) => true,
7
        (FocusEventFilter::RotateClockwise, EventType::RotateClockwise) => true,
6
        (FocusEventFilter::RotateCounterClockwise, EventType::RotateCounterClockwise) => true,
        // Pen — `FocusEventFilter` has carried Down/Move/Up since the filter
        // was introduced, but this table had no arm for any of them, so a
        // focused node could never receive a pen event even once dispatch
        // planning named the filter. (Enter/Leave have no Focus twin: a pen
        // crossing a node's bounds is not a focus change.)
5
        (FocusEventFilter::PenDown, EventType::PenDown) => true,
5
        (FocusEventFilter::PenMove, EventType::PenMove) => true,
5
        (FocusEventFilter::PenUp, EventType::PenUp) => true,
        // Thumb buttons. Gated on the payload like every other
        // button-specific arm — a payloadless event must not claim a button.
        (FocusEventFilter::BackMouseDown, EventType::MouseDown) => {
            check_mouse_button(&event.data, MouseButton::Other(MOUSE_BUTTON_BACK))
        }
        (FocusEventFilter::BackMouseUp, EventType::MouseUp) => {
            check_mouse_button(&event.data, MouseButton::Other(MOUSE_BUTTON_BACK))
        }
        (FocusEventFilter::ForwardMouseDown, EventType::MouseDown) => {
            check_mouse_button(&event.data, MouseButton::Other(MOUSE_BUTTON_FORWARD))
        }
        (FocusEventFilter::ForwardMouseUp, EventType::MouseUp) => {
            check_mouse_button(&event.data, MouseButton::Other(MOUSE_BUTTON_FORWARD))
        }
4
        (FocusEventFilter::Submit, EventType::Submit) => true,
4
        (FocusEventFilter::Change, EventType::Change) => true,
4
        (FocusEventFilter::Reset, EventType::Reset) => true,
4
        (FocusEventFilter::Invalid, EventType::Invalid) => true,
36138
        _ => false,
    }
36746
}
/// Check if an application filter matches the event.
///
/// Application events are not hit-tested and have no meaningful target: a
/// device arriving or a monitor being unplugged belongs to the application,
/// not to whichever node happened to be under the cursor. They are dispatched
/// at the root and reach any subscriber by propagation, which is why this
/// table ignores the phase exactly as the window table does.
///
/// This arm returned a flat `false` — "will be implemented in future" — so all
/// four variants were structurally unreachable no matter what a shell emitted.
/// Every other layer was already in place: `event_type_to_filters` had named
/// `EF::Application(..)` for the monitor pair the whole time.
// Exhaustive (filter, event-type) truth table — see matches_hover_filter.
#[allow(clippy::match_same_arms)]
3584
const fn matches_application_filter(
3584
    filter: ApplicationEventFilter,
3584
    event: &SyntheticEvent,
3584
    _phase: EventPhase,
3584
) -> bool {
    use ApplicationEventFilter::{
        DeviceConnected, DeviceDisconnected, MediaControl, MonitorConnected, MonitorDisconnected,
        SystemAudioChange,
    };
3564
    matches!(
3584
        (filter, &event.event_type),
        (MediaControl, EventType::MediaControl)
            | (SystemAudioChange, EventType::SystemAudioChange)
            | (DeviceConnected, EventType::DeviceConnected)
            | (DeviceDisconnected, EventType::DeviceDisconnected)
            | (MonitorConnected, EventType::MonitorConnected)
            | (MonitorDisconnected, EventType::MonitorDisconnected)
    )
3584
}
/// Check if an external filter matches the event (11c).
///
/// Media events are not hit-tested: the player is not a device with a
/// position, so there is no node "under" a `TimeUpdate`. Like the window and
/// application tables this therefore ignores the phase; the event's `target`
/// still names the media node, for callbacks that serve more than one.
// Exhaustive (filter, event-type) truth table — see matches_hover_filter.
#[allow(clippy::match_same_arms)]
3582
const fn matches_external_filter(
3582
    filter: ExternalEventFilter,
3582
    event: &SyntheticEvent,
3582
    _phase: EventPhase,
3582
) -> bool {
3546
    matches!(
3582
        (filter, &event.event_type),
        (ExternalEventFilter::Play, EventType::Play)
            | (ExternalEventFilter::Pause, EventType::Pause)
            | (ExternalEventFilter::Ended, EventType::Ended)
            | (ExternalEventFilter::TimeUpdate, EventType::TimeUpdate)
            | (ExternalEventFilter::VolumeChange, EventType::VolumeChange)
            | (ExternalEventFilter::MediaError, EventType::MediaError)
    )
3582
}
/// Check if a window filter matches the event.
// Exhaustive (filter, event-type) truth table — see matches_hover_filter.
#[allow(clippy::match_same_arms, clippy::too_many_lines)]
52828
fn matches_window_filter(
52828
    filter: WindowEventFilter,
52828
    event: &SyntheticEvent,
52828
    _phase: EventPhase,
52828
) -> bool {
    use WindowEventFilter::{
        BiometricResult, CloseRequested, Drag, DragEnd, DragEnter, DragLeave, DragOver, DragStart,
        Drop, DroppedFile, FocusLost, FocusReceived, FrameChanged, GamepadInput, GeolocationError,
        GeolocationFix, HoveredFile, HoveredFileCancelled, KeyringResult, LeftMouseDown,
        LeftMouseUp, MiddleMouseDown, MiddleMouseUp, ModifiersChanged, MouseDown, MouseEnter,
        MouseLeave, MouseMove, MouseOver, MouseUp, Moved, PenDoubleTap, PenDown, PenEnter,
        PenHover, PenLeave, PenMove, PenSqueeze, PenUp, PermissionChanged, PointerLockChange,
        RawMouseMotion, Resized, RightMouseDown, RightMouseUp, ScreenColorPicked, Scroll,
        ScrollEnd, ScrollStart, SensorChanged, TextInput, ThemeChanged, TouchCancel, TouchEnd,
        TouchMove, TouchStart, VirtualKeyDown, VirtualKeyUp, WindowFocusLost, WindowFocusReceived,
    };
52828
    match (filter, &event.event_type) {
52
        (MouseOver, EventType::MouseOver) => true,
22
        (MouseMove, EventType::MouseMove) => true,
28
        (MouseDown, EventType::MouseDown) => true,
28
        (LeftMouseDown, EventType::MouseDown) => check_mouse_button(&event.data, MouseButton::Left),
        (RightMouseDown, EventType::MouseDown) => {
27
            check_mouse_button(&event.data, MouseButton::Right)
        }
        (MiddleMouseDown, EventType::MouseDown) => {
27
            check_mouse_button(&event.data, MouseButton::Middle)
        }
29
        (MouseUp, EventType::MouseUp) => true,
30
        (LeftMouseUp, EventType::MouseUp) => check_mouse_button(&event.data, MouseButton::Left),
28
        (RightMouseUp, EventType::MouseUp) => check_mouse_button(&event.data, MouseButton::Right),
28
        (MiddleMouseUp, EventType::MouseUp) => check_mouse_button(&event.data, MouseButton::Middle),
53
        (MouseEnter, EventType::MouseEnter) => true,
7
        (MouseLeave, EventType::MouseLeave) => true,
6
        (Scroll, EventType::Scroll) => true,
5
        (ScrollStart, EventType::ScrollStart) => true,
5
        (ScrollEnd, EventType::ScrollEnd) => true,
4
        (TextInput, EventType::Input) => true,
        // `KeyPress` (a key that produced a character) and `Change` (a value
        // committed on blur) both plan onto the `TextInput` filter, which is
        // what an app registers for "text arrived here". Planning named that
        // filter and this table then rejected it, so both dispatched to
        // nothing.
4
        (TextInput, EventType::KeyPress) => true,
5
        (TextInput, EventType::Change) => true,
        // A context-menu request is not a `MouseDown`, so the button-payload
        // check on the `RightMouseDown` arm cannot answer for it. Routing it
        // to the same filter means the Menu/Apps key, Shift+F10 and the
        // accessibility `ShowContextMenu` action all reach the handler an app
        // already registered for right-click, without inventing a new filter
        // variant for each spelling of "open the context menu".
4
        (RightMouseDown, EventType::ContextMenu) => true,
24
        (VirtualKeyDown, EventType::KeyDown) => true,
23
        (VirtualKeyUp, EventType::KeyUp) => true,
4
        (HoveredFile, EventType::FileHover) => true,
4
        (DroppedFile, EventType::FileDrop) => true,
4
        (HoveredFileCancelled, EventType::FileHoverCancel) => true,
15
        (Resized, EventType::WindowResize) => true,
4
        (FrameChanged, EventType::WindowFrameChanged) => true,
6
        (Moved, EventType::WindowMove) => true,
17
        (TouchStart, EventType::TouchStart) => true,
5
        (TouchMove, EventType::TouchMove) => true,
5
        (TouchEnd, EventType::TouchEnd) => true,
5
        (TouchCancel, EventType::TouchCancel) => true,
5
        (PenDown, EventType::PenDown) => true,
5
        (PenMove, EventType::PenMove) => true,
5
        (PenUp, EventType::PenUp) => true,
5
        (PenEnter, EventType::PenEnter) => true,
5
        (PenLeave, EventType::PenLeave) => true,
29
        (FocusReceived, EventType::Focus) => true,
16
        (FocusLost, EventType::Blur) => true,
4
        (CloseRequested, EventType::WindowClose) => true,
4
        (ThemeChanged, EventType::ThemeChange) => true,
5
        (WindowFocusReceived, EventType::WindowFocusIn) => true,
6
        (WindowFocusLost, EventType::WindowFocusOut) => true,
2
        (PointerLockChange, EventType::PointerLockChange) => true,
16
        (SensorChanged, EventType::SensorChanged) => true,
16
        (GamepadInput, EventType::GamepadInput) => true,
4
        (GeolocationFix, EventType::GeolocationFix) => true,
4
        (GeolocationError, EventType::GeolocationError) => true,
4
        (PermissionChanged, EventType::PermissionChanged) => true,
4
        (BiometricResult, EventType::BiometricResult) => true,
4
        (ScreenColorPicked, EventType::ScreenColorPicked) => true,
4
        (KeyringResult, EventType::KeyringResult) => true,
4
        (DragStart, EventType::DragStart) => true,
4
        (Drag, EventType::Drag) => true,
4
        (DragEnd, EventType::DragEnd) => true,
4
        (DragEnter, EventType::DragEnter) => true,
4
        (DragOver, EventType::DragOver) => true,
4
        (DragLeave, EventType::DragLeave) => true,
4
        (Drop, EventType::Drop) => true,
        // Gestures — same gap as the hover table.
6
        (WindowEventFilter::LongPress, EventType::LongPress) => true,
7
        (WindowEventFilter::SwipeLeft, EventType::SwipeLeft) => true,
6
        (WindowEventFilter::SwipeRight, EventType::SwipeRight) => true,
6
        (WindowEventFilter::SwipeUp, EventType::SwipeUp) => true,
6
        (WindowEventFilter::SwipeDown, EventType::SwipeDown) => true,
7
        (WindowEventFilter::PinchIn, EventType::PinchIn) => true,
6
        (WindowEventFilter::PinchOut, EventType::PinchOut) => true,
7
        (WindowEventFilter::RotateClockwise, EventType::RotateClockwise) => true,
6
        (WindowEventFilter::RotateCounterClockwise, EventType::RotateCounterClockwise) => true,
        // Pen barrel gestures and hover. The filter variants shipped long
        // before any `EventType` existed that could reach them.
2
        (PenSqueeze, EventType::PenSqueeze) => true,
2
        (PenDoubleTap, EventType::PenDoubleTap) => true,
2
        (PenHover, EventType::PenHover) => true,
        // Thumb buttons. Gated on the payload like every other
        // button-specific arm — a payloadless event must not claim a button.
        (WindowEventFilter::BackMouseDown, EventType::MouseDown) => {
            check_mouse_button(&event.data, MouseButton::Other(MOUSE_BUTTON_BACK))
        }
        (WindowEventFilter::BackMouseUp, EventType::MouseUp) => {
            check_mouse_button(&event.data, MouseButton::Other(MOUSE_BUTTON_BACK))
        }
        (WindowEventFilter::ForwardMouseDown, EventType::MouseDown) => {
            check_mouse_button(&event.data, MouseButton::Other(MOUSE_BUTTON_FORWARD))
        }
        (WindowEventFilter::ForwardMouseUp, EventType::MouseUp) => {
            check_mouse_button(&event.data, MouseButton::Other(MOUSE_BUTTON_FORWARD))
        }
        (RawMouseMotion, EventType::RawMouseMotion) => true,
        (ModifiersChanged, EventType::ModifiersChanged) => true,
        (WindowEventFilter::HidReport, EventType::HidReport) => true,
3
        (WindowEventFilter::DialRotate, EventType::DialRotate) => true,
3
        (WindowEventFilter::DialClick, EventType::DialClick) => true,
        // Media (11c). These six `EventType`s shipped with no filter in ANY
        // family, so they planned an empty list and dispatched to nothing.
6
        (WindowEventFilter::Play, EventType::Play) => true,
6
        (WindowEventFilter::Pause, EventType::Pause) => true,
6
        (WindowEventFilter::Ended, EventType::Ended) => true,
6
        (WindowEventFilter::TimeUpdate, EventType::TimeUpdate) => true,
6
        (WindowEventFilter::VolumeChange, EventType::VolumeChange) => true,
6
        (WindowEventFilter::MediaError, EventType::MediaError) => true,
52040
        _ => false,
    }
52828
}
/// Detect lifecycle events by comparing old and new DOM state.
///
/// This is the simple, index-based lifecycle detection that doesn't account for
/// node reordering. For more sophisticated reconciliation that can detect moves,
/// use `detect_lifecycle_events_with_reconciliation`.
///
/// Generates Mount, Unmount, and Resize events by comparing DOM hierarchies.
#[allow(clippy::needless_pass_by_value)] // owned azul value taken by value (public API / ownership-transfer convention)
#[must_use]
62
pub fn detect_lifecycle_events(
62
    old_dom_id: DomId,
62
    new_dom_id: DomId,
62
    old_hierarchy: Option<&crate::id::NodeHierarchy>,
62
    new_hierarchy: Option<&crate::id::NodeHierarchy>,
62
    old_layout: Option<&BTreeMap<NodeId, LogicalRect>>,
62
    new_layout: Option<&BTreeMap<NodeId, LogicalRect>>,
62
    timestamp: Instant,
62
) -> Vec<SyntheticEvent> {
62
    let old_nodes = collect_node_ids(old_hierarchy);
62
    let new_nodes = collect_node_ids(new_hierarchy);
62
    let mut events = Vec::new();
    // Mount events: nodes in new but not in old
62
    if let Some(layout) = new_layout {
60
        for &node_id in new_nodes.difference(&old_nodes) {
60
            events.push(create_mount_event(node_id, new_dom_id, layout, &timestamp));
60
        }
21
    }
    // Unmount events: nodes in old but not in new
62
    if let Some(layout) = old_layout {
59
        for &node_id in old_nodes.difference(&new_nodes) {
58
            events.push(create_unmount_event(
58
                node_id, old_dom_id, layout, &timestamp,
58
            ));
58
        }
22
    }
    // Resize events: nodes in both with changed bounds
62
    if let (Some(old_l), Some(new_l)) = (old_layout, new_layout) {
61
        for &node_id in old_nodes.intersection(&new_nodes) {
61
            if let Some(ev) = create_resize_event(node_id, new_dom_id, old_l, new_l, &timestamp) {
21
                events.push(ev);
40
            }
        }
41
    }
62
    events
62
}
127
fn collect_node_ids(hierarchy: Option<&crate::id::NodeHierarchy>) -> BTreeSet<NodeId> {
127
    hierarchy
127
        .map(|h| h.as_ref().linear_iter().collect())
127
        .unwrap_or_default()
127
}
144
fn create_lifecycle_event(
144
    event_type: EventType,
144
    node_id: NodeId,
144
    dom_id: DomId,
144
    timestamp: &Instant,
144
    data: LifecycleEventData,
144
) -> SyntheticEvent {
144
    let dom_node_id = DomNodeId {
144
        dom: dom_id,
144
        node: NodeHierarchyItemId::from_crate_internal(Some(node_id)),
144
    };
144
    SyntheticEvent {
144
        event_type,
144
        source: EventSource::Lifecycle,
144
        phase: EventPhase::Target,
144
        target: dom_node_id,
144
        current_target: dom_node_id,
144
        timestamp: timestamp.clone(),
144
        data: EventData::Lifecycle(data),
144
        stopped: false,
144
        stopped_immediate: false,
144
        prevented_default: false,
144
        at_target_only: false,
144
    }
144
}
63
fn create_mount_event(
63
    node_id: NodeId,
63
    dom_id: DomId,
63
    layout: &BTreeMap<NodeId, LogicalRect>,
63
    timestamp: &Instant,
63
) -> SyntheticEvent {
63
    let current_bounds = layout.get(&node_id).copied().unwrap_or(LogicalRect::zero());
63
    create_lifecycle_event(
63
        EventType::Mount,
63
        node_id,
63
        dom_id,
63
        timestamp,
63
        LifecycleEventData {
63
            reason: LifecycleReason::InitialMount,
63
            previous_bounds: None,
63
            current_bounds,
63
        },
    )
63
}
59
fn create_unmount_event(
59
    node_id: NodeId,
59
    dom_id: DomId,
59
    layout: &BTreeMap<NodeId, LogicalRect>,
59
    timestamp: &Instant,
59
) -> SyntheticEvent {
59
    let previous_bounds = layout.get(&node_id).copied().unwrap_or(LogicalRect::zero());
59
    create_lifecycle_event(
59
        EventType::Unmount,
59
        node_id,
59
        dom_id,
59
        timestamp,
59
        LifecycleEventData {
59
            reason: LifecycleReason::Unmount,
59
            previous_bounds: Some(previous_bounds),
59
            current_bounds: LogicalRect::zero(),
59
        },
    )
59
}
/// Returns `true` iff the two logical sizes differ after fixed-point
/// quantization (~0.001 tolerance), treating a dimension that is NaN on *both*
/// sides as unchanged so a degenerate layout cannot emit a Resize every frame.
44
fn size_changed(old: crate::geom::LogicalSize, new: crate::geom::LogicalSize) -> bool {
64
    fn dim_changed(a: f32, b: f32) -> bool {
64
        if a.is_nan() && b.is_nan() {
4
            return false;
60
        }
        // Fixed-point quantization mirrors `LogicalSize`'s `Ord`/`Hash`.
        // `f32 as i64` saturates on overflow (no wasm32 wraparound); a lone
        // NaN quantizes to `i64::MIN` and so registers as changed.
        #[allow(clippy::cast_possible_truncation)]
        // intentional fixed-point quantization; saturates
120
        let q = |v: f32| -> i64 {
120
            if v.is_nan() {
2
                i64::MIN
            } else {
118
                (v * 1000.0) as i64
            }
120
        };
60
        q(a) != q(b)
64
    }
44
    dim_changed(old.width, new.width) || dim_changed(old.height, new.height)
44
}
68
fn create_resize_event(
68
    node_id: NodeId,
68
    dom_id: DomId,
68
    old_layout: &BTreeMap<NodeId, LogicalRect>,
68
    new_layout: &BTreeMap<NodeId, LogicalRect>,
68
    timestamp: &Instant,
68
) -> Option<SyntheticEvent> {
68
    let old_bounds = *old_layout.get(&node_id)?;
28
    let new_bounds = *new_layout.get(&node_id)?;
    // Quantized/tolerance compare with an explicit NaN guard. A raw `==` on
    // `LogicalSize` used to compare f32 bit patterns, so a single NaN dimension
    // made `old != new` true *every frame forever* -> an endless Resize-event
    // loop. `size_changed` treats a NaN dimension present on both sides as
    // "unchanged" and otherwise compares fixed-point-quantized values.
27
    if !size_changed(old_bounds.size, new_bounds.size) {
5
        return None;
22
    }
22
    Some(create_lifecycle_event(
22
        EventType::Resize,
22
        node_id,
22
        dom_id,
22
        timestamp,
22
        LifecycleEventData {
22
            reason: LifecycleReason::Resize,
22
            previous_bounds: Some(old_bounds),
22
            current_bounds: new_bounds,
22
        },
22
    ))
68
}
/// A `Resize` lifecycle event (`ComponentEventFilter::NodeResized`) for
/// `node_id` whose layout box went from `old` to `new`.
///
/// `None` when its SIZE did not change: a position-only move is not a
/// resize, and a NaN dimension present on both sides reads as unchanged (see
/// `size_changed`; a raw `!=` once produced a Resize every frame forever).
///
/// This is the constructor the layout tail uses after EVERY solve (full
/// rebuild, pre-cascade relayout, window-resize fast path). The older
/// reconcile-time emitter compared layout maps that production always
/// passed EMPTY, so `NodeResized` had never fired in a running app.
#[must_use]
pub fn resize_event_for_bounds(
    dom_id: DomId,
    node_id: NodeId,
    old: LogicalRect,
    new: LogicalRect,
    timestamp: &Instant,
) -> Option<SyntheticEvent> {
    if !size_changed(old.size, new.size) {
        return None;
    }
    Some(create_lifecycle_event(
        EventType::Resize,
        node_id,
        dom_id,
        timestamp,
        LifecycleEventData {
            reason: LifecycleReason::Resize,
            previous_bounds: Some(old),
            current_bounds: new,
        },
    ))
}
/// Result of lifecycle event detection with reconciliation.
///
/// Contains both the generated lifecycle events and a mapping from old to new
/// node IDs for state migration (focus, scroll, etc.).
#[derive(Debug, Clone, Default)]
pub struct LifecycleEventResult {
    /// Lifecycle events (Mount, Unmount, Resize, Update)
    pub events: Vec<SyntheticEvent>,
    /// Maps old `NodeId` -> new `NodeId` for matched nodes.
    /// Use this to migrate focus, scroll state, and other node-specific state.
    pub node_id_mapping: OrderedMap<NodeId, NodeId>,
}
/// Detect lifecycle events using reconciliation with stable keys and content hashing.
///
/// This is the advanced lifecycle detection that can correctly identify:
/// - **Moves**: When a node changes position but keeps its identity (via key or hash)
/// - **Mounts**: When a new node appears
/// - **Unmounts**: When an existing node disappears
/// - **Resizes**: When a node's layout bounds change
/// - **Updates**: When a keyed node's content changes
///
/// The reconciliation strategy is:
/// 1. **Stable Key Match:** Nodes with `.with_reconciliation_key()` are matched by key (O(1))
/// 2. **Hash Match:** Nodes without keys are matched by content hash (enables reorder detection)
/// 3. **Fallback:** Unmatched nodes generate Mount/Unmount events
///
/// # Arguments
/// * `dom_id` - The DOM identifier
/// * `old_node_data` - Node data from the previous frame
/// * `new_node_data` - Node data from the current frame
/// * `old_layout` - Layout bounds from the previous frame
/// * `new_layout` - Layout bounds from the current frame
/// * `timestamp` - Current timestamp for events
///
/// # Returns
/// A `LifecycleEventResult` containing:
/// - `events`: Lifecycle events to dispatch
/// - `node_id_mapping`: Mapping from old to new `NodeIds` for state migration
///
/// # Example
/// ```rust,ignore
/// let result = detect_lifecycle_events_with_reconciliation(
///     dom_id,
///     &old_node_data,
///     &new_node_data,
///     &old_layout,
///     &new_layout,
///     timestamp,
/// );
///
/// // Dispatch lifecycle events
/// for event in result.events {
///     dispatch_event(event);
/// }
///
/// // Migrate focus to new node ID
/// if let Some(focused) = focus_manager.focused_node {
///     if let Some(&new_id) = result.node_id_mapping.get(&focused) {
///         focus_manager.focused_node = Some(new_id);
///     } else {
///         // Focused node was unmounted
///         focus_manager.focused_node = None;
///     }
/// }
/// ```
#[must_use]
1
pub fn detect_lifecycle_events_with_reconciliation(
1
    dom_id: DomId,
1
    old_node_data: &[crate::dom::NodeData],
1
    new_node_data: &[crate::dom::NodeData],
1
    old_hierarchy: &[crate::styled_dom::NodeHierarchyItem],
1
    new_hierarchy: &[crate::styled_dom::NodeHierarchyItem],
1
    old_layout: &OrderedMap<NodeId, LogicalRect>,
1
    new_layout: &OrderedMap<NodeId, LogicalRect>,
1
    timestamp: Instant,
1
) -> LifecycleEventResult {
1
    let diff_result = crate::diff::reconcile_dom(
1
        old_node_data,
1
        new_node_data,
1
        old_hierarchy,
1
        new_hierarchy,
1
        old_layout,
1
        new_layout,
1
        dom_id,
1
        timestamp,
    );
1
    LifecycleEventResult {
1
        events: diff_result.events,
1
        node_id_mapping: crate::diff::create_migration_map(&diff_result.node_moves),
1
    }
1
}
/// Event filter that only fires when an element is hovered over.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub enum HoverEventFilter {
    /// Mouse moved over the hovered element
    MouseOver,
    /// Any mouse button pressed on the hovered element
    MouseDown,
    /// Left mouse button pressed on the hovered element
    LeftMouseDown,
    /// Right mouse button pressed on the hovered element
    RightMouseDown,
    /// Middle mouse button pressed on the hovered element
    MiddleMouseDown,
    /// A completed ACTIVATION on this element: press and release on the same
    /// node, per W3C `click`. This - not `MouseUp` - is what "the user
    /// activated this control" means, and it is what Enter/Space on a focused
    /// element and an assistive technology's default action also dispatch.
    /// `MouseUp` stays the raw pointer-release event.
    Click,
    /// Any mouse button released on the hovered element
    MouseUp,
    /// Left mouse button released on the hovered element
    LeftMouseUp,
    /// Right mouse button released on the hovered element
    RightMouseUp,
    /// Middle mouse button released on the hovered element
    MiddleMouseUp,
    /// Mouse entered the hovered element bounds
    MouseEnter,
    /// Mouse left the hovered element bounds
    MouseLeave,
    /// Scroll event on the hovered element
    Scroll,
    /// Scroll started on the hovered element
    ScrollStart,
    /// Scroll ended on the hovered element
    ScrollEnd,
    /// Text input received while element is hovered
    TextInput,
    /// Virtual key pressed while element is hovered
    VirtualKeyDown,
    /// Virtual key released while element is hovered
    VirtualKeyUp,
    /// File is being hovered over the element
    HoveredFile,
    /// File was dropped onto the element
    DroppedFile,
    /// File hover was cancelled
    HoveredFileCancelled,
    /// Touch started on the hovered element
    TouchStart,
    /// Touch moved on the hovered element
    TouchMove,
    /// Touch ended on the hovered element
    TouchEnd,
    /// Touch was cancelled on the hovered element
    TouchCancel,
    /// Pen/stylus made contact on the hovered element
    PenDown,
    /// Pen/stylus moved while in contact on the hovered element
    PenMove,
    /// Pen/stylus lifted from the hovered element
    PenUp,
    /// Pen/stylus entered proximity of the hovered element
    PenEnter,
    /// Pen/stylus left proximity of the hovered element
    PenLeave,
    /// Apple Pencil 2 / Surface Slim Pen 2 barrel squeeze on the hovered
    /// element. Fires once per squeeze. The matching W3C primitive is the
    /// `PointerEvent` with `pointerType: "pen"` and a transient
    /// `tangentialPressure` spike — most apps tie a tool-switch to it.
    PenSqueeze,
    /// Apple Pencil 2 side double-tap on the hovered element. Fires once
    /// per gesture. Usually mapped to "undo" or "switch eraser".
    PenDoubleTap,
    /// Pen/stylus is hovering above the hovered element (in proximity,
    /// not in contact). Continuous: fires per pen-axis update while the
    /// stylus is held above the surface. Maps to W3C
    /// `PointerEvent('pointermove')` with `buttons: 0` and
    /// `pointerType: 'pen'`.
    PenHover,
    /// New GPS / network location fix arrived for a `GeolocationProbe`
    /// in this node's subtree. Payload accessor:
    /// `CallbackInfo::get_geolocation_fix()`.
    GeolocationFix,
    /// Native geolocation subscription errored / was revoked /
    /// timed out.
    GeolocationError,
    /// A motion-sensor reading changed (P6). Window-level mirror:
    /// `WindowEventFilter::SensorChanged`. Read via `get_sensor_reading`.
    SensorChanged,
    /// A gamepad's state changed / it (dis)connected (P6). Read via
    /// `get_primary_gamepad` / `get_gamepad_state`.
    GamepadInput,
    /// Drag started on the hovered element
    DragStart,
    /// Drag in progress on the hovered element
    Drag,
    /// Drag ended on the hovered element
    DragEnd,
    /// Dragged element entered this element (drop target)
    DragEnter,
    /// Dragged element is over this element (drop target, fires continuously)
    DragOver,
    /// Dragged element left this element (drop target)
    DragLeave,
    /// Element was dropped on this element (drop target)
    Drop,
    /// Double-click detected on the hovered element
    DoubleClick,
    /// Long press detected on the hovered element
    LongPress,
    /// Swipe left gesture on the hovered element
    SwipeLeft,
    /// Swipe right gesture on the hovered element
    SwipeRight,
    /// Swipe up gesture on the hovered element
    SwipeUp,
    /// Swipe down gesture on the hovered element
    SwipeDown,
    /// Pinch-in (zoom out) gesture on the hovered element
    PinchIn,
    /// Pinch-out (zoom in) gesture on the hovered element
    PinchOut,
    /// Clockwise rotation gesture on the hovered element
    RotateClockwise,
    /// Counter-clockwise rotation gesture on the hovered element
    RotateCounterClockwise,
    // W3C MouseOut event (bubbling version of MouseLeave)
    /// Mouse left the element OR moved to a child element (W3C `mouseout`, bubbles)
    MouseOut,
    // W3C Focus events (bubbling versions)
    /// Focus is about to move INTO this element or a descendant (W3C `focusin`, bubbles)
    FocusIn,
    /// Focus is about to move OUT of this element or a descendant (W3C `focusout`, bubbles)
    FocusOut,
    // IME Composition events
    /// IME composition started (W3C `compositionstart`)
    CompositionStart,
    /// IME composition updated (W3C `compositionupdate`)
    CompositionUpdate,
    /// IME composition ended (W3C `compositionend`)
    CompositionEnd,
    // Internal System Events (not exposed to user callbacks)
    #[doc(hidden)]
    /// Internal: Single click for text cursor placement
    SystemTextSingleClick,
    #[doc(hidden)]
    /// Internal: Double click for word selection
    SystemTextDoubleClick,
    #[doc(hidden)]
    /// Internal: Triple click for paragraph/line selection
    SystemTextTripleClick,
    // Async capability outcomes (MWA-A1b)
    /// A permission's OS-observed state changed while this node (the
    /// capability's most recent subscriber) is in the target chain.
    PermissionChanged,
    /// A biometric authentication prompt completed.
    BiometricResult,
    /// The screen eyedropper finished (picked or cancelled).
    ScreenColorPicked,
    /// A keyring store / get / delete operation completed.
    KeyringResult,
    /// The thumb "back" button was pressed. APPENDED at the end for ABI
    /// stability.
    ///
    /// Every shell already routes this button — Win32 `WM_XBUTTONDOWN`, macOS
    /// `otherMouseDown:`, X11 button 8 — into `MouseButton::Other(3)`, and it
    /// died there because no filter named it. Nearly every mouse sold in a
    /// decade has the pair, and browsers, IDEs and file managers all bind them
    /// to navigate back/forward.
    BackMouseDown,
    /// The thumb "back" button was released.
    BackMouseUp,
    /// The thumb "forward" button was pressed.
    ForwardMouseDown,
    /// The thumb "forward" button was released.
    ForwardMouseUp,
    /// A form was submitted — Enter on a focused control, or a submit
    /// button activated. APPENDED at the end for ABI stability.
    Submit,
    /// A control's value was COMMITTED, which is not the same as edited.
    /// APPENDED at the end.
    ///
    /// `TextInput` fires on every keystroke; this fires once, when the value
    /// settles — on blur, or on Enter. A field that validates on `TextInput`
    /// scolds the user halfway through typing an email address; one that
    /// validates on `Change` waits until they have finished.
    Change,
    /// A form was reset to its initial values. APPENDED at the end.
    Reset,
    /// A control failed validation. APPENDED at the end.
    Invalid,
    /// A dial turned over this node. APPENDED at the end.
    DialRotate,
    /// A dial was clicked over this node. APPENDED at the end.
    DialClick,
    /// The pointer moved while over this node. APPENDED at the end.
    MouseMove,
}
impl HoverEventFilter {
    /// Check if this is an internal system event that should not be exposed to user callbacks
    #[must_use]
34
    pub const fn is_system_internal(&self) -> bool {
31
        matches!(
34
            self,
            Self::SystemTextSingleClick | Self::SystemTextDoubleClick | Self::SystemTextTripleClick
        )
34
    }
    // Exhaustive On -> Option<FocusEventFilter> mapping table; the several `=> None`
    // rows (window-only events) are intentional 1:1 rows — merging would collapse the table.
    #[allow(clippy::match_same_arms)]
    #[must_use]
12
    pub const fn to_focus_event_filter(&self) -> Option<FocusEventFilter> {
12
        match self {
            // No focus mirror: a dial is delivered by POSITION (hover) or to
            // the window, never by focus.
            Self::DialRotate | Self::DialClick => None,
1
            Self::MouseOver => Some(FocusEventFilter::MouseOver),
            Self::MouseMove => Some(FocusEventFilter::MouseMove),
            Self::MouseDown => Some(FocusEventFilter::MouseDown),
1
            Self::LeftMouseDown => Some(FocusEventFilter::LeftMouseDown),
            Self::RightMouseDown => Some(FocusEventFilter::RightMouseDown),
            Self::MiddleMouseDown => Some(FocusEventFilter::MiddleMouseDown),
            // Activation is HOVER-scoped: it targets the node that was
            // activated, and dispatch already walks that node's ancestors, so
            // there is no separate focus-scoped spelling to map onto.
            Self::Click => None,
            Self::MouseUp => Some(FocusEventFilter::MouseUp),
            Self::LeftMouseUp => Some(FocusEventFilter::LeftMouseUp),
1
            Self::RightMouseUp => Some(FocusEventFilter::RightMouseUp),
            Self::MiddleMouseUp => Some(FocusEventFilter::MiddleMouseUp),
            Self::MouseEnter => Some(FocusEventFilter::MouseEnter),
            Self::MouseLeave => Some(FocusEventFilter::MouseLeave),
            Self::Scroll => Some(FocusEventFilter::Scroll),
            Self::ScrollStart => Some(FocusEventFilter::ScrollStart),
            Self::ScrollEnd => Some(FocusEventFilter::ScrollEnd),
1
            Self::TextInput => Some(FocusEventFilter::TextInput),
1
            Self::VirtualKeyDown => Some(FocusEventFilter::VirtualKeyDown),
            Self::VirtualKeyUp => Some(FocusEventFilter::VirtualKeyUp),
            Self::HoveredFile => None,
1
            Self::DroppedFile => None,
            Self::HoveredFileCancelled => None,
1
            Self::TouchStart => None,
            Self::TouchMove => None,
            Self::TouchEnd => None,
            Self::TouchCancel => None,
            Self::PenDown => Some(FocusEventFilter::PenDown),
            Self::PenMove => Some(FocusEventFilter::PenMove),
            Self::PenUp => Some(FocusEventFilter::PenUp),
            Self::PenEnter => None,
            Self::PenLeave => None,
            Self::PenSqueeze => None,
            Self::PenDoubleTap => None,
            Self::PenHover => None,
            Self::GeolocationFix => None,
            Self::GeolocationError => None,
            Self::SensorChanged => None,
            Self::GamepadInput => None,
1
            Self::DragStart => Some(FocusEventFilter::DragStart),
            Self::Drag => Some(FocusEventFilter::Drag),
            Self::DragEnd => Some(FocusEventFilter::DragEnd),
            Self::DragEnter => Some(FocusEventFilter::DragEnter),
            Self::DragOver => Some(FocusEventFilter::DragOver),
            Self::DragLeave => Some(FocusEventFilter::DragLeave),
1
            Self::Drop => Some(FocusEventFilter::Drop),
            Self::DoubleClick => Some(FocusEventFilter::DoubleClick),
            Self::LongPress => Some(FocusEventFilter::LongPress),
            Self::SwipeLeft => Some(FocusEventFilter::SwipeLeft),
            Self::SwipeRight => Some(FocusEventFilter::SwipeRight),
            Self::SwipeUp => Some(FocusEventFilter::SwipeUp),
            Self::SwipeDown => Some(FocusEventFilter::SwipeDown),
            Self::PinchIn => Some(FocusEventFilter::PinchIn),
            Self::PinchOut => Some(FocusEventFilter::PinchOut),
            Self::RotateClockwise => Some(FocusEventFilter::RotateClockwise),
            Self::RotateCounterClockwise => Some(FocusEventFilter::RotateCounterClockwise),
            Self::MouseOut => Some(FocusEventFilter::MouseLeave), /* mouseout → closest focus
                                                                    * equivalent */
            Self::FocusIn => Some(FocusEventFilter::FocusIn),
            Self::FocusOut => Some(FocusEventFilter::FocusOut),
            Self::CompositionStart => Some(FocusEventFilter::CompositionStart),
            Self::CompositionUpdate => Some(FocusEventFilter::CompositionUpdate),
            Self::CompositionEnd => Some(FocusEventFilter::CompositionEnd),
            // System internal events - don't convert to focus events
1
            Self::SystemTextSingleClick => None,
1
            Self::SystemTextDoubleClick => None,
1
            Self::SystemTextTripleClick => None,
            // Async capability outcomes — no focus-filter equivalents
            Self::PermissionChanged => None,
            Self::BiometricResult => None,
            Self::ScreenColorPicked => None,
            Self::KeyringResult => None,
            // Thumb buttons have a Focus twin; the rest of the additions do
            // not (a HID report and a modifier change belong to the window).
            Self::BackMouseDown => Some(FocusEventFilter::BackMouseDown),
            Self::BackMouseUp => Some(FocusEventFilter::BackMouseUp),
            Self::ForwardMouseDown => Some(FocusEventFilter::ForwardMouseDown),
            Self::ForwardMouseUp => Some(FocusEventFilter::ForwardMouseUp),
            // Form events have a Focus twin: they belong to the control that
            // was being edited, not to whatever is hovered.
            Self::Submit => Some(FocusEventFilter::Submit),
            Self::Change => Some(FocusEventFilter::Change),
            Self::Reset => Some(FocusEventFilter::Reset),
            Self::Invalid => Some(FocusEventFilter::Invalid),
        }
12
    }
}
/// Event filter similar to `HoverEventFilter` that only fires when the element is focused.
///
/// **Important**: In order for this to fire, the item must have a `tabindex` attribute
/// (to indicate that the item is focus-able).
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub enum FocusEventFilter {
    /// Mouse moved over the focused element
    MouseOver,
    /// Any mouse button pressed on the focused element
    MouseDown,
    /// Left mouse button pressed on the focused element
    LeftMouseDown,
    /// Right mouse button pressed on the focused element
    RightMouseDown,
    /// Middle mouse button pressed on the focused element
    MiddleMouseDown,
    /// Any mouse button released on the focused element
    MouseUp,
    /// Left mouse button released on the focused element
    LeftMouseUp,
    /// Right mouse button released on the focused element
    RightMouseUp,
    /// Middle mouse button released on the focused element
    MiddleMouseUp,
    /// Mouse entered the focused element bounds
    MouseEnter,
    /// Mouse left the focused element bounds
    MouseLeave,
    /// Scroll event on the focused element
    Scroll,
    /// Scroll started on the focused element
    ScrollStart,
    /// Scroll ended on the focused element
    ScrollEnd,
    /// Text input received while element is focused
    TextInput,
    /// Virtual key pressed while element is focused
    VirtualKeyDown,
    /// Virtual key released while element is focused
    VirtualKeyUp,
    /// Element received keyboard focus
    FocusReceived,
    /// Element lost keyboard focus
    FocusLost,
    /// Pen/stylus made contact on the focused element
    PenDown,
    /// Pen/stylus moved while in contact on the focused element
    PenMove,
    /// Pen/stylus lifted from the focused element
    PenUp,
    /// Drag started on the focused element
    DragStart,
    /// Drag in progress on the focused element
    Drag,
    /// Drag ended on the focused element
    DragEnd,
    /// Dragged element entered this focused element (drop target)
    DragEnter,
    /// Dragged element is over this focused element (drop target)
    DragOver,
    /// Dragged element left this focused element (drop target)
    DragLeave,
    /// Element was dropped on this focused element (drop target)
    Drop,
    /// Double-click detected on the focused element
    DoubleClick,
    /// Long press detected on the focused element
    LongPress,
    /// Swipe left gesture on the focused element
    SwipeLeft,
    /// Swipe right gesture on the focused element
    SwipeRight,
    /// Swipe up gesture on the focused element
    SwipeUp,
    /// Swipe down gesture on the focused element
    SwipeDown,
    /// Pinch-in (zoom out) gesture on the focused element
    PinchIn,
    /// Pinch-out (zoom in) gesture on the focused element
    PinchOut,
    /// Clockwise rotation gesture on the focused element
    RotateClockwise,
    /// Counter-clockwise rotation gesture on the focused element
    RotateCounterClockwise,
    // W3C Focus events (bubbling versions, fires on focused element when focus changes)
    /// Focus moved into this element or a descendant (W3C `focusin`)
    FocusIn,
    /// Focus moved out of this element or a descendant (W3C `focusout`)
    FocusOut,
    // IME Composition events
    /// IME composition started (W3C `compositionstart`)
    CompositionStart,
    /// IME composition updated (W3C `compositionupdate`)
    CompositionUpdate,
    /// IME composition ended (W3C `compositionend`)
    CompositionEnd,
    // Clipboard events (W3C clipboard-events; MWA-C-clipboard: fire on the
    // focused element BEFORE the OS default action, which preventDefault
    // suppresses). APPENDED at the end for ABI stability — sync to api.json
    // via azul-doc autofix in Phase D.
    /// Content is about to be copied from the focused element (W3C `copy`)
    Copy,
    /// Content is about to be cut from the focused element (W3C `cut`)
    Cut,
    /// Content is about to be pasted into the focused element (W3C `paste`)
    Paste,
    /// A structural document edit was recorded on (or under) the focused
    /// element and awaits the app's apply-and-ack (see
    /// `EventType::DocumentEdit`). APPENDED at the end for ABI stability.
    DocumentEdit,
    /// The focused editable's text was committed (see
    /// `EventType::TextChanged`): the post-commit counterpart of `TextInput`,
    /// which fires before the pending insertion is applied. APPENDED at the
    /// end for ABI stability.
    TextChanged,
    /// The thumb "back" button was pressed. APPENDED at the end for ABI
    /// stability.
    ///
    /// Every shell already routes this button — Win32 `WM_XBUTTONDOWN`, macOS
    /// `otherMouseDown:`, X11 button 8 — into `MouseButton::Other(3)`, and it
    /// died there because no filter named it. Nearly every mouse sold in a
    /// decade has the pair, and browsers, IDEs and file managers all bind them
    /// to navigate back/forward.
    BackMouseDown,
    /// The thumb "back" button was released.
    BackMouseUp,
    /// The thumb "forward" button was pressed.
    ForwardMouseDown,
    /// The thumb "forward" button was released.
    ForwardMouseUp,
    /// A form was submitted — Enter on a focused control, or a submit
    /// button activated. APPENDED at the end for ABI stability.
    Submit,
    /// A control's value was COMMITTED, which is not the same as edited.
    /// APPENDED at the end.
    ///
    /// `TextInput` fires on every keystroke; this fires once, when the value
    /// settles — on blur, or on Enter. A field that validates on `TextInput`
    /// scolds the user halfway through typing an email address; one that
    /// validates on `Change` waits until they have finished.
    Change,
    /// A form was reset to its initial values. APPENDED at the end.
    Reset,
    /// A control failed validation. APPENDED at the end.
    Invalid,
    /// The pointer moved while this node had focus. APPENDED at the end.
    MouseMove,
}
/// Event filter that fires when any action fires on the entire window
/// (regardless of whether any element is hovered or focused over).
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub enum WindowEventFilter {
    /// Mouse moved anywhere in window
    MouseOver,
    /// Any mouse button pressed anywhere in window
    MouseDown,
    /// Left mouse button pressed anywhere in window
    LeftMouseDown,
    /// Right mouse button pressed anywhere in window
    RightMouseDown,
    /// Middle mouse button pressed anywhere in window
    MiddleMouseDown,
    /// Any mouse button released anywhere in window
    MouseUp,
    /// Left mouse button released anywhere in window
    LeftMouseUp,
    /// Right mouse button released anywhere in window
    RightMouseUp,
    /// Middle mouse button released anywhere in window
    MiddleMouseUp,
    /// Mouse entered the window
    MouseEnter,
    /// Mouse left the window
    MouseLeave,
    /// Scroll event anywhere in window
    Scroll,
    /// Scroll started anywhere in window
    ScrollStart,
    /// Scroll ended anywhere in window
    ScrollEnd,
    /// Text input received in window
    TextInput,
    /// Virtual key pressed in window
    VirtualKeyDown,
    /// Virtual key released in window
    VirtualKeyUp,
    /// File is being hovered over the window
    HoveredFile,
    /// File was dropped onto the window
    DroppedFile,
    /// File hover was cancelled
    HoveredFileCancelled,
    /// Window was resized
    Resized,
    /// Window was moved
    Moved,
    /// Window was minimized, maximized, restored, or toggled fullscreen
    FrameChanged,
    /// Touch started anywhere in window
    TouchStart,
    /// Touch moved anywhere in window
    TouchMove,
    /// Touch ended anywhere in window
    TouchEnd,
    /// Touch was cancelled
    TouchCancel,
    /// Window received focus
    FocusReceived,
    /// Window lost focus
    FocusLost,
    /// Window close was requested
    CloseRequested,
    /// System theme changed (light/dark mode)
    ThemeChanged,
    /// Window received OS-level focus
    WindowFocusReceived,
    /// Window lost OS-level focus
    WindowFocusLost,
    /// Pen/stylus made contact anywhere in window
    PenDown,
    /// Pen/stylus moved while in contact anywhere in window
    PenMove,
    /// Pen/stylus lifted anywhere in window
    PenUp,
    /// Pen/stylus entered window proximity
    PenEnter,
    /// Pen/stylus left window proximity
    PenLeave,
    /// Pen barrel-squeeze gesture fired in the window. See
    /// [`HoverEventFilter::PenSqueeze`].
    PenSqueeze,
    /// Pen side double-tap gesture fired in the window. See
    /// [`HoverEventFilter::PenDoubleTap`].
    PenDoubleTap,
    /// Pen hover in the window (in proximity, not in contact). See
    /// [`HoverEventFilter::PenHover`].
    PenHover,
    /// New GPS / network location fix arrived. Payload accessor:
    /// `CallbackInfo::get_geolocation_fix()`. Window-level rather
    /// than per-node because the user's location isn't bound to any
    /// particular DOM node — but a node-level mirror
    /// (`HoverEventFilter::GeolocationFix`) fires on every
    /// `GeolocationProbe` in the tree as well, for the common
    /// "redraw this node when the location changes" pattern.
    GeolocationFix,
    /// Native geolocation subscription dropped or errored (signal
    /// lost, no provider, permission revoked mid-session).
    GeolocationError,
    /// A motion-sensor reading changed (P6). Fires window-level (the device
    /// isn't bound to a node); read via `CallbackInfo::get_sensor_reading`.
    SensorChanged,
    /// A gamepad's buttons / axes changed or it (dis)connected (P6); read via
    /// `get_primary_gamepad` / `get_gamepad_state`.
    GamepadInput,
    /// Drag started anywhere in window
    DragStart,
    /// Drag in progress anywhere in window
    Drag,
    /// Drag ended anywhere in window
    DragEnd,
    /// Dragged element entered a drop target in window
    DragEnter,
    /// Dragged element is over a drop target in window
    DragOver,
    /// Dragged element left a drop target in window
    DragLeave,
    /// Element was dropped on a drop target in window
    Drop,
    /// Double-click detected anywhere in window
    DoubleClick,
    /// Long press detected anywhere in window
    LongPress,
    /// Swipe left gesture anywhere in window
    SwipeLeft,
    /// Swipe right gesture anywhere in window
    SwipeRight,
    /// Swipe up gesture anywhere in window
    SwipeUp,
    /// Swipe down gesture anywhere in window
    SwipeDown,
    /// Pinch-in (zoom out) gesture anywhere in window
    PinchIn,
    /// Pinch-out (zoom in) gesture anywhere in window
    PinchOut,
    /// Clockwise rotation gesture anywhere in window
    RotateClockwise,
    /// Counter-clockwise rotation gesture anywhere in window
    RotateCounterClockwise,
    /// The window's DPI scale factor changed (e.g., moved to a monitor with
    /// different scaling). The new DPI is available via `CallbackInfo::get_hidpi_factor()`.
    DpiChanged,
    /// The window moved to a different monitor. The new monitor is available
    /// via `CallbackInfo::get_current_monitor()`.
    MonitorChanged,
    // Async capability outcomes (MWA-A1b) — window-level mirrors (the
    // outcome isn't inherently bound to a node).
    /// A permission's OS-observed state changed.
    PermissionChanged,
    /// A biometric authentication prompt completed.
    BiometricResult,
    /// The screen eyedropper finished (picked or cancelled).
    ScreenColorPicked,
    /// A keyring store / get / delete operation completed.
    KeyringResult,
    /// The thumb "back" button was pressed. APPENDED at the end for ABI
    /// stability.
    ///
    /// Every shell already routes this button — Win32 `WM_XBUTTONDOWN`, macOS
    /// `otherMouseDown:`, X11 button 8 — into `MouseButton::Other(3)`, and it
    /// died there because no filter named it. Nearly every mouse sold in a
    /// decade has the pair, and browsers, IDEs and file managers all bind them
    /// to navigate back/forward.
    BackMouseDown,
    /// The thumb "back" button was released.
    BackMouseUp,
    /// The thumb "forward" button was pressed.
    ForwardMouseDown,
    /// The thumb "forward" button was released.
    ForwardMouseUp,
    /// Raw, pre-acceleration pointer motion. APPENDED at the end for ABI
    /// stability.
    ///
    /// Window-scoped rather than hover-scoped because raw motion has no
    /// position: there is no node under it to hit-test, and a locked pointer
    /// is a window-wide mode.
    RawMouseMotion,
    /// A modifier or lock key changed state. APPENDED at the end.
    ModifiersChanged,
    /// A HID device delivered an input report. APPENDED at the end.
    ///
    /// Window-scoped like `RawMouseMotion`: a HID report has no position, so
    /// there is no node it belongs to.
    HidReport,
    /// A dial turned. APPENDED at the end.
    ///
    /// Window-scoped as well as node-scoped: a dial used OFF the screen (every
    /// device except a Surface Dial on a Surface Studio) reports no contact
    /// point, so no node is under it and only the window can receive it.
    DialRotate,
    /// A dial with a physical click was pressed. APPENDED at the end.
    DialClick,
    /// The pointer moved anywhere in the window. APPENDED at the end.
    MouseMove,
    /// The pointer lock was taken, released, or ended by the platform
    /// (9d-ii-c). Window-level: the lock belongs to the window, not a node.
    PointerLockChange,
    /// Media playback started (11c). APPENDED at the end for ABI stability.
    ///
    /// The window mirror of [`ExternalEventFilter::Play`]. Media state is
    /// reported by an EXTERNAL player, not by a device the window hit-tests,
    /// so `External` is its home; this pair exists because a media event
    /// belongs to the window in exactly the sense a monitor being unplugged
    /// does, and an app that already listens window-wide should not have to
    /// learn a second family to hear it.
    Play,
    /// Media playback paused. APPENDED at the end.
    Pause,
    /// Media playback reached the end. APPENDED at the end.
    Ended,
    /// The media position advanced (throttled — see
    /// `managers::media_player::TIME_UPDATE_INTERVAL_S`). APPENDED at the end.
    TimeUpdate,
    /// The media volume or mute state changed. APPENDED at the end.
    VolumeChange,
    /// The media pipeline failed. APPENDED at the end.
    MediaError,
}
impl WindowEventFilter {
    // Exhaustive On -> Option<HoverEventFilter> mapping table (see to_focus_event_filter).
    #[allow(clippy::match_same_arms)]
    #[must_use]
47
    pub const fn to_hover_event_filter(&self) -> Option<HoverEventFilter> {
47
        match self {
            Self::DialRotate => Some(HoverEventFilter::DialRotate),
            Self::DialClick => Some(HoverEventFilter::DialClick),
2
            Self::MouseOver => Some(HoverEventFilter::MouseOver),
            Self::MouseMove => Some(HoverEventFilter::MouseMove),
1
            Self::MouseDown => Some(HoverEventFilter::MouseDown),
2
            Self::LeftMouseDown => Some(HoverEventFilter::LeftMouseDown),
1
            Self::RightMouseDown => Some(HoverEventFilter::RightMouseDown),
1
            Self::MiddleMouseDown => Some(HoverEventFilter::MiddleMouseDown),
1
            Self::MouseUp => Some(HoverEventFilter::MouseUp),
1
            Self::LeftMouseUp => Some(HoverEventFilter::LeftMouseUp),
2
            Self::RightMouseUp => Some(HoverEventFilter::RightMouseUp),
1
            Self::MiddleMouseUp => Some(HoverEventFilter::MiddleMouseUp),
1
            Self::Scroll => Some(HoverEventFilter::Scroll),
            Self::ScrollStart => Some(HoverEventFilter::ScrollStart),
            Self::ScrollEnd => Some(HoverEventFilter::ScrollEnd),
2
            Self::TextInput => Some(HoverEventFilter::TextInput),
2
            Self::VirtualKeyDown => Some(HoverEventFilter::VirtualKeyDown),
1
            Self::VirtualKeyUp => Some(HoverEventFilter::VirtualKeyUp),
1
            Self::HoveredFile => Some(HoverEventFilter::HoveredFile),
2
            Self::DroppedFile => Some(HoverEventFilter::DroppedFile),
1
            Self::HoveredFileCancelled => Some(HoverEventFilter::HoveredFileCancelled),
            // MouseEnter and MouseLeave on the **window** - does not mean a mouseenter
            // and a mouseleave on the hovered element
1
            Self::MouseEnter => None,
1
            Self::MouseLeave => None,
1
            Self::Resized => None,
1
            Self::Moved => None,
            // A frame transition is a WINDOW fact; there is no per-element
            // hover equivalent to map it onto.
            Self::FrameChanged => None,
2
            Self::TouchStart => Some(HoverEventFilter::TouchStart),
            Self::TouchMove => Some(HoverEventFilter::TouchMove),
1
            Self::TouchEnd => Some(HoverEventFilter::TouchEnd),
            Self::TouchCancel => Some(HoverEventFilter::TouchCancel),
1
            Self::FocusReceived => None,
1
            Self::FocusLost => None,
1
            Self::CloseRequested => None,
1
            Self::ThemeChanged => None,
1
            Self::WindowFocusReceived => None, // specific to window!
1
            Self::WindowFocusLost => None,     // specific to window!
            Self::PointerLockChange => None,   // specific to window!
1
            Self::PenDown => Some(HoverEventFilter::PenDown),
            Self::PenMove => Some(HoverEventFilter::PenMove),
            Self::PenUp => Some(HoverEventFilter::PenUp),
            Self::PenEnter => Some(HoverEventFilter::PenEnter),
            Self::PenLeave => Some(HoverEventFilter::PenLeave),
            Self::PenSqueeze => Some(HoverEventFilter::PenSqueeze),
            Self::PenDoubleTap => Some(HoverEventFilter::PenDoubleTap),
            Self::PenHover => Some(HoverEventFilter::PenHover),
            Self::GeolocationFix => Some(HoverEventFilter::GeolocationFix),
            Self::GeolocationError => Some(HoverEventFilter::GeolocationError),
            Self::SensorChanged => Some(HoverEventFilter::SensorChanged),
            Self::GamepadInput => Some(HoverEventFilter::GamepadInput),
2
            Self::DragStart => Some(HoverEventFilter::DragStart),
            Self::Drag => Some(HoverEventFilter::Drag),
            Self::DragEnd => Some(HoverEventFilter::DragEnd),
            Self::DragEnter => Some(HoverEventFilter::DragEnter),
            Self::DragOver => Some(HoverEventFilter::DragOver),
            Self::DragLeave => Some(HoverEventFilter::DragLeave),
2
            Self::Drop => Some(HoverEventFilter::Drop),
1
            Self::DoubleClick => Some(HoverEventFilter::DoubleClick),
            Self::LongPress => Some(HoverEventFilter::LongPress),
            Self::SwipeLeft => Some(HoverEventFilter::SwipeLeft),
            Self::SwipeRight => Some(HoverEventFilter::SwipeRight),
            Self::SwipeUp => Some(HoverEventFilter::SwipeUp),
            Self::SwipeDown => Some(HoverEventFilter::SwipeDown),
            Self::PinchIn => Some(HoverEventFilter::PinchIn),
            Self::PinchOut => Some(HoverEventFilter::PinchOut),
            Self::RotateClockwise => Some(HoverEventFilter::RotateClockwise),
            Self::RotateCounterClockwise => Some(HoverEventFilter::RotateCounterClockwise),
            // Window-specific events with no hover equivalent
1
            Self::DpiChanged => None,
1
            Self::MonitorChanged => None,
            // Async capability outcomes — mirror to the hover twin
1
            Self::PermissionChanged => Some(HoverEventFilter::PermissionChanged),
1
            Self::BiometricResult => Some(HoverEventFilter::BiometricResult),
1
            Self::ScreenColorPicked => Some(HoverEventFilter::ScreenColorPicked),
1
            Self::KeyringResult => Some(HoverEventFilter::KeyringResult),
            Self::BackMouseDown => Some(HoverEventFilter::BackMouseDown),
            Self::BackMouseUp => Some(HoverEventFilter::BackMouseUp),
            Self::ForwardMouseDown => Some(HoverEventFilter::ForwardMouseDown),
            Self::ForwardMouseUp => Some(HoverEventFilter::ForwardMouseUp),
            // Window-only: no position to hit-test, so no hover twin.
            Self::RawMouseMotion | Self::ModifiersChanged | Self::HidReport => None,
            // Media state (11c) has no hover twin either: it is reported by an
            // external player, and there is no pointer position that could
            // decide which node it "happened over".
            Self::Play
            | Self::Pause
            | Self::Ended
            | Self::TimeUpdate
            | Self::VolumeChange
            | Self::MediaError => None,
        }
47
    }
}
/// Defines events related to the lifecycle of a DOM node itself.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub enum ComponentEventFilter {
    /// Fired after the component is first mounted into the DOM.
    AfterMount,
    /// Fired just before the component is removed from the DOM.
    BeforeUnmount,
    /// Fired when the node's layout rectangle has been resized.
    NodeResized,
    /// Fired to trigger the default action for an accessibility component.
    DefaultAction,
    /// Fired when the component becomes selected.
    Selected,
    /// Fired when a keyed component's content has changed (props/state update).
    Updated,
    /// Fired on a `<transient-window>` the user dismissed (outside click or
    /// Escape). The popup is closed by the engine regardless; this is where
    /// the app clears its own `open` state so the next layout agrees.
    Dismissed,
    /// Fired on a `<transient-window>` the user tore off its anchor by
    /// dragging its `-azul-app-region: drag` strip; it is a free toplevel
    /// now. The event's `current_bounds` is its rect in the parent.
    TornOff,
    /// Fired on a torn-off `<transient-window>` the user docked back - onto
    /// its anchor, or onto a `tearoff-zone` node, which is its anchor from
    /// here on.
    Docked,
}
/// Defines application-level events not tied to a specific window or node.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub enum ApplicationEventFilter {
    /// Fired when a new hardware device is connected.
    DeviceConnected,
    /// Fired when a hardware device is disconnected.
    DeviceDisconnected,
    /// Fired when a new monitor/display is connected to the system.
    /// Callback receives updated monitor list via `CallbackInfo::get_monitors()`.
    MonitorConnected,
    /// Fired when a monitor/display is disconnected from the system.
    MonitorDisconnected,
    /// The platform's media controls asked for a seek (9h-i-a-i-a). APPENDED
    /// at the end for ABI stability.
    MediaControl,
    /// The system changed the app's hold on the audio (9h-i-a-i-d-i).
    SystemAudioChange,
}
/// Events reported by something OUTSIDE the input pipeline (11c).
///
/// The other four families answer "where did this land?" — hovered, focused,
/// window-wide, on this component. A media player answers none of those: the
/// state change happens in an external player (a decoder thread, a platform
/// media service, the app's own transport calls) and is then reported IN. It
/// is the same shape as a monitor being unplugged, one level closer to the
/// app.
///
/// Dispatched like a window filter: every node carrying a matching callback
/// is invoked, and the event's `target` names the media node so a callback
/// serving several players can tell them apart.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub enum ExternalEventFilter {
    /// Media playback started.
    Play,
    /// Media playback paused.
    Pause,
    /// Media playback reached the end of its known duration. Fires exactly
    /// once per arrival at the end (reaching it also stops the transport).
    Ended,
    /// The media position advanced. THROTTLED to one event per 250 ms of
    /// media time (`managers::media_player::TIME_UPDATE_INTERVAL_S`) — the
    /// web's ~4/s budget — because a playing video would otherwise raise one
    /// per frame for its entire length.
    TimeUpdate,
    /// The media volume or mute state changed.
    VolumeChange,
    /// The media pipeline reported a failure; the transport is stopped.
    MediaError,
}
/// Sets the target for what events can reach the callbacks specifically.
///
/// This determines the condition under which an event is fired, such as whether
/// the node is hovered, focused, or if the event is window-global.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C, u8)]
pub enum EventFilter {
    /// Calls the attached callback when the mouse is actively over the
    /// given element.
    Hover(HoverEventFilter),
    /// Calls the attached callback when the element is currently focused.
    Focus(FocusEventFilter),
    /// Calls the callback when anything related to the window is happening.
    /// The "hit item" will be the root item of the DOM.
    /// For example, this can be useful for tracking the mouse position
    /// (in relation to the window). In difference to `Desktop`, this only
    /// fires when the window is focused.
    ///
    /// This can also be good for capturing controller input, touch input
    /// (i.e. global gestures that aren't attached to any component, but rather
    /// the "window" itself).
    Window(WindowEventFilter),
    /// API stub: Something happened with the node itself (node resized, created or removed).
    Component(ComponentEventFilter),
    /// Something happened with the application (started, shutdown, device plugged in).
    Application(ApplicationEventFilter),
    /// Something was reported by an external source that the hit test cannot
    /// place — media playback state, today. APPENDED at the end for ABI
    /// stability (`EventFilter` is `repr(C, u8)`; a variant inserted anywhere
    /// but the tail would renumber every discriminant after it).
    External(ExternalEventFilter),
}
impl EventFilter {
    #[must_use]
450657
    pub const fn is_focus_callback(&self) -> bool {
450657
        matches!(self, Self::Focus(_))
450657
    }
    #[must_use]
15354
    pub const fn is_window_callback(&self) -> bool {
15354
        matches!(self, Self::Window(_))
15354
    }
}
/// Creates a function inside an impl <enum type> block that returns a single
/// variant if the enum is that variant.
macro_rules! get_single_enum_type {
    ($fn_name:ident, $enum_name:ident:: $variant:ident($return_type:ty)) => {
        #[must_use]
6
        pub const fn $fn_name(&self) -> Option<$return_type> {
            use self::$enum_name::*;
6
            match self {
3
                $variant(e) => Some(*e),
3
                _ => None,
            }
6
        }
    };
}
impl EventFilter {
    get_single_enum_type!(as_hover_event_filter, EventFilter::Hover(HoverEventFilter));
    get_single_enum_type!(as_focus_event_filter, EventFilter::Focus(FocusEventFilter));
    get_single_enum_type!(
        as_window_event_filter,
        EventFilter::Window(WindowEventFilter)
    );
}
/// Convert from `On` enum to `EventFilter`.
///
/// This determines which specific filter variant is used based on the event type.
/// For example, `On::TextInput` becomes a Focus event filter, while `On::VirtualKeyDown`
/// becomes a Window event filter (since it's global to the window).
impl From<On> for EventFilter {
    // Exhaustive On -> EventFilter mapping table; the a11y events (Default/Collapse/
    // Expand/Increment/Decrement) all map to MouseUp ("click") as intentional 1:1
    // documented rows — merging would drop the per-row rationale comments.
    #[allow(clippy::match_same_arms)]
12
    fn from(input: On) -> Self {
        use crate::dom::On::{
            Collapse, Decrement, Default, DroppedFile, Expand, FocusLost, FocusReceived,
            HoveredFile, HoveredFileCancelled, Increment, LeftMouseDown, LeftMouseUp,
            MiddleMouseDown, MiddleMouseUp, MouseDown, MouseEnter, MouseLeave, MouseMove,
            MouseOver, MouseUp, RightMouseDown, RightMouseUp, Scroll, TextInput, VirtualKeyDown,
            VirtualKeyUp,
        };
12
        match input {
1
            MouseOver => Self::Hover(HoverEventFilter::MouseOver),
            MouseMove => Self::Hover(HoverEventFilter::MouseMove),
            MouseDown => Self::Hover(HoverEventFilter::MouseDown),
            LeftMouseDown => Self::Hover(HoverEventFilter::LeftMouseDown),
            MiddleMouseDown => Self::Hover(HoverEventFilter::MiddleMouseDown),
            RightMouseDown => Self::Hover(HoverEventFilter::RightMouseDown),
1
            On::Click => Self::Hover(HoverEventFilter::Click),
            MouseUp => Self::Hover(HoverEventFilter::MouseUp),
            LeftMouseUp => Self::Hover(HoverEventFilter::LeftMouseUp),
            MiddleMouseUp => Self::Hover(HoverEventFilter::MiddleMouseUp),
            RightMouseUp => Self::Hover(HoverEventFilter::RightMouseUp),
            MouseEnter => Self::Hover(HoverEventFilter::MouseEnter),
            MouseLeave => Self::Hover(HoverEventFilter::MouseLeave),
            Scroll => Self::Hover(HoverEventFilter::Scroll),
2
            TextInput => Self::Focus(FocusEventFilter::TextInput), // focus!
            On::DocumentEdit => Self::Focus(FocusEventFilter::DocumentEdit), // focus!
            On::TextChanged => Self::Focus(FocusEventFilter::TextChanged), // focus!
1
            VirtualKeyDown => Self::Window(WindowEventFilter::VirtualKeyDown), // window!
1
            VirtualKeyUp => Self::Window(WindowEventFilter::VirtualKeyUp), // window!
            HoveredFile => Self::Hover(HoverEventFilter::HoveredFile),
            DroppedFile => Self::Hover(HoverEventFilter::DroppedFile),
            HoveredFileCancelled => Self::Hover(HoverEventFilter::HoveredFileCancelled),
            FocusReceived => Self::Focus(FocusEventFilter::FocusReceived), // focus!
            FocusLost => Self::Focus(FocusEventFilter::FocusLost),         // focus!
            // Accessibility events are ACTIVATIONS, so they map to `Click` -
            // the same filter a pointer click and a keyboard Enter/Space
            // reach. They used to map to `MouseUp`, which conflated
            // activation with a raw pointer release.
2
            Default => Self::Hover(HoverEventFilter::Click),
1
            Collapse => Self::Hover(HoverEventFilter::Click),
1
            Expand => Self::Hover(HoverEventFilter::Click),
1
            Increment => Self::Hover(HoverEventFilter::Click),
1
            Decrement => Self::Hover(HoverEventFilter::Click),
        }
12
    }
}
// Cross-Platform Event Dispatch System
// NOTE: The old dispatch_synthetic_events / CallbackTarget / CallbackToInvoke / EventDispatchResult
// pipeline has been removed. Event dispatch now goes through dispatch_events_propagated() in
// event_v2.rs which uses propagate_event() for W3C Capture→Target→Bubble propagation.
/// Trait for managers to provide their pending events.
///
/// Each manager (`TextInputManager`, `ScrollManager`, etc.) implements this to
/// report what events occurred since the last frame. This enables a unified,
/// lazy event determination system.
pub trait EventProvider {
    /// Get all pending events from this manager.
    ///
    /// Events should include:
    ///
    /// - `target`: The `DomNodeId` that was affected
    /// - `event_type`: What happened (Input, Scroll, Focus, etc.)
    /// - `source`: `EventSource::User` for input, `EventSource::Programmatic` for API calls
    /// - `data`: Type-specific event data
    ///
    /// After calling this, the manager should mark events as "read" so they
    /// aren't returned again next frame.
    fn get_pending_events(&self, timestamp: Instant) -> Vec<SyntheticEvent>;
}
/// Deduplicate synthetic events by (target node, event type).
///
/// Groups by (target.dom, target.node, `event_type`), keeping the latest timestamp.
#[must_use]
1928
pub fn deduplicate_synthetic_events(mut events: Vec<SyntheticEvent>) -> Vec<SyntheticEvent> {
1928
    if events.len() <= 1 {
1468
        return events;
460
    }
    // The pointer SEAT is part of the key (9b-ii-b): two cursors pressing the
    // same node are two presses, not one. Non-pointer events key on the
    // primary and coalesce exactly as before.
327138
    let seat_of = |e: &SyntheticEvent| match &e.data {
989
        EventData::Mouse(m) => m.seat_id,
72
        EventData::Scroll(s) => s.seat_id,
96
        EventData::Touch(t) => t.seat_id,
        EventData::Composition(c) => c.seat_id,
325981
        _ => crate::window::PRIMARY_POINTER_SEAT,
327138
    };
186804
    events.sort_by_key(|e| (e.target.dom, e.target.node, e.event_type, seat_of(e)));
    // Coalesce consecutive events with same target, event_type and seat
460
    let mut result = Vec::with_capacity(events.len());
460
    let mut iter = events.into_iter();
460
    if let Some(mut prev) = iter.next() {
74432
        for curr in iter {
73972
            if prev.target == curr.target
70763
                && prev.event_type == curr.event_type
70167
                && seat_of(&prev) == seat_of(&curr)
            {
                // Keep the one with later timestamp
70154
                prev = if curr.timestamp > prev.timestamp {
70037
                    curr
                } else {
117
                    prev
                };
3818
            } else {
3818
                result.push(prev);
3818
                prev = curr;
3818
            }
        }
460
        result.push(prev);
    }
460
    result
1928
}
/// Every `HoverEventFilter` variant, so planning can be derived from matching.
static ALL_HOVER: &[HoverEventFilter] = &[
    HoverEventFilter::MouseOver,
    HoverEventFilter::MouseMove,
    HoverEventFilter::MouseDown,
    HoverEventFilter::LeftMouseDown,
    HoverEventFilter::RightMouseDown,
    HoverEventFilter::MiddleMouseDown,
    HoverEventFilter::Click,
    HoverEventFilter::MouseUp,
    HoverEventFilter::LeftMouseUp,
    HoverEventFilter::RightMouseUp,
    HoverEventFilter::MiddleMouseUp,
    HoverEventFilter::MouseEnter,
    HoverEventFilter::MouseLeave,
    HoverEventFilter::Scroll,
    HoverEventFilter::ScrollStart,
    HoverEventFilter::ScrollEnd,
    HoverEventFilter::TextInput,
    HoverEventFilter::VirtualKeyDown,
    HoverEventFilter::VirtualKeyUp,
    HoverEventFilter::HoveredFile,
    HoverEventFilter::DroppedFile,
    HoverEventFilter::HoveredFileCancelled,
    HoverEventFilter::TouchStart,
    HoverEventFilter::TouchMove,
    HoverEventFilter::TouchEnd,
    HoverEventFilter::TouchCancel,
    HoverEventFilter::PenDown,
    HoverEventFilter::PenMove,
    HoverEventFilter::PenUp,
    HoverEventFilter::PenEnter,
    HoverEventFilter::PenLeave,
    HoverEventFilter::PenSqueeze,
    HoverEventFilter::PenDoubleTap,
    HoverEventFilter::PenHover,
    HoverEventFilter::GeolocationFix,
    HoverEventFilter::GeolocationError,
    HoverEventFilter::SensorChanged,
    HoverEventFilter::GamepadInput,
    HoverEventFilter::DragStart,
    HoverEventFilter::Drag,
    HoverEventFilter::DragEnd,
    HoverEventFilter::DragEnter,
    HoverEventFilter::DragOver,
    HoverEventFilter::DragLeave,
    HoverEventFilter::Drop,
    HoverEventFilter::DoubleClick,
    HoverEventFilter::LongPress,
    HoverEventFilter::SwipeLeft,
    HoverEventFilter::SwipeRight,
    HoverEventFilter::SwipeUp,
    HoverEventFilter::SwipeDown,
    HoverEventFilter::PinchIn,
    HoverEventFilter::PinchOut,
    HoverEventFilter::RotateClockwise,
    HoverEventFilter::RotateCounterClockwise,
    HoverEventFilter::MouseOut,
    HoverEventFilter::FocusIn,
    HoverEventFilter::FocusOut,
    HoverEventFilter::CompositionStart,
    HoverEventFilter::CompositionUpdate,
    HoverEventFilter::CompositionEnd,
    HoverEventFilter::SystemTextSingleClick,
    HoverEventFilter::SystemTextDoubleClick,
    HoverEventFilter::SystemTextTripleClick,
    HoverEventFilter::PermissionChanged,
    HoverEventFilter::BiometricResult,
    HoverEventFilter::ScreenColorPicked,
    HoverEventFilter::KeyringResult,
    // Form events. These have matcher arms and planning arms, but were absent
    // from THIS list — and planning is DERIVED by probing it, so a filter the
    // list does not name can never be planned and dispatches to nothing. Same
    // dead-filter shape the arc exists to close, reintroduced by the arc.
    HoverEventFilter::Submit,
    HoverEventFilter::Change,
    HoverEventFilter::Reset,
    HoverEventFilter::Invalid,
    // Planning is DERIVED by probing this list, so a filter missing from it
    // can never be planned — the failure this arc has hit repeatedly.
    HoverEventFilter::DialRotate,
    HoverEventFilter::DialClick,
];
/// Every `FocusEventFilter` variant, so planning can be derived from matching.
static ALL_FOCUS: &[FocusEventFilter] = &[
    FocusEventFilter::MouseOver,
    FocusEventFilter::MouseMove,
    FocusEventFilter::MouseDown,
    FocusEventFilter::LeftMouseDown,
    FocusEventFilter::RightMouseDown,
    FocusEventFilter::MiddleMouseDown,
    FocusEventFilter::MouseUp,
    FocusEventFilter::LeftMouseUp,
    FocusEventFilter::RightMouseUp,
    FocusEventFilter::MiddleMouseUp,
    FocusEventFilter::MouseEnter,
    FocusEventFilter::MouseLeave,
    FocusEventFilter::Scroll,
    FocusEventFilter::ScrollStart,
    FocusEventFilter::ScrollEnd,
    FocusEventFilter::TextInput,
    FocusEventFilter::VirtualKeyDown,
    FocusEventFilter::VirtualKeyUp,
    FocusEventFilter::FocusReceived,
    FocusEventFilter::FocusLost,
    FocusEventFilter::PenDown,
    FocusEventFilter::PenMove,
    FocusEventFilter::PenUp,
    FocusEventFilter::DragStart,
    FocusEventFilter::Drag,
    FocusEventFilter::DragEnd,
    FocusEventFilter::DragEnter,
    FocusEventFilter::DragOver,
    FocusEventFilter::DragLeave,
    FocusEventFilter::Drop,
    FocusEventFilter::DoubleClick,
    FocusEventFilter::LongPress,
    FocusEventFilter::SwipeLeft,
    FocusEventFilter::SwipeRight,
    FocusEventFilter::SwipeUp,
    FocusEventFilter::SwipeDown,
    FocusEventFilter::PinchIn,
    FocusEventFilter::PinchOut,
    FocusEventFilter::RotateClockwise,
    FocusEventFilter::RotateCounterClockwise,
    FocusEventFilter::FocusIn,
    FocusEventFilter::FocusOut,
    FocusEventFilter::CompositionStart,
    FocusEventFilter::CompositionUpdate,
    FocusEventFilter::CompositionEnd,
    FocusEventFilter::Copy,
    FocusEventFilter::Cut,
    FocusEventFilter::Paste,
    FocusEventFilter::DocumentEdit,
    FocusEventFilter::TextChanged,
    // Form events. These have matcher arms and planning arms, but were absent
    // from THIS list — and planning is DERIVED by probing it, so a filter the
    // list does not name can never be planned and dispatches to nothing. Same
    // dead-filter shape the arc exists to close, reintroduced by the arc.
    FocusEventFilter::Submit,
    FocusEventFilter::Change,
    FocusEventFilter::Reset,
    FocusEventFilter::Invalid,
];
/// Every `WindowEventFilter` variant, so planning can be derived from matching.
static ALL_WINDOW: &[WindowEventFilter] = &[
    WindowEventFilter::MouseOver,
    WindowEventFilter::MouseMove,
    WindowEventFilter::MouseDown,
    WindowEventFilter::LeftMouseDown,
    WindowEventFilter::RightMouseDown,
    WindowEventFilter::MiddleMouseDown,
    WindowEventFilter::MouseUp,
    WindowEventFilter::LeftMouseUp,
    WindowEventFilter::RightMouseUp,
    WindowEventFilter::MiddleMouseUp,
    WindowEventFilter::MouseEnter,
    WindowEventFilter::MouseLeave,
    WindowEventFilter::Scroll,
    WindowEventFilter::ScrollStart,
    WindowEventFilter::ScrollEnd,
    WindowEventFilter::TextInput,
    WindowEventFilter::VirtualKeyDown,
    WindowEventFilter::VirtualKeyUp,
    WindowEventFilter::HoveredFile,
    WindowEventFilter::DroppedFile,
    WindowEventFilter::HoveredFileCancelled,
    WindowEventFilter::Resized,
    WindowEventFilter::Moved,
    WindowEventFilter::FrameChanged,
    WindowEventFilter::TouchStart,
    WindowEventFilter::TouchMove,
    WindowEventFilter::TouchEnd,
    WindowEventFilter::TouchCancel,
    WindowEventFilter::FocusReceived,
    WindowEventFilter::FocusLost,
    WindowEventFilter::CloseRequested,
    WindowEventFilter::ThemeChanged,
    WindowEventFilter::WindowFocusReceived,
    WindowEventFilter::WindowFocusLost,
    WindowEventFilter::PointerLockChange,
    WindowEventFilter::PenDown,
    WindowEventFilter::PenMove,
    WindowEventFilter::PenUp,
    WindowEventFilter::PenEnter,
    WindowEventFilter::PenLeave,
    WindowEventFilter::PenSqueeze,
    WindowEventFilter::PenDoubleTap,
    WindowEventFilter::PenHover,
    WindowEventFilter::GeolocationFix,
    WindowEventFilter::GeolocationError,
    WindowEventFilter::SensorChanged,
    WindowEventFilter::GamepadInput,
    WindowEventFilter::DragStart,
    WindowEventFilter::Drag,
    WindowEventFilter::DragEnd,
    WindowEventFilter::DragEnter,
    WindowEventFilter::DragOver,
    WindowEventFilter::DragLeave,
    WindowEventFilter::Drop,
    WindowEventFilter::DoubleClick,
    WindowEventFilter::LongPress,
    WindowEventFilter::SwipeLeft,
    WindowEventFilter::SwipeRight,
    WindowEventFilter::SwipeUp,
    WindowEventFilter::SwipeDown,
    WindowEventFilter::PinchIn,
    WindowEventFilter::PinchOut,
    WindowEventFilter::RotateClockwise,
    WindowEventFilter::RotateCounterClockwise,
    WindowEventFilter::DpiChanged,
    WindowEventFilter::MonitorChanged,
    WindowEventFilter::PermissionChanged,
    WindowEventFilter::BiometricResult,
    WindowEventFilter::ScreenColorPicked,
    WindowEventFilter::KeyringResult,
    WindowEventFilter::DialRotate,
    WindowEventFilter::DialClick,
    // Media (11c). Planning is DERIVED by probing this list, so a filter the
    // list does not name can never be planned, whatever its matcher says.
    WindowEventFilter::Play,
    WindowEventFilter::Pause,
    WindowEventFilter::Ended,
    WindowEventFilter::TimeUpdate,
    WindowEventFilter::VolumeChange,
    WindowEventFilter::MediaError,
];
/// Every `ComponentEventFilter` variant, so planning can be derived from
/// matching. This is the family the derivation FORGOT when it replaced the
/// hand-written table: with no component probe, `Mount` planned zero filters
/// and every `AfterMount` / `Updated` / `NodeResized` / `Dismissed` /
/// `TornOff` / `Docked` callback in the engine went silent — the reconcile
/// diff kept emitting the events, the dispatcher's `Component` arm simply
/// never saw one (`headless_lifecycle` caught it: mount=0 on the first frame).
/// `DefaultAction` and `Selected` have no event type, so probing them is a
/// no-op today; they are listed so the table stays the whole enum.
static ALL_COMPONENT: &[ComponentEventFilter] = &[
    ComponentEventFilter::AfterMount,
    ComponentEventFilter::BeforeUnmount,
    ComponentEventFilter::NodeResized,
    ComponentEventFilter::DefaultAction,
    ComponentEventFilter::Selected,
    ComponentEventFilter::Updated,
    ComponentEventFilter::Dismissed,
    ComponentEventFilter::TornOff,
    ComponentEventFilter::Docked,
];
/// Every `ExternalEventFilter`, for planning to probe. See [`ALL_COMPONENT`].
static ALL_EXTERNAL: &[ExternalEventFilter] = &[
    ExternalEventFilter::Play,
    ExternalEventFilter::Pause,
    ExternalEventFilter::Ended,
    ExternalEventFilter::TimeUpdate,
    ExternalEventFilter::VolumeChange,
    ExternalEventFilter::MediaError,
];
/// Every `ApplicationEventFilter`, for planning to probe. See [`ALL_COMPONENT`].
static ALL_APPLICATION: &[ApplicationEventFilter] = &[
    ApplicationEventFilter::DeviceConnected,
    ApplicationEventFilter::DeviceDisconnected,
    ApplicationEventFilter::MonitorConnected,
    ApplicationEventFilter::MonitorDisconnected,
    ApplicationEventFilter::MediaControl,
    ApplicationEventFilter::SystemAudioChange,
];
/// Which listeners an event should reach.
///
/// DERIVED from `matches_filter_phase`, the phase-matching table, so the two
/// can no longer disagree. They used to be two hand-written tables that had
/// to be kept in step by discipline, and an exhaustive cross-product found 61
/// pairs where they had drifted - in BOTH directions. A filter the matcher
/// accepts but planning never emitted produced a listener that could never
/// fire (pen enter/leave, scroll start/end, every focus-scoped drag event);
/// a filter planned but not matched collected a callback and dropped it. The
/// visible symptoms were Enter/Space activating nothing and, briefly, a
/// pointer click activating a control TWICE.
///
/// Dispatch sites use this to decide which callbacks to COLLECT and then ask
/// the matcher again per callback, so "collected" and "fired" now answer to
/// one table.
///
/// The universe is the four `ALL_*` tables - Hover, Focus, Window,
/// Component - and it has to be ALL of them: a family missing from the probe
/// is a whole
/// class of listeners that can never fire, and nothing else in the pipeline
/// notices (the events are still produced, the callbacks still registered).
/// That is how every lifecycle callback went dead when the derivation first
/// shipped without `ALL_COMPONENT`; the cross-product test
/// `planning_and_matching_agree_for_every_event_and_filter` now covers all
/// four families so that the next omission fails there.
///
/// Cost: one pass over the filter universe per EVENT (not per node, not per
/// callback) - a few hundred `match` arms, nanoseconds, and it happens once
/// where the old table was also built once.
#[must_use]
596
pub fn event_type_to_filters(event_type: EventType, event_data: &EventData) -> Vec<EventFilter> {
    // Built through the public constructor so a new field on `SyntheticEvent`
    // cannot silently change what planning probes with.
596
    let probe = SyntheticEvent::new(
596
        event_type,
596
        EventSource::User,
596
        DomNodeId {
596
            dom: DomId::ROOT_ID,
596
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(0))),
596
        },
596
        Instant::Tick(crate::task::SystemTick::new(0)),
596
        event_data.clone(),
    );
596
    let mut out = Vec::new();
44700
    for f in ALL_HOVER {
44104
        if matches_filter_phase(EventFilter::Hover(*f), &probe, EventPhase::Bubble) {
476
            out.push(EventFilter::Hover(*f));
43628
        }
    }
32780
    for f in ALL_FOCUS {
32184
        if matches_filter_phase(EventFilter::Focus(*f), &probe, EventPhase::Bubble) {
397
            out.push(EventFilter::Focus(*f));
31787
        }
    }
47084
    for f in ALL_WINDOW {
46488
        if matches_filter_phase(EventFilter::Window(*f), &probe, EventPhase::Bubble) {
525
            out.push(EventFilter::Window(*f));
45963
        }
    }
    // Component and Application were simply not probed here. Their matcher
    // arms (`matches_component_filter` / `matches_application_filter`) were
    // correct — but planning never asked them anything, so NO lifecycle or
    // application event could ever be planned, and every
    // `EventFilter::Component(..)` callback in every app was dead.
5960
    for f in ALL_COMPONENT {
5364
        if matches_filter_phase(EventFilter::Component(*f), &probe, EventPhase::Bubble) {
32
            out.push(EventFilter::Component(*f));
5332
        }
    }
4172
    for f in ALL_APPLICATION {
3576
        if matches_filter_phase(EventFilter::Application(*f), &probe, EventPhase::Bubble) {
14
            out.push(EventFilter::Application(*f));
3562
        }
    }
4172
    for f in ALL_EXTERNAL {
3576
        if matches_filter_phase(EventFilter::External(*f), &probe, EventPhase::Bubble) {
30
            out.push(EventFilter::External(*f));
3546
        }
    }
596
    out
596
}
// Internal System Event Processing
/// Framework-determined side effects (system changes).
///
/// Unlike `CallbackChange` (from user callbacks), these are determined by the
/// framework's event analysis: hit tests, gesture detection, focus rules,
/// text selection, keyboard shortcuts, etc.
///
/// Both `CallbackChange` (user) and `SystemChange` (framework) are processed
/// through exhaustive match on `PlatformWindowV2` — adding a new variant
/// causes a compile error in `apply_system_change()`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[must_use = "SystemChange must be processed through apply_system_change()"]
pub enum SystemChange {
    /// Advance layout animations by an EXACT step, bypassing the wall clock.
    ///
    /// Only the E2E surface emits this. A headless scenario cannot sample real
    /// time: the same test would land on a different point of the curve on a
    /// fast machine than a slow one, so any assertion mid-flight would be
    /// flaky. Stepping by a fixed `dt` makes the trajectory a pure function of
    /// how many times this ran.
    ///
    /// A `SystemChange` rather than a direct call because `CallbackInfo` hands
    /// out `&LayoutWindow` only — mutation is required to go through this
    /// channel, which is also where the mutable window actually exists.
    // === Text Selection ===
    /// Process a mouse click for text selection (single/double/triple click).
    TextSelectionClick {
        position: LogicalPosition,
        timestamp: Instant,
    },
    /// Extend text selection via mouse drag.
    TextSelectionDrag {
        start_position: LogicalPosition,
        current_position: LogicalPosition,
    },
    /// Unified selection operation: cursor movement, selection extension, or deletion.
    ///
    /// Replaces the old `ArrowKeyNavigation` and `DeleteTextSelection` variants.
    /// Every keyboard shortcut maps to a single `SelectionOp` — see its docs.
    ApplySelectionOp {
        target: DomNodeId,
        op: SelectionOp,
        /// The SEAT whose key this was (9b-ii-a-i-d-ii-b): the op acts on that
        /// seat's caret. Seat 0 is the primary.
        seat_id: u64,
    },
    // === Keyboard Shortcuts ===
    /// Copy selected text to system clipboard (Ctrl+C / Cmd+C).
    CopyToClipboard,
    /// Cut selected text to clipboard and delete (Ctrl+X / Cmd+X).
    CutToClipboard { target: DomNodeId },
    /// Paste text from system clipboard at cursor (Ctrl+V / Cmd+V).
    PasteFromClipboard,
    /// Select all text in focused node (Ctrl+A / Cmd+A).
    SelectAllText,
    /// Undo last text edit (Ctrl+Z / Cmd+Z).
    UndoTextEdit { target: DomNodeId },
    /// Redo last undone edit (Ctrl+Y / Ctrl+Shift+Z / Cmd+Shift+Z).
    RedoTextEdit { target: DomNodeId },
    // === Multi-Cursor ===
    /// Add a cursor at the clicked position (Ctrl+Click).
    /// The position will be hit-tested to find the text cursor location.
    AddCursorAtClick { position: LogicalPosition },
    /// Select the next occurrence of the current selection's text (Ctrl+D).
    /// If the primary selection is a cursor, expand it to the word first.
    SelectNextOccurrence { target: DomNodeId },
    /// A NON-primary seat's editing shortcut (9b-ii-a-i-d-ii-b-i): Copy /
    /// Cut / Paste / Select-all / Undo / Redo on THAT seat's focus and caret.
    /// The primary's shortcuts stay the dedicated variants above.
    SeatShortcut {
        seat_id: u64,
        target: DomNodeId,
        shortcut: KeyboardShortcut,
    },
    // === Text Input ===
    /// Apply pending text input from platform (keyboard/IME).
    ApplyPendingTextInput,
    /// Apply text changeset (incremental relayout).
    ApplyTextChangeset,
    // === Drag & Drop ===
    /// Activate node drag on a draggable element.
    ActivateNodeDrag { dom_id: DomId, node_id: NodeId },
    /// Activate window drag (CSD titlebar).
    ActivateWindowDrag,
    /// Set up drag visual state (:dragging pseudo-state, GPU transform key).
    InitDragVisualState,
    /// Set :drag-over pseudo-state on a target node.
    SetDragOverState { target: DomNodeId, active: bool },
    /// Update current drop target in drag context.
    UpdateDropTarget { target: DomNodeId },
    /// Update GPU transform for active node drag.
    UpdateDragGpuTransform,
    /// End drag: clear pseudo-states, remove GPU keys, end drag session.
    DeactivateDrag,
    // === Focus ===
    /// Move a NON-primary seat's focus (9b-ii-a-i-d): only that seat's
    /// entry changes - no `:focus` restyle, no caret / blink timer, no soft
    /// keyboard, which all follow the primary's focus (the text-edit session
    /// is one). A primary-seat change is `SetFocus`.
    SetSeatFocus {
        seat_id: u64,
        new_focus: Option<DomNodeId>,
        old_focus: Option<DomNodeId>,
    },
    /// Change focus to a new target (or clear focus if None).
    /// Handles: `set_focused_node`, `apply_focus_restyle`, `scroll_node_into_view`,
    /// `cursor_blink_timer` start/stop.
    SetFocus {
        new_focus: Option<DomNodeId>,
        old_focus: Option<DomNodeId>,
        /// Should this focus be INDICATED - the W3C `:focus-visible` question.
        ///
        /// It travels WITH the change because the handler restyles and
        /// regenerates the display list, and the focus ring is emitted by that
        /// regeneration. Setting the flag afterwards (which the shell used to
        /// do for the keyboard route) means the frame that was just built did
        /// not know focus was indicated, so the ring only appeared on whatever
        /// repaint happened NEXT - a click, a resize. On the device that read
        /// as "Tab does not ring anything until you click something", while the
        /// E2E harness - which happened to set the flag first - showed a ring
        /// and passed (device report, 2026-09-01).
        visible: bool,
    },
    /// Clear all text selections.
    ClearAllSelections,
    /// Finalize pending focus changes (cursor initialization after layout).
    FinalizePendingFocusChanges,
    // === Scroll ===
    /// Scroll cursor/selection into view.
    ScrollSelectionIntoView,
    /// Scroll a specific node into view.
    ScrollNodeIntoView { target: DomNodeId },
    /// Scroll cursor into view after text input (needs relayout first).
    ScrollCursorIntoViewAfterTextInput,
    // === Auto-Scroll Timer ===
    /// Start auto-scroll timer for drag-to-scroll (60Hz).
    StartAutoScrollTimer,
    /// Cancel auto-scroll timer.
    StopAutoScrollTimer,
}
impl_option!(
    SystemChange,
    OptionSystemChange,
    copy = false,
    clone = false,
    [Debug, Clone, PartialEq, Eq]
);
impl_vec!(
    SystemChange,
    SystemChangeVec,
    SystemChangeVecDestructor,
    SystemChangeVecDestructorType,
    SystemChangeVecSlice,
    OptionSystemChange
);
impl_vec_debug!(SystemChange, SystemChangeVec);
impl_vec_clone!(SystemChange, SystemChangeVec, SystemChangeVecDestructor);
impl_vec_partialeq!(SystemChange, SystemChangeVec);
/// Result of pre-callback internal event filtering
#[derive(Debug, Clone, PartialEq)]
pub struct PreCallbackFilterResult {
    /// System changes to process BEFORE user callbacks
    pub system_changes: Vec<SystemChange>,
    /// Regular events that will be passed to user callbacks
    pub user_events: Vec<SyntheticEvent>,
}
/// Flattened focus/selection state for the input interpreter (replaces trait objects).
#[derive(Debug, Clone, Copy)]
pub struct InputInterpreterState {
    pub focused_node: Option<DomNodeId>,
    pub click_count: u8,
    pub drag_start_position: Option<LogicalPosition>,
    pub has_selection: bool,
    /// Whether focus sits in a TEXT-EDITING context (a contenteditable host,
    /// a text input) - the only place arrow keys mean "move the caret".
    ///
    /// Without this the interpreter claimed every arrow key for a caret op
    /// and returned `AddAndSkip`, which SWALLOWS the event: it never reached
    /// user callbacks at all. A focused Slider or colour picker therefore
    /// could not implement arrow keys - the handler was never called (device
    /// report, 2026-09-01: "the arrow keys for sliders do not work at all,
    /// nor the four arrow keys for navigating the color gradient").
    pub focus_is_editable: bool,
}
/// All context needed by the input interpreter to map events to system changes.
///
/// Passed to the interpreter callback. Contains references to the current
/// events and window state. The interpreter reads this and returns system changes.
#[derive(Debug)]
pub struct InputInterpreterInfo<'a> {
    pub events: &'a [SyntheticEvent],
    pub hit_test: Option<&'a FullHitTest>,
    pub keyboard_state: &'a crate::window::KeyboardState,
    pub mouse_state: &'a crate::window::MouseState,
    pub state: InputInterpreterState,
    /// The focused node of each NON-primary keyboard seat present in
    /// `events` (9b-ii-a-i-d), from `seat_focus_of_events`; a seat missing
    /// here resolves to the primary's `state.focused_node`.
    pub seat_focus: &'a [(u64, Option<DomNodeId>)],
}
/// The `extern "C"` callback type for the input interpreter.
///
/// The first `RefAny` is the user data (vim mode, repeat counter, etc.)
/// held in `InputInterpreterCallback.ctx`. The `*const ()` is an opaque
/// pointer to `InputInterpreterInfo` — callers use the safe wrapper
/// methods to access event data. Returns a `PreCallbackFilterResult`.
///
/// For C/Python: the trampoline extracts the foreign callable from `RefAny.ctx`.
/// For Rust: use `InputInterpreterCallback::from(fn_ptr)` which sets ctx=None.
pub type InputInterpreterCallbackType = extern "C" fn(
    crate::refany::RefAny,
    *const InputInterpreterInfo<'static>, // Opaque; actual lifetime managed by caller
) -> PreCallbackFilterResult;
/// Configurable input interpreter callback.
///
/// Maps raw platform events + window state → semantic `SystemChange` actions.
/// The default (`default_input_interpreter`) handles standard desktop keybindings.
/// Replace this on `LayoutWindow` to implement vim, game controls, etc.
///
/// ## Pattern
/// - **Rust**: `InputInterpreterCallback::from(my_fn_ptr)` — `ctx` is None
/// - **Python/C**: Set `cb` to a trampoline, `ctx` to `RefAny` wrapping the foreign callable
#[repr(C)]
pub struct InputInterpreterCallback {
    pub cb: InputInterpreterCallbackType,
    pub ctx: crate::refany::OptionRefAny,
}
impl_callback!(InputInterpreterCallback, InputInterpreterCallbackType);
impl Default for InputInterpreterCallback {
29051
    fn default() -> Self {
29051
        Self {
29051
            cb: default_input_interpreter_extern,
29051
            ctx: crate::refany::OptionRefAny::None,
29051
        }
29051
    }
}
/// The `extern "C"` callback type for the post-callback filter.
pub type PostFilterCallbackType = extern "C" fn(
    crate::refany::RefAny,
    bool,                 // prevent_default
    SystemChangeVecSlice, // pre_changes (immutable slice)
    DomNodeId,            // old_focus (0xFFFF = None)
    DomNodeId,            // new_focus (0xFFFF = None)
) -> SystemChangeVec;
/// Configurable post-callback filter.
#[repr(C)]
pub struct PostFilterCallback {
    pub cb: PostFilterCallbackType,
    pub ctx: crate::refany::OptionRefAny,
}
impl_callback!(PostFilterCallback, PostFilterCallbackType);
impl Default for PostFilterCallback {
29051
    fn default() -> Self {
29051
        Self {
29051
            cb: default_post_filter_extern,
29051
            ctx: crate::refany::OptionRefAny::None,
29051
        }
29051
    }
}
/// What JSON type an op argument expects.
///
/// Spelled out rather than left to prose, because this is read by machines:
/// an agent choosing arguments and a UI validating a macro form both need the
/// type, not a sentence describing it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde-json", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde-json", serde(rename_all = "lowercase"))]
pub enum E2eOpArgType {
    String,
    Number,
    Bool,
    Object,
    Array,
    /// Any JSON value is acceptable.
    #[default]
    Any,
}
/// One argument of one op.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde-json", derive(serde::Serialize, serde::Deserialize))]
pub struct E2eOpArg {
    pub name: String,
    #[cfg_attr(feature = "serde-json", serde(rename = "type"))]
    pub arg_type: E2eOpArgType,
    pub required: bool,
    pub description: String,
}
/// A worked example: what to send, and what comes back.
///
/// Both halves matter. The arguments alone tell a caller how to invoke the op;
/// the RETURN tells it what it can then assert on, which is what a scenario
/// author and an agent each need before committing to a call.
#[derive(Debug, Clone, PartialEq, Default)]
#[cfg_attr(feature = "serde-json", derive(serde::Serialize, serde::Deserialize))]
pub struct E2eOpExample {
    pub description: String,
    /// Example arguments — a real JSON value, not a string containing JSON.
    ///
    /// These were `String` first, which serialized as escaped JSON inside
    /// JSON: every consumer parsed twice and nothing checked the inner text
    /// was even well-formed, so a malformed example sat in the schema looking
    /// fine.
    pub args: crate::json::Json,
    /// What the op returns for those arguments.
    ///
    /// MUST contain a `success` boolean — validated when the schema is
    /// installed, see `E2eOpSchema::validate`.
    pub returns: crate::json::Json,
}
/// One op the application answers.
#[derive(Debug, Clone, PartialEq, Default)]
#[cfg_attr(feature = "serde-json", derive(serde::Serialize, serde::Deserialize))]
pub struct E2eOpDef {
    pub name: String,
    /// One line, for a list or a picker.
    pub summary: String,
    /// The long form, for a tooltip or an agent's context.
    pub description: String,
    pub args: Vec<E2eOpArg>,
    pub examples: Vec<E2eOpExample>,
}
/// Everything an application advertises about its ops.
///
/// Built in memory as a normal Rust struct and serialized to `Json` at the
/// boundary — on BOTH sides, framework and application. The `Json` hop is a
/// deliberate interim bridge so the shape can be iterated on without an ABI
/// break each time; these types get exposed through api.json later and the
/// bridge goes away.
#[derive(Debug, Clone, PartialEq, Default)]
#[cfg_attr(feature = "serde-json", derive(serde::Serialize, serde::Deserialize))]
pub struct E2eOpSchema {
    pub ops: Vec<E2eOpDef>,
}
/// Does this value have a top-level `success` boolean?
///
/// Deliberately requires a BOOLEAN, not merely the key: `"success": "yes"` and
/// `"success": null` are the shapes a hand-written schema actually produces,
/// and each would otherwise pass while telling a consumer nothing.
// Only the `not(serde-json)` arm is const-eligible (it is a literal `true`);
// the serde arm calls `to_serde_value`, which allocates. Marking the fn `const`
// would therefore stop compiling in the configuration that actually parses.
#[allow(clippy::missing_const_for_fn)]
4
fn json_has_success_bool(v: &crate::json::Json) -> bool {
    #[cfg(feature = "serde-json")]
    {
4
        v.to_serde_value()
4
            .get("success")
4
            .is_some_and(serde_json::Value::is_boolean)
    }
    #[cfg(not(feature = "serde-json"))]
    {
        // Without serde there is no parser here. Returning TRUE would silently
        // pass every schema; the honest fallback is a textual check that can
        // only reject things that are definitely wrong.
        let _ = v;
        true
    }
4
}
/// Why an advertised schema is unusable.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum E2eSchemaError {
    /// An op has no name.
    UnnamedOp { index: usize },
    /// Two ops share a name, so dispatch by name is ambiguous.
    DuplicateOpName { name: String },
    /// An argument has no name, or no usable type.
    UnnamedArg { op: String, index: usize },
    /// An example's `returns` has no `success` boolean.
    ///
    /// The contract is that every op result says whether it worked. An
    /// example that omits it is advertising a result shape the runtime is
    /// required to reject.
    ExampleMissingSuccess { op: String, index: usize },
}
impl core::fmt::Display for E2eSchemaError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::UnnamedOp { index } => write!(f, "op #{index} has an empty name"),
            Self::DuplicateOpName { name } => {
                write!(
                    f,
                    "two ops are both named '{name}'; dispatch would be ambiguous"
                )
            }
            Self::UnnamedArg { op, index } => {
                write!(f, "op '{op}' argument #{index} has an empty name")
            }
            Self::ExampleMissingSuccess { op, index } => write!(
                f,
                "op '{op}' example #{index}: `returns` has no `success` boolean. Every op result \
                 must say whether it worked, or a failure is indistinguishable from a success"
            ),
        }
    }
}
impl E2eOpSchema {
    /// Check the schema is usable, BEFORE anything reads or dispatches it.
    ///
    /// Called when the schema is installed, not on first invocation. The whole
    /// point of advertising a schema is that a plugin, an MCP server or an
    /// agent reads it before calling anything — a schema that only proves
    /// malformed when an op is finally invoked has failed at its one job. An
    /// app shipping an unusable advertisement is a bug in the app, and its own
    /// startup is the cheapest place to catch it.
    ///
    /// # Errors
    ///
    /// Returns [`E2eSchemaError`] if the schema is malformed: a duplicate or
    /// empty op name, or an argument whose declared type is not a valid JSON
    /// type name.
4
    pub fn validate(&self) -> Result<(), E2eSchemaError> {
4
        let mut seen: Vec<&str> = Vec::new();
5
        for (i, op) in self.ops.iter().enumerate() {
5
            if op.name.trim().is_empty() {
                return Err(E2eSchemaError::UnnamedOp { index: i });
5
            }
5
            if seen.contains(&op.name.as_str()) {
1
                return Err(E2eSchemaError::DuplicateOpName {
1
                    name: op.name.clone(),
1
                });
4
            }
4
            seen.push(op.name.as_str());
4
            for (a, arg) in op.args.iter().enumerate() {
4
                if arg.name.trim().is_empty() {
                    return Err(E2eSchemaError::UnnamedArg {
                        op: op.name.clone(),
                        index: a,
                    });
4
                }
            }
4
            for (e, ex) in op.examples.iter().enumerate() {
4
                if !json_has_success_bool(&ex.returns) {
2
                    return Err(E2eSchemaError::ExampleMissingSuccess {
2
                        op: op.name.clone(),
2
                        index: e,
2
                    });
2
                }
            }
        }
1
        Ok(())
4
    }
    /// Serialize to the `Json` that crosses the C ABI.
    #[must_use]
31720
    pub fn to_json(&self) -> crate::json::Json {
        #[cfg(feature = "serde-json")]
        {
            // Falling back to an empty-op object rather than to null: a
            // consumer must never be handed something that reads as "not
            // parseable" when the truth is "serialization failed".
            // serde_json preserves declaration order; `Json::parse` does NOT
            // (it re-serializes sorted, which buried `name` and `summary`
            // under `args`/`description`/`examples`). Keep the serialized text
            // and wrap it, rather than round-tripping through the parser.
76
            serde_json::to_string(self).ok().map_or_else(
                || crate::json::Json {
                    value_type: crate::json::JsonType::Object,
                    internal: crate::json::JsonInternal {
                        string_value: AzString::from_const_str(r#"{"ops":[]}"#),
                        ..Default::default()
                    },
                },
                |text| crate::json::Json {
76
                    value_type: crate::json::JsonType::Object,
76
                    internal: crate::json::JsonInternal {
76
                        string_value: AzString::from(text),
76
                        ..Default::default()
76
                    },
76
                },
            )
        }
        #[cfg(not(feature = "serde-json"))]
31644
        crate::json::Json {
31644
            value_type: crate::json::JsonType::Object,
31644
            internal: crate::json::JsonInternal {
31644
                string_value: AzString::from_const_str(r#"{"ops":[]}"#),
31644
                ..Default::default()
31644
            },
31644
        }
31720
    }
}
/// Outcome of a user-defined E2E op.
#[repr(C)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CustomE2eOpResult {
    /// Whether the application RECOGNISED this op name.
    ///
    /// This is not "did it succeed" — it is "was this op mine at all". The
    /// debug server turns `false` into an explicit unknown-op error rather
    /// than an OK. Without it, a hook that returns a result for every name
    /// makes a typo'd op in a scenario indistinguishable from one that ran:
    /// non-assert ops produce no output of their own, so a silent success and
    /// a silent miss look identical from the outside.
    pub handled: bool,
    /// Result payload, JSON. Reported back to the scenario as-is, so a
    /// scenario can assert on it. Empty string is a valid empty result.
    pub json: AzString,
}
impl Default for CustomE2eOpResult {
    /// "Not my op": `handled: false` with an empty payload — the value a
    /// bridge (e.g. the generated Python trampoline) returns when no user
    /// handler can run. Mirrors the debug server's unknown-op semantics.
    fn default() -> Self {
        Self {
            handled: false,
            json: AzString::from_const_str(""),
        }
    }
}
/// The `extern "C"` callback type for a user-defined E2E op.
///
/// Receives the op name and its arguments as a JSON string, exactly as they
/// appeared in the scenario, and returns a `CustomE2eOpResult`. This is the
/// hook for driving application-level actions from a scenario — "now load the
/// document" — that the engine has no way to express on the app's behalf.
pub type CustomE2eOpCallbackType = extern "C" fn(
    crate::refany::RefAny, // ctx
    AzString,              // op name
    AzString,              // arguments, JSON
) -> CustomE2eOpResult;
/// Application-provided handler for E2E ops the engine does not implement.
#[repr(C)]
pub struct CustomE2eOpCallback {
    pub cb: CustomE2eOpCallbackType,
    pub ctx: crate::refany::OptionRefAny,
    /// Describes every op `cb` answers: name, summary, description, the JSON
    /// type each argument expects, usage examples, and example returns.
    ///
    /// DATA, not a second callback — discovery is a field read, so it needs
    /// no invocation and no debug HTTP server. That is what lets a plugin
    /// enumerate host capabilities, a locally-spawned MCP server expose the
    /// app to an agent that would otherwise drive it by screenshot, or a
    /// `script.json` be handed straight to the binary.
    ///
    /// The examples and types are not documentation garnish: they are what a
    /// macro picker renders and what an agent reads in place of a screenshot.
    ///
    /// `Json` deliberately, not typed structs — the schema can then follow an
    /// OpenAPI-style operation shape and gain fields without an ABI break.
    /// Typed structs come later.
    pub op_schema: crate::json::Json,
}
// `impl_callback_traits!` only ever reads `self.cb`, so it is correct here.
// The full `impl_callback!` is NOT usable: its generated `Clone` and `From`
// construct `Self { cb, ctx }` literally, and this struct has a third field.
impl_callback_traits!(CustomE2eOpCallback);
impl Clone for CustomE2eOpCallback {
    fn clone(&self) -> Self {
        Self {
            cb: self.cb,
            ctx: self.ctx.clone(),
            op_schema: self.op_schema.clone(),
        }
    }
}
impl From<CustomE2eOpCallbackType> for CustomE2eOpCallback {
    /// Installs a handler that advertises NOTHING.
    ///
    /// A bare fn pointer carries no schema, so this cannot invent one. An app
    /// converting from a fn pointer gets a working handler whose ops are
    /// undiscoverable until it sets `op_schema` — visible in a plugin listing
    /// as an empty op list, which is the honest answer rather than a guess.
    fn from(cb: CustomE2eOpCallbackType) -> Self {
        Self {
            cb,
            ..Self::default()
        }
    }
}
impl Default for CustomE2eOpCallback {
31718
    fn default() -> Self {
31718
        Self {
31718
            cb: default_custom_e2e_op_extern,
31718
            ctx: crate::refany::OptionRefAny::None,
31718
            // An empty LIST, not an empty string or a null. A consumer must
31718
            // be able to tell "this app advertises no ops" from "this app
31718
            // returned nothing parseable"; those mean different things to a
31718
            // plugin deciding whether the host is usable at all.
31718
            // An empty LIST, not an empty string or a null. A consumer must
31718
            // be able to tell "this app advertises no ops" from "this app
31718
            // returned nothing parseable"; those mean different things to a
31718
            // plugin deciding whether the host is usable at all.
31718
            op_schema: E2eOpSchema::default().to_json(),
31718
        }
31718
    }
}
/// Default handler: recognises NOTHING.
///
/// `handled: false` is the load-bearing part. An app that has not installed a
/// handler must make a scenario referencing a custom op FAIL, not pass
/// quietly — the default has to be the safe answer, because it is the one
/// that ships when nobody thought about this.
#[must_use]
1
pub extern "C" fn default_custom_e2e_op_extern(
1
    _ctx: crate::refany::RefAny,
1
    _op: AzString,
1
    _args: AzString,
1
) -> CustomE2eOpResult {
1
    CustomE2eOpResult {
1
        handled: false,
1
        json: AzString::from_const_str(""),
1
    }
1
}
// Keep simpler Rust fn pointer aliases for internal use
pub type InputInterpreterFn = fn(info: &InputInterpreterInfo<'_>) -> PreCallbackFilterResult;
pub type PostFilterFn = fn(
    prevent_default: bool,
    pre_changes: &[SystemChange],
    old_focus: Option<DomNodeId>,
    new_focus: Option<DomNodeId>,
) -> Vec<SystemChange>;
/// Mouse button state for drag tracking
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MouseButtonState {
    pub left_down: bool,
    pub right_down: bool,
    pub middle_down: bool,
}
/// Arrow key / cursor navigation directions
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ArrowDirection {
    Left,
    Right,
    Up,
    Down,
    /// Home key: move to start of current line
    LineStart,
    /// End key: move to end of current line
    LineEnd,
    /// Ctrl+Home: move to start of document
    DocumentStart,
    /// Ctrl+End: move to end of document
    DocumentEnd,
}
impl ArrowDirection {
    /// Map a `VirtualKeyCode` plus the `ctrl` modifier into an `ArrowDirection`.
    /// Returns `None` if the key is not a navigation key.
    #[must_use]
363
    pub const fn from_key(vk: crate::window::VirtualKeyCode, ctrl: bool) -> Option<Self> {
        use crate::window::VirtualKeyCode::{Down, End, Home, Left, Right, Up};
5
        Some(match vk {
6
            Left => Self::Left,
4
            Right => Self::Right,
3
            Up => Self::Up,
5
            Down => Self::Down,
3
            Home if ctrl => Self::DocumentStart,
2
            Home => Self::LineStart,
3
            End if ctrl => Self::DocumentEnd,
2
            End => Self::LineEnd,
335
            _ => return None,
        })
363
    }
    /// Convert to a `(SelectionDirection, SelectionStep)` pair for the
    /// selection-op interpreter. `ctrl` upgrades arrow keys to word jumps.
    #[must_use]
31
    pub const fn to_selection(self, ctrl: bool) -> (SelectionDirection, SelectionStep) {
8
        match self {
3
            Self::Left if ctrl => (SelectionDirection::Backward, SelectionStep::Word),
2
            Self::Right if ctrl => (SelectionDirection::Forward, SelectionStep::Word),
5
            Self::Left => (SelectionDirection::Backward, SelectionStep::Character),
3
            Self::Right => (SelectionDirection::Forward, SelectionStep::Character),
5
            Self::Up => (SelectionDirection::Backward, SelectionStep::VisualLine),
4
            Self::Down => (SelectionDirection::Forward, SelectionStep::VisualLine),
3
            Self::LineStart => (SelectionDirection::Backward, SelectionStep::Line),
1
            Self::LineEnd => (SelectionDirection::Forward, SelectionStep::Line),
1
            Self::DocumentStart => (SelectionDirection::Backward, SelectionStep::Document),
4
            Self::DocumentEnd => (SelectionDirection::Forward, SelectionStep::Document),
        }
31
    }
}
/// Direction of cursor movement or selection expansion.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C)]
pub enum SelectionDirection {
    Forward,
    Backward,
}
/// Granularity of cursor movement or selection expansion.
///
/// Combined with `SelectionDirection`, determines how far a cursor moves
/// or a selection expands. Reused for navigation, deletion, and visual
/// selection — a single code path for word boundaries etc.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C)]
pub enum SelectionStep {
    /// One grapheme cluster (arrow keys, Backspace, Delete)
    Character,
    /// One word boundary (Ctrl+arrow, Ctrl+Backspace, Ctrl+Delete)
    Word,
    /// To line boundary (Home/End)
    Line,
    /// One visual line up/down (Up/Down arrows)
    VisualLine,
    /// To document boundary (Ctrl+Home/End)
    Document,
}
/// What to do with the selection after moving.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C)]
pub enum SelectionMode {
    /// Collapse selection to cursor, then move (plain arrow key).
    Move,
    /// Extend selection from anchor to new position (Shift+arrow).
    Extend,
    /// Expand cursor to range in the given direction, then delete the range
    /// (Backspace/Delete). If a range already exists, just delete it.
    Delete,
}
/// A unified selection operation that replaces all cursor movement,
/// selection extension, and text deletion commands.
///
/// Every keyboard shortcut for cursor movement or deletion maps to this:
/// - Arrow Left = (Backward, Character, Move, 1)
/// - Shift+Right = (Forward, Character, Extend, 1)
/// - Ctrl+Backspace = (Backward, Word, Delete, 1)
/// - Home = (Backward, Line, Move, 1)
/// - Ctrl+End = (Forward, Document, Move, 1)
///
/// The `repeat` field enables vim-style commands: 3w = (Forward, Word, Move, 3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C)]
pub struct SelectionOp {
    pub direction: SelectionDirection,
    pub step: SelectionStep,
    pub mode: SelectionMode,
    pub repeat: usize,
}
impl SelectionOp {
    #[must_use]
118
    pub const fn new(
118
        direction: SelectionDirection,
118
        step: SelectionStep,
118
        mode: SelectionMode,
118
    ) -> Self {
118
        Self {
118
            direction,
118
            step,
118
            mode,
118
            repeat: 1,
118
        }
118
    }
}
/// Keyboard shortcuts for text editing
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum KeyboardShortcut {
    Copy,      // Ctrl+C
    Cut,       // Ctrl+X
    Paste,     // Ctrl+V
    SelectAll, // Ctrl+A
    Undo,      // Ctrl+Z
    Redo,      // Ctrl+Y or Ctrl+Shift+Z
}
impl KeyboardShortcut {
    /// Map a `(VirtualKeyCode, primary, shift)` triple to a text-editing
    /// shortcut. Returns `None` if the key combination is not a recognized
    /// shortcut or if `primary` is not held. `primary` is the platform's
    /// primary modifier — Cmd on macOS, Ctrl elsewhere — obtained from
    /// `KeyboardState::primary_down()` (MWA-A2: hardcoding Ctrl here made
    /// every editing shortcut dead on macOS).
    #[must_use]
351
    pub const fn from_key(
351
        vk: crate::window::VirtualKeyCode,
351
        primary: bool,
351
        shift: bool,
351
    ) -> Option<Self> {
        use crate::window::VirtualKeyCode::{A, C, V, X, Y, Z};
351
        if !primary {
329
            return None;
22
        }
5
        Some(match vk {
6
            C => Self::Copy,
2
            X => Self::Cut,
2
            V => Self::Paste,
2
            A => Self::SelectAll,
3
            Z if shift => Self::Redo,
2
            Z => Self::Undo,
2
            Y => Self::Redo,
3
            _ => return None,
        })
351
    }
}
/// Default input interpreter: standard desktop keybindings.
///
/// This is the default `InputInterpreterFn` that handles arrow keys, Home/End,
/// Backspace/Delete, Ctrl+C/V/A/Z, mouse clicks, and drag selection.
/// Replace it on `LayoutWindow` to implement vim, game controls, etc.
/// `extern "C"` trampoline for `default_input_interpreter`.
#[allow(clippy::not_unsafe_ptr_arg_deref)]
// SAFETY/FFI: `*const T` is the C-ABI signature; the fn null-checks then derefs under the
// documented caller contract (C guarantees a valid ptr/len). Marking it `unsafe fn` would force
// unsafe blocks into the generated dll bindings.
#[must_use]
1
pub extern "C" fn default_input_interpreter_extern(
1
    _user_data: crate::refany::RefAny,
1
    info_ptr: *const InputInterpreterInfo<'static>,
1
) -> PreCallbackFilterResult {
1
    if info_ptr.is_null() {
1
        return PreCallbackFilterResult {
1
            system_changes: Vec::new(),
1
            user_events: Vec::new(),
1
        };
    }
    let info = unsafe { &*info_ptr };
    default_input_interpreter(info)
1
}
/// `extern "C"` trampoline for `default_post_filter`.
#[must_use]
pub extern "C" fn default_post_filter_extern(
    _user_data: crate::refany::RefAny,
    prevent_default: bool,
    pre_changes: SystemChangeVecSlice,
    old_focus: DomNodeId,
    new_focus: DomNodeId,
) -> SystemChangeVec {
    let pre_changes_slice = pre_changes.as_slice();
    let old = old_focus.node.into_crate_internal().map(|_| old_focus);
    let new = new_focus.node.into_crate_internal().map(|_| new_focus);
    default_post_filter(prevent_default, pre_changes_slice, old, new).into()
}
#[must_use]
126
pub fn default_input_interpreter(info: &InputInterpreterInfo<'_>) -> PreCallbackFilterResult {
126
    let ctx = FilterContext {
126
        hit_test: info.hit_test,
126
        keyboard_state: info.keyboard_state,
126
        mouse_state: info.mouse_state,
126
        click_count: info.state.click_count,
126
        focused_node: info.state.focused_node,
126
        drag_start_position: info.state.drag_start_position,
126
        focus_is_editable: info.state.focus_is_editable,
126
        seat_focus: info.seat_focus,
126
    };
126
    let (system_changes, user_events) = info.events.iter().fold(
126
        (Vec::new(), Vec::new()),
245
        |(mut internal, mut user), event| {
245
            match process_event_for_internal(&ctx, event) {
5
                Some(InternalEventAction::AddAndSkip(evt)) => {
5
                    internal.push(evt);
5
                }
45
                Some(InternalEventAction::AddAndPass(evt)) => {
45
                    internal.push(evt);
45
                    user.push(event.clone());
45
                }
195
                None => {
195
                    user.push(event.clone());
195
                }
            }
245
            (internal, user)
245
        },
    );
126
    PreCallbackFilterResult {
126
        system_changes,
126
        user_events,
126
    }
126
}
/// Backward-compatible wrapper that calls `default_input_interpreter`.
7
pub fn pre_callback_filter_internal_events<SM, FM>(
7
    events: &[SyntheticEvent],
7
    hit_test: Option<&FullHitTest>,
7
    keyboard_state: &crate::window::KeyboardState,
7
    mouse_state: &crate::window::MouseState,
7
    selection_manager: &SM,
7
    focus_manager: &FM,
7
    // See `InputInterpreterState::focus_is_editable` - only a text-editing
7
    // focus owns the arrow keys.
7
    focus_is_editable: bool,
7
) -> PreCallbackFilterResult
7
where
7
    SM: SelectionManagerQuery,
7
    FM: FocusManagerQuery,
{
7
    let seat_focus = seat_focus_of_events(events, focus_manager);
7
    let info = InputInterpreterInfo {
7
        events,
7
        hit_test,
7
        keyboard_state,
7
        mouse_state,
7
        seat_focus: &seat_focus,
7
        state: InputInterpreterState {
7
            focused_node: focus_manager.get_focused_node_id(),
7
            click_count: selection_manager.get_click_count(),
7
            drag_start_position: selection_manager.get_drag_start_position(),
7
            has_selection: selection_manager.has_selection(),
7
            focus_is_editable,
7
        },
7
    };
7
    default_input_interpreter(&info)
7
}
/// Context for filtering internal events (used by `default_input_interpreter`)
struct FilterContext<'a> {
    hit_test: Option<&'a FullHitTest>,
    keyboard_state: &'a crate::window::KeyboardState,
    mouse_state: &'a crate::window::MouseState,
    click_count: u8,
    focused_node: Option<DomNodeId>,
    drag_start_position: Option<LogicalPosition>,
    /// See `InputInterpreterState::focus_is_editable`.
    focus_is_editable: bool,
    /// See `InputInterpreterInfo::seat_focus`.
    seat_focus: &'a [(u64, Option<DomNodeId>)],
}
impl FilterContext<'_> {
    /// The focus a key event of seat `seat_id` acts on (9b-ii-a-i-d).
26
    fn focused_node_for(&self, seat_id: u64) -> Option<DomNodeId> {
26
        if seat_id == crate::window::PRIMARY_POINTER_SEAT {
24
            return self.focused_node;
2
        }
2
        self.seat_focus
2
            .iter()
2
            .find(|(seat, _)| *seat == seat_id)
2
            .map_or(self.focused_node, |(_, focus)| *focus)
26
    }
}
/// Process a single event and determine if it generates an internal event
245
fn process_event_for_internal(
245
    ctx: &FilterContext<'_>,
245
    event: &SyntheticEvent,
245
) -> Option<InternalEventAction> {
245
    match event.event_type {
23
        EventType::MouseDown => handle_mouse_down(
23
            event,
23
            ctx.hit_test,
23
            ctx.click_count,
23
            ctx.mouse_state,
23
            ctx.keyboard_state,
        ),
        // Drag-selection needs MOVEMENT while the button is down, so it
        // follows `MouseMove`. Leaving it on `MouseOver` after that event
        // became entry-only would have silently killed drag-to-select: the
        // handler would fire once on entry and never again.
20
        EventType::MouseMove => handle_mouse_move(
20
            event,
20
            ctx.hit_test,
20
            ctx.mouse_state,
20
            ctx.drag_start_position,
        ),
        EventType::KeyDown => {
            // A seat's key acts on THAT seat's focus (9b-ii-a-i-d).
26
            let seat_id = match &event.data {
25
                EventData::Keyboard(k) => k.seat_id,
1
                _ => crate::window::PRIMARY_POINTER_SEAT,
            };
26
            handle_key_down(
26
                event,
26
                ctx.keyboard_state,
26
                ctx.focused_node_for(seat_id),
26
                ctx.focus_is_editable,
            )
        }
21
        EventType::MouseUp => Some(handle_mouse_up()),
155
        _ => None,
    }
245
}
/// Releasing the button ends a text-selection drag, so the autoscroll timer
/// has to go.
///
/// `StopAutoScrollTimer` existed and was handled, but NOTHING emitted it:
/// teardown relied entirely on the 60Hz callback noticing on its next tick
/// that the button had been released and terminating itself. Any path that
/// loses the release — a grab broken by the window manager, a crossing that
/// swallows it — left a timer running at 60Hz for the life of the window.
///
/// It passes to callbacks: a `MouseUp` is a user event, and stopping an
/// internal timer must not swallow it.
22
const fn handle_mouse_up() -> InternalEventAction {
22
    InternalEventAction::AddAndPass(SystemChange::StopAutoScrollTimer)
22
}
/// Action to take after processing an event for internal system events
enum InternalEventAction {
    /// Add system change and skip passing to user callbacks
    AddAndSkip(SystemChange),
    /// Add system change but also pass to user callbacks
    AddAndPass(SystemChange),
}
/// Extract the front-most hovered node from a hit test.
///
/// Picks the node with the minimum `hit_depth` (0 = frontmost/topmost in
/// z-order) across every hovered DOM. The previous implementation took the
/// first entry of the `BTreeMap` (lowest `NodeId`), which ignored z-order
/// entirely and targeted the back-most node under overlapping elements.
/// Ties are broken deterministically by (`DomId`, `NodeId`) iteration order.
39
fn get_first_hovered_node(hit_test: Option<&FullHitTest>) -> Option<DomNodeId> {
39
    let ht = hit_test?;
35
    let mut best: Option<(DomId, NodeId, u32)> = None;
68
    for (dom_id, hit_data) in &ht.hovered_nodes {
118
        for (node_id, item) in &hit_data.regular_hit_test_nodes {
85
            let is_better = match best {
32
                None => true,
53
                Some((_, _, best_depth)) => item.hit_depth < best_depth,
            };
85
            if is_better {
80
                best = Some((*dom_id, *node_id, item.hit_depth));
80
            }
        }
    }
35
    let (dom_id, node_id, _) = best?;
32
    Some(DomNodeId {
32
        dom: dom_id,
32
        node: NodeHierarchyItemId::from_crate_internal(Some(node_id)),
32
    })
39
}
/// Extract mouse position from event data, falling back to `mouse_state` if not available
41
fn get_mouse_position_with_fallback(
41
    event: &SyntheticEvent,
41
    mouse_state: &crate::window::MouseState,
41
) -> LogicalPosition {
41
    match &event.data {
38
        EventData::Mouse(mouse_data) => mouse_data.position,
        _ => {
            // Fallback: use current cursor position from mouse_state
            // This handles synthetic events from debug API and automation
            // where EventData may not contain the mouse position
3
            mouse_state
3
                .cursor_position
3
                .get_position()
3
                .unwrap_or(LogicalPosition::zero())
        }
    }
41
}
/// Handle `MouseDown` event - detect text selection clicks and Ctrl+Click for multi-cursor
35
fn handle_mouse_down(
35
    event: &SyntheticEvent,
35
    hit_test: Option<&FullHitTest>,
35
    click_count: u8,
35
    mouse_state: &crate::window::MouseState,
35
    keyboard_state: &crate::window::KeyboardState,
35
) -> Option<InternalEventAction> {
35
    let effective_click_count = if click_count == 0 { 1 } else { click_count };
35
    if effective_click_count > 3 {
4
        return None;
31
    }
31
    let _target = get_first_hovered_node(hit_test)?;
27
    let position = get_mouse_position_with_fallback(event, mouse_state);
    // Ctrl+Click (or Cmd+Click on macOS): add cursor at click position.
    // Use the platform PRIMARY modifier so this fires on Cmd on macOS
    // (where Ctrl+Click is the secondary-click gesture) — `ctrl_down()`
    // was wrong there.
27
    if keyboard_state.primary_down() && effective_click_count == 1 {
1
        return Some(InternalEventAction::AddAndPass(
1
            SystemChange::AddCursorAtClick { position },
1
        ));
26
    }
26
    Some(InternalEventAction::AddAndPass(
26
        SystemChange::TextSelectionClick {
26
            position,
26
            timestamp: event.timestamp.clone(),
26
        },
26
    ))
35
}
/// Handle `MouseMove` event - detect drag selection
25
fn handle_mouse_move(
25
    event: &SyntheticEvent,
25
    _hit_test: Option<&FullHitTest>,
25
    mouse_state: &crate::window::MouseState,
25
    drag_start_position: Option<LogicalPosition>,
25
) -> Option<InternalEventAction> {
25
    if !mouse_state.left_down {
17
        return None;
8
    }
8
    let start_position = drag_start_position?;
    // Deliberately NOT gated on a hovered hit node. A drag that leaves the
    // text — into the container's padding, over a gap, past the last line —
    // still extends the selection in every native editor, and the endpoint is
    // resolved from the pointer position against the ANCHOR block's layout
    // (`process_mouse_drag_for_selection`), not from whatever happens to be
    // under the cursor. Requiring a hit node froze the selection exactly where
    // the user was reaching for more of it.
6
    let current_position = get_mouse_position_with_fallback(event, mouse_state);
6
    Some(InternalEventAction::AddAndPass(
6
        SystemChange::TextSelectionDrag {
6
            start_position,
6
            current_position,
6
        },
6
    ))
25
}
/// Handle `KeyDown` event - detect shortcuts, arrow keys, and delete keys
44
fn handle_key_down(
44
    event: &SyntheticEvent,
44
    keyboard_state: &crate::window::KeyboardState,
44
    focused_node: Option<DomNodeId>,
44
    focus_is_editable: bool,
44
) -> Option<InternalEventAction> {
    use crate::window::VirtualKeyCode;
44
    let target = focused_node?;
35
    let EventData::Keyboard(kbd) = &event.data else {
2
        return None;
    };
    // Read the key and modifiers from THIS event's payload, not from the live
    // `keyboard_state`. The live state can have advanced (another key pressed /
    // released) between when the event was queued and when it is dispatched, so
    // reading it here could act on the wrong key/modifiers. `keyboard_state` is
    // retained only for the platform where the event does not carry a key.
33
    let _ = keyboard_state;
    // MWA-A2: standard shortcuts key off the PRIMARY modifier (Cmd on
    // macOS, Ctrl elsewhere); word-jump / word-delete keys off the
    // platform's word modifier (Option on macOS, Ctrl elsewhere).
33
    let primary = if cfg!(target_os = "macos") {
        kbd.modifiers.meta
    } else {
33
        kbd.modifiers.ctrl
    };
33
    let word_mod = if cfg!(target_os = "macos") {
        kbd.modifiers.alt
    } else {
33
        kbd.modifiers.ctrl
    };
33
    let shift = kbd.modifiers.shift;
33
    let vk_owned = VirtualKeyCode::from_u32(kbd.key_code)?;
29
    let vk = &vk_owned;
    // Check keyboard shortcuts (primary+key) → emit specific SystemChange
    // variants. Standard editing shortcuts are routed through the
    // `KeyboardShortcut` enum, and a couple of additional Azul-specific
    // primary-modifier combos are matched after.
29
    if primary {
4
        if let Some(shortcut) = KeyboardShortcut::from_key(*vk, primary, shift) {
            // A second seat's shortcut acts on ITS caret (9b-ii-a-i-d-ii-b-i).
3
            if kbd.seat_id != crate::window::PRIMARY_POINTER_SEAT {
                return Some(InternalEventAction::AddAndSkip(
                    SystemChange::SeatShortcut {
                        seat_id: kbd.seat_id,
                        target,
                        shortcut,
                    },
                ));
3
            }
3
            let change = match shortcut {
3
                KeyboardShortcut::Copy => SystemChange::CopyToClipboard,
                KeyboardShortcut::Cut => SystemChange::CutToClipboard { target },
                KeyboardShortcut::Paste => SystemChange::PasteFromClipboard,
                KeyboardShortcut::SelectAll => SystemChange::SelectAllText,
                KeyboardShortcut::Undo => SystemChange::UndoTextEdit { target },
                KeyboardShortcut::Redo => SystemChange::RedoTextEdit { target },
            };
3
            return Some(InternalEventAction::AddAndSkip(change));
1
        }
1
        if matches!(vk, VirtualKeyCode::D) {
            // Ctrl+D adds a multi-cursor, which is the primary's alone
            // (9b-ii-a-i-d-ii-b-i): a seat's passes through to callbacks.
            if kbd.seat_id != crate::window::PRIMARY_POINTER_SEAT {
                return None;
            }
            return Some(InternalEventAction::AddAndSkip(
                SystemChange::SelectNextOccurrence { target },
            ));
1
        }
25
    }
    // Unified: arrow keys, Home/End, Backspace/Delete all map to SelectionOp.
26
    let mode_for_shift = if shift {
2
        SelectionMode::Extend
    } else {
24
        SelectionMode::Move
    };
26
    let selection_op = if let Some(arrow) = ArrowDirection::from_key(*vk, word_mod) {
        // ONLY a text-editing context owns the arrows. Anywhere else they
        // belong to the focused widget (a slider steps its value, a colour
        // plane moves its marker) and, failing that, to the scroll default
        // action. Claiming them here returned `AddAndSkip`, which swallowed
        // the key before any callback could see it.
6
        if !focus_is_editable {
3
            return None;
3
        }
3
        let (direction, step) = arrow.to_selection(word_mod);
3
        SelectionOp::new(direction, step, mode_for_shift)
    } else {
20
        match vk {
            // Backspace/Delete = Delete mode (word modifier upgrades to
            // Word: Option+Backspace on macOS, Ctrl+Backspace elsewhere)
3
            VirtualKeyCode::Back => SelectionOp::new(
3
                SelectionDirection::Backward,
3
                if word_mod {
1
                    SelectionStep::Word
                } else {
2
                    SelectionStep::Character
                },
3
                SelectionMode::Delete,
            ),
2
            VirtualKeyCode::Delete => SelectionOp::new(
2
                SelectionDirection::Forward,
2
                if word_mod {
                    SelectionStep::Word
                } else {
2
                    SelectionStep::Character
                },
2
                SelectionMode::Delete,
            ),
15
            _ => return None,
        }
    };
8
    Some(InternalEventAction::AddAndSkip(
8
        SystemChange::ApplySelectionOp {
8
            target,
8
            op: selection_op,
8
            seat_id: kbd.seat_id,
8
        },
8
    ))
44
}
/// Trait for querying selection manager state.
///
/// This allows `pre_callback_filter_internal_events` to query manager state
/// without depending on the concrete `SelectionManager` type from layout crate.
pub trait SelectionManagerQuery {
    /// Get the current click count (1 = single, 2 = double, 3 = triple)
    fn get_click_count(&self) -> u8;
    /// Get the drag start position if a drag is in progress
    fn get_drag_start_position(&self) -> Option<LogicalPosition>;
    /// Check if any selection exists (click selection or drag selection)
    fn has_selection(&self) -> bool;
}
/// Trait for querying focus manager state.
///
/// This allows `pre_callback_filter_internal_events` to query manager state
/// without depending on the concrete `FocusManager` type from layout crate.
pub trait FocusManagerQuery {
    /// Get the currently focused node ID
    fn get_focused_node_id(&self) -> Option<DomNodeId>;
    /// The node seat `seat_id` focuses (9b-ii-a-i-d). A manager without
    /// per-seat focus answers the shared one for every seat.
    fn get_focused_node_for_seat(&self, seat_id: u64) -> Option<DomNodeId> {
        let _ = seat_id;
        self.get_focused_node_id()
    }
}
/// The focused node of every NON-primary keyboard seat that `events` carry
/// (9b-ii-a-i-d), for `InputInterpreterInfo::seat_focus`.
///
/// The interpreter resolves a seat's key against that seat's focus, not the
/// primary's.
#[must_use]
124
pub fn seat_focus_of_events<FM: FocusManagerQuery + ?Sized>(
124
    events: &[SyntheticEvent],
124
    focus_manager: &FM,
124
) -> Vec<(u64, Option<DomNodeId>)> {
124
    let mut out: Vec<(u64, Option<DomNodeId>)> = Vec::new();
366
    for event in events {
242
        let EventData::Keyboard(k) = &event.data else {
199
            continue;
        };
43
        if k.seat_id == crate::window::PRIMARY_POINTER_SEAT
4
            || out.iter().any(|(seat, _)| *seat == k.seat_id)
        {
39
            continue;
4
        }
4
        out.push((
4
            k.seat_id,
4
            focus_manager.get_focused_node_for_seat(k.seat_id),
4
        ));
    }
124
    out
124
}
/// Post-callback filter: Determine additional system changes needed after user callbacks.
///
/// Takes the pre-callback system changes and focus state to determine what
/// post-callback system changes are needed (text input, scrolling, timers).
/// Default post-callback filter: scroll-into-view after cursor ops, auto-scroll during drag.
#[must_use]
24
pub fn default_post_filter(
24
    prevent_default: bool,
24
    pre_changes: &[SystemChange],
24
    old_focus: Option<DomNodeId>,
24
    new_focus: Option<DomNodeId>,
24
) -> Vec<SystemChange> {
24
    post_callback_filter_system_changes(prevent_default, pre_changes, old_focus, new_focus)
24
}
// SystemChange dispatch table; a few arms incidentally push the same follow-up
// change but are kept as distinct documented cases.
#[allow(clippy::match_same_arms)]
#[must_use]
145
pub fn post_callback_filter_system_changes(
145
    prevent_default: bool,
145
    pre_changes: &[SystemChange],
145
    old_focus: Option<DomNodeId>,
145
    new_focus: Option<DomNodeId>,
145
) -> Vec<SystemChange> {
145
    let mut changes = Vec::new();
145
    if prevent_default {
        // Only focus change passes through preventDefault
6
        if old_focus != new_focus {
3
            changes.push(SystemChange::SetFocus {
3
                new_focus,
3
                old_focus,
3
                // A focus move a callback made (or that survived
3
                // preventDefault) is programmatic, not a keyboard walk: focused
3
                // but not indicated, like `autofocus`.
3
                visible: false,
3
            });
3
        }
6
        return changes;
139
    }
    // Always apply pending text input
139
    changes.push(SystemChange::ApplyPendingTextInput);
    // Determine post-callback actions based on pre-callback system changes
5158
    for change in pre_changes {
5019
        match change {
            SystemChange::TextSelectionClick { .. }
            | SystemChange::ApplySelectionOp { .. }
            | SystemChange::AddCursorAtClick { .. }
5004
            | SystemChange::SelectNextOccurrence { .. } => {
5004
                changes.push(SystemChange::ScrollSelectionIntoView);
5004
            }
5
            SystemChange::TextSelectionDrag { .. } => {
5
                changes.push(SystemChange::StartAutoScrollTimer);
5
            }
            SystemChange::CutToClipboard { .. }
            | SystemChange::PasteFromClipboard
            | SystemChange::UndoTextEdit { .. }
            | SystemChange::RedoTextEdit { .. }
9
            | SystemChange::SelectAllText => {
9
                changes.push(SystemChange::ScrollSelectionIntoView);
9
            }
            // Other system changes don't generate post-callback actions
1
            _ => {}
        }
    }
    // Focus changed during callbacks
139
    if old_focus != new_focus {
5
        changes.push(SystemChange::SetFocus {
5
            new_focus,
5
            old_focus,
5
            visible: false,
5
        });
134
    }
139
    changes
145
}
#[cfg(test)]
#[path = "events_test.rs"]
mod events_test;