quadraui 0.6.0

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
//! Backend-neutral event type.
//!
//! `UiEvent` is what flows up from the active [`Backend`][crate::Backend] to
//! the app each frame. Backends translate their native input events (crossterm
//! key events, GTK signals, Win32 messages, Cocoa responder methods) into
//! `UiEvent` variants; apps dispatch on the variant without caring which
//! backend produced it.
//!
//! ## Invariants
//!
//! Every `UiEvent` satisfies:
//! - `Debug + Clone + PartialEq + Serialize + Deserialize` — see
//!   `docs/decisions/BACKEND_TRAIT_PROPOSAL.md` §2 for rationale. One
//!   variant, [`Self::User`], satisfies the `Serialize`/`Deserialize`/
//!   `PartialEq` half only nominally — see [`UserPayload`]'s doc for why
//!   an opaque `Any` payload can't do better and what its impls actually
//!   do instead.
//! - Owned data only — no closures, no non-`'static` references. A `UiEvent`
//!   can be logged, replayed, serialised for a plugin boundary, or sent
//!   across threads with no ceremony. [`Self::User`] is the one exception
//!   to "serialised for a plugin boundary" — it's an in-process-only
//!   handoff by design.
//! - Mouse events carry `Option<WidgetId>` — the backend does hit-testing
//!   **before** emitting so apps dispatch on widget identity.
//!
//! ## Event routing — hit-test vs focus
//!
//! | Class | Routed by |
//! |---|---|
//! | Mouse (`MouseDown`, `MouseUp`, `MouseMoved`, `MouseEntered`, `MouseLeft`, `DoubleClick`, `Scroll`) | Hit-test at cursor position |
//! | Keyboard (`KeyPressed`, `CharTyped`) | Focus |
//! | Accelerator | [`AcceleratorScope`][crate::AcceleratorScope] |
//! | Window (`WindowResized`, `WindowClose`, `WindowFocused`, `DpiChanged`) | Application-global |
//! | `FilesDropped` | Hit-test at drop position |
//! | `ClipboardPaste` | Focus |
//! | `TextCopied` | Broadcast (no target) |
//! | `FocusChanged` | Broadcast — names the new focus, if any |
//! | `OpenRequested` | Broadcast (no target) |
//! | `SystemThemeChanged` | Broadcast (no target) |
//! | `DisplaysChanged` | Broadcast (no target) |
//!
//! The consequence apps rely on: **scroll wheel events dispatch to the
//! widget under the cursor, regardless of which widget has keyboard focus.**
//! Native convention on Win32, Cocoa, and GTK.
//!
//! ## Emission conformance — required vs. optional
//!
//! Not every backend emits every variant, and not every variant needs
//! to be emitted by every backend to be conformant. `docs/BACKEND.md`'s
//! "UiEvent emission matrix" is the published required/optional table
//! per backend, kept in sync with `docs/TESTING.md`'s C2 conformance
//! tier; `docs/decisions/DECISIONS.md`'s D-010 records the per-variant disposition
//! (wire / optional-capability / keep-undocumented-no-longer) this doc
//! comment reflects. Two variants get their own doc-comment note below
//! because the matrix alone doesn't explain *why*: [`Self::CharTyped`]
//! (the IME-vs-raw-keystroke duality) and [`Self::WindowClose`] (wired
//! for GTK/Win/macOS — issue #951 closed the macOS gap — with TUI's
//! legitimate non-applicability tracked as a separate, non-gap
//! disposition).
//!
//! ## Unit contract — `Point`, `Rect`, `Viewport`
//!
//! `Point`/`Rect`'s fields are bare `f32` — no `Px`/`Cell` newtype, no
//! marker generic. That is a deliberate, audited choice, not an
//! oversight: see `docs/decisions/DECISIONS.md` D-016 for the full
//! blast-radius argument (2000+ call sites across every primitive and
//! both rasterisers) against introducing one now. What *is* new here is
//! making the contract a type-level statement instead of an implicit
//! convention every call site has to already know:
//!
//! 1. **A `Point`/`Rect` value's unit is whatever its *producing*
//!    backend's [`Viewport`] uses** — TUI: whole cells. GTK / Win-GUI:
//!    device-independent pixels. macOS: Core Graphics points.
//!    A value never carries its own unit tag; the *call site* (which
//!    `Backend` impl produced it) is the only thing that says which one
//!    it is. There is no silent conversion between a TUI `Rect` and a
//!    GTK `Rect` — they are not interchangeable even though the type is
//!    the same.
//! 2. **[`Viewport::scale`] is a DPI/backing-scale factor *within* one
//!    GUI backend** (physical pixels ÷ logical pixels — see
//!    `GtkBackend::dpi_scale`), nothing more. GTK, Win-GUI, and macOS
//!    each derive it live in their real run loops (GTK's
//!    `notify::scale-factor` handler, Win-GUI's `GetDpiForWindow` /
//!    `WM_DPICHANGED`, macOS's `backingScaleFactor()`), so it varies
//!    whenever one of those backends runs on a non-1x display. Only
//!    every backend's *test harness* pins it to `1.0` — a headless
//!    surface has no live display to read a ratio from — and TUI pins
//!    it to `1.0` unconditionally, since a terminal cell has no DPI
//!    concept at all. **It is not a cross-backend conversion factor** —
//!    there is no `scale` value that turns a TUI cell count into a GTK
//!    pixel count, because a terminal cell's pixel size is a font
//!    metric (`line_height`/`char_width`), not a DPI ratio. A prior
//!    revision of this doc comment on [`Point`] read "apps that need to
//!    convert should use `Viewport::scale`" — that line was the bug: it
//!    told a reader `scale` solves a problem it cannot solve. Removed;
//!    see point 3.
//! 3. **Cross-backend-portable code derives sizes, it never hardcodes
//!    them.** Any shared `AppLogic`/compose-helper code that needs a
//!    dimension — a status-bar height, a dropdown row pitch — must
//!    compute it from [`crate::Backend::line_height`],
//!    [`crate::Backend::char_width`], [`crate::Backend::viewport`], or
//!    a `*_layout()` result. A bare numeric literal (`24.0`, `lh +
//!    4.0`) smuggles in an implicit unit assumption that is wrong on at
//!    least one backend. This isn't new policy — `docs/LESSONS.md`'s
//!    "Shared AppLogic code must not hardcode backend-native units" and
//!    "Dropdown item sizing must use backend-native units" entries are
//!    the two real incidents this generalises from — but it previously
//!    lived only in LESSONS.md, discoverable after the fact. It is now
//!    also stated here, on the types themselves, where `rustdoc` surfaces
//!    it before a third incident.

use serde::{Deserialize, Serialize};
use std::any::Any;
use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;

use crate::backend::SystemTheme;
use crate::types::{Modifiers, WidgetId};
use crate::{
    ActivityBarEvent, ChartEvent, DataTableEvent, FormEvent, ListViewEvent, PaletteEvent,
    StatusBarEvent, TabBarEvent, TerminalEvent, TextDisplayEvent, TreeEvent,
};

// ─── Supporting types ───────────────────────────────────────────────────────

/// Keyboard key identity — a printable character or a named non-printable.
///
/// Apps that want every keystroke (text inputs, terminal passthrough) match
/// on `Key`; apps that only want keybindings prefer [`UiEvent::Accelerator`]
/// which already resolves the key + modifiers to a declared
/// [`AcceleratorId`][crate::AcceleratorId].
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Key {
    /// Printable character (after keyboard layout resolution).
    Char(char),
    /// Named non-printable key.
    Named(NamedKey),
}

/// Non-printable keyboard keys that have a stable cross-platform name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum NamedKey {
    Escape,
    Tab,
    BackTab,
    Enter,
    Backspace,
    Delete,
    Insert,
    Home,
    End,
    PageUp,
    PageDown,
    Up,
    Down,
    Left,
    Right,
    /// Function key 1-24. Values outside that range are backend-specific
    /// (emitted via [`UiEvent::BackendNative`] instead).
    F(u8),
    /// Caps lock, num lock, scroll lock — typically consumed by the OS but
    /// emitted for completeness.
    CapsLock,
    NumLock,
    ScrollLock,
    /// Menu / application key (right-click keyboard equivalent).
    Menu,
}

/// Mouse button identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum MouseButton {
    #[default]
    Left,
    Right,
    Middle,
    /// Back / forward navigation buttons on 5-button mice.
    X1,
    X2,
    /// Backend-specific button index.
    Other(u8),
}

/// Bitmask of mouse buttons currently held down during a `MouseMoved` event.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ButtonMask {
    #[serde(default)]
    pub left: bool,
    #[serde(default)]
    pub right: bool,
    #[serde(default)]
    pub middle: bool,
}

/// Cursor position in the backend's native units.
///
/// - **TUI**: whole cells (typically integral values stored as `f32`).
/// - **GTK**: device-independent pixels (Cairo / Pango coordinates).
/// - **Win-GUI**: Direct2D DIPs.
/// - **macOS**: Core Graphics points.
///
/// See this module's "Unit contract" doc section for what "native
/// units" means precisely and why [`Viewport::scale`] does **not** help
/// convert a `Point` from one backend's unit to another's.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct Point {
    pub x: f32,
    pub y: f32,
}

impl Point {
    pub const fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }
}

/// Scroll-wheel delta. Positive `y` = scroll up (toward the top of content).
/// Backends that report scroll in lines/cells/pixels normalise to their
/// native unit before emitting.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct ScrollDelta {
    pub x: f32,
    pub y: f32,
}

impl ScrollDelta {
    pub const fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }
}

/// Rectangular region in the backend's native units.
///
/// Same unit contract as [`Point`] — TUI cells, GTK/Win-GUI DIPs,
/// macOS points — see this module's "Unit contract" doc
/// section. A `Rect` produced by one backend is not meaningful passed
/// to another; there is no implicit conversion.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct Rect {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
}

impl Rect {
    pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }

    pub fn contains(&self, p: Point) -> bool {
        p.x >= self.x && p.x < self.x + self.width && p.y >= self.y && p.y < self.y + self.height
    }
}

/// Backend viewport dimensions in native units.
///
/// TUI: `width` and `height` are cell counts; `scale` is always `1.0`
/// (a terminal has no DPI concept). GTK / Win-GUI / macOS: pixel-ish
/// units with `scale` = backing/DPI ratio (physical px ÷ logical px).
///
/// `scale` answers "how many physical pixels per logical pixel on
/// *this* GUI backend's display", not "how do I convert this value
/// from one backend's unit into another's" — see this module's "Unit
/// contract" doc section.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Viewport {
    pub width: f32,
    pub height: f32,
    pub scale: f32,
}

impl Viewport {
    pub const fn new(width: f32, height: f32, scale: f32) -> Self {
        Self {
            width,
            height,
            scale,
        }
    }
}

impl Default for Viewport {
    fn default() -> Self {
        Self::new(80.0, 24.0, 1.0)
    }
}

/// Backend-specific event the crate couldn't normalise.
///
/// The `payload` is an opaque backend-defined string (typically JSON). Apps
/// ignore this variant by default; only special-case it when a specific
/// platform feature is required.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BackendNativeEvent {
    /// Backend identifier — matches [`Backend::platform_name`][crate::PlatformServices::platform_name].
    pub backend: String,
    /// Short name for the native event, e.g. `"win32.wm_sizing"`.
    pub kind: String,
    /// Opaque payload. Apps choosing to handle this variant parse it
    /// per-backend.
    pub payload: String,
}

// ─── Background-thread wake payload ────────────────────────────────────────

/// Opaque payload carried by [`UiEvent::User`].
///
/// Every other `UiEvent` variant satisfies this module's documented
/// invariant — `Debug + Clone + PartialEq + Serialize + Deserialize` — for
/// free, via the enum-level `#[derive(..)]`. An arbitrary app value can't:
/// a boxed trait object has no generic `Clone` (the vtable doesn't carry
/// one), no generic equality, and nothing to serialise into. `UserPayload`
/// is a hand-rolled wrapper that satisfies the same four traits by
/// necessity rather than by content:
///
/// - **`Clone`** — wraps `Arc<dyn Any + Send + Sync>` rather than
///   `Box<dyn Any + Send>`, so cloning bumps a refcount instead of
///   requiring the erased payload to know how to duplicate itself. This is
///   also what makes a `UiEvent::User` cross-thread-safe *after* delivery
///   (`Send + Sync`), on top of `Backend::waker`'s closure needing `Send`
///   to be called from a background thread in the first place.
/// - **`PartialEq`** — pointer identity ([`Arc::ptr_eq`]), the only
///   equality relation that makes sense for an erased type with no `Eq`
///   bound of its own.
/// - **`Debug`** — a fixed placeholder; the payload's real shape is opaque
///   by design.
/// - **`Serialize`/`Deserialize`** — both fail at the call site with a
///   descriptive error instead of failing to compile. `UiEvent::User` is
///   an in-process-only handoff (a background thread's result, delivered
///   through [`crate::Backend::waker`]) — it never legitimately crosses a
///   JSON boundary (a conformance scenario replay, a plugin wire format),
///   so there is no "right" wire representation to invent. A caller that
///   accidentally serialises a `Vec<UiEvent>` containing one gets a clear
///   error naming the cause instead of a silently-dropped field or a type
///   that doesn't compile for every other, genuinely serialisable variant.
pub struct UserPayload(Arc<dyn Any + Send + Sync>);

impl UserPayload {
    /// Wrap `value` for delivery as `UiEvent::User` — see
    /// [`crate::Backend::waker`] for the intended background-thread usage.
    pub fn new<T: Any + Send + Sync + 'static>(value: T) -> Self {
        Self(Arc::new(value))
    }

    /// Attempt to recover the original value. Returns `None` if `T` doesn't
    /// match the concrete type [`Self::new`] was called with.
    pub fn downcast_ref<T: Any + Send + Sync + 'static>(&self) -> Option<&T> {
        self.0.downcast_ref::<T>()
    }
}

// The raw-`Arc` seam between `UserPayload` and `crate::runtime::UserEventQueue`.
// Gated on exactly the same predicate as `mod runtime` in `lib.rs`, because
// those are its only callers: `from_arc` from `UserEventQueue::drain_into`,
// `into_arc` from each backend's `Backend::waker` closure (tui, gtk, macos,
// win). A default-features build (no backend feature at all) compiles
// `UserPayload` — `UiEvent::User` is unconditional — but not `runtime`, so
// without this gate both methods are dead code and `-D warnings` fails the
// `cargo package` verification build. Keep this cfg in lockstep with
// `lib.rs`'s `mod runtime` gate; a backend added to one must be added to the
// other.
#[cfg(any(
    feature = "tui",
    feature = "gtk",
    all(feature = "macos", target_os = "macos"),
    feature = "win"
))]
impl UserPayload {
    /// Crate-internal constructor for backends draining their own
    /// already-erased staging queue (`crate::runtime::UserEventQueue`)
    /// straight into a `UiEvent::User`.
    pub(crate) fn from_arc(payload: Arc<dyn Any + Send + Sync>) -> Self {
        Self(payload)
    }

    /// Crate-internal inverse of [`Self::from_arc`] — recovers the raw
    /// `Arc` so a `Backend::waker` closure can push it straight into
    /// [`crate::runtime::UserEventQueue`] without re-wrapping.
    pub(crate) fn into_arc(self) -> Arc<dyn Any + Send + Sync> {
        self.0
    }
}

impl fmt::Debug for UserPayload {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("UserPayload").field(&"<opaque>").finish()
    }
}

impl Clone for UserPayload {
    fn clone(&self) -> Self {
        Self(Arc::clone(&self.0))
    }
}

impl PartialEq for UserPayload {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }
}

impl Serialize for UserPayload {
    fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        Err(serde::ser::Error::custom(
            "UiEvent::User carries an opaque Arc<dyn Any> payload and cannot be serialised",
        ))
    }
}

impl<'de> Deserialize<'de> for UserPayload {
    fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Err(serde::de::Error::custom(
            "UiEvent::User cannot be deserialised — it is an in-process-only \
             background-thread wake payload, never a wire value",
        ))
    }
}

// ─── The main event enum ────────────────────────────────────────────────────

/// Everything a user (or platform) can do that an app might care about.
///
/// Produced by [`Backend::poll_events`][crate::Backend::poll_events] every
/// frame; consumed by app dispatch code.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum UiEvent {
    // ── Input ───────────────────────────────────────────────────────────
    /// A declared accelerator fired. The backend matched a
    /// [`KeyBinding`][crate::KeyBinding] to one of the app's registered
    /// accelerators and is reporting the ID.
    Accelerator(crate::AcceleratorId, Modifiers),

    /// A raw key was pressed. Routes to the focused widget. Apps that only
    /// want keybindings should prefer `Accelerator` — the backend handles
    /// match-and-dispatch for them.
    KeyPressed {
        key: Key,
        modifiers: Modifiers,
        repeat: bool,
    },

    /// An IME **committed** the composed text for one character. Routes
    /// to the focused text-input widget, same as [`Self::KeyPressed`].
    ///
    /// This is reserved exclusively for the *output* of an IME
    /// composition sequence (dead-key accents, Japanese/Chinese/Korean
    /// input, emoji picker commit) — text a user produced through
    /// multiple keystrokes/UI interactions that resolve to one commit,
    /// which has no sensible `KeyPressed` translation of its own.
    ///
    /// A future IME backend must not emit both `CharTyped` and
    /// `KeyPressed{Key::Char}` for the same keystroke: real IME
    /// composition consumes the raw keydown while a composition is in
    /// progress (nothing reaches `KeyPressed` for it), and only the
    /// final commit produces `CharTyped`. Emitting both would double-
    /// insert on any consumer that (correctly, per its own doc) listens
    /// to both.
    CharTyped(char),

    // ── Mouse ──────────────────────────────────────────────────────────
    MouseDown {
        widget: Option<WidgetId>,
        button: MouseButton,
        position: Point,
        modifiers: Modifiers,
    },
    MouseUp {
        widget: Option<WidgetId>,
        button: MouseButton,
        position: Point,
    },
    MouseMoved {
        position: Point,
        buttons: ButtonMask,
    },
    /// Optional capability — hover state is a real, likely-future
    /// desktop need (tooltip auto-show, hover highlighting) that has no
    /// substitute mechanism. A backend that never emits this is fully
    /// conformant.
    MouseEntered {
        widget: WidgetId,
    },
    /// See [`Self::MouseEntered`] — same optional-capability status,
    /// same rationale, always emitted/not-emitted as a pair.
    MouseLeft {
        widget: WidgetId,
    },
    DoubleClick {
        widget: Option<WidgetId>,
        position: Point,
    },
    /// Scroll-wheel event. **Routes to the widget under the cursor, not
    /// to the focused widget.** This is the native convention on every
    /// major desktop platform.
    Scroll {
        widget: Option<WidgetId>,
        delta: ScrollDelta,
        position: Point,
    },

    // ── Window ─────────────────────────────────────────────────────────
    WindowResized {
        viewport: Viewport,
    },
    /// Required capability on every windowed (non-TUI) backend —
    /// the app's only hook to observe or veto an OS-level window close
    /// (the "×" button, Alt-F4, window-manager close). Not applicable
    /// to TUI: a terminal has no OS window to close independently of
    /// the process exiting. The app's `Reaction` gates whether the close
    /// proceeds: `Exit` allows it, anything else vetoes it.
    WindowClose,
    WindowFocused(bool),
    /// Optional capability — Win emits this from `WM_DPICHANGED`;
    /// GTK observes the `DrawingArea`'s `notify::scale-factor` signal
    /// and macOS observes `NSWindowDidChangeBackingPropertiesNotification`,
    /// both firing on a live runtime DPI change (monitor move, external
    /// monitor plug/unplug) as well as at startup; TUI is always
    /// `scale == 1.0`, so it never applies there. `crate::runtime::preprocess_event`
    /// forces `EventOutcome::Redraw` for this variant regardless of what
    /// `AppLogic::handle` itself returns, so a repaint (and therefore a
    /// re-measure of any DPI-dependent layout) always follows receipt.
    DpiChanged(f32),

    /// Optional capability — the OS toggled one of the window's tri-state
    /// chrome flags (maximize/restore, fullscreen enter/exit,
    /// minimize/restore) other than through [`Backend::toggle_window_maximize`]
    /// or [`WindowControl::set_fullscreen`][crate::backend::WindowControl::set_fullscreen]
    /// themselves — a window-manager keyboard shortcut, a title-bar
    /// double-click GTK/macOS handle natively, `Cmd+Ctrl+F`, etc. Backends
    /// that wire this connect to their native "state changed" signal
    /// and push this with the window's fresh tri-state snapshot; apps use
    /// it to keep their own "is maximized" UI in sync with state the user
    /// changed outside the app's own controls. Not applicable to TUI: a
    /// terminal has no OS-level maximize/fullscreen/minimize state
    /// distinct from the alt-screen it already occupies.
    WindowStateChanged {
        maximized: bool,
        fullscreen: bool,
        minimized: bool,
    },

    // ── Drops + paste ──────────────────────────────────────────────────
    /// Optional capability — emitted by GTK (`gtk::DropTarget` on the
    /// `DrawingArea`), macOS (`NSDraggingDestination` on `QuadraView`),
    /// and Windows (`WM_DROPFILES`) when the user drops OS files onto
    /// the window. Not applicable to TUI: a terminal has no native
    /// drag-and-drop surface. `position` is in the same native units as
    /// every other pointer event (DIPs for GTK/macOS/Win).
    FilesDropped {
        paths: Vec<PathBuf>,
        position: Point,
    },
    ClipboardPaste(String),

    // ── Deep links / file associations / single-instance forwarding ────
    /// The OS asked this app to open one or more URLs and/or files.
    /// Emitted in two situations that apps handle identically:
    ///
    /// 1. **At startup**, decoded from `argv` (a `myapp://...` URL or a
    ///    document path the OS launched the process with — "open with",
    ///    a registered URL scheme handler, an OAuth callback redirect).
    /// 2. **At runtime**, when [`RunConfig::single_instance`] is enabled
    ///    and a second launch of the same app hands its request to the
    ///    already-running instance instead of starting a new process.
    ///
    /// `urls` and `files` are populated independently — a single launch
    /// can carry either, both, or (rarely) neither. Deliberately `String`
    /// rather than a parsed URL type: every value here is copied verbatim
    /// from whatever the OS handed the process with no validation.
    /// `files` uses `PathBuf` — same convention as [`Self::FilesDropped`].
    ///
    /// Registering as the OS handler for a scheme or extension is a
    /// packaging concern — quadraui does not do this for you. This
    /// variant only covers the runtime half: receiving the event once
    /// the OS has already routed it here.
    ///
    /// Routing: broadcast — there is no widget to hit-test or focus to
    /// route through.
    /// ```text
    /// $ grep -rn 'OpenRequested' ~/src/coord-tui/src ~/src/vimcode/src
    /// (no output — zero hits in both)
    /// ```
    ///
    /// Zero hits means neither consumer references this variant yet, but
    /// the real question for a *new enum variant* is whether either
    /// consumer's existing `match`es over `UiEvent` are exhaustive (no
    /// wildcard arm), since those would need to add one:
    ///
    /// - `vimcode`'s `tui_main/shell_app.rs::handle()` top-level dispatch
    ///   (`match event { UiEvent::KeyPressed { .. } => .., ..,
    ///   _ => Reaction::Continue }`) already ends in a wildcard arm.
    /// - `coord-tui`'s `app/events.rs::dispatch_handle()` top-level
    ///   dispatch (`match &event { UiEvent::KeyPressed { .. } => .., ..,
    ///   _ => {} }`) likewise already ends in a wildcard arm.
    ///
    /// Every other `UiEvent` match in both consumers is either an `if
    /// let` on one specific variant or itself wildcard-terminated. Adding
    /// `OpenRequested` compiles clean against both `develop`-tip
    /// checkouts with no consumer changes required.
    OpenRequested {
        urls: Vec<String>,
        files: Vec<PathBuf>,
    },

    // ── Clipboard copy notification ────────────────────────────────
    /// Text was copied to the clipboard by the TUI runner's built-in
    /// text-selection mechanism (click-drag → Ctrl-C). The payload is
    /// the text that was copied.
    ///
    /// This event is **distinct from [`Self::ClipboardPaste`]**. Paste
    /// means "insert text into the focused input"; `TextCopied` is a
    /// one-way notification that lets apps display a confirmation badge
    /// ("Copied!") without any risk of accidentally inserting text into
    /// an input widget that happens to handle `ClipboardPaste`.
    ///
    /// Routing: broadcast (no widget target — it is not input-focus
    /// routed). Apps that don't need copy confirmation can ignore it.
    TextCopied(String),

    // ── Focus ────────────────────────────────────────────────────────
    /// Keyboard focus moved (or was cleared).
    ///
    /// Emitted by the shared runner pipeline
    /// ([`crate::runtime::preprocess_event`]) whenever
    /// [`crate::focus::FocusManager::focus_next`]/`focus_prev` (driven
    /// by Tab/Shift+Tab) or [`crate::focus::FocusManager::set_focus`]
    /// actually changes [`crate::Backend::focus_manager`]'s
    /// [`crate::focus::FocusManager::focused`] value. `None` means focus
    /// was cleared — no widget focused. A no-op cycle (e.g. Tab in a
    /// single-widget tab order) does not re-fire this event.
    ///
    /// Routing: broadcast — apps read the new value directly off the
    /// payload (or off [`crate::Backend::focus_manager`] at any later
    /// point) rather than this being routed to a specific widget's
    /// handler. Only fires for apps that opt in by returning a
    /// non-empty [`crate::runner::AppLogic::tab_stops`].
    FocusChanged(Option<WidgetId>),

    // ── System theme change ─────────────────────────────────────────────
    /// The OS-level light/dark/accent/high-contrast preference changed
    /// while the app was running — the live counterpart to
    /// [`PlatformServices::system_theme`][crate::PlatformServices::system_theme]'s
    /// poll-on-demand query. Payload is the new value; apps that want the
    /// theme at startup call `system_theme()` once instead of waiting for
    /// this to fire.
    ///
    /// **No backend emits this yet.** Same "declare the gap, don't fake
    /// it" posture as [`Self::WindowStateChanged`] (also zero producers
    /// today): the variant exists so app code and the event vocabulary are
    /// ready before a backend wires the native change notification (GTK's
    /// `Settings::connect_gtk_application_prefer_dark_theme_notify`,
    /// macOS KVO on `effectiveAppearance`, Win's
    /// `WM_SETTINGCHANGE("ImmersiveColorSet")`) into it. TUI has no
    /// equivalent OS notification at all — a terminal can't push, only
    /// answer a query — so it will never emit this variant.
    ///
    /// Routing: broadcast, like [`Self::TextCopied`]/[`Self::FocusChanged`].
    ///
    /// ## Downstream impact (CLAUDE.md rule 8)
    ///
    /// `UiEvent` is **not** `#[non_exhaustive]`, so a consumer that
    /// exhaustively `match`es every variant with no wildcard arm would
    /// fail to compile the moment this variant landed. Blast-radius grep,
    /// per CLAUDE.md's mandatory rule 1 (this covers the new
    /// `PlatformServices::system_theme` method and `SystemTheme` struct
    /// as well as this variant — all three landed together):
    ///
    /// ```text
    /// $ grep -rn 'SystemThemeChanged\|SystemTheme\|system_theme' ~/src/coord-tui/src ~/src/vimcode/src
    /// (no output — zero hits in both)
    /// ```
    ///
    /// Zero hits means neither consumer references any of the three new
    /// items yet, but the real question for a *new enum variant* is
    /// whether either consumer's existing `match`es over `UiEvent` are
    /// exhaustive (no wildcard arm), since those would need to add one:
    ///
    /// - `vimcode`'s `tui_main/shell_app.rs` top-level `UiEvent` dispatch
    ///   (`shell_app.rs:2403,2689`) already ends in a wildcard `_ =>` arm.
    /// - `coord-tui`'s `app/events.rs` top-level `UiEvent` dispatch
    ///   (`events.rs:1390,3973`) likewise already ends in a wildcard
    ///   `_ =>` arm.
    ///
    /// Every other `UiEvent` match in both consumers is either an `if
    /// let` on one specific variant or itself wildcard-terminated. Adding
    /// `SystemThemeChanged` compiles clean against both `develop`-tip
    /// checkouts with no consumer changes required.
    SystemThemeChanged(SystemTheme),

    // ── Display topology change ─────────────────────────────────────────
    /// The set of connected displays changed — a monitor was plugged in,
    /// unplugged, or its resolution/DPI/work-area changed — while the app
    /// was running. No payload: apps that care call
    /// [`PlatformServices::displays`][crate::PlatformServices::displays]
    /// again to get the fresh list, the same "event is a poke, not a
    /// snapshot" shape [`crate::UiEvent::FocusChanged`] uses for a
    /// pointer-sized payload instead of duplicating state that already has
    /// a getter. `DpiChanged` stays the narrower, already-wired live
    /// signal for "this window's own backing scale changed"; this variant
    /// is the broader "the whole display topology moved" one it doesn't
    /// cover (a monitor unplugged behind the window, say, with the
    /// window's own scale unaffected).
    ///
    /// **No backend emits this yet.** Same "declare the gap, don't fake
    /// it" posture as [`Self::SystemThemeChanged`]/[`Self::WindowStateChanged`]
    /// (also zero producers today): the variant exists so app code and the
    /// event vocabulary are ready before a backend wires the native
    /// change notification (GTK's `gdk::Display::monitors`
    /// `items-changed` signal on the returned `gio::ListModel`, macOS's
    /// `NSApplicationDidChangeScreenParametersNotification`, Win's
    /// `WM_DISPLAYCHANGE`) into it. TUI has no equivalent OS notification
    /// — a terminal resize arrives as [`Self::WindowResized`], not a
    /// display-topology change — so it will never emit this variant.
    ///
    /// Routing: broadcast, like [`Self::TextCopied`]/[`Self::FocusChanged`].
    ///
    /// ## Downstream impact (CLAUDE.md rule 8)
    ///
    /// `UiEvent` is **not** `#[non_exhaustive]`, so a consumer that
    /// exhaustively `match`es every variant with no wildcard arm would
    /// fail to compile the moment this variant landed. Blast-radius grep,
    /// per CLAUDE.md's mandatory rule 1 (this covers the new
    /// `PlatformServices::displays`/`cursor_screen_point` methods and the
    /// `Display` struct as well as this variant — all landed together):
    ///
    /// ```text
    /// $ grep -rn 'DisplaysChanged\|PlatformServices::displays\|cursor_screen_point\|backend::Display\b' \
    ///     ~/src/coord-tui/src ~/src/vimcode/src
    /// (no output — zero hits in both)
    /// ```
    /// Zero hits means neither consumer references this variant yet, but
    /// the real question for a *new enum variant* is whether either
    /// consumer's existing `match`es over `UiEvent` are exhaustive
    /// (no wildcard arm). Both top-level `UiEvent` dispatches are large
    /// multi-hundred-line matches that already end in a wildcard `_ =>`
    /// arm. Adding `DisplaysChanged` compiles clean with no consumer
    /// changes required.
    DisplaysChanged,

    // ── Cross-primitive scroll event ──────────────────────────────────
    /// A scrollbar drag or click resolved to a new offset. Generic
    /// over widget type — the `widget` field carries whatever
    /// `WidgetId` the app used when calling
    /// [`crate::DragState::begin`] with
    /// [`crate::DragTarget::ScrollbarY`]. Apps dispatch on `widget`
    /// and apply `new_offset` to the corresponding scroll-state
    /// field (palette `scroll_offset`, tree `scroll_top`, etc.).
    /// Replaces the old per-primitive `ScrollOffsetChanged` variants.
    ScrollOffsetChanged {
        widget: WidgetId,
        new_offset: usize,
    },

    // ── Text selection ────────────────────────────────────────────────
    /// A mouse text-selection drag extended or finalised its range.
    /// Emitted by [`crate::dispatch::dispatch_mouse_drag`] while a
    /// [`crate::DragTarget::TextSelection`] is active.
    ///
    /// `anchor` is the screen position where the drag started (set
    /// once at click-down; does not change during the drag). `focus`
    /// is the current cursor position. Both are in the backend's
    /// native units (TUI: cells; GTK/macOS: pixels).
    ///
    /// The range `anchor → focus` defines what is currently selected —
    /// call [`crate::dispatch::text_selection_line_range`] to convert
    /// the pair to a list of `(row, col_start, col_end)` spans.
    /// The TUI backend applies selection highlights automatically
    /// inside the draw loop; other backends may consume this event to
    /// drive native selection highlight.
    ///
    /// If the user releases without moving (plain click), this event
    /// is never emitted; the app receives a plain `MouseDown + MouseUp`
    /// pair instead.
    TextSelectionChanged {
        region: WidgetId,
        anchor: Point,
        focus: Point,
    },

    // ── Split-tree divider drag ────────────────────────────────────────
    /// A [`crate::SplitTree`] divider drag moved. Emitted by
    /// [`crate::dispatch::dispatch_mouse_drag`] while a
    /// [`crate::DragTarget::SplitDivider`] is active.
    ///
    /// `tree` identifies which tree (apps may host more than one — e.g.
    /// vimcode's editor-group tree and per-group window tree); apps
    /// dispatch on it and apply the update to the corresponding
    /// `SplitTree` state. `split_index` is the pre-order index of the
    /// `SplitTree::Split` node being resized (see
    /// [`crate::SplitTreeDivider::split_index`]). `new_ratio` is the
    /// resolved, already-clamped `0.0..=1.0` ratio ready to feed
    /// directly to [`crate::SplitTree::set_ratio_at_index`].
    SplitDividerDragged {
        tree: WidgetId,
        split_index: usize,
        new_ratio: f32,
    },

    // ── Native menu activation ────────────────────────────────────────
    /// A menu item was activated via a native menu installer
    /// ([`Backend::install_menu_bar`][crate::Backend::install_menu_bar]).
    /// Carries the activated item's `WidgetId` regardless of nesting
    /// depth — submenu structure is transparent to the app.
    ///
    /// The in-window `MenuBar` primitive resolves clicks via
    /// [`crate::MenuBarLayout::hit_test`] / [`crate::MenuBarHit::Item`]
    /// instead; this variant is specifically for system-installed menus
    /// (macOS NSMenu; future Win32 `SetMenu`).
    MenuActivated(WidgetId),

    /// A native right-click context menu (shown via
    /// [`Backend::show_context_menu`][crate::Backend::show_context_menu])
    /// had one of its items activated. Carries the activated item's
    /// `WidgetId`. Distinct from [`Self::MenuActivated`] so apps can
    /// route menu-bar and context-menu activations through different
    /// handlers when needed.
    ContextMenuItemActivated(WidgetId),

    /// A native right-click context menu was dismissed — either after
    /// activation (immediately following the matching
    /// [`Self::ContextMenuItemActivated`]) or by cancel (Escape /
    /// click outside / second right-click). Apps that don't track
    /// open-menu state can ignore this variant.
    ContextMenuDismissed,

    // ── Tray / status-bar icon ──────────────────────────────────────────
    /// The user clicked the app's tray/status-bar icon
    /// ([`crate::backend::TrayService::set_icon`]) with no menu currently
    /// intercepting the click. Carries which mouse button was pressed —
    /// tray icons commonly bind left-click to "show/focus the main
    /// window" and right-click to something else, so apps need the
    /// distinction the way [`Self::MouseDown`] already carries one.
    ///
    /// **Does not fire while a menu is attached** via
    /// [`crate::backend::TrayService::set_menu`] on every backend that
    /// implements one today — clicking (either button) opens the menu
    /// instead, and menu selection arrives as
    /// [`Self::ContextMenuItemActivated`], the same variant a right-click
    /// context menu produces (see each backend's `impl TrayService` doc,
    /// e.g. `macos::tray`'s module doc, for the native platform
    /// behaviour this mirrors). Detach the menu (an empty
    /// [`ContextMenu`][crate::primitives::context_menu::ContextMenu]) to
    /// go back to receiving this variant.
    ///
    /// Routing: broadcast, like [`Self::TextCopied`] — a tray icon has no
    /// `WidgetId` of its own to route through.
    ///
    /// Not applicable to TUI: [`crate::backend::Backend::tray`] is
    /// permanently `None` there (a terminal has no notification-area
    /// concept — see that method's doc), so `TuiBackend` never produces
    /// this variant.
    TrayClicked {
        button: MouseButton,
    },

    // ── System notification activation ──────────────────────────────────
    /// The user activated a system notification sent through
    /// [`crate::backend::PlatformServices::send_notification`] — either
    /// the notification body itself (`action: None`) or one of the
    /// action buttons registered on it via
    /// [`crate::backend::Notification::with_action`] (`action:
    /// Some(id)`, the same `WidgetId` passed to that call).
    ///
    /// `tag` carries [`crate::backend::Notification::tag`]'s value
    /// through unchanged, so an app that fired several tagged
    /// notifications can tell which one this activation belongs to
    /// without inventing its own out-of-band id scheme. `None` when the
    /// firing `Notification` carried no tag.
    ///
    /// **Not every backend can produce this.** Only GTK has a native
    /// click-through channel today — `gio::Notification`'s action/
    /// default-action `GAction`s, wired in `gtk::services` (see that
    /// module's doc). macOS's unbundled `osascript` fallback and Win's
    /// `Shell_NotifyIconW` balloon fallback have no click-through
    /// mechanism to report through and honestly never emit this variant
    /// — see each backend's `send_notification` doc for what a real
    /// implementation there (`UNUserNotificationCenter`, WinRT
    /// `ToastNotificationManager`) would need. TUI (and any other
    /// backend with `BackendCaps::notifications == false`) degrades
    /// notifications to the in-canvas `Toast` primitive instead (see
    /// `compose::notification::notify_or_toast`); a toast's own action
    /// button click resolves through
    /// [`crate::primitives::toast::ToastStackLayout::hit_test`] /
    /// [`crate::primitives::toast::ToastHit`] from an ordinary
    /// `MouseDown`/`MouseUp`, not through this variant.
    ///
    /// Routing: broadcast, like [`Self::TrayClicked`] — a notification
    /// has no `WidgetId` of its own to route through (its *action*
    /// does, carried in the payload instead).
    ///
    /// ## Downstream impact (CLAUDE.md rule 8)
    ///
    /// `UiEvent` is **not** `#[non_exhaustive]`, so a consumer that
    /// exhaustively `match`es every variant with no wildcard arm would
    /// fail to compile the moment this variant landed. Blast-radius grep,
    /// per CLAUDE.md's mandatory rule 1 (this covers the new
    /// `Notification` builder methods and `notify_or_toast` helper as
    /// well as this variant):
    ///
    /// ```text
    /// $ grep -rn 'NotificationActivated\|send_notification\|backend::Notification' \
    ///     ~/src/coord-tui/src ~/src/vimcode/src
    /// (no output — zero hits in both; neither consumer calls
    /// PlatformServices::send_notification or constructs Notification today)
    /// ```
    /// Zero hits means neither consumer references this variant yet, but
    /// the real question for a *new enum variant* is whether either
    /// consumer's existing `match`es over `UiEvent` are exhaustive
    /// (no wildcard arm). Both top-level `UiEvent` dispatches are large
    /// multi-hundred-line matches that already end in a wildcard `_ =>`
    /// arm. Adding `NotificationActivated` compiles clean with no
    /// consumer changes required.
    NotificationActivated {
        tag: Option<String>,
        action: Option<WidgetId>,
    },

    // ── Primitive-specific events bubble up by WidgetId ───────────────
    Tree(WidgetId, TreeEvent),
    List(WidgetId, ListViewEvent),
    Form(WidgetId, FormEvent),
    Palette(WidgetId, PaletteEvent),
    TabBar(WidgetId, TabBarEvent),
    StatusBar(WidgetId, StatusBarEvent),
    ActivityBar(WidgetId, ActivityBarEvent),
    Terminal(WidgetId, TerminalEvent),
    TextDisplay(WidgetId, TextDisplayEvent),
    Chart(WidgetId, ChartEvent),
    DataTable(WidgetId, DataTableEvent),

    // ── Escape hatch ───────────────────────────────────────────────────
    /// Backend-specific event the crate couldn't normalise. Apps ignore
    /// unless they want to special-case a platform.
    BackendNative(BackendNativeEvent),

    // ── Background-thread wake ──────────────────────────────────────────
    /// An app-defined value delivered from a background thread through
    /// [`crate::Backend::waker`].
    ///
    /// `waker()` returns a `Send + Sync` closure any thread can call
    /// with a [`UserPayload`]; the backend wakes its event loop and
    /// delivers the payload as `UiEvent::User` to
    /// [`crate::runner::AppLogic::handle`], the same way any other
    /// event reaches the app.
    ///
    /// Routing: broadcast — there is no widget to hit-test or focus to
    /// route through. Apps downcast the payload via
    /// [`UserPayload::downcast_ref`] against whatever concrete type they
    /// handed to [`UserPayload::new`] on the producing thread.
    User(UserPayload),
}

// ─── Shared constructors ────────────────────────────────────────────────────
//
// Every backend's `events.rs` translates native input into `UiEvent`.
// Only three things are genuinely backend-native: the keysym/keycode → `Key`
// table, the button-number → `MouseButton` map, and the modifier-mask →
// `Modifiers` map. The event *shape* — which fields `MouseDown` carries,
// that `widget` starts `None` pending hit-test, the scroll sign-flip
// convention — is shared across all backends. These free functions are the
// single place that shape lives; backends call them instead of writing the
// `UiEvent::MouseDown { .. }` struct literal themselves.

/// Build a [`UiEvent::MouseDown`]. `widget` always starts `None` — hit-test
/// resolution happens downstream in [`crate::dispatch`], not in the
/// translator.
pub fn mouse_down(button: MouseButton, x: f32, y: f32, modifiers: Modifiers) -> UiEvent {
    UiEvent::MouseDown {
        widget: None,
        button,
        position: Point::new(x, y),
        modifiers,
    }
}

/// Build a [`UiEvent::MouseUp`].
pub fn mouse_up(button: MouseButton, x: f32, y: f32) -> UiEvent {
    UiEvent::MouseUp {
        widget: None,
        button,
        position: Point::new(x, y),
    }
}

/// Build a [`UiEvent::MouseMoved`].
pub fn mouse_moved(x: f32, y: f32, buttons: ButtonMask) -> UiEvent {
    UiEvent::MouseMoved {
        position: Point::new(x, y),
        buttons,
    }
}

/// Build a [`UiEvent::Scroll`], owning the native-to-quadraui sign flip
/// once instead of every backend re-deriving (and re-commenting) it.
///
/// `dy_native_down_positive` is the backend's raw vertical delta using the
/// convention where **positive means scroll-down / content-forward** — GTK
/// `EventControllerScroll`'s `dy`, Cocoa `NSEvent.scrollingDeltaY`, and
/// crossterm's `ScrollUp`/`ScrollDown` (translated to the equivalent -1.0 /
/// +1.0 notch) all use this convention natively. `UiEvent::Scroll::delta`'s
/// convention is the opposite — **positive `y` = up, toward the top of
/// content** — so this negates once, here, rather than in each caller.
///
/// `dx` is passed straight through unnegated: every native backend
/// quadraui supports already agrees with quadraui's positive-x-is-right
/// convention, so there is no flip to own.
///
/// Win-GUI is the one native backend that does *not* follow the
/// positive-down convention on its raw delta (`win::events::win_wheel_to_uievent`'s
/// doc explains why) — its translator does not call this constructor.
pub fn scroll(dx: f32, dy_native_down_positive: f32, x: f32, y: f32) -> UiEvent {
    UiEvent::Scroll {
        widget: None,
        delta: ScrollDelta::new(dx, -dy_native_down_positive),
        position: Point::new(x, y),
    }
}

/// Build a [`UiEvent::WindowResized`].
pub fn window_resized(width: f32, height: f32, scale: f32) -> UiEvent {
    UiEvent::WindowResized {
        viewport: Viewport::new(width, height, scale),
    }
}

/// Build a [`UiEvent::FilesDropped`]. `x`/`y` are the drop
/// position in the backend's native units — already-scaled DIPs for
/// GTK/macOS/Win, matching every other pointer event's convention.
pub fn files_dropped(paths: Vec<PathBuf>, x: f32, y: f32) -> UiEvent {
    UiEvent::FilesDropped {
        paths,
        position: Point::new(x, y),
    }
}

/// Build a [`UiEvent::OpenRequested`] by classifying a flat
/// list of raw OS-provided strings — `argv`, or a decoded
/// `WM_COPYDATA`/single-instance-forwarding payload — into the variant's
/// `urls`/`files` buckets.
///
/// A string containing `"://"` is treated as a URL (`myapp://callback`,
/// `https://example.com/...`); everything else is treated as a
/// filesystem path. This is the same heuristic a shell already applies
/// when it decides whether to hand a bare command-line argument to a
/// URL-scheme handler or open it as a file.
///
/// Not every backend needs this: GTK's `gio::File` arrives
/// pre-classified (`File::path()` vs `File::uri()`) and macOS's Launch
/// Services delegate methods are already split into
/// `application:openURLs:` / `application:openFiles:`, so only Win's
/// plain-string `argv` and `WM_COPYDATA` payload actually call this.
pub fn classify_open_args(args: impl IntoIterator<Item = String>) -> UiEvent {
    let mut urls = Vec::new();
    let mut files = Vec::new();
    for arg in args {
        if arg.contains("://") {
            urls.push(arg);
        } else {
            files.push(PathBuf::from(arg));
        }
    }
    UiEvent::OpenRequested { urls, files }
}

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

    #[test]
    fn downcast_ref_recovers_the_original_type() {
        let payload = UserPayload::new(42_i32);
        assert_eq!(payload.downcast_ref::<i32>(), Some(&42));
        assert_eq!(payload.downcast_ref::<String>(), None);
    }

    #[test]
    fn clone_is_a_shallow_arc_clone_not_a_deep_copy() {
        let payload = UserPayload::new(String::from("hello"));
        let cloned = payload.clone();
        // Both point at the exact same allocation — cloning a `UserPayload`
        // must not require the erased inner type to implement `Clone`.
        assert_eq!(
            cloned.downcast_ref::<String>(),
            payload.downcast_ref::<String>()
        );
        assert_eq!(payload, cloned, "a clone must be `==` to its source");
    }

    #[test]
    fn partial_eq_is_pointer_identity_not_structural() {
        let a = UserPayload::new(1_i32);
        let b = UserPayload::new(1_i32);
        assert_ne!(
            a, b,
            "two payloads with equal contents but distinct allocations must not be equal — \
             there is no generic structural equality for an erased Any"
        );
        let a_clone = a.clone();
        assert_eq!(a, a_clone, "a clone of the same allocation must be equal");
    }

    #[test]
    fn debug_never_panics_and_never_exposes_raw_content() {
        let payload = UserPayload::new("do not leak me".to_string());
        let rendered = format!("{payload:?}");
        assert!(
            !rendered.contains("do not leak me"),
            "Debug must print a placeholder, not the erased payload's contents"
        );
    }

    #[test]
    fn serialize_fails_with_a_descriptive_error_instead_of_panicking() {
        let payload = UserPayload::new(1_i32);
        let err = serde_json::to_string(&payload)
            .expect_err("UiEvent::User payloads must not be serialisable");
        assert!(err.to_string().contains("cannot be serialised"));
    }

    #[test]
    fn deserialize_fails_with_a_descriptive_error_instead_of_panicking() {
        let err = serde_json::from_str::<UserPayload>("null")
            .expect_err("UiEvent::User must never be constructible from wire data");
        assert!(err.to_string().contains("cannot be deserialised"));
    }

    /// A `UserPayload` must round-trip through a `UiEvent::User` and back
    /// out through the crate's own `Clone`/`PartialEq`/`Debug` derives.
    #[test]
    fn user_event_clones_and_compares_via_the_wrapped_payload() {
        let ev = UiEvent::User(UserPayload::new(7_i32));
        let cloned = ev.clone();
        assert_eq!(ev, cloned);
        match &cloned {
            UiEvent::User(payload) => assert_eq!(payload.downcast_ref::<i32>(), Some(&7)),
            other => panic!("expected UiEvent::User, got {other:?}"),
        }
    }
}

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

    #[test]
    fn mouse_down_builds_expected_shape() {
        let mods = Modifiers {
            ctrl: true,
            ..Default::default()
        };
        let ev = mouse_down(MouseButton::Left, 1.0, 2.0, mods);
        match ev {
            UiEvent::MouseDown {
                widget,
                button,
                position,
                modifiers,
            } => {
                assert!(widget.is_none());
                assert_eq!(button, MouseButton::Left);
                assert_eq!(position, Point::new(1.0, 2.0));
                assert!(modifiers.ctrl);
            }
            other => panic!("expected MouseDown, got {other:?}"),
        }
    }

    #[test]
    fn mouse_up_builds_expected_shape() {
        let ev = mouse_up(MouseButton::Right, 3.0, 4.0);
        assert_eq!(
            ev,
            UiEvent::MouseUp {
                widget: None,
                button: MouseButton::Right,
                position: Point::new(3.0, 4.0),
            }
        );
    }

    #[test]
    fn mouse_moved_builds_expected_shape() {
        let buttons = ButtonMask {
            left: true,
            ..Default::default()
        };
        let ev = mouse_moved(5.0, 6.0, buttons);
        assert_eq!(
            ev,
            UiEvent::MouseMoved {
                position: Point::new(5.0, 6.0),
                buttons,
            }
        );
    }

    #[test]
    fn scroll_negates_native_down_positive_dy() {
        // Native wheel-down (dy = +1) becomes quadraui's "not up" (-1).
        let ev = scroll(0.0, 1.0, 10.0, 20.0);
        assert_eq!(
            ev,
            UiEvent::Scroll {
                widget: None,
                delta: ScrollDelta::new(0.0, -1.0),
                position: Point::new(10.0, 20.0),
            }
        );
    }

    #[test]
    fn scroll_leaves_dx_unflipped() {
        let ev = scroll(2.5, 0.0, 0.0, 0.0);
        match ev {
            UiEvent::Scroll { delta, .. } => {
                assert_eq!(delta.x, 2.5);
                assert_eq!(delta.y, 0.0);
            }
            other => panic!("expected Scroll, got {other:?}"),
        }
    }

    #[test]
    fn window_resized_builds_expected_shape() {
        let ev = window_resized(1920.0, 1080.0, 2.0);
        assert_eq!(
            ev,
            UiEvent::WindowResized {
                viewport: Viewport::new(1920.0, 1080.0, 2.0),
            }
        );
    }

    #[test]
    fn classify_open_args_splits_urls_from_files() {
        let ev = classify_open_args(vec![
            "myapp://callback?code=abc".to_string(),
            "/home/user/report.pdf".to_string(),
            "https://example.com/oauth".to_string(),
            "relative/path.txt".to_string(),
        ]);
        assert_eq!(
            ev,
            UiEvent::OpenRequested {
                urls: vec![
                    "myapp://callback?code=abc".to_string(),
                    "https://example.com/oauth".to_string(),
                ],
                files: vec![
                    PathBuf::from("/home/user/report.pdf"),
                    PathBuf::from("relative/path.txt"),
                ],
            }
        );
    }

    #[test]
    fn classify_open_args_handles_empty_input() {
        let ev = classify_open_args(Vec::<String>::new());
        assert_eq!(
            ev,
            UiEvent::OpenRequested {
                urls: vec![],
                files: vec![],
            }
        );
    }
}