noesis_runtime 0.12.1

Rust bindings for the Noesis GUI Native SDK: load XAML UI, drive the view and renderer, and write custom controls in Rust. Renderer-agnostic; Bevy integration lives in noesis_bevy.
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
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
//! Subscribe Rust callbacks to Noesis routed events.
//!
//! Start with [`subscribe_click`] for `BaseButton::Click` and
//! [`subscribe_keydown`] for `UIElement::KeyDown`. For any other routed
//! event reach for the generic [`subscribe_event`] (typed by [`RoutedEvent`])
//! or its `&str` escape hatch [`subscribe_event_by_name`]. Non-routed
//! lifecycle notifications (`Loaded`, `IsEnabledChanged`, and friends) go
//! through [`subscribe_lifecycle`]. Every subscription returns an RAII token:
//! a heap-allocated handler that owns its registration and holds a `+1` ref on
//! the source element, so dropping the token unsubscribes.
//!
//! # Threading
//!
//! Click callbacks fire from inside Noesis's input pump (typically
//! `IView::MouseButtonUp` or `IView::Update`), on whatever thread is driving
//! the view. The callback signature has no `Send` bound at the FFI level;
//! the safe wrapper enforces it on the Rust side via the trait. Keep work
//! in the callback small: push to a queue / channel and process from a
//! regular Bevy system step if you need anything heavier than a flag flip.
//!
//! # Lifetime
//!
//! [`ClickSubscription`] is RAII: while alive, the registered handler stays
//! on the button's `Click` event. Drop the subscription to unsubscribe.
//! The subscription holds a `+1` ref on the button so the handler list
//! stays valid even if the only other reference to the element was the
//! [`crate::view::FrameworkElement`] you used to subscribe.
//!
//! Every subscription type here may be dropped from *inside its own callback*:
//! the C++ handler owns the boxed closure and defers its own destruction until
//! the callback frame unwinds, so unsubscribing re-entrantly is safe (no
//! use-after-free of the handler object or the boxed closure).

#![allow(unsafe_op_in_unsafe_fn)] // thin FFI surface; explicit blocks add noise

use core::marker::PhantomData;
use core::ptr::NonNull;
use std::ffi::{CString, c_void};

use crate::ffi::{
    noesis_element_datacontext_get_u64, noesis_event_args_kind, noesis_key_args_key,
    noesis_mouse_args_position, noesis_mouse_button_args_button, noesis_mouse_wheel_args_delta,
    noesis_routed_args_source, noesis_routed_events_add_copying_handler,
    noesis_routed_events_add_pasting_handler, noesis_routed_events_do_drag_drop,
    noesis_routed_events_drag_data, noesis_routed_events_drag_effects,
    noesis_routed_events_drag_position, noesis_routed_events_drag_set_effects,
    noesis_routed_events_focus_new, noesis_routed_events_focus_old,
    noesis_routed_events_manip_cumulative, noesis_routed_events_manip_delta,
    noesis_routed_events_manip_is_inertial, noesis_routed_events_manip_origin,
    noesis_routed_events_manip_velocities, noesis_routed_events_remove_data_object_handler,
    noesis_size_changed_args_new_size, noesis_subscribe_click, noesis_subscribe_event,
    noesis_subscribe_keydown, noesis_subscribe_lifecycle, noesis_subscribe_selection_changed,
    noesis_text_args_ch, noesis_unsubscribe_click, noesis_unsubscribe_event,
    noesis_unsubscribe_keydown, noesis_unsubscribe_lifecycle, noesis_unsubscribe_selection_changed,
};
use crate::view::{FrameworkElement, Key, MouseButton};

/// Free trampoline for a donated `Box<Box<dyn Handler>>` subscription box (`T`
/// is the inner `Box<dyn Handler>`). Every subscription in this module donates
/// its box to the C++ handler along with one of these; the handler calls it
/// exactly once when it is actually destroyed (deferred past any in-flight
/// callback), so the box is never freed while a callback's borrow is live.
///
/// SAFETY: `userdata` is a `Box<T>` produced by `Box::into_raw` in the matching
/// subscribe, and the C++ side invokes this at most once.
unsafe extern "C" fn free_donated<T>(userdata: *mut c_void) {
    crate::panic_guard::guard(|| {
        if userdata.is_null() {
            return;
        }
        // SAFETY: reclaim the exact box leaked in subscribe; runs once.
        drop(unsafe { Box::from_raw(userdata.cast::<T>()) });
    })
}

/// Arg-shape discriminant mirroring the C++ `DmArgKind` in `noesis_events.cpp`
/// (exposed by [`noesis_event_args_kind`]). This is the authoritative event
/// classifier: the typed accessors deliberately share sentinels, so the `is_*`
/// checks key on the discriminant rather than probing accessors. Keep in sync
/// with the C++ enum.
mod arg_kind {
    pub const MOUSE_WHEEL: i32 = 3;
}

/// Rust-side click handler. Implementors receive a single `()` notification
/// per fired click; if you need the sender or event args, subscribe through
/// the generic [`subscribe_event`] / [`RoutedEventHandler`] instead.
///
/// The `Send + 'static` bounds let the handler live inside a Bevy
/// `Resource` or be moved onto the render thread.
/// Takes `&self` (re-entrant: a handler may re-raise the subscribed event on
/// the same element via [`crate::reflection::raise_event`], re-entering this
/// same box; use interior mutability for handler state).
pub trait ClickHandler: Send + 'static {
    fn on_click(&self);
}

impl<F: Fn() + Send + 'static> ClickHandler for F {
    fn on_click(&self) {
        self();
    }
}

/// SAFETY: `userdata` must be a pointer produced by [`subscribe_click`] and
/// still alive (the [`ClickSubscription`] hasn't been dropped).
unsafe extern "C" fn click_trampoline(userdata: *mut c_void) {
    crate::panic_guard::guard(|| {
        // Shared `&`: re-entrant handler box (see `ClickHandler`).
        let handler = &*userdata.cast::<Box<dyn ClickHandler>>();
        handler.on_click();
    })
}

/// RAII subscription token. Drop to unsubscribe and free the boxed handler.
///
/// Holds a `+1` ref on the underlying button (managed C++-side); dropping
/// this releases that ref and removes the handler from the routed-event
/// list. Drop before [`crate::shutdown`] like every other owning handle in
/// this crate.
#[must_use = "dropping the subscription immediately unsubscribes the handler"]
pub struct ClickSubscription {
    token: NonNull<c_void>,
}

// SAFETY: Send-only (NOT Sync); see the crate-level "Thread affinity" docs.
unsafe impl Send for ClickSubscription {}

impl Drop for ClickSubscription {
    fn drop(&mut self) {
        // SAFETY: token produced by subscribe_click. Unsubscribe frees the
        // donated handler box exactly once (deferred if we are dropping from
        // inside the callback). Safe to drop re-entrantly.
        unsafe { noesis_unsubscribe_click(self.token.as_ptr()) }
    }
}

/// Subscribe `handler` to `BaseButton::Click` on `element`. Returns `None`
/// if the element is not castable to `BaseButton` (e.g. it's a plain
/// `ContentControl` or a `UserControl` whose root isn't a button).
///
/// The returned [`ClickSubscription`] keeps the handler installed for as
/// long as it lives; drop it (or replace it) to unsubscribe. Dropping it from
/// inside the click callback is safe (see the module "Lifetime" docs).
pub fn subscribe_click<H: ClickHandler>(
    element: &FrameworkElement,
    handler: H,
) -> Option<ClickSubscription> {
    // Double-Box gives a stable thin pointer for the C ABI userdata, same
    // pattern as the providers.
    let outer: Box<Box<dyn ClickHandler>> = Box::new(Box::new(handler));
    let userdata = Box::into_raw(outer);

    // SAFETY: trampoline is `extern "C"`; userdata is freshly leaked and donated
    // to the C++ handler (freed via the free trampoline when it is destroyed);
    // the element pointer is borrowed for the call duration only.
    let token = unsafe {
        noesis_subscribe_click(
            element.raw(),
            click_trampoline,
            userdata.cast(),
            free_donated::<Box<dyn ClickHandler>>,
        )
    };

    if let Some(token) = NonNull::new(token) {
        Some(ClickSubscription { token })
    } else {
        // Subscription failed (e.g. element wasn't a button); C++ took no
        // ownership. Free the userdata we leaked above so we don't leak it.
        // SAFETY: userdata came from Box::into_raw moments ago; nothing else
        // ever saw the pointer.
        unsafe { drop(Box::from_raw(userdata)) };
        None
    }
}

/// Rust-side handler for `Selector::SelectionChanged`. Receives a single `()`
/// notification each time the selection moves; the authoritative selection is
/// read back afterwards (through `ICollectionView` currency or the bound model),
/// so this handler only signals "re-poll".
///
/// The `Send + 'static` bounds let the handler live inside a Bevy `Resource` or
/// be moved onto the render thread. Takes `&self` (re-entrant: a handler that
/// mutates the selection re-enters this same box; use interior mutability for
/// handler state).
pub trait SelectionChangedHandler: Send + 'static {
    fn on_selection_changed(&self);
}

impl<F: Fn() + Send + 'static> SelectionChangedHandler for F {
    fn on_selection_changed(&self) {
        self();
    }
}

/// SAFETY: `userdata` must be a pointer produced by
/// [`subscribe_selection_changed`] and still alive (the
/// [`SelectionChangedSubscription`] hasn't been dropped).
unsafe extern "C" fn selection_changed_trampoline(userdata: *mut c_void) {
    crate::panic_guard::guard(|| {
        // Shared `&`: re-entrant handler box (see `SelectionChangedHandler`).
        let handler = &*userdata.cast::<Box<dyn SelectionChangedHandler>>();
        handler.on_selection_changed();
    })
}

/// RAII subscription token for [`subscribe_selection_changed`]. Drop to
/// unsubscribe and free the boxed handler. Mirrors [`ClickSubscription`].
#[must_use = "dropping the subscription immediately unsubscribes the handler"]
pub struct SelectionChangedSubscription {
    token: NonNull<c_void>,
}

// SAFETY: Send-only (NOT Sync); see the crate-level "Thread affinity" docs.
unsafe impl Send for SelectionChangedSubscription {}

impl Drop for SelectionChangedSubscription {
    fn drop(&mut self) {
        // SAFETY: token produced by subscribe_selection_changed; unsubscribe
        // frees the donated box exactly once (deferred if dropping from inside
        // the callback).
        unsafe { noesis_unsubscribe_selection_changed(self.token.as_ptr()) }
    }
}

/// Subscribe `handler` to `Selector::SelectionChanged` on `element` (a
/// `Selector`: `ListBox` / `ListView` / `ComboBox` / `TabControl` / ...).
/// Returns `None` if `element` is not a `Selector`.
///
/// The returned [`SelectionChangedSubscription`] keeps the handler installed for
/// as long as it lives; drop it (or replace it) to unsubscribe. This is the
/// push counterpart of polling the selection each frame: pair it with
/// `ICollectionView` currency / the bound `Selected` marker to learn *what*
/// changed. Dropping the subscription from inside the callback is safe (see the
/// module "Lifetime" docs).
pub fn subscribe_selection_changed<H: SelectionChangedHandler>(
    element: &FrameworkElement,
    handler: H,
) -> Option<SelectionChangedSubscription> {
    // Double-Box: stable thin pointer for the C ABI userdata.
    let outer: Box<Box<dyn SelectionChangedHandler>> = Box::new(Box::new(handler));
    let userdata = Box::into_raw(outer);

    // SAFETY: trampoline is `extern "C"`; userdata is freshly leaked and donated
    // to the C++ handler; the element pointer is borrowed for the call only.
    let token = unsafe {
        noesis_subscribe_selection_changed(
            element.raw(),
            selection_changed_trampoline,
            userdata.cast(),
            free_donated::<Box<dyn SelectionChangedHandler>>,
        )
    };

    if let Some(token) = NonNull::new(token) {
        Some(SelectionChangedSubscription { token })
    } else {
        // Subscription failed (not a Selector); C++ took no ownership. Free the
        // leaked userdata.
        // SAFETY: userdata came from Box::into_raw moments ago; nothing else
        // ever saw the pointer.
        unsafe { drop(Box::from_raw(userdata)) };
        None
    }
}

/// Rust-side keydown handler. Receives the pressed key plus a writable flag;
/// setting the flag to `true` marks the routed event handled, stopping
/// propagation (e.g. prevents the backtick keystroke that opens the console
/// from also being typed into a focused `TextBox`).
///
/// The `Send + 'static` bounds let the handler live inside a Bevy
/// `Resource` or be moved onto the render thread.
pub trait KeyDownHandler: Send + 'static {
    /// Called once per `KeyDown` event on the subscribed element. Return
    /// value: `true` to mark the routed event handled, `false` to let it
    /// continue propagating.
    ///
    /// Takes `&self` (re-entrant per [`ClickHandler`]; use interior mutability
    /// for handler state).
    fn on_keydown(&self, key: Key) -> bool;
}

impl<F: Fn(Key) -> bool + Send + 'static> KeyDownHandler for F {
    fn on_keydown(&self, key: Key) -> bool {
        self(key)
    }
}

/// SAFETY: `userdata` must be a pointer produced by [`subscribe_keydown`]
/// and still alive (the [`KeyDownSubscription`] hasn't been dropped).
/// `out_handled` must be a non-null pointer to a writable bool (the C++
/// shim guarantees this).
unsafe extern "C" fn keydown_trampoline(userdata: *mut c_void, key: i32, out_handled: *mut bool) {
    crate::panic_guard::guard(|| {
        // Shared `&`: re-entrant handler box (see `KeyDownHandler`).
        let handler = &*userdata.cast::<Box<dyn KeyDownHandler>>();
        // Best-effort map of the raw ordinal back to our safe `Key` mirror.
        // Anything outside the mirrored set arrives as `Key::None`; callers
        // can still observe the event and choose to ignore unmapped keys.
        let mapped = key_from_raw(key);
        let handled = handler.on_keydown(mapped);
        if !out_handled.is_null() {
            *out_handled = handled;
        }
    })
}

/// Convert a raw `Noesis::Key` ordinal back into the safe [`Key`] mirror.
/// Unmapped ordinals collapse to [`Key::None`]; the caller's handler can
/// still match on the value but won't be able to distinguish *which*
/// unmapped key fired. Add variants to [`Key`] (and the C++ `static_assert`s
/// in `noesis_view.cpp`) when a missing key earns it.
fn key_from_raw(raw: i32) -> Key {
    // Match table rather than transmute: transmute would be UB for an ordinal
    // outside the declared variants. Order mirrors the `Key` enum in src/view.rs.
    match raw {
        0 => Key::None,
        2 => Key::Back,
        3 => Key::Tab,
        6 => Key::Return,
        7 => Key::Pause,
        8 => Key::CapsLock,
        13 => Key::Escape,
        18 => Key::Space,
        19 => Key::PageUp,
        20 => Key::PageDown,
        21 => Key::End,
        22 => Key::Home,
        23 => Key::Left,
        24 => Key::Up,
        25 => Key::Right,
        26 => Key::Down,
        30 => Key::PrintScreen,
        31 => Key::Insert,
        32 => Key::Delete,
        33 => Key::Help,
        34..=43 => match raw {
            34 => Key::D0,
            35 => Key::D1,
            36 => Key::D2,
            37 => Key::D3,
            38 => Key::D4,
            39 => Key::D5,
            40 => Key::D6,
            41 => Key::D7,
            42 => Key::D8,
            43 => Key::D9,
            _ => Key::None,
        },
        44..=69 => match raw {
            44 => Key::A,
            45 => Key::B,
            46 => Key::C,
            47 => Key::D,
            48 => Key::E,
            49 => Key::F,
            50 => Key::G,
            51 => Key::H,
            52 => Key::I,
            53 => Key::J,
            54 => Key::K,
            55 => Key::L,
            56 => Key::M,
            57 => Key::N,
            58 => Key::O,
            59 => Key::P,
            60 => Key::Q,
            61 => Key::R,
            62 => Key::S,
            63 => Key::T,
            64 => Key::U,
            65 => Key::V,
            66 => Key::W,
            67 => Key::X,
            68 => Key::Y,
            69 => Key::Z,
            _ => Key::None,
        },
        70 => Key::LWin,
        71 => Key::RWin,
        72 => Key::Apps,
        74..=83 => match raw {
            74 => Key::NumPad0,
            75 => Key::NumPad1,
            76 => Key::NumPad2,
            77 => Key::NumPad3,
            78 => Key::NumPad4,
            79 => Key::NumPad5,
            80 => Key::NumPad6,
            81 => Key::NumPad7,
            82 => Key::NumPad8,
            83 => Key::NumPad9,
            _ => Key::None,
        },
        84 => Key::Multiply,
        85 => Key::Add,
        87 => Key::Subtract,
        88 => Key::Decimal,
        89 => Key::Divide,
        90..=113 => match raw {
            90 => Key::F1,
            91 => Key::F2,
            92 => Key::F3,
            93 => Key::F4,
            94 => Key::F5,
            95 => Key::F6,
            96 => Key::F7,
            97 => Key::F8,
            98 => Key::F9,
            99 => Key::F10,
            100 => Key::F11,
            101 => Key::F12,
            102 => Key::F13,
            103 => Key::F14,
            104 => Key::F15,
            105 => Key::F16,
            106 => Key::F17,
            107 => Key::F18,
            108 => Key::F19,
            109 => Key::F20,
            110 => Key::F21,
            111 => Key::F22,
            112 => Key::F23,
            113 => Key::F24,
            _ => Key::None,
        },
        114 => Key::NumLock,
        115 => Key::ScrollLock,
        116 => Key::LeftShift,
        117 => Key::RightShift,
        118 => Key::LeftCtrl,
        119 => Key::RightCtrl,
        120 => Key::LeftAlt,
        121 => Key::RightAlt,
        140 => Key::OemSemicolon,
        141 => Key::OemPlus,
        142 => Key::OemComma,
        143 => Key::OemMinus,
        144 => Key::OemPeriod,
        145 => Key::OemSlash,
        146 => Key::OemTilde,
        149 => Key::OemOpenBrackets,
        150 => Key::OemPipe,
        151 => Key::OemCloseBrackets,
        152 => Key::OemQuotes,
        175 => Key::GamepadLeft,
        176 => Key::GamepadUp,
        177 => Key::GamepadRight,
        178 => Key::GamepadDown,
        179 => Key::GamepadAccept,
        180 => Key::GamepadCancel,
        181 => Key::GamepadMenu,
        182 => Key::GamepadView,
        183 => Key::GamepadPageUp,
        184 => Key::GamepadPageDown,
        185 => Key::GamepadPageLeft,
        186 => Key::GamepadPageRight,
        187 => Key::GamepadContext1,
        188 => Key::GamepadContext2,
        189 => Key::GamepadContext3,
        190 => Key::GamepadContext4,
        _ => Key::None,
    }
}

/// RAII subscription token for [`subscribe_keydown`]. Drop to unsubscribe
/// and free the boxed handler. Mirrors [`ClickSubscription`].
#[must_use = "dropping the subscription immediately unsubscribes the handler"]
pub struct KeyDownSubscription {
    token: NonNull<c_void>,
}

// SAFETY: Send-only (NOT Sync); see the crate-level "Thread affinity" docs.
unsafe impl Send for KeyDownSubscription {}

impl Drop for KeyDownSubscription {
    fn drop(&mut self) {
        // SAFETY: token produced by subscribe_keydown; unsubscribe frees the
        // donated box exactly once (deferred if dropping from inside the
        // callback).
        unsafe { noesis_unsubscribe_keydown(self.token.as_ptr()) }
    }
}

/// Subscribe `handler` to `UIElement::KeyDown` on `element`. Returns
/// `None` if the element is not a `UIElement` (rare: essentially every
/// visual element is, but the cast is included so callers don't have to
/// trust the FFI blindly).
///
/// The returned [`KeyDownSubscription`] keeps the handler installed for
/// as long as it lives; drop it (or replace it) to unsubscribe.
///
/// Setting the handler's return value to `true` marks the routed event
/// handled, useful for swallowing the backtick that opens the console
/// so it doesn't get typed into a focused `TextBox`. Dropping the subscription
/// from inside the callback is safe (see the module "Lifetime" docs).
pub fn subscribe_keydown<H: KeyDownHandler>(
    element: &FrameworkElement,
    handler: H,
) -> Option<KeyDownSubscription> {
    let outer: Box<Box<dyn KeyDownHandler>> = Box::new(Box::new(handler));
    let userdata = Box::into_raw(outer);

    // SAFETY: trampoline is `extern "C"`; userdata is freshly leaked and donated
    // to the C++ handler; the element pointer is borrowed for the call only.
    let token = unsafe {
        noesis_subscribe_keydown(
            element.raw(),
            keydown_trampoline,
            userdata.cast(),
            free_donated::<Box<dyn KeyDownHandler>>,
        )
    };

    if let Some(token) = NonNull::new(token) {
        Some(KeyDownSubscription { token })
    } else {
        // Subscription failed (e.g. element wasn't a UIElement); C++ took no
        // ownership. Free the userdata we leaked above so we don't leak it.
        // SAFETY: userdata came from Box::into_raw moments ago; nothing
        // else ever saw the pointer.
        unsafe { drop(Box::from_raw(userdata)) };
        None
    }
}

/// Borrowed view over a routed event's arguments, handed to a
/// [`RoutedEventHandler`] **by reference** for the duration of one callback.
/// Backed by the opaque C++ `args` pointer; the typed accessors read whichever
/// concrete arg struct actually fired (a generic callback can probe several and
/// act on the one that returns `Some`).
///
/// The handler receives `&EventArgs`, never an owned value. The underlying C++
/// args live on the stack of the Noesis input pump and are valid only while the
/// callback runs; do not stash the borrow or the `source_ptr` beyond the call.
/// (The type deliberately carries no lifetime parameter: a generic-lifetime
/// arg type defeats closure HRTB inference, so the borrow is expressed through
/// the `&EventArgs` the handler is handed instead.)
pub struct EventArgs {
    raw: *const c_void,
    _not_send: PhantomData<*const c_void>,
}

impl EventArgs {
    /// Wrap a borrowed live-args pointer (the opaque handle a
    /// [`RoutedEventHandler`] receives) in an [`EventArgs`] view. Hidden from
    /// the public docs: it exists so test harnesses and advanced callers that
    /// dispatch through a custom C trampoline can reuse the typed accessors.
    ///
    /// # Safety
    ///
    /// `raw` must be a valid args handle produced by the C++ shim and alive for
    /// the lifetime of the returned value (i.e. only for the duration of the
    /// callback that handed it over). The returned `EventArgs` must not outlive
    /// that callback.
    #[doc(hidden)]
    pub unsafe fn from_raw(raw: *const c_void) -> Self {
        EventArgs {
            raw,
            _not_send: PhantomData,
        }
    }

    /// Pointer position in the source element's coordinate space, for mouse,
    /// mouse-button and mouse-wheel events. `None` for other event kinds.
    pub fn position(&self) -> Option<(f32, f32)> {
        let mut x = 0.0f32;
        let mut y = 0.0f32;
        // SAFETY: `raw` is the opaque handle the trampoline received; the
        // accessor validates the arg kind and writes only on a match.
        let ok = unsafe { noesis_mouse_args_position(self.raw, &mut x, &mut y) };
        ok.then_some((x, y))
    }

    /// Changed mouse button for a mouse-button event; `None` otherwise.
    pub fn mouse_button(&self) -> Option<MouseButton> {
        // SAFETY: opaque handle; accessor returns -1 unless it's a button event.
        let raw = unsafe { noesis_mouse_button_args_button(self.raw) };
        match raw {
            0 => Some(MouseButton::Left),
            1 => Some(MouseButton::Right),
            2 => Some(MouseButton::Middle),
            3 => Some(MouseButton::XButton1),
            4 => Some(MouseButton::XButton2),
            _ => None,
        }
    }

    /// Wheel rotation delta for a mouse-wheel event (signed, ~120 per notch).
    /// `None` for non-wheel events (including plain `MouseMove`, which also
    /// carries a position). Classification is exact: it reads the event's
    /// arg-kind discriminant rather than probing the 0-delta sentinel, so a
    /// zero-scroll wheel event still yields `Some(0)` and a mouse-move yields
    /// `None`.
    pub fn wheel_delta(&self) -> Option<i32> {
        if !self.is_wheel() {
            return None;
        }
        // SAFETY: opaque handle; accessor returns 0 unless it's a wheel event.
        Some(unsafe { noesis_mouse_wheel_args_delta(self.raw) })
    }

    /// The event's arg-shape discriminant (see [`arg_kind`]), or `-1` if the
    /// handle is null. The authoritative event classifier.
    fn kind(&self) -> i32 {
        // SAFETY: opaque handle; the accessor reads the carried discriminant.
        unsafe { noesis_event_args_kind(self.raw) }
    }

    /// Whether the live args are a mouse-wheel event, keyed on the exact arg-kind
    /// discriminant (not the ambiguous position/button/0-delta heuristics).
    fn is_wheel(&self) -> bool {
        self.kind() == arg_kind::MOUSE_WHEEL
    }

    /// Pressed/released key for a key event, mapped to the safe [`Key`] mirror.
    /// `None` for non-key events. Keys outside the mirrored set arrive as
    /// `Some(Key::None)`.
    pub fn key(&self) -> Option<Key> {
        // SAFETY: opaque handle; accessor returns -1 unless it's a key event.
        let raw = unsafe { noesis_key_args_key(self.raw) };
        (raw >= 0).then(|| key_from_raw(raw))
    }

    /// Input character (UTF-32 code point) for a `TextInput` event; `None`
    /// otherwise.
    pub fn text_char(&self) -> Option<char> {
        // SAFETY: opaque handle; accessor returns -1 unless it's text input.
        let raw = unsafe { noesis_text_args_ch(self.raw) };
        if raw < 0 {
            return None;
        }
        char::from_u32(raw as u32)
    }

    /// New size for a `SizeChanged` event (DIPs); `None` otherwise.
    pub fn new_size(&self) -> Option<(f32, f32)> {
        let mut w = 0.0f32;
        let mut h = 0.0f32;
        // SAFETY: opaque handle; accessor validates the kind and writes on match.
        let ok = unsafe { noesis_size_changed_args_new_size(self.raw, &mut w, &mut h) };
        ok.then_some((w, h))
    }

    /// Borrowed raw pointer to the event's originating element
    /// (`RoutedEventArgs::source`). `None` if there is no source.
    ///
    /// The pointer is NOT reference-counted and is valid only for the callback
    /// duration; do not wrap it in a [`FrameworkElement`] (that would
    /// over-release) and do not let it escape the handler.
    pub fn source_ptr(&self) -> Option<*mut c_void> {
        // SAFETY: opaque handle; returns a borrowed pointer or null.
        let p = unsafe { noesis_routed_args_source(self.raw) };
        (!p.is_null()).then_some(p)
    }

    /// Read a `u64` field named `prop_name` off the (inherited) `DataContext` of
    /// this event's originating element (`RoutedEventArgs::source`). This is the
    /// per-row identity hook for templated list rows: a handler subscribed once
    /// on the `ItemsControl` recovers the clicked row's stable id (e.g. a Bevy
    /// `Entity`'s bits stashed via the hidden `__entity` field) straight from the
    /// event source: no `x:Name`, no per-row subscription, no borrowed pointer
    /// kept past the callback.
    ///
    /// Returns `None` if the event carries no source, the source is not a
    /// `FrameworkElement`, it has no `DataContext`, or that context exposes no
    /// `u64` field of that name. See
    /// [`FrameworkElement::data_context_u64`](crate::view::FrameworkElement::data_context_u64)
    /// for the field-resolution rules.
    ///
    /// # Panics
    ///
    /// Panics if `prop_name` contains an interior NUL byte.
    #[must_use]
    pub fn source_data_context_u64(&self, prop_name: &str) -> Option<u64> {
        let source = self.source_ptr()?;
        let c = CString::new(prop_name).expect("property name contained interior NUL");
        let mut out: u64 = 0;
        // SAFETY: `source` is the borrowed live event source for the callback
        // duration; the C side borrows its DataContext and writes `out` only on a
        // hit. We never retain `source` past this call.
        let ok = unsafe { noesis_element_datacontext_get_u64(source, c.as_ptr(), &mut out) };
        ok.then_some(out)
    }

    /// Borrowed pointer to the element that previously had focus
    /// (`KeyboardFocusChangedEventArgs::oldFocus`), for the `GotKeyboardFocus` /
    /// `LostKeyboardFocus` events (and their `Preview*` variants). `None` for
    /// other event kinds, or when there was no previously-focused element.
    ///
    /// Not reference-counted; valid only for the callback duration (same
    /// contract as [`source_ptr`](Self::source_ptr)).
    pub fn focus_old_ptr(&self) -> Option<*mut c_void> {
        // SAFETY: opaque handle; returns a borrowed pointer or null.
        let p = unsafe { noesis_routed_events_focus_old(self.raw) };
        (!p.is_null()).then_some(p)
    }

    /// Borrowed pointer to the element focus moved to
    /// (`KeyboardFocusChangedEventArgs::newFocus`), for the keyboard-focus
    /// events. `None` for other kinds / when there is no new focus. Not
    /// reference-counted; valid only for the callback duration.
    pub fn focus_new_ptr(&self) -> Option<*mut c_void> {
        // SAFETY: opaque handle; returns a borrowed pointer or null.
        let p = unsafe { noesis_routed_events_focus_new(self.raw) };
        (!p.is_null()).then_some(p)
    }

    /// Drag effect / allowed-effect / key-state bitsets for a drag event
    /// (`DragEnter` / `DragOver` / `DragLeave` / `Drop` and their `Preview*`
    /// variants). `None` for non-drag events. See [`DragEffects`] /
    /// [`DragKeyStates`].
    pub fn drag(&self) -> Option<DragInfo> {
        let mut effects = 0u32;
        let mut allowed = 0u32;
        let mut key_states = 0u32;
        // SAFETY: opaque handle; accessor validates the kind and writes on match.
        let ok = unsafe {
            noesis_routed_events_drag_effects(self.raw, &mut effects, &mut allowed, &mut key_states)
        };
        ok.then_some(DragInfo {
            effects: DragEffects(effects),
            allowed_effects: DragEffects(allowed),
            key_states: DragKeyStates(key_states),
        })
    }

    /// Set the drop result (`DragEventArgs::effects`) a `Drop` / `DragOver`
    /// handler reports back to the drag source. Returns `true` if written (i.e.
    /// the live args are a drag event).
    #[must_use = "a false return means the effect was not set because the live args are not a drag event"]
    pub fn set_drag_effects(&self, effects: DragEffects) -> bool {
        // SAFETY: opaque handle; accessor validates the kind before writing.
        unsafe { noesis_routed_events_drag_set_effects(self.raw, effects.bits()) }
    }

    /// Borrowed pointer to the dragged data object (`DragEventArgs::data`).
    /// `None` for non-drag events or when no data is carried. Not
    /// reference-counted; valid only for the callback duration.
    pub fn drag_data_ptr(&self) -> Option<*mut c_void> {
        // SAFETY: opaque handle; returns a borrowed pointer or null.
        let p = unsafe { noesis_routed_events_drag_data(self.raw) };
        (!p.is_null()).then_some(p)
    }

    /// Drop point in `relative_to`'s coordinate space
    /// (`DragEventArgs::GetPosition`). `None` for non-drag events. `relative_to`
    /// must be a live element.
    pub fn drag_position(&self, relative_to: &FrameworkElement) -> Option<(f32, f32)> {
        let mut x = 0.0f32;
        let mut y = 0.0f32;
        // SAFETY: opaque handle + a borrowed live element pointer; accessor
        // validates the kind and writes on match.
        let ok = unsafe {
            noesis_routed_events_drag_position(self.raw, relative_to.raw(), &mut x, &mut y)
        };
        ok.then_some((x, y))
    }

    /// Manipulation origin point (`manipulationOrigin`), present on the
    /// `ManipulationStarted` / `Delta` / `Completed` / `InertiaStarting`
    /// events. `None` for other kinds.
    pub fn manip_origin(&self) -> Option<(f32, f32)> {
        let mut x = 0.0f32;
        let mut y = 0.0f32;
        // SAFETY: opaque handle; accessor validates the kind and writes on match.
        let ok = unsafe { noesis_routed_events_manip_origin(self.raw, &mut x, &mut y) };
        ok.then_some((x, y))
    }

    /// The most-recent manipulation transform: `deltaManipulation` on a
    /// `ManipulationDelta` event, `totalManipulation` on a
    /// `ManipulationCompleted` event. `None` for other kinds.
    pub fn manip_delta(&self) -> Option<ManipulationDelta> {
        let mut d = ManipulationDelta::default();
        // SAFETY: opaque handle; accessor validates the kind and writes on match.
        let ok = unsafe {
            noesis_routed_events_manip_delta(
                self.raw,
                &mut d.translation.0,
                &mut d.translation.1,
                &mut d.scale,
                &mut d.rotation,
                &mut d.expansion.0,
                &mut d.expansion.1,
            )
        };
        ok.then_some(d)
    }

    /// The cumulative manipulation transform (`cumulativeManipulation`) on a
    /// `ManipulationDelta` event. `None` for other kinds.
    pub fn manip_cumulative(&self) -> Option<ManipulationDelta> {
        let mut d = ManipulationDelta::default();
        // SAFETY: opaque handle; accessor validates the kind and writes on match.
        let ok = unsafe {
            noesis_routed_events_manip_cumulative(
                self.raw,
                &mut d.translation.0,
                &mut d.translation.1,
                &mut d.scale,
                &mut d.rotation,
                &mut d.expansion.0,
                &mut d.expansion.1,
            )
        };
        ok.then_some(d)
    }

    /// Manipulation velocities: `velocities` (Delta), `finalVelocities`
    /// (Completed) or `initialVelocities` (`InertiaStarting`). `None` for other
    /// kinds.
    pub fn manip_velocities(&self) -> Option<ManipulationVelocities> {
        let mut v = ManipulationVelocities::default();
        // SAFETY: opaque handle; accessor validates the kind and writes on match.
        let ok = unsafe {
            noesis_routed_events_manip_velocities(
                self.raw,
                &mut v.angular,
                &mut v.linear.0,
                &mut v.linear.1,
                &mut v.expansion.0,
                &mut v.expansion.1,
            )
        };
        ok.then_some(v)
    }

    /// Whether a `ManipulationDelta` / `ManipulationCompleted` event occurred
    /// during the inertia phase (`isInertial`). `None` for other kinds.
    pub fn manip_is_inertial(&self) -> Option<bool> {
        // SAFETY: opaque handle; accessor returns -1 unless it's a delta/completed event.
        match unsafe { noesis_routed_events_manip_is_inertial(self.raw) } {
            0 => Some(false),
            1 => Some(true),
            _ => None,
        }
    }
}

/// A typed bitset of `Noesis::DragDropEffects` (`DragEventArgs` effects /
/// allowed-effects): the operations a drag offers or reports. Compose with
/// [`Self::with`] / [`FromIterator`] and test with [`Self::contains`]; convert
/// to/from the raw bitmask Noesis uses with [`Self::bits`] / [`Self::from_bits`].
/// Modeled on [`crate::input::ModifierKeys`] / [`crate::view::RenderFlags`].
///
/// ```
/// use noesis_runtime::events::DragEffects;
/// let e = DragEffects::COPY.with(DragEffects::MOVE);
/// assert!(e.contains(DragEffects::COPY));
/// assert!(!e.contains(DragEffects::LINK));
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DragEffects(pub u32);

impl DragEffects {
    /// The drag-and-drop operation transfers no data.
    pub const NONE: Self = Self(0);
    /// The data is copied.
    pub const COPY: Self = Self(1);
    /// The data is moved.
    pub const MOVE: Self = Self(2);
    /// The data is linked.
    pub const LINK: Self = Self(4);
    /// Scrolling is about to start or is occurring in the target.
    pub const SCROLL: Self = Self(0x8000_0000);
    /// `COPY | MOVE | SCROLL`.
    pub const ALL: Self = Self(Self::COPY.0 | Self::MOVE.0 | Self::SCROLL.0);

    /// Wrap a raw `Noesis::DragDropEffects` bitmask.
    #[must_use]
    pub const fn from_bits(bits: u32) -> Self {
        Self(bits)
    }

    /// The raw bitmask Noesis uses.
    #[must_use]
    pub const fn bits(self) -> u32 {
        self.0
    }

    /// A copy of this set with `other`'s bits added.
    #[must_use]
    pub const fn with(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    /// Whether every bit of `other` is present (with [`Self::NONE`], always
    /// `true`).
    #[must_use]
    pub const fn contains(self, other: Self) -> bool {
        self.0 & other.0 == other.0
    }

    /// Whether no effects are set.
    #[must_use]
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }
}

impl core::ops::BitOr for DragEffects {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self {
        Self(self.0 | rhs.0)
    }
}

impl FromIterator<DragEffects> for DragEffects {
    fn from_iter<I: IntoIterator<Item = DragEffects>>(iter: I) -> Self {
        let mut acc = 0;
        for e in iter {
            acc |= e.0;
        }
        Self(acc)
    }
}

/// A typed bitset of `Noesis::DragDropKeyStates` (`DragEventArgs::keyStates`):
/// the modifier-key / mouse-button state during a drag. Compose and test like
/// [`DragEffects`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DragKeyStates(pub u32);

impl DragKeyStates {
    /// No modifier keys or mouse buttons are pressed.
    pub const NONE: Self = Self(0);
    /// The left mouse button is pressed.
    pub const LEFT_MOUSE_BUTTON: Self = Self(1);
    /// The right mouse button is pressed.
    pub const RIGHT_MOUSE_BUTTON: Self = Self(2);
    /// The Shift key is pressed.
    pub const SHIFT_KEY: Self = Self(4);
    /// The Ctrl key is pressed.
    pub const CONTROL_KEY: Self = Self(8);
    /// The middle mouse button is pressed.
    pub const MIDDLE_MOUSE_BUTTON: Self = Self(16);
    /// The Alt key is pressed.
    pub const ALT_KEY: Self = Self(32);

    /// Wrap a raw `Noesis::DragDropKeyStates` bitmask.
    #[must_use]
    pub const fn from_bits(bits: u32) -> Self {
        Self(bits)
    }

    /// The raw bitmask Noesis uses.
    #[must_use]
    pub const fn bits(self) -> u32 {
        self.0
    }

    /// A copy of this set with `other`'s bits added.
    #[must_use]
    pub const fn with(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    /// Whether every bit of `other` is present (with [`Self::NONE`], always
    /// `true`).
    #[must_use]
    pub const fn contains(self, other: Self) -> bool {
        self.0 & other.0 == other.0
    }

    /// Whether no keys/buttons are held.
    #[must_use]
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }
}

impl core::ops::BitOr for DragKeyStates {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self {
        Self(self.0 | rhs.0)
    }
}

impl FromIterator<DragKeyStates> for DragKeyStates {
    fn from_iter<I: IntoIterator<Item = DragKeyStates>>(iter: I) -> Self {
        let mut acc = 0;
        for k in iter {
            acc |= k.0;
        }
        Self(acc)
    }
}

/// Drag bitmask snapshot read from a [`DragEventArgs`](EventArgs::drag).
/// `effects` is the current/result effect, `allowed_effects` the operations the
/// source permits, `key_states` the modifier/button state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DragInfo {
    pub effects: DragEffects,
    pub allowed_effects: DragEffects,
    pub key_states: DragKeyStates,
}

/// Accumulated manipulation transform (`Noesis::ManipulationDelta`). Translation
/// in pixels, `scale` as a multiplier, `rotation` in degrees, `expansion` in
/// pixels.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct ManipulationDelta {
    pub translation: (f32, f32),
    pub scale: f32,
    pub rotation: f32,
    pub expansion: (f32, f32),
}

/// Manipulation velocities (`Noesis::ManipulationVelocities`). `angular` in
/// degrees/ms, `linear` and `expansion` in pixels/ms.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct ManipulationVelocities {
    pub angular: f32,
    pub linear: (f32, f32),
    pub expansion: (f32, f32),
}

/// Rust-side handler for the generic routed-event path. Receives a borrowed
/// [`EventArgs`] and returns `true` to mark the routed event handled (stops
/// same-element handlers that opted out of `handled_too`, plus cross-element
/// bubbling/tunneling).
///
/// The `Send + 'static` bounds let the handler live inside a Bevy `Resource`
/// or be moved onto the render thread.
/// Takes `&self` (re-entrant: a handler may re-raise the same event via
/// [`crate::reflection::raise_event`], re-entering this box; use interior
/// mutability for handler state).
pub trait RoutedEventHandler: Send + 'static {
    fn on_event(&self, args: &EventArgs) -> bool;
}

impl<F: Fn(&EventArgs) -> bool + Send + 'static> RoutedEventHandler for F {
    fn on_event(&self, args: &EventArgs) -> bool {
        self(args)
    }
}

/// SAFETY: `userdata` must be a pointer produced by [`subscribe_event`] and
/// still alive (the [`EventSubscription`] hasn't been dropped). `args` is the
/// opaque handle the C++ shim passes; it is valid only for this call.
/// `out_handled` must be a non-null pointer to a writable bool.
unsafe extern "C" fn event_trampoline(
    userdata: *mut c_void,
    args: *const c_void,
    out_handled: *mut bool,
) {
    crate::panic_guard::guard(|| {
        // Shared `&`: re-entrant handler box (see `RoutedEventHandler`).
        let handler = &*userdata.cast::<Box<dyn RoutedEventHandler>>();
        let ev = EventArgs {
            raw: args,
            _not_send: PhantomData,
        };
        let handled = handler.on_event(&ev);
        if !out_handled.is_null() {
            *out_handled = handled;
        }
    })
}

/// RAII subscription token for [`subscribe_event`]. Drop to unsubscribe and
/// free the boxed handler. Mirrors [`ClickSubscription`] / [`KeyDownSubscription`].
#[must_use = "dropping the subscription immediately unsubscribes the handler"]
pub struct EventSubscription {
    token: NonNull<c_void>,
}

// SAFETY: Send-only (NOT Sync); see the crate-level "Thread affinity" docs.
unsafe impl Send for EventSubscription {}

impl Drop for EventSubscription {
    fn drop(&mut self) {
        // SAFETY: token produced by subscribe_event; unsubscribe frees the
        // donated box exactly once (deferred if dropping from inside the
        // callback).
        unsafe { noesis_unsubscribe_event(self.token.as_ptr()) }
    }
}

/// A documented `Noesis::RoutedEvent` accepted by [`subscribe_event`]. Each
/// variant maps to a curated entry in the C++ event table (`noesis_events.cpp`),
/// so the typed accessors on [`EventArgs`] know which concrete arg struct fired.
/// Use [`subscribe_event_by_name`] for arbitrary/custom events not listed here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RoutedEvent {
    /// `UIElement.MouseEnter`.
    MouseEnter,
    /// `UIElement.MouseLeave`.
    MouseLeave,
    /// `UIElement.MouseMove`.
    MouseMove,
    /// `UIElement.PreviewMouseMove`.
    PreviewMouseMove,
    /// `UIElement.GotMouseCapture`.
    GotMouseCapture,
    /// `UIElement.LostMouseCapture`.
    LostMouseCapture,
    /// `UIElement.MouseDown`.
    MouseDown,
    /// `UIElement.MouseUp`.
    MouseUp,
    /// `UIElement.MouseLeftButtonDown`.
    MouseLeftButtonDown,
    /// `UIElement.MouseLeftButtonUp`.
    MouseLeftButtonUp,
    /// `UIElement.MouseRightButtonDown`.
    MouseRightButtonDown,
    /// `UIElement.MouseRightButtonUp`.
    MouseRightButtonUp,
    /// `UIElement.PreviewMouseDown`.
    PreviewMouseDown,
    /// `UIElement.PreviewMouseUp`.
    PreviewMouseUp,
    /// `UIElement.PreviewMouseLeftButtonDown`.
    PreviewMouseLeftButtonDown,
    /// `UIElement.PreviewMouseLeftButtonUp`.
    PreviewMouseLeftButtonUp,
    /// `UIElement.PreviewMouseRightButtonDown`.
    PreviewMouseRightButtonDown,
    /// `UIElement.PreviewMouseRightButtonUp`.
    PreviewMouseRightButtonUp,
    /// `UIElement.MouseWheel`.
    MouseWheel,
    /// `UIElement.PreviewMouseWheel`.
    PreviewMouseWheel,
    /// `UIElement.KeyDown`.
    KeyDown,
    /// `UIElement.KeyUp`.
    KeyUp,
    /// `UIElement.PreviewKeyDown`.
    PreviewKeyDown,
    /// `UIElement.PreviewKeyUp`.
    PreviewKeyUp,
    /// `UIElement.TextInput`.
    TextInput,
    /// `UIElement.PreviewTextInput`.
    PreviewTextInput,
    /// `UIElement.GotFocus`.
    GotFocus,
    /// `UIElement.LostFocus`.
    LostFocus,
    /// `UIElement.GotKeyboardFocus`.
    GotKeyboardFocus,
    /// `UIElement.LostKeyboardFocus`.
    LostKeyboardFocus,
    /// `UIElement.PreviewGotKeyboardFocus`.
    PreviewGotKeyboardFocus,
    /// `UIElement.PreviewLostKeyboardFocus`.
    PreviewLostKeyboardFocus,
    /// `FrameworkElement.Loaded`.
    Loaded,
    /// `FrameworkElement.Unloaded`.
    Unloaded,
    /// `FrameworkElement.SizeChanged`.
    SizeChanged,
    /// `UIElement.TouchDown`.
    TouchDown,
    /// `UIElement.TouchMove`.
    TouchMove,
    /// `UIElement.TouchUp`.
    TouchUp,
    /// `UIElement.TouchEnter`.
    TouchEnter,
    /// `UIElement.TouchLeave`.
    TouchLeave,
    /// `UIElement.Tapped`.
    Tapped,
    /// `UIElement.DoubleTapped`.
    DoubleTapped,
    /// `UIElement.Holding`.
    Holding,
    /// `UIElement.RightTapped`.
    RightTapped,
    /// `UIElement.ManipulationStarting`.
    ManipulationStarting,
    /// `UIElement.ManipulationStarted`.
    ManipulationStarted,
    /// `UIElement.ManipulationDelta`.
    ManipulationDelta,
    /// `UIElement.ManipulationInertiaStarting`.
    ManipulationInertiaStarting,
    /// `UIElement.ManipulationCompleted`.
    ManipulationCompleted,
    /// `UIElement.DragEnter`.
    DragEnter,
    /// `UIElement.DragOver`.
    DragOver,
    /// `UIElement.DragLeave`.
    DragLeave,
    /// `UIElement.Drop`.
    Drop,
    /// `UIElement.PreviewDragEnter`.
    PreviewDragEnter,
    /// `UIElement.PreviewDragOver`.
    PreviewDragOver,
    /// `UIElement.PreviewDragLeave`.
    PreviewDragLeave,
    /// `UIElement.PreviewDrop`.
    PreviewDrop,
}

impl RoutedEvent {
    /// The WPF/Noesis event name this variant maps to (the string the C++ event
    /// table keys on).
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::MouseEnter => "MouseEnter",
            Self::MouseLeave => "MouseLeave",
            Self::MouseMove => "MouseMove",
            Self::PreviewMouseMove => "PreviewMouseMove",
            Self::GotMouseCapture => "GotMouseCapture",
            Self::LostMouseCapture => "LostMouseCapture",
            Self::MouseDown => "MouseDown",
            Self::MouseUp => "MouseUp",
            Self::MouseLeftButtonDown => "MouseLeftButtonDown",
            Self::MouseLeftButtonUp => "MouseLeftButtonUp",
            Self::MouseRightButtonDown => "MouseRightButtonDown",
            Self::MouseRightButtonUp => "MouseRightButtonUp",
            Self::PreviewMouseDown => "PreviewMouseDown",
            Self::PreviewMouseUp => "PreviewMouseUp",
            Self::PreviewMouseLeftButtonDown => "PreviewMouseLeftButtonDown",
            Self::PreviewMouseLeftButtonUp => "PreviewMouseLeftButtonUp",
            Self::PreviewMouseRightButtonDown => "PreviewMouseRightButtonDown",
            Self::PreviewMouseRightButtonUp => "PreviewMouseRightButtonUp",
            Self::MouseWheel => "MouseWheel",
            Self::PreviewMouseWheel => "PreviewMouseWheel",
            Self::KeyDown => "KeyDown",
            Self::KeyUp => "KeyUp",
            Self::PreviewKeyDown => "PreviewKeyDown",
            Self::PreviewKeyUp => "PreviewKeyUp",
            Self::TextInput => "TextInput",
            Self::PreviewTextInput => "PreviewTextInput",
            Self::GotFocus => "GotFocus",
            Self::LostFocus => "LostFocus",
            Self::GotKeyboardFocus => "GotKeyboardFocus",
            Self::LostKeyboardFocus => "LostKeyboardFocus",
            Self::PreviewGotKeyboardFocus => "PreviewGotKeyboardFocus",
            Self::PreviewLostKeyboardFocus => "PreviewLostKeyboardFocus",
            Self::Loaded => "Loaded",
            Self::Unloaded => "Unloaded",
            Self::SizeChanged => "SizeChanged",
            Self::TouchDown => "TouchDown",
            Self::TouchMove => "TouchMove",
            Self::TouchUp => "TouchUp",
            Self::TouchEnter => "TouchEnter",
            Self::TouchLeave => "TouchLeave",
            Self::Tapped => "Tapped",
            Self::DoubleTapped => "DoubleTapped",
            Self::Holding => "Holding",
            Self::RightTapped => "RightTapped",
            Self::ManipulationStarting => "ManipulationStarting",
            Self::ManipulationStarted => "ManipulationStarted",
            Self::ManipulationDelta => "ManipulationDelta",
            Self::ManipulationInertiaStarting => "ManipulationInertiaStarting",
            Self::ManipulationCompleted => "ManipulationCompleted",
            Self::DragEnter => "DragEnter",
            Self::DragOver => "DragOver",
            Self::DragLeave => "DragLeave",
            Self::Drop => "Drop",
            Self::PreviewDragEnter => "PreviewDragEnter",
            Self::PreviewDragOver => "PreviewDragOver",
            Self::PreviewDragLeave => "PreviewDragLeave",
            Self::PreviewDrop => "PreviewDrop",
        }
    }
}

/// Subscribe `handler` to the typed routed `event` on `element`.
///
/// `handled_too`: when `false`, the handler is skipped if a prior handler on
/// the same element already marked the event handled. (This SDK's `AddHandler`
/// has no `handledEventsToo` parameter, so already-handled events are never
/// re-routed across elements regardless; the flag governs the per-element
/// handler chain.)
///
/// Returns `None` if `element` is not a `UIElement` or the C++ subscription
/// fails. The returned [`EventSubscription`] keeps the handler installed until
/// dropped. For arbitrary/custom events use [`subscribe_event_by_name`].
pub fn subscribe_event<H: RoutedEventHandler>(
    element: &FrameworkElement,
    event: RoutedEvent,
    handled_too: bool,
    handler: H,
) -> Option<EventSubscription> {
    subscribe_event_by_name(element, event.as_str(), handled_too, handler)
}

/// Subscribe `handler` to the routed event named `event_name` on `element`, the
/// `&str` escape hatch behind the typed [`subscribe_event`], for custom or
/// not-yet-enumerated events.
///
/// `event_name` uses the WPF/Noesis event names: `"MouseMove"`,
/// `"MouseLeftButtonDown"`, `"MouseWheel"`, `"KeyDown"`, `"KeyUp"`,
/// `"GotFocus"`, `"LostFocus"`, `"Loaded"`, `"Unloaded"`, `"SizeChanged"`,
/// `"TextInput"`, `"Drop"`, `"Tapped"`, and the `Preview*` variants, among
/// others. Unknown-but-reflected names fall back to the SDK's `FindRoutedEvent`
/// lookup (only [`EventArgs::source_ptr`] applies to those).
///
/// `handled_too`: when `false`, the handler is skipped if a prior handler on
/// the same element already marked the event handled. (This SDK's `AddHandler`
/// has no `handledEventsToo` parameter, so already-handled events are never
/// re-routed across elements regardless; the flag governs the per-element
/// handler chain.)
///
/// Returns `None` if `element` is not a `UIElement`, `event_name` is unknown
/// or contains an interior NUL, or the C++ subscription fails. The returned
/// [`EventSubscription`] keeps the handler installed until dropped.
pub fn subscribe_event_by_name<H: RoutedEventHandler>(
    element: &FrameworkElement,
    event_name: &str,
    handled_too: bool,
    handler: H,
) -> Option<EventSubscription> {
    let cname = CString::new(event_name).ok()?;

    let outer: Box<Box<dyn RoutedEventHandler>> = Box::new(Box::new(handler));
    let userdata = Box::into_raw(outer);

    // SAFETY: trampoline is `extern "C"`; userdata is freshly leaked and donated
    // to the C++ handler; the element + name pointers are borrowed for the call
    // duration only.
    let token = unsafe {
        noesis_subscribe_event(
            element.raw(),
            cname.as_ptr(),
            handled_too,
            event_trampoline,
            userdata.cast(),
            free_donated::<Box<dyn RoutedEventHandler>>,
        )
    };

    if let Some(token) = NonNull::new(token) {
        Some(EventSubscription { token })
    } else {
        // Subscription failed (unknown event / not a UIElement); C++ took no
        // ownership. Free the userdata we leaked above so we don't leak it.
        // SAFETY: userdata came from Box::into_raw moments ago; nothing else
        // ever saw the pointer.
        unsafe { drop(Box::from_raw(userdata)) };
        None
    }
}

// `Initialized`, `LayoutUpdated`, `DataContextChanged` and the `Is*Changed`
// notifications are NOT routed events; they ride Noesis's `Event_<T>`
// mechanism (`AddEventHandler(Symbol, EventHandler)`), so they go through a
// separate name-keyed entrypoint rather than the routed `subscribe_event` path.
// They carry no arguments we surface, so the handler is a bare `Fn()`.

/// Rust-side handler for a non-routed lifecycle event. These notifications
/// carry no arguments we surface, so the callback takes none.
///
/// The `Send + 'static` bounds let the handler live inside a Bevy `Resource`
/// or be moved onto the render thread.
/// Takes `&self` (re-entrant: a lifecycle handler that re-parents its element
/// can trigger another lifecycle event synchronously on the same box; use
/// interior mutability for handler state).
pub trait LifecycleHandler: Send + 'static {
    fn on_event(&self);
}

impl<F: Fn() + Send + 'static> LifecycleHandler for F {
    fn on_event(&self) {
        self();
    }
}

/// SAFETY: `userdata` must be a pointer produced by [`subscribe_lifecycle`] and
/// still alive (the [`LifecycleSubscription`] hasn't been dropped).
unsafe extern "C" fn lifecycle_trampoline(userdata: *mut c_void) {
    crate::panic_guard::guard(|| {
        // Shared `&`: re-entrant handler box (see `LifecycleHandler`).
        let handler = &*userdata.cast::<Box<dyn LifecycleHandler>>();
        handler.on_event();
    })
}

/// RAII subscription token for [`subscribe_lifecycle`]. Drop to unsubscribe and
/// free the boxed handler. Mirrors [`ClickSubscription`].
#[must_use = "dropping the subscription immediately unsubscribes the handler"]
pub struct LifecycleSubscription {
    token: NonNull<c_void>,
}

// SAFETY: Send-only (NOT Sync); see the crate-level "Thread affinity" docs.
unsafe impl Send for LifecycleSubscription {}

impl Drop for LifecycleSubscription {
    fn drop(&mut self) {
        // SAFETY: token produced by subscribe_lifecycle; unsubscribe frees the
        // donated box exactly once (deferred if dropping from inside the
        // callback).
        unsafe { noesis_unsubscribe_lifecycle(self.token.as_ptr()) }
    }
}

/// A documented non-routed lifecycle event accepted by [`subscribe_lifecycle`].
/// Each variant maps to an entry in the C++ `ApplyLifecycle` table
/// (`noesis_events.cpp`). Use [`subscribe_lifecycle_by_name`] for any name not
/// enumerated here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum LifecycleEvent {
    /// `FrameworkElement.Initialized`.
    Initialized,
    /// `FrameworkElement.LayoutUpdated`.
    LayoutUpdated,
    /// `FrameworkElement.DataContextChanged`.
    DataContextChanged,
    /// `UIElement.IsEnabledChanged`.
    IsEnabledChanged,
    /// `UIElement.IsVisibleChanged`.
    IsVisibleChanged,
    /// `UIElement.IsHitTestVisibleChanged`.
    IsHitTestVisibleChanged,
    /// `UIElement.IsKeyboardFocusedChanged`.
    IsKeyboardFocusedChanged,
    /// `UIElement.IsKeyboardFocusWithinChanged`.
    IsKeyboardFocusWithinChanged,
    /// `UIElement.IsMouseCapturedChanged`.
    IsMouseCapturedChanged,
    /// `UIElement.IsMouseCaptureWithinChanged`.
    IsMouseCaptureWithinChanged,
    /// `UIElement.IsMouseDirectlyOverChanged`.
    IsMouseDirectlyOverChanged,
    /// `UIElement.FocusableChanged`.
    FocusableChanged,
}

impl LifecycleEvent {
    /// The event name this variant maps to (the string the C++ lifecycle table
    /// keys on).
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Initialized => "Initialized",
            Self::LayoutUpdated => "LayoutUpdated",
            Self::DataContextChanged => "DataContextChanged",
            Self::IsEnabledChanged => "IsEnabledChanged",
            Self::IsVisibleChanged => "IsVisibleChanged",
            Self::IsHitTestVisibleChanged => "IsHitTestVisibleChanged",
            Self::IsKeyboardFocusedChanged => "IsKeyboardFocusedChanged",
            Self::IsKeyboardFocusWithinChanged => "IsKeyboardFocusWithinChanged",
            Self::IsMouseCapturedChanged => "IsMouseCapturedChanged",
            Self::IsMouseCaptureWithinChanged => "IsMouseCaptureWithinChanged",
            Self::IsMouseDirectlyOverChanged => "IsMouseDirectlyOverChanged",
            Self::FocusableChanged => "FocusableChanged",
        }
    }
}

/// Subscribe `handler` to the typed non-routed lifecycle `event` on `element`.
///
/// Returns `None` if `element` is not a `FrameworkElement` or the C++
/// subscription fails. The returned [`LifecycleSubscription`] keeps the handler
/// installed until dropped; it holds a `+1` ref on the element so the
/// subscription survives the caller dropping every other handle. For any name
/// not enumerated by [`LifecycleEvent`] use [`subscribe_lifecycle_by_name`].
pub fn subscribe_lifecycle<H: LifecycleHandler>(
    element: &FrameworkElement,
    event: LifecycleEvent,
    handler: H,
) -> Option<LifecycleSubscription> {
    subscribe_lifecycle_by_name(element, event.as_str(), handler)
}

/// Subscribe `handler` to the non-routed lifecycle event named `name` on
/// `element`, the `&str` escape hatch behind the typed [`subscribe_lifecycle`].
///
/// Supported names: `"Initialized"`, `"LayoutUpdated"`, `"DataContextChanged"`,
/// `"IsEnabledChanged"`, `"IsVisibleChanged"`, `"IsHitTestVisibleChanged"`,
/// `"IsKeyboardFocusedChanged"`, `"IsKeyboardFocusWithinChanged"`,
/// `"IsMouseCapturedChanged"`, `"IsMouseCaptureWithinChanged"`,
/// `"IsMouseDirectlyOverChanged"`, `"FocusableChanged"`.
///
/// Returns `None` if `element` is not a `FrameworkElement`, `name` is unknown
/// or contains an interior NUL, or the C++ subscription fails. The returned
/// [`LifecycleSubscription`] keeps the handler installed until dropped; it holds
/// a `+1` ref on the element so the subscription survives the caller dropping
/// every other handle.
pub fn subscribe_lifecycle_by_name<H: LifecycleHandler>(
    element: &FrameworkElement,
    name: &str,
    handler: H,
) -> Option<LifecycleSubscription> {
    let cname = CString::new(name).ok()?;

    let outer: Box<Box<dyn LifecycleHandler>> = Box::new(Box::new(handler));
    let userdata = Box::into_raw(outer);

    // SAFETY: trampoline is `extern "C"`; userdata is freshly leaked and donated
    // to the C++ handler; the element + name pointers are borrowed for the call
    // duration only.
    let token = unsafe {
        noesis_subscribe_lifecycle(
            element.raw(),
            cname.as_ptr(),
            lifecycle_trampoline,
            userdata.cast(),
            free_donated::<Box<dyn LifecycleHandler>>,
        )
    };

    if let Some(token) = NonNull::new(token) {
        Some(LifecycleSubscription { token })
    } else {
        // Subscription failed (unknown name / not a FrameworkElement); C++ took
        // no ownership. Free the userdata we leaked above so we don't leak it.
        // SAFETY: userdata came from Box::into_raw moments ago; nothing else
        // ever saw the pointer.
        unsafe { drop(Box::from_raw(userdata)) };
        None
    }
}

/// Initiate a drag-and-drop operation from `source`, carrying `data` as the
/// drag payload and advertising `allowed_effects` (a [`DragEffects`] set).
///
/// Wraps `Noesis::DragDrop::DoDragDrop`. The drag is subsequently driven by the
/// host's pointer/drag input; there is no synchronous result and no headless
/// completion. `data` may be any element used as
/// the transferred payload (this SDK exposes no `DataObject` *builder*, so an
/// element stands in for the data object).
///
/// Returns `false` if `source` is not a `DependencyObject` (it always is for a
/// `FrameworkElement`, so this is effectively infallible for live elements).
pub fn do_drag_drop(
    source: &FrameworkElement,
    data: &FrameworkElement,
    allowed_effects: DragEffects,
) -> bool {
    // SAFETY: both pointers are borrowed live elements; DoDragDrop copies what
    // it needs and does not retain the raw pointers past the call we make here.
    unsafe { noesis_routed_events_do_drag_drop(source.raw(), data.raw(), allowed_effects.bits()) }
}

/// Rust-side handler for the `DataObject.Copying` / `.Pasting` attached events.
/// Receives a borrowed pointer to the clipboard data object (`None` when none
/// is carried), whether the operation originates from a drag-drop, and returns
/// `true` to cancel the copy/paste.
///
/// The `Send + 'static` bounds let the handler live inside a Bevy `Resource`
/// or be moved onto the render thread.
pub trait DataObjectHandler: Send + 'static {
    /// Called when the copy/paste fires. `data_object` is borrowed (valid only
    /// for the call); `is_drag_drop` distinguishes a drag-drop transfer from a
    /// clipboard one. Return `true` to cancel.
    ///
    /// Takes `&self` (re-entrant per [`ClickHandler`]; use interior mutability
    /// for handler state).
    fn on_data_object(&self, data_object: Option<*mut c_void>, is_drag_drop: bool) -> bool;
}

impl<F: Fn(Option<*mut c_void>, bool) -> bool + Send + 'static> DataObjectHandler for F {
    fn on_data_object(&self, data_object: Option<*mut c_void>, is_drag_drop: bool) -> bool {
        self(data_object, is_drag_drop)
    }
}

/// SAFETY: `userdata` must be a pointer produced by a `subscribe_data_object_*`
/// call and still alive (its [`DataObjectSubscription`] hasn't been dropped).
/// `out_cancel` must be a non-null pointer to a writable bool.
unsafe extern "C" fn data_object_trampoline(
    userdata: *mut c_void,
    data_object: *mut c_void,
    is_drag_drop: bool,
    out_cancel: *mut bool,
) {
    crate::panic_guard::guard(|| {
        // Shared `&`: re-entrant handler box (see `DataObjectHandler`).
        let handler = &*userdata.cast::<Box<dyn DataObjectHandler>>();
        let data = (!data_object.is_null()).then_some(data_object);
        let cancel = handler.on_data_object(data, is_drag_drop);
        if !out_cancel.is_null() {
            *out_cancel = cancel;
        }
    })
}

/// RAII subscription token for a `DataObject.Copying` / `.Pasting` handler.
/// Drop to detach the handler and free the boxed closure. Mirrors
/// [`EventSubscription`]; holds a `+1` ref on the element.
#[must_use = "dropping the subscription immediately unsubscribes the handler"]
pub struct DataObjectSubscription {
    token: NonNull<c_void>,
}

// SAFETY: Send-only (NOT Sync); see the crate-level "Thread affinity" docs.
unsafe impl Send for DataObjectSubscription {}

impl Drop for DataObjectSubscription {
    fn drop(&mut self) {
        // SAFETY: token produced by a subscribe call; remove frees the donated
        // box exactly once (deferred if dropping from inside the callback).
        unsafe { noesis_routed_events_remove_data_object_handler(self.token.as_ptr()) }
    }
}

/// Which `DataObject` attached event a [`subscribe_data_object`] call targets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DataObjectEvent {
    /// `DataObject.Copying`: raised before data is placed on the clipboard
    /// (e.g. by `Ctrl+C` in a `TextBox`).
    Copying,
    /// `DataObject.Pasting`: raised before clipboard data is consumed (e.g. by
    /// `Ctrl+V`).
    Pasting,
}

/// Attach `handler` to the `DataObject.Copying` or `.Pasting` attached event on
/// `element`. Returns `None` if `element` is not a `UIElement` or the C++
/// subscription fails. The returned [`DataObjectSubscription`] keeps the handler
/// installed until dropped.
pub fn subscribe_data_object<H: DataObjectHandler>(
    element: &FrameworkElement,
    event: DataObjectEvent,
    handler: H,
) -> Option<DataObjectSubscription> {
    let outer: Box<Box<dyn DataObjectHandler>> = Box::new(Box::new(handler));
    let userdata = Box::into_raw(outer);

    // SAFETY: trampoline is `extern "C"`; userdata is freshly leaked and donated
    // to the C++ handler; the element pointer is borrowed for the call only.
    let token = unsafe {
        match event {
            DataObjectEvent::Copying => noesis_routed_events_add_copying_handler(
                element.raw(),
                data_object_trampoline,
                userdata.cast(),
                free_donated::<Box<dyn DataObjectHandler>>,
            ),
            DataObjectEvent::Pasting => noesis_routed_events_add_pasting_handler(
                element.raw(),
                data_object_trampoline,
                userdata.cast(),
                free_donated::<Box<dyn DataObjectHandler>>,
            ),
        }
    };

    if let Some(token) = NonNull::new(token) {
        Some(DataObjectSubscription { token })
    } else {
        // Subscription failed (not a UIElement); C++ took no ownership. Free the
        // userdata we leaked.
        // SAFETY: userdata came from Box::into_raw moments ago; nothing else
        // ever saw the pointer.
        unsafe { drop(Box::from_raw(userdata)) };
        None
    }
}