teksilo-core 0.9.1

Core of the Teksilo GUI framework — widget trait, arena, layout engine, event dispatch, focus, signals and theming.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

use teksilo_canvas::{Point, Rect};

use crate::gesture::GestureEvent;

/// Pointer button identifiers.
///
/// `Forward` and `Back` correspond to the auxiliary mouse buttons (mouse
/// 4 / mouse 5) typically labelled "browser back / forward". Platforms
/// that don't have those buttons simply never emit them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PointerButton {
    /// Left-click (or main-action button on left-handed mice).
    Primary,
    /// Right-click.
    Secondary,
    /// Middle / wheel-click.
    Middle,
    /// "Back" auxiliary button (mouse 4 on most 5-button mice). Often
    /// bound to "navigate back" in browsers.
    Back,
    /// "Forward" auxiliary button (mouse 5). Often bound to "navigate
    /// forward".
    Forward,
}

/// Set of pointer buttons a gesture recognizer is configured to fire
/// for. Used by the four click-style recognizers (`TapRecognizer`,
/// `DoubleTapRecognizer`, `TripleTapRecognizer`, `LongPressRecognizer`)
/// and the matching widget-level builders (`accept_tap_buttons`, …).
///
/// Default for every recognizer is [`ButtonMask::PRIMARY`] — left-click
/// only — which matches the user's expectation for a "tap" and keeps
/// right-click free to open a context menu without spuriously
/// activating the widget. Use [`ButtonMask::ALL`] or a hand-built
/// `PRIMARY | SECONDARY` etc. to opt into broader button sets.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ButtonMask(u8);

impl ButtonMask {
    /// Empty mask — no buttons accepted.
    pub const NONE: Self = Self(0);
    /// Left-click on most desktop pointing devices.
    pub const PRIMARY: Self = Self(1 << 0);
    /// Right-click on most desktop pointing devices.
    pub const SECONDARY: Self = Self(1 << 1);
    /// Middle / wheel-click.
    pub const MIDDLE: Self = Self(1 << 2);
    /// "Back" auxiliary button (mouse 4).
    pub const BACK: Self = Self(1 << 3);
    /// "Forward" auxiliary button (mouse 5).
    pub const FORWARD: Self = Self(1 << 4);
    /// All buttons currently representable by [`PointerButton`].
    pub const ALL: Self = Self(0b0001_1111);

    /// `true` when the mask contains the given button.
    pub const fn contains(self, button: PointerButton) -> bool {
        let bit = match button {
            PointerButton::Primary => 1 << 0,
            PointerButton::Secondary => 1 << 1,
            PointerButton::Middle => 1 << 2,
            PointerButton::Back => 1 << 3,
            PointerButton::Forward => 1 << 4,
        };
        self.0 & bit != 0
    }

    /// `true` when no buttons are accepted.
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    /// Union — accept any button in either mask.
    pub const fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    /// Intersection — accept only buttons present in both masks.
    pub const fn intersection(self, other: Self) -> Self {
        Self(self.0 & other.0)
    }
}

impl From<PointerButton> for ButtonMask {
    fn from(button: PointerButton) -> Self {
        match button {
            PointerButton::Primary => Self::PRIMARY,
            PointerButton::Secondary => Self::SECONDARY,
            PointerButton::Middle => Self::MIDDLE,
            PointerButton::Back => Self::BACK,
            PointerButton::Forward => Self::FORWARD,
        }
    }
}

impl<const N: usize> From<[PointerButton; N]> for ButtonMask {
    fn from(buttons: [PointerButton; N]) -> Self {
        let mut mask = Self::NONE;
        let mut i = 0;
        while i < N {
            mask = mask.union(ButtonMask::from(buttons[i]));
            i += 1;
        }
        mask
    }
}

impl std::ops::BitOr for ButtonMask {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self {
        self.union(rhs)
    }
}

impl std::ops::BitAnd for ButtonMask {
    type Output = Self;
    fn bitand(self, rhs: Self) -> Self {
        self.intersection(rhs)
    }
}

impl std::ops::BitOrAssign for ButtonMask {
    fn bitor_assign(&mut self, rhs: Self) {
        self.0 |= rhs.0;
    }
}

impl std::ops::BitAndAssign for ButtonMask {
    fn bitand_assign(&mut self, rhs: Self) {
        self.0 &= rhs.0;
    }
}

impl Default for ButtonMask {
    fn default() -> Self {
        Self::PRIMARY
    }
}

/// Keyboard key identifiers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum Key {
    Space,
    Enter,
    Escape,
    Tab,
    Backspace,
    Delete,
    Insert,
    ArrowUp,
    ArrowDown,
    ArrowLeft,
    ArrowRight,
    Home,
    End,
    PageUp,
    PageDown,
    // Letters
    A,
    B,
    C,
    D,
    E,
    F,
    G,
    H,
    I,
    J,
    K,
    L,
    M,
    N,
    O,
    P,
    Q,
    R,
    S,
    T,
    U,
    V,
    W,
    X,
    Y,
    Z,
    // Function keys
    F1,
    F2,
    F3,
    F4,
    F5,
    F6,
    F7,
    F8,
    F9,
    F10,
    F11,
    F12,
    F13,
    F14,
    F15,
    F16,
    F17,
    F18,
    F19,
    F20,
    F21,
    F22,
    F23,
    F24,
    // Other
    /// Caps Lock. Delivered as a discrete key press/release (winit's
    /// `ModifiersState` does not carry lock state), so consumers that
    /// need the *active* lock state track it themselves on the
    /// key-down edge. See `WindowState::caps_lock`.
    CapsLock,
    /// The dedicated context-menu key: `VK_APPS` on Windows (the key between
    /// the right Alt and the right Ctrl on most PC layouts), `keysyms::Menu` on
    /// X11 and Wayland.
    ///
    /// **macOS never produces it.** Its keyboards have no such key and
    /// `winit-0.30.13`'s AppKit backend references the variant zero times, so
    /// on that platform the only keyboard route to a context menu is a chord.
    /// See the dispatcher's context-menu handling for the chords Teksilo
    /// reserves.
    ContextMenu,
    Character(char),
}

impl Key {
    /// Returns the character this key represents, if any.
    /// Maps `Key::A`..`Key::Z` to `'a'`..`'z'` (lowercase) and
    /// `Key::Character(ch)` to `ch`.
    pub fn to_char(&self) -> Option<char> {
        match self {
            Key::A => Some('a'),
            Key::B => Some('b'),
            Key::C => Some('c'),
            Key::D => Some('d'),
            Key::E => Some('e'),
            Key::F => Some('f'),
            Key::G => Some('g'),
            Key::H => Some('h'),
            Key::I => Some('i'),
            Key::J => Some('j'),
            Key::K => Some('k'),
            Key::L => Some('l'),
            Key::M => Some('m'),
            Key::N => Some('n'),
            Key::O => Some('o'),
            Key::P => Some('p'),
            Key::Q => Some('q'),
            Key::R => Some('r'),
            Key::S => Some('s'),
            Key::T => Some('t'),
            Key::U => Some('u'),
            Key::V => Some('v'),
            Key::W => Some('w'),
            Key::X => Some('x'),
            Key::Y => Some('y'),
            Key::Z => Some('z'),
            Key::Character(ch) => Some(*ch),
            _ => None,
        }
    }

    /// The text the platform attaches to this key, for the handful of named
    /// keys that carry any. Mirrors winit's `NamedKey::to_text`, which is
    /// where these values reach the app from.
    ///
    /// Worth knowing because it is surprising: Escape arrives carrying
    /// U+001B, so a widget that reads `KeyDown::text` sees text on a key
    /// nobody thinks of as text. A `TextInputField` used to filter that
    /// control character out, read the empty result as "input rejected" and
    /// swallow the key — which is how Escape stopped bubbling out of a
    /// focused field.
    ///
    /// Character keys are deliberately absent: `Key::A` is `None` here, and
    /// the way to simulate typing is `type_text`, which already sends text.
    /// The gap this closes is only the surprising one.
    pub fn to_text(&self) -> Option<&'static str> {
        match self {
            Key::Enter => Some("\r"),
            Key::Backspace => Some("\u{8}"),
            Key::Tab => Some("\t"),
            Key::Space => Some(" "),
            Key::Escape => Some("\u{1b}"),
            _ => None,
        }
    }
}

/// Keyboard modifier state.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize,
)]
pub struct Modifiers {
    bits: u8,
}

impl Modifiers {
    pub const NONE: Modifiers = Modifiers { bits: 0 };
    pub const CTRL: Modifiers = Modifiers { bits: 1 };
    pub const SHIFT: Modifiers = Modifiers { bits: 2 };
    pub const ALT: Modifiers = Modifiers { bits: 4 };
    pub const SUPER: Modifiers = Modifiers { bits: 8 };

    /// The **primary accelerator** modifier for this platform: [`SUPER`]
    /// (Command, ⌘) on macOS, [`CTRL`] everywhere else.
    ///
    /// Desktop platforms disagree about which physical key carries application
    /// accelerators, and on macOS the disagreement is not cosmetic: Control is
    /// reserved there for the text system and for the secondary click, while ⌘
    /// is what a user presses for Save, Copy or Find. Code that hard-codes
    /// [`CTRL`] to mean "the accelerator" therefore listens to the wrong key on
    /// one of the three desktop platforms.
    ///
    /// Compare against this constant (or call [`Modifiers::command`]) and the
    /// same code means Ctrl+A on Windows and Linux and ⌘A on macOS. This
    /// mirrors Qt's `Qt::CTRL`, which likewise resolves to ⌘ on macOS, and the
    /// convention the native menu bar already applies when it turns a declared
    /// chord into an `NSMenuItem` key equivalent.
    ///
    /// [`SUPER`]: Modifiers::SUPER
    /// [`CTRL`]: Modifiers::CTRL
    pub const COMMAND: Modifiers = if cfg!(target_os = "macos") {
        Self::SUPER
    } else {
        Self::CTRL
    };

    pub fn empty() -> Self {
        Self::NONE
    }

    pub fn ctrl(self) -> bool {
        self.bits & 1 != 0
    }

    pub fn shift(self) -> bool {
        self.bits & 2 != 0
    }

    pub fn alt(self) -> bool {
        self.bits & 4 != 0
    }

    pub fn super_key(self) -> bool {
        self.bits & 8 != 0
    }

    /// Whether the platform's primary accelerator modifier
    /// ([`Modifiers::COMMAND`]) is held: Command (⌘) on macOS, Control
    /// everywhere else.
    ///
    /// Use this instead of [`ctrl`](Self::ctrl) wherever the chord means "the
    /// accelerator" — select-all, the discontiguous-selection click, jump to
    /// the end of a list. Keep [`ctrl`](Self::ctrl) for the chords that really
    /// are Control on every platform, macOS included: Ctrl+Tab cycles tabs
    /// there too (⌘Tab belongs to the application switcher and never reaches
    /// an app).
    pub fn command(self) -> bool {
        self.contains(Self::COMMAND)
    }

    /// Whether every modifier in `other` is held.
    pub fn contains(self, other: Modifiers) -> bool {
        self.bits & other.bits == other.bits
    }

    /// These modifiers with `other` removed.
    pub fn without(self, other: Modifiers) -> Modifiers {
        Modifiers {
            bits: self.bits & !other.bits,
        }
    }

    /// These modifiers with a declared `CTRL` reinterpreted as the platform's
    /// primary accelerator — see [`Modifiers::COMMAND`] and
    /// [`KeyStroke::with_command_convention`](crate::shortcut::KeyStroke::with_command_convention),
    /// which is where this is applied.
    ///
    /// A no-op off macOS (where `COMMAND` *is* `CTRL`), and a no-op for a chord
    /// that already names `SUPER` explicitly: `Ctrl+Super` stays ⌃⌘, a genuine
    /// two-modifier chord, rather than collapsing to one.
    pub fn with_command_convention(self) -> Modifiers {
        self.with_command_convention_using(Self::COMMAND)
    }

    /// The platform-parameterised core of
    /// [`with_command_convention`](Self::with_command_convention). Split out so
    /// the macOS branch is exercised by tests running on any host — the whole
    /// point of the convention is behaviour a Linux CI cannot otherwise see.
    ///
    /// `pub(crate)` rather than private because the same split continues up the
    /// stack: [`KeyStroke`](crate::shortcut::KeyStroke) and
    /// [`Shortcut`](crate::shortcut::Shortcut) each carry a `_using` twin that
    /// bottoms out here, so a shortcut's resolution can be asked "as macOS
    /// would read it" from a Linux host without restating the rule.
    pub(crate) fn with_command_convention_using(self, command: Modifiers) -> Modifiers {
        if self.ctrl() && !self.super_key() {
            self.without(Self::CTRL) | command
        } else {
            self
        }
    }
}

impl std::fmt::Display for Key {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Key::Space => f.write_str("Space"),
            Key::Enter => f.write_str("Enter"),
            Key::Escape => f.write_str("Esc"),
            Key::Tab => f.write_str("Tab"),
            Key::Backspace => f.write_str("Backspace"),
            Key::Delete => f.write_str("Del"),
            Key::Insert => f.write_str("Ins"),
            Key::ArrowUp => f.write_str("Up"),
            Key::ArrowDown => f.write_str("Down"),
            Key::ArrowLeft => f.write_str("Left"),
            Key::ArrowRight => f.write_str("Right"),
            Key::Home => f.write_str("Home"),
            Key::End => f.write_str("End"),
            Key::PageUp => f.write_str("PageUp"),
            Key::PageDown => f.write_str("PageDown"),
            Key::A => f.write_str("A"),
            Key::B => f.write_str("B"),
            Key::C => f.write_str("C"),
            Key::D => f.write_str("D"),
            Key::E => f.write_str("E"),
            Key::F => f.write_str("F"),
            Key::G => f.write_str("G"),
            Key::H => f.write_str("H"),
            Key::I => f.write_str("I"),
            Key::J => f.write_str("J"),
            Key::K => f.write_str("K"),
            Key::L => f.write_str("L"),
            Key::M => f.write_str("M"),
            Key::N => f.write_str("N"),
            Key::O => f.write_str("O"),
            Key::P => f.write_str("P"),
            Key::Q => f.write_str("Q"),
            Key::R => f.write_str("R"),
            Key::S => f.write_str("S"),
            Key::T => f.write_str("T"),
            Key::U => f.write_str("U"),
            Key::V => f.write_str("V"),
            Key::W => f.write_str("W"),
            Key::X => f.write_str("X"),
            Key::Y => f.write_str("Y"),
            Key::Z => f.write_str("Z"),
            Key::F1 => f.write_str("F1"),
            Key::F2 => f.write_str("F2"),
            Key::F3 => f.write_str("F3"),
            Key::F4 => f.write_str("F4"),
            Key::F5 => f.write_str("F5"),
            Key::F6 => f.write_str("F6"),
            Key::F7 => f.write_str("F7"),
            Key::F8 => f.write_str("F8"),
            Key::F9 => f.write_str("F9"),
            Key::F10 => f.write_str("F10"),
            Key::F11 => f.write_str("F11"),
            Key::F12 => f.write_str("F12"),
            Key::F13 => f.write_str("F13"),
            Key::F14 => f.write_str("F14"),
            Key::F15 => f.write_str("F15"),
            Key::F16 => f.write_str("F16"),
            Key::F17 => f.write_str("F17"),
            Key::F18 => f.write_str("F18"),
            Key::F19 => f.write_str("F19"),
            Key::F20 => f.write_str("F20"),
            Key::F21 => f.write_str("F21"),
            Key::F22 => f.write_str("F22"),
            Key::F23 => f.write_str("F23"),
            Key::F24 => f.write_str("F24"),
            Key::CapsLock => f.write_str("CapsLock"),
            Key::ContextMenu => f.write_str("Menu"),
            Key::Character(c) => write!(f, "{}", c.to_uppercase()),
        }
    }
}

impl std::fmt::Display for Modifiers {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.ctrl() {
            f.write_str("Ctrl+")?;
        }
        if self.alt() {
            f.write_str("Alt+")?;
        }
        if self.shift() {
            f.write_str("Shift+")?;
        }
        if self.super_key() {
            // Named for the key the user is looking at. This string reaches
            // assistive tech through the accessibility tree's
            // `keyboard_shortcut`, and a Mac screen-reader user announced
            // "Super+S" for ⌘S has been told the wrong key.
            f.write_str(if cfg!(target_os = "macos") {
                "Cmd+"
            } else {
                "Super+"
            })?;
        }
        Ok(())
    }
}

impl std::ops::BitOr for Modifiers {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self {
        Modifiers {
            bits: self.bits | rhs.bits,
        }
    }
}

/// Scroll delta from mouse wheel or trackpad.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ScrollDelta {
    /// Line-based scrolling (mouse wheel).
    Lines { x: f32, y: f32 },
    /// Pixel-based scrolling (trackpad).
    Pixels { x: f32, y: f32 },
}

/// Where a [`WidgetEvent::ScrollIntoView`] target should come to rest on the
/// scroll container's vertical axis.
///
/// The horizontal axis is always revealed minimally — a fraction only has an
/// obvious meaning for the axis the request is *about*, and pinning a caret
/// vertically must not yank a horizontally-scrolled view sideways.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ScrollAlign {
    /// Scroll the least amount that makes the target fully visible, and not at
    /// all when it already is. This is what focus-driven reveals and
    /// [`EventContext::ensure_visible`](crate::widget::EventContext::ensure_visible)
    /// use, and it is the behaviour every scroll container had before
    /// alignment existed.
    Minimal,
    /// Pin the target at `f` of the way down the viewport — `0.0` flush with
    /// the top, `0.5` centred, `1.0` flush with the bottom — **whether or not
    /// it is already visible**. Being unconditional is the whole point: a
    /// typewriter-scrolling caret that only moved the view when it fell off
    /// the edge would not be pinned at all.
    ///
    /// The container still clamps to its scroll range, so a target near the
    /// start or end of the content comes to rest as close to `f` as the range
    /// allows. See [`ScrollArea::scroll_past_end`] for buying range past the
    /// end of the content so the last line can still reach the pin.
    ///
    /// [`ScrollArea::scroll_past_end`]: https://docs.rs/teksilo-widgets
    Fraction(f32),
}

/// Whether a [`WidgetEvent::ScrollIntoView`] should jump or glide.
///
/// Split out from the container's own `smooth_scrolling` setting because the
/// right answer depends on the *request*, not the container: a caret pinned on
/// every keystroke must snap (animating it is what produces the "screen
/// bouncing" typewriter-mode users complain about in other editors), while the
/// same container gliding for a page-down or a search hit reads as polish.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScrollMotion {
    /// Jump straight to the target offset.
    Instant,
    /// Animate to the target offset, if the container has smooth scrolling
    /// enabled. Containers with `smooth_scrolling(false)` still jump.
    Smooth,
}

/// Events dispatched to widgets.
#[derive(Debug, Clone)]
pub enum WidgetEvent {
    PointerDown {
        position: Point,
        button: PointerButton,
        modifiers: Modifiers,
    },
    PointerUp {
        position: Point,
        button: PointerButton,
        modifiers: Modifiers,
    },
    PointerMove {
        position: Point,
    },
    PointerEnter,
    PointerLeave,
    Scroll {
        delta: ScrollDelta,
        /// Modifier keys held at the time of the scroll event.
        /// Defaults to `Modifiers::NONE` for synthesized events
        /// (tests, keyboard-driven scroll requests). Real-platform
        /// scroll events populate this from the platform's tracked
        /// modifier state — apps detect Ctrl-wheel-to-zoom by
        /// inspecting `modifiers.ctrl()`.
        modifiers: Modifiers,
    },
    KeyDown {
        key: Key,
        modifiers: Modifiers,
        text: Option<String>,
    },
    KeyUp {
        key: Key,
        modifiers: Modifiers,
    },
    ImeComposition {
        text: String,
        cursor: Option<std::ops::Range<usize>>,
    },
    ImeCommit {
        text: String,
    },
    FocusGained {
        origin: crate::focus::FocusOrigin,
    },
    FocusLost,
    AccessAction {
        action: accesskit::Action,
        target: Option<crate::widget_id::WidgetId>,
        /// Raw AccessKit NodeId from the original `ActionRequest`.
        /// May be a synthetic (widget-emitted child) NodeId — use
        /// `crate::accessibility::is_synthetic` to distinguish it
        /// from a widget-derived NodeId. The widget that registered
        /// the parent (retrieved via `tree.widget_for_synthetic`)
        /// is the one set in `target`.
        target_node: accesskit::NodeId,
        /// Payload carried by the `ActionRequest`. For
        /// `Action::SetTextSelection` this is
        /// `ActionData::SetTextSelection(TextSelection)`, for
        /// `Action::SetValue` it's `ActionData::Value(Box<str>)`,
        /// for scroll actions it carries scroll offsets, etc.
        /// Widgets that declare these actions must read the payload
        /// to honour screen-reader-initiated requests.
        data: Option<accesskit::ActionData>,
    },
    /// Dispatched by the framework to a clipping ancestor when a child
    /// gains focus but is outside the viewport. The scroll area adjusts
    /// its offset to make the target bounds visible, with an optional
    /// margin around the target.
    ScrollIntoView {
        target_bounds: Rect,
        /// Extra margin (in logical pixels) to keep around the target
        /// when scrolling it into view. Defaults to 0.0.
        margin: f32,
        /// Where the target should end up on the scroll container's
        /// **vertical** axis. [`ScrollAlign::Minimal`] (the default, and what
        /// every focus-driven reveal uses) only scrolls when the target is not
        /// already fully visible; [`ScrollAlign::Fraction`] *pins* it to a
        /// fixed height in the viewport whether or not it was already visible.
        align: ScrollAlign,
        /// Whether the container should jump to the new offset or glide to it.
        /// See [`ScrollMotion`].
        motion: ScrollMotion,
        /// Optional back-channel for the handling scroll container to report
        /// how far it actually scrolled (`(dx, dy)` in content pixels). When
        /// several nested scroll containers must each reveal the same target,
        /// the ancestor walk (`scroll_rect_into_view`) reads this after
        /// dispatching to an inner container and shifts `target_bounds` by the
        /// negated delta before asking the next (outer) one — so the outer sees
        /// where the target will land once the inner's (deferred) scroll
        /// applies, not its pre-scroll position. `None` disables reporting (the
        /// nested-reveal refinement is unavailable). A handler that ignores it
        /// still works for the common single-container case.
        ///
        /// `Arc<Mutex<..>>` (not `Rc<Cell<..>>`) so `WidgetEvent` stays `Send`
        /// — some events are posted across threads. This one is only ever
        /// touched on the dispatch thread, so the lock is always uncontended.
        applied_scroll: Option<std::sync::Arc<std::sync::Mutex<teksilo_canvas::Point>>>,
    },
    /// A recognized gesture event, routed through the same preview/bubble system.
    Gesture {
        gesture: GestureEvent,
    },
}

/// The result of handling an event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventResponse {
    /// The event was handled; stop propagation.
    Handled,
    /// The event was not handled; let it bubble.
    Ignored,
}

#[cfg(test)]
mod modifier_tests {
    use super::*;

    // The convention itself, exercised on both platform settings from any host.
    // `Modifiers::COMMAND` resolves at compile time, so a Linux CI would
    // otherwise only ever see half of what this rule does — and the half it
    // cannot see is the one the rule exists for.

    #[test]
    fn command_convention_rewrites_a_bare_ctrl_on_macos() {
        let mac = Modifiers::CTRL.with_command_convention_using(Modifiers::SUPER);
        assert_eq!(mac, Modifiers::SUPER);

        let mac =
            (Modifiers::CTRL | Modifiers::SHIFT).with_command_convention_using(Modifiers::SUPER);
        assert_eq!(mac, Modifiers::SUPER | Modifiers::SHIFT);
    }

    #[test]
    fn command_convention_is_a_no_op_where_command_is_ctrl() {
        for m in [
            Modifiers::CTRL,
            Modifiers::CTRL | Modifiers::SHIFT,
            Modifiers::ALT,
            Modifiers::NONE,
            Modifiers::SUPER,
        ] {
            assert_eq!(m.with_command_convention_using(Modifiers::CTRL), m);
        }
    }

    #[test]
    fn command_convention_leaves_an_explicit_super_alone() {
        // A chord that already names Super is a deliberate ⌘ chord, and
        // `Ctrl+Super` is a genuine two-modifier chord — neither collapses.
        assert_eq!(
            Modifiers::SUPER.with_command_convention_using(Modifiers::SUPER),
            Modifiers::SUPER
        );
        let both = Modifiers::CTRL | Modifiers::SUPER;
        assert_eq!(both.with_command_convention_using(Modifiers::SUPER), both);
    }

    #[test]
    fn command_convention_is_idempotent() {
        for command in [Modifiers::CTRL, Modifiers::SUPER] {
            for m in [
                Modifiers::CTRL,
                Modifiers::CTRL | Modifiers::SHIFT | Modifiers::ALT,
                Modifiers::SUPER,
                Modifiers::NONE,
            ] {
                let once = m.with_command_convention_using(command);
                assert_eq!(once.with_command_convention_using(command), once);
            }
        }
    }

    #[test]
    fn command_predicate_follows_the_platform() {
        // Whichever platform this runs on, `COMMAND` is one of the two, and
        // `command()` tracks exactly it.
        assert!(Modifiers::COMMAND.command());
        assert!(!Modifiers::ALT.command());
        assert!((Modifiers::COMMAND | Modifiers::SHIFT).command());

        if cfg!(target_os = "macos") {
            assert_eq!(Modifiers::COMMAND, Modifiers::SUPER);
            assert!(!Modifiers::CTRL.command());
        } else {
            assert_eq!(Modifiers::COMMAND, Modifiers::CTRL);
            assert!(!Modifiers::SUPER.command());
        }
    }

    #[test]
    fn contains_requires_every_named_modifier() {
        let cs = Modifiers::CTRL | Modifiers::SHIFT;
        assert!(cs.contains(Modifiers::CTRL));
        assert!(cs.contains(cs));
        assert!(!cs.contains(Modifiers::CTRL | Modifiers::ALT));
        assert!(cs.contains(Modifiers::NONE));
    }

    #[test]
    fn without_clears_only_the_named_modifiers() {
        let all = Modifiers::CTRL | Modifiers::SHIFT | Modifiers::SUPER;
        assert_eq!(
            all.without(Modifiers::SUPER),
            Modifiers::CTRL | Modifiers::SHIFT
        );
        assert_eq!(all.without(Modifiers::ALT), all);
    }
}