swiftui-native 0.0.1

SwiftUI from pure Rust — no Swift bridge, no shim, only swift-runtime calls
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
//! Closure arguments.

use super::*;
use crate::abi;
use crate::resolve;
use core::ffi::c_void;
use crate::mangle::swift_type;
// ── Closure arguments ──

//
// A Swift closure is two words — an entry point and a context — so it drops
// straight into the integer argument list like any other pair of registers.
// What varies is the *shape* of the callback, and that is what the thunks in
// `abi` are for: which registers the argument arrives in, and whether the
// closure has to write a result through x8.
//
// Every context here is leaked. SwiftUI stores an escaping closure for as long
// as the view lives, and a non-escaping one is called before the modifier
// returns, so leaking is either necessary or harmless; freeing is neither.

/// The two words of a Swift `() -> ()` closure that runs `action`.
pub(crate) fn action_words(action: impl Fn() + 'static) -> [u64; 2] {
    let ctx = Box::leak(Box::new(abi::ClosureCtx::new(invoke_action, boxed_ctx(Box::new(action) as Box<dyn Fn()>))))
        as *mut abi::ClosureCtx;
    [abi::swift_closure_thunk as *const () as u64, ctx as u64]
}

/// The two words of a `() -> ()` closure that runs an already-boxed action.
///
/// [`action_words`] takes the closure by value and boxes it; this takes the box
/// straight, which is what an `Option<Box<dyn Fn()>>` argument already holds.
pub(crate) fn boxed_action_words(action: Box<dyn Fn()>) -> [u64; 2] {
    let ctx = Box::leak(Box::new(abi::ClosureCtx::new(
        super::controls::run_boxed_action,
        super::boxed_ctx(action),
    ))) as *mut abi::ClosureCtx;
    [abi::swift_closure_thunk as *const () as u64, ctx as u64]
}

/// The two words of a `@ViewBuilder () -> V` closure returning `view`.
///
/// The view is built here and handed back whenever SwiftUI asks, which is what
/// a `ViewBuilder` closure over a fixed subtree amounts to. `V` is the view's
/// own type — the caller has to name it in the `Content.Type` it passes, and
/// `view.meta`/`view.wt` are what to name it with.
pub(crate) fn view_words(view: &ViewHandle) -> [u64; 2] {
    let ctx = Box::leak(Box::new(abi::ClosureCtx::new(
        emit_tuple,
        Child::leak(view, Content::Concrete),
    ))) as *mut abi::ClosureCtx;
    [abi::swift_closure_thunk as *const () as u64, ctx as u64]
}

/// The two words of a one-argument, no-result closure.
pub(crate) fn wide_words(
    body: unsafe extern "C" fn(u64, u64, u64, *mut c_void),
    payload: *mut c_void,
) -> [u64; 2] {
    let ctx = Box::leak(Box::new(abi::WideClosureCtx::new(body, payload)))
        as *mut abi::WideClosureCtx;
    [abi::wide_closure_thunk as *const () as u64, ctx as u64]
}

/// The two words of a two-argument, no-result closure.
pub(crate) fn pair_words(
    body: unsafe extern "C" fn(*const u8, *const u8, *mut c_void),
    payload: *mut c_void,
) -> [u64; 2] {
    let ctx = Box::leak(Box::new(abi::PairClosureCtx::new(body, payload)))
        as *mut abi::PairClosureCtx;
    [abi::pair_closure_thunk as *const () as u64, ctx as u64]
}

/// A callback that receives an enum's case number.
///
/// Whether the case arrives as a value or as an address is not the closure's
/// choice: a `@frozen` enum is loadable and travels in x0, a resilient one of
/// the very same single byte travels by pointer. `indirect` records which, and
/// `getEnumTag` turns either into a case number.
pub(crate) struct TagCallback {
    pub(crate) f: Box<dyn Fn(i64)>,
    pub(crate) meta: *const c_void,
    pub(crate) indirect: bool,
}

pub(crate) unsafe extern "C" fn invoke_tag(a0: u64, _a1: u64, _a2: u64, payload: *mut c_void) {
    unsafe {
        let cb = &*(payload as *const TagCallback);
        let tag = if cb.indirect {
            abi::read_enum_tag(a0 as *const u8, cb.meta)
        } else {
            abi::read_enum_tag(a0.to_le_bytes().as_ptr(), cb.meta)
        };
        (cb.f)(i64::from(tag));
    }
}

/// The two words of an `(E) -> ()` closure delivering `E`'s case number.
pub(crate) unsafe fn tag_words(f: impl Fn(i64) + 'static, meta: *const c_void, indirect: bool) -> [u64; 2] {
    let cb = Box::leak(Box::new(TagCallback { f: Box::new(f), meta, indirect }));
    wide_words(invoke_tag, cb as *mut TagCallback as *mut c_void)
}

pub(crate) unsafe extern "C" fn invoke_bool(a0: u64, _a1: u64, _a2: u64, payload: *mut c_void) {
    let f = unsafe { boxed_ref::<dyn Fn(bool)>(payload) };
    f(a0 & 1 != 0);
}

/// The two words of a `(Bool) -> ()` closure.
pub(crate) fn bool_words(f: impl Fn(bool) + 'static) -> [u64; 2] {
    wide_words(invoke_bool, boxed_ctx(Box::new(f) as Box<dyn Fn(bool)>))
}

pub(crate) unsafe extern "C" fn invoke_url(a0: u64, _a1: u64, _a2: u64, payload: *mut c_void) {
    unsafe {
        let f = boxed_ref::<dyn Fn(&str)>(payload);
        // `URL` is resilient, so it arrives by address; `absoluteString` is the
        // one accessor that turns it back into something Rust can read.
        let (s0, s1): (u64, u64);
        core::arch::asm!("blr {f}", f = in(reg) resolve::url_absolute_string(),
            in("x20") a0,
            lateout("x0") s0, lateout("x1") s1,
            lateout("x2") _, lateout("x3") _, lateout("x4") _, lateout("x5") _,
            lateout("x6") _, lateout("x7") _, lateout("x8") _, lateout("x9") _,
            lateout("x10") _, lateout("x11") _, lateout("x12") _, lateout("x13") _,
            lateout("x14") _, lateout("x15") _, lateout("x16") _, lateout("x17") _,
            lateout("lr") _, lateout("x21") _, clobber_abi("C"),
        );
        let mut raw = [0u8; 16];
        raw[..8].copy_from_slice(&s0.to_le_bytes());
        raw[8..].copy_from_slice(&s1.to_le_bytes());
        f(&abi::read_swift_string(raw));
    }
}

/// The two words of a `(URL) -> ()` closure, delivering the absolute string.
pub(crate) fn url_words(f: impl Fn(&str) + 'static) -> [u64; 2] {
    wide_words(invoke_url, boxed_ctx(Box::new(f) as Box<dyn Fn(&str)>))
}

/// A callback receiving two enum case numbers.
pub(crate) struct TagPairCallback {
    pub(crate) f: Box<dyn Fn(i64, i64)>,
    pub(crate) meta: *const c_void,
}

pub(crate) unsafe extern "C" fn invoke_tag_pair(a: *const u8, b: *const u8, payload: *mut c_void) {
    unsafe {
        let cb = &*(payload as *const TagPairCallback);
        // Both are frozen single-byte enums, so the registers hold the values.
        let ta = abi::read_enum_tag((a as u64).to_le_bytes().as_ptr(), cb.meta);
        let tb = abi::read_enum_tag((b as u64).to_le_bytes().as_ptr(), cb.meta);
        (cb.f)(i64::from(ta), i64::from(tb));
    }
}

pub(crate) unsafe extern "C" fn invoke_word_pair(a: *const u8, b: *const u8, payload: *mut c_void) {
    let f = unsafe { boxed_ref::<dyn Fn(u64, u64)>(payload) };
    f(a as u64, b as u64);
}

/// Apply a modifier with one generic parameter, given the whole argument list.
///
/// [`generic1_modifier`] leads with a pointer to the value, which is right when
/// the generic parameter *is* the argument. A `@ViewBuilder` modifier is the
/// other case: the generic parameter is what the closure returns, so the
/// argument list is the closure's two words and the type arguments still have
/// to follow.
pub(crate) unsafe fn generic1_modifier_ints(
    func: *const c_void,
    oret: *const c_void,
    view: &ViewHandle,
    arg_meta: *const c_void,
    arg_wt: *const c_void,
    leading: &[u64],
    floats: [f64; 4],
) -> ViewHandle {
    unsafe {
        let subst = [view.meta, arg_meta, view.wt, arg_wt];
        let (meta, wt, size) = opaque_result_type(oret, &subst);
        let mut ints = Vec::with_capacity(leading.len() + 4);
        ints.extend_from_slice(leading);
        ints.push(view.meta as u64);
        ints.push(arg_meta as u64);
        ints.push(view.wt as u64);
        ints.push(arg_wt as u64);
        let r = abi::call_modifier_generic(func, view.value_ptr(), &ints, floats, size);
        wrap_owned(r, meta, wt)
    }
}

/// Apply a `@ViewBuilder content:` modifier whose content is a fixed subtree.
pub(crate) unsafe fn content_modifier(
    func: *const c_void,
    oret: *const c_void,
    view: &ViewHandle,
    leading: &[u64],
    content: &ViewHandle,
) -> ViewHandle {
    unsafe {
        let mut ints = leading.to_vec();
        ints.extend_from_slice(&view_words(content));
        generic1_modifier_ints(
            func,
            oret,
            view,
            content.meta,
            content.wt,
            &ints,
            [0.0; 4],
        )
    }
}

/// Read a `@frozen` static property that fits in one register.
///
/// The counterpart to [`resilient_static`]: a frozen type of eight bytes or
/// fewer is loadable, so its getter returns the value in x0 rather than
/// writing it through x8.
pub(crate) unsafe fn frozen_static(meta: *const c_void, getter: &'static core::ffi::CStr) -> u64 {
    unsafe {
        let f = resolve::sym(getter);
        assert!(!f.is_null(), "missing static: {}", crate::diag::symbol_name(getter));
        abi::static_regs(f, meta)[0]
    }
}

/// A member of `SwiftUI.AccessibilityActionKind`.
///
/// Three of these are platform-specific, and asking for one where it does not
/// exist is not a missing symbol — the symbol is there on every platform and
/// traps with "Unavailable code reached" when called. Availability is in the
/// SDK's declarations, not in the export trie, so it is written out here.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ActionKind {
    /// Every platform.
    Default,
    /// Every platform.
    Escape,
    /// iOS, tvOS and watchOS only.
    /// Unavailable on macOS: SwiftUI ships a trap stub there, so
    /// reaching this aborts with "Unavailable code reached".
    #[cfg(not(target_os = "macos"))]
    MagicTap,
    /// macOS only.
    ShowMenu,
    /// macOS only.
    Delete,
}

impl ActionKind {
    pub(crate) fn getter(self) -> &'static core::ffi::CStr {
        match self {
            Self::Default => c"$s7SwiftUI23AccessibilityActionKindV7defaultACvgZ",
            Self::Escape => c"$s7SwiftUI23AccessibilityActionKindV6escapeACvgZ",
            #[cfg(not(target_os = "macos"))]
            Self::MagicTap => c"$s7SwiftUI23AccessibilityActionKindV8magicTapACvgZ",
            Self::ShowMenu => c"$s7SwiftUI23AccessibilityActionKindV8showMenuACvgZ",
            Self::Delete => c"$s7SwiftUI23AccessibilityActionKindV6deleteACvgZ",
        }
    }
}

swift_statics! {
    /// A member of `SwiftUI.SubmitTriggers`.
    pub enum SubmitTrigger {
        Text = c"$s7SwiftUI14SubmitTriggersV4textACvgZ",
        Search = c"$s7SwiftUI14SubmitTriggersV6searchACvgZ",
        Collection = c"$s7SwiftUI14SubmitTriggersV10collectionACvgZ",
    }
}

swift_statics! {
    /// A member of `SwiftUI.EventModifiers`.
    pub enum EventModifier {
        Shift = c"$s7SwiftUI14EventModifiersV5shiftACvgZ",
        Control = c"$s7SwiftUI14EventModifiersV7controlACvgZ",
        Option = c"$s7SwiftUI14EventModifiersV6optionACvgZ",
        Command = c"$s7SwiftUI14EventModifiersV7commandACvgZ",
        CapsLock = c"$s7SwiftUI14EventModifiersV8capsLockACvgZ",
        Function = c"$s7SwiftUI14EventModifiersV8functionACvgZ",
        NumericPad = c"$s7SwiftUI14EventModifiersV10numericPadACvgZ",
        All = c"$s7SwiftUI14EventModifiersV3allACvgZ",
    }
}

/// Apply `.accessibilityAction(_:_:)`.
pub fn accessibility_action(view: &ViewHandle, kind: ActionKind, action: impl Fn() + 'static) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::a11y_action_kind_ma());
        let k = resilient_static(meta, kind.getter());
        let c = action_words(action);
        a11y_modifier(resolve::a11y_action_fn(), view, &[k.as_ptr() as u64, c[0], c[1]], [0.0; 4])
    }
}

/// Apply `.accessibilityAdjustableAction(_:)`.
///
/// The direction reaches the callback as a case number: 0 is `.increment`,
/// 1 is `.decrement`.
pub fn accessibility_adjustable_action(view: &ViewHandle, action: impl Fn(i64) + 'static) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::a11y_adjustment_direction_ma());
        // Resilient, so the case arrives by address even though it is one byte.
        let c = tag_words(action, meta, true);
        a11y_modifier(resolve::a11y_adjustable_action_fn(), view, &c, [0.0; 4])
    }
}

/// Apply `.accessibilityScrollAction(_:)`.
///
/// The edge reaches the callback as a case number, in `Edge`'s declared order:
/// top, leading, bottom, trailing.
pub fn accessibility_scroll_action(view: &ViewHandle, action: impl Fn(i64) + 'static) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::edge_enum_ma());
        // `Edge` is frozen, so the case travels in the register itself.
        let c = tag_words(action, meta, false);
        a11y_modifier(resolve::a11y_scroll_action_fn(), view, &c, [0.0; 4])
    }
}

/// Apply `.renameAction(_:)`.
pub fn rename_action(view: &ViewHandle, action: impl Fn() + 'static) -> ViewHandle {
    unsafe {
        opaque_modifier(
            resolve::rename_action_fn(),
            resolve::rename_action_oret(),
            view,
            &action_words(action),
            [0.0; 4],
        )
    }
}

/// Apply `.onSubmit(of:_:)`.
pub fn on_submit(view: &ViewHandle, trigger: SubmitTrigger, action: impl Fn() + 'static) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::submit_triggers_ma());
        let t = resilient_static(meta, trigger.getter());
        let c = action_words(action);
        opaque_modifier(
            resolve::on_submit_fn(),
            resolve::on_submit_oret(),
            view,
            &[t.as_ptr() as u64, c[0], c[1]],
            [0.0; 4],
        )
    }
}

/// Apply `.onDeleteCommand(perform:)`.
pub fn on_delete_command(view: &ViewHandle, action: impl Fn() + 'static) -> ViewHandle {
    unsafe {
        opaque_modifier(
            resolve::on_delete_command_fn(),
            resolve::on_delete_command_oret(),
            view,
            &action_words(action),
            [0.0; 4],
        )
    }
}

/// Apply `.onExitCommand(perform:)`.
pub fn on_exit_command(view: &ViewHandle, action: impl Fn() + 'static) -> ViewHandle {
    unsafe {
        opaque_modifier(
            resolve::on_exit_command_fn(),
            resolve::on_exit_command_oret(),
            view,
            &action_words(action),
            [0.0; 4],
        )
    }
}

/// Apply `.onMoveCommand(perform:)`.
///
/// The direction arrives as a case number: up, down, left, right.
pub fn on_move_command(view: &ViewHandle, action: impl Fn(i64) + 'static) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::move_command_direction_ma());
        let c = tag_words(action, meta, true);
        opaque_modifier(
            resolve::on_move_command_fn(),
            resolve::on_move_command_oret(),
            view,
            &c,
            [0.0; 4],
        )
    }
}

/// Apply `.onInteractiveResizeChange(_:)`.
pub fn on_interactive_resize_change(view: &ViewHandle, action: impl Fn(bool) + 'static) -> ViewHandle {
    unsafe {
        opaque_modifier(
            resolve::on_interactive_resize_fn(),
            resolve::on_interactive_resize_oret(),
            view,
            &bool_words(action),
            [0.0; 4],
        )
    }
}

/// Apply `.onScrollVisibilityChange(threshold:_:)`.
pub fn on_scroll_visibility_change(
    view: &ViewHandle,
    threshold: f64,
    action: impl Fn(bool) + 'static,
) -> ViewHandle {
    unsafe {
        opaque_modifier(
            resolve::on_scroll_visibility_fn(),
            resolve::on_scroll_visibility_oret(),
            view,
            &bool_words(action),
            [threshold, 0.0, 0.0, 0.0],
        )
    }
}

/// Apply `.onOpenURL(perform:)`.
pub fn on_open_url(view: &ViewHandle, action: impl Fn(&str) + 'static) -> ViewHandle {
    unsafe {
        opaque_modifier(
            resolve::on_open_url_fn(),
            resolve::on_open_url_oret(),
            view,
            &url_words(action),
            [0.0; 4],
        )
    }
}

/// Apply `.onScrollPhaseChange(_:)`.
///
/// Both phases arrive as case numbers, in `ScrollPhase`'s declared order:
/// idle, tracking, interacting, decelerating, animating.
pub fn on_scroll_phase_change(view: &ViewHandle, action: impl Fn(i64, i64) + 'static) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::scroll_phase_ma());
        let cb = Box::leak(Box::new(TagPairCallback { f: Box::new(action), meta }));
        let c = pair_words(invoke_tag_pair, cb as *mut TagPairCallback as *mut c_void);
        opaque_modifier(
            resolve::on_scroll_phase_change_fn(),
            resolve::on_scroll_phase_change_oret(),
            view,
            &c,
            [0.0; 4],
        )
    }
}

/// A `SwiftUI.Transaction` being handed to a `.transaction` callback.
///
/// Only for the duration of the call: the pointer is the one SwiftUI passed
/// `inout`, and writing through it after the callback returns writes to a dead
/// stack slot.
#[derive(Clone, Copy, Debug)]
pub struct TransactionRef(*mut c_void);

impl TransactionRef {
    /// Set `disablesAnimations`.
    pub fn set_disables_animations(self, value: bool) {
        unsafe {
            abi::call_out(
                resolve::transaction_disables_animations_set(),
                abi::ints(&[u64::from(value)]),
                [0.0; 4],
                self.0 as u64,
                core::ptr::null_mut(),
            );
        }
    }
}

pub(crate) unsafe extern "C" fn invoke_transaction(a0: u64, _a1: u64, _a2: u64, payload: *mut c_void) {
    let f = unsafe { boxed_ref::<dyn Fn(TransactionRef)>(payload) };
    f(TransactionRef(a0 as *mut c_void));
}

/// Apply `.transaction(_:)`.
///
/// The transaction is `inout`, so it arrives by address whether or not it would
/// otherwise be loadable, and the callback can write to it in place.
pub fn transaction(view: &ViewHandle, action: impl Fn(TransactionRef) + 'static) -> ViewHandle {
    unsafe {
        let c = wide_words(invoke_transaction, boxed_ctx(Box::new(action) as Box<dyn Fn(TransactionRef)>));
        opaque_modifier(resolve::transaction_fn(), resolve::transaction_oret(), view, &c, [0.0; 4])
    }
}

/// Apply `.accessibilityChildren(children:)`.
pub fn accessibility_children(view: &ViewHandle, children: &ViewHandle) -> ViewHandle {
    unsafe {
        content_modifier(
            resolve::a11y_children_fn(),
            resolve::a11y_children_oret(),
            view,
            &[],
            children,
        )
    }
}

/// Apply `.accessibilityRepresentation(representation:)`.
pub fn accessibility_representation(view: &ViewHandle, representation: &ViewHandle) -> ViewHandle {
    unsafe {
        content_modifier(
            resolve::a11y_representation_fn(),
            resolve::a11y_representation_oret(),
            view,
            &[],
            representation,
        )
    }
}

swift_statics! {
    /// A member of `SwiftUI.AccessibilityActionCategory`.
    pub enum ActionCategory {
        Default = c"$s7SwiftUI27AccessibilityActionCategoryV7defaultACvgZ",
        Edit = c"$s7SwiftUI27AccessibilityActionCategoryV4editACvgZ",
    }
}

/// Apply `.accessibilityActions(category:_:)`.
pub fn accessibility_actions(
    view: &ViewHandle,
    category: ActionCategory,
    content: &ViewHandle,
) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::a11y_action_category_ma());
        let c = resilient_static(meta, category.getter());
        content_modifier(
            resolve::a11y_actions_fn(),
            resolve::a11y_actions_oret(),
            view,
            &[c.as_ptr() as u64],
            content,
        )
    }
}

/// Apply `.toolbarTitleMenu(content:)`.
pub fn toolbar_title_menu(view: &ViewHandle, content: &ViewHandle) -> ViewHandle {
    unsafe {
        content_modifier(
            resolve::toolbar_title_menu_fn(),
            resolve::toolbar_title_menu_oret(),
            view,
            &[],
            content,
        )
    }
}

/// Apply `.sectionActions(content:)`.
pub fn section_actions(view: &ViewHandle, content: &ViewHandle) -> ViewHandle {
    unsafe {
        content_modifier(
            resolve::section_actions_fn(),
            resolve::section_actions_oret(),
            view,
            &[],
            content,
        )
    }
}

/// Apply `.tabItem(_:)`.
pub fn tab_item(view: &ViewHandle, label: &ViewHandle) -> ViewHandle {
    unsafe {
        content_modifier(resolve::tab_item_fn(), resolve::tab_item_oret(), view, &[], label)
    }
}

#[cfg(test)]
mod closure_tests {
    use super::*;
    use std::sync::atomic::{AtomicI64, Ordering};

    /// Call a closure the way Swift does: argument in x0, context in x20.
    ///
    /// Constructing a modifier proves only that the closure's two words were
    /// accepted. Whether the callback runs, and whether it reads the argument
    /// out of the right register, is not visible in the view's type or in a
    /// dump of its value — so it is checked here directly.
    unsafe fn call_closure(words: [u64; 2], arg: u64) {
        unsafe {
            core::arch::asm!("blr {f}", f = in(reg) words[0],
                in("x0") arg, in("x20") words[1],
                lateout("x1") _, lateout("x2") _, lateout("x3") _, lateout("x4") _,
                lateout("x5") _, lateout("x6") _, lateout("x7") _, lateout("x8") _,
                lateout("x9") _, lateout("x10") _, lateout("x11") _, lateout("x12") _,
                lateout("x13") _, lateout("x14") _, lateout("x15") _, lateout("x16") _,
                lateout("x17") _, lateout("lr") _, lateout("x21") _, clobber_abi("C"),
            );
        }
    }

    static SEEN: AtomicI64 = AtomicI64::new(-1);

    fn record(v: i64) {
        SEEN.store(v, Ordering::SeqCst);
    }

    #[test]
    fn frozen_enum_case_arrives_in_the_register() {
        unsafe {
            // `Edge` is frozen and one byte, so the case number *is* x0.
            let meta = abi::metadata0(resolve::edge_enum_ma());
            let words = tag_words(record, meta, false);
            for case in 0..4u64 {
                SEEN.store(-1, Ordering::SeqCst);
                call_closure(words, case);
                assert_eq!(SEEN.load(Ordering::SeqCst), case as i64, "Edge case {case}");
            }
        }
    }

    #[test]
    fn resilient_enum_case_arrives_by_address() {
        unsafe {
            // `MoveCommandDirection` is the same one byte but not frozen, so
            // x0 holds a pointer to it rather than the case itself.
            let meta = abi::metadata0(resolve::move_command_direction_ma());
            let words = tag_words(record, meta, true);
            for case in 0..4u32 {
                let mut buf = vec![0u8; abi::type_bytes(meta)];
                abi::inject_enum_tag(&mut buf, meta, case);
                SEEN.store(-1, Ordering::SeqCst);
                call_closure(words, buf.as_ptr() as u64);
                assert_eq!(SEEN.load(Ordering::SeqCst), i64::from(case), "direction {case}");
            }
        }
    }

    fn record_bool(v: bool) {
        SEEN.store(i64::from(v), Ordering::SeqCst);
    }

    #[test]
    fn bool_closure_reads_the_low_bit() {
        let words = bool_words(record_bool);
        unsafe {
            SEEN.store(-1, Ordering::SeqCst);
            call_closure(words, 1);
            assert_eq!(SEEN.load(Ordering::SeqCst), 1);
            call_closure(words, 0);
            assert_eq!(SEEN.load(Ordering::SeqCst), 0);
        }
    }

    /// A round trip through the enum witnesses: inject a case, read it back.
    #[test]
    fn enum_tag_round_trips() {
        unsafe {
            let meta = abi::metadata0(resolve::scroll_phase_ma());
            let mut buf = vec![0u8; abi::type_bytes(meta)];
            for case in 0..5u32 {
                abi::inject_enum_tag(&mut buf, meta, case);
                assert_eq!(abi::read_enum_tag(buf.as_ptr(), meta), case);
            }
        }
    }

    /// The context must survive the call that installed it, so the words a
    /// closure is built from have to point at something leaked rather than at
    /// a temporary.
    #[test]
    fn closure_context_outlives_construction() {
        let words = {
            let view = text("gone by now");
            view_words(&view)
        };
        assert_ne!(words[0], 0);
        assert_ne!(words[1], 0);
        let mut out = 0u64;
        unsafe {
            core::arch::asm!("blr {f}", f = in(reg) words[0],
                in("x8") &mut out as *mut u64, in("x20") words[1],
                lateout("x0") _, lateout("x1") _, lateout("x2") _, lateout("x3") _,
                lateout("x4") _, lateout("x5") _, lateout("x6") _, lateout("x7") _,
                lateout("x9") _, lateout("x10") _, lateout("x11") _, lateout("x12") _,
                lateout("x13") _, lateout("x14") _, lateout("x15") _, lateout("x16") _,
                lateout("x17") _, lateout("lr") _, lateout("x21") _, clobber_abi("C"),
            );
        }
        assert_ne!(out, 0, "the ViewBuilder closure handed back nothing");
    }
}

/// The two words of a `(V) -> ()` closure that ignores its argument.
///
/// SwiftUI hands these callbacks a `DragSession`, a `PencilSqueezeGesturePhase`
/// and the like — values this crate has no reader for yet. The callback still
/// fires; only the argument is dropped, and the wide thunk forwards x0 through
/// x2 so it does not matter whether the value came in registers or by address.
pub(crate) fn ignoring_value_words(action: impl Fn() + 'static) -> [u64; 2] {
    wide_words(invoke_ignoring_value, boxed_ctx(Box::new(action) as Box<dyn Fn()>))
}

pub(crate) unsafe extern "C" fn invoke_ignoring_value(
    _a0: u64,
    _a1: u64,
    _a2: u64,
    payload: *mut c_void,
) {
    let f = unsafe { boxed_ref::<dyn Fn()>(payload) };
    f();
}

/// Apply `.accessibilityZoomAction(_:)`.
pub fn accessibility_zoom_action(view: &ViewHandle, action: impl Fn() + 'static) -> ViewHandle {
    unsafe { a11y_modifier(resolve::a11y_zoom_action_fn(), view, &ignoring_value_words(action), [0.0; 4]) }
}

/// Apply `.onContinueUserActivity(_:perform:)`.
pub fn on_continue_user_activity(view: &ViewHandle, kind: &str, action: impl Fn() + 'static) -> ViewHandle {
    unsafe {
        let s = abi::swift_string(kind);
        let c = ignoring_value_words(action);
        opaque_modifier(
            resolve::on_continue_user_activity_fn(),
            resolve::on_continue_user_activity_oret(),
            view,
            &[
                u64::from_le_bytes(s[..8].try_into().expect("lo")),
                u64::from_le_bytes(s[8..].try_into().expect("hi")),
                c[0],
                c[1],
            ],
            [0.0; 4],
        )
    }
}

/// Apply `.presentationBackground(alignment:content:)`.
pub fn presentation_background(
    view: &ViewHandle,
    alignment: Alignment,
    content: &ViewHandle,
) -> ViewHandle {
    unsafe {
        let a = alignment.words();
        content_modifier(
            resolve::presentation_background_fn(),
            resolve::presentation_background_oret(),
            view,
            &[a[0], a[1]],
            content,
        )
    }
}

swift_statics! {
    /// A content type, as `UTType`'s own static properties name them.
    pub enum ContentType {
        PlainText = c"$s22UniformTypeIdentifiers6UTTypeV9plainTextACvgZ",
        Text = c"$s22UniformTypeIdentifiers6UTTypeV4textACvgZ",
        Url = c"$s22UniformTypeIdentifiers6UTTypeV3urlACvgZ",
    }
}

/// The two words of a closure returning a single word.
pub(crate) fn word_closure(
    body: unsafe extern "C" fn(*mut c_void, u64) -> u64,
    payload: *mut c_void,
) -> [u64; 2] {
    let ctx = Box::leak(Box::new(abi::WordClosureCtx::new(body, payload)))
        as *mut abi::WordClosureCtx;
    [abi::word_closure_thunk as *const () as u64, ctx as u64]
}

unsafe impl Send for ItemProvider {}
unsafe impl Sync for ItemProvider {}

/// A Swift `[NSItemProvider]` built from Rust.
pub(crate) unsafe fn provider_array(items: &[&str]) -> u64 {
    unsafe {
        let meta = crate::type_by_name!(swift_type!(objc NSItemProvider).as_bytes());
        let stride = abi::type_bytes(meta);
        let mut bytes = vec![0u8; stride * items.len()];
        for (i, t) in items.iter().enumerate() {
            let p = ItemProvider::plain_text(t);
            bytes[i * stride..i * stride + 8].copy_from_slice(&(p.0 as u64).to_le_bytes());
        }
        abi::swift_array(meta, items.len(), &bytes)
    }
}

/// Whether a drop should be accepted — `onDrop`'s `isTargeted`-style predicate.
pub(crate) type DropDecide = Box<dyn Fn(&[ItemProvider]) -> bool>;

/// What a drop handler is told, with no answer expected.
pub(crate) type DropObserve = Box<dyn Fn(&[ItemProvider])>;

/// What an item-provider closure carries.
pub(crate) struct ProviderPayload {
    array: u64,
    decide: Option<DropDecide>,
    observe: Option<DropObserve>,
}

pub(crate) unsafe extern "C" fn emit_providers(payload: *mut c_void, _arg: u64) -> u64 {
    unsafe {
        let p = &*(payload as *const ProviderPayload);
        swift_runtime_sys::RuntimeRaw::swift_retain(p.array as *mut c_void);
        p.array
    }
}

pub(crate) unsafe extern "C" fn emit_first_provider(payload: *mut c_void, _arg: u64) -> u64 {
    unsafe {
        let p = &*(payload as *const ProviderPayload);
        let items = read_provider_array(p.array);
        items.first().map_or(0, |i| i.0 as u64)
    }
}

pub(crate) unsafe extern "C" fn decide_on_providers(payload: *mut c_void, arg: u64) -> u64 {
    unsafe {
        let p = &*(payload as *const ProviderPayload);
        let items = read_provider_array(arg);
        u64::from(p.decide.as_ref().map(|f| f(&items)).unwrap_or(false))
    }
}

pub(crate) unsafe extern "C" fn observe_providers(
    a0: u64,
    _a1: u64,
    _a2: u64,
    payload: *mut c_void,
) {
    unsafe {
        let p = &*(payload as *const ProviderPayload);
        if let Some(f) = p.observe.as_ref() {
            f(&read_provider_array(a0));
        }
    }
}

pub(crate) fn provider_payload(
    array: u64,
    decide: Option<DropDecide>,
    observe: Option<DropObserve>,
) -> *mut c_void {
    Box::leak(Box::new(ProviderPayload { array, decide, observe })) as *mut ProviderPayload
        as *mut c_void
}

swift_statics! {
    /// Where a container background sits.
    /// Where a `.containerBackground` is drawn.
    ///
    /// **`Navigation` and `NavigationSplitView` are unavailable on macOS** —
    /// SwiftUI ships trap stubs for them there, so reaching one aborts with
    /// "Unavailable code reached" rather than failing to resolve. `Window` and
    /// `Presentation` work on every platform. Measured, not assumed: each case
    /// was called on macOS and the two named here are the ones that trap.
    pub enum ContainerBackgroundPlacement {
        Window = c"$s7SwiftUI28ContainerBackgroundPlacementV6windowACvgZ",
        /// Unavailable on macOS: SwiftUI ships a trap stub there, so
        /// reaching this aborts with "Unavailable code reached".
        #[cfg(not(target_os = "macos"))]
        Navigation = c"$s7SwiftUI28ContainerBackgroundPlacementV10navigationACvgZ",
        Presentation = c"$s7SwiftUI28ContainerBackgroundPlacementV12presentationACvgZ",
        /// Unavailable on macOS: SwiftUI ships a trap stub there, so
        /// reaching this aborts with "Unavailable code reached".
        #[cfg(not(target_os = "macos"))]
        NavigationSplitView = c"$s7SwiftUI28ContainerBackgroundPlacementV19navigationSplitViewACvgZ",
    }
}

swift_cases! {
    /// `SwiftUI.VerticalEdge`.
    pub enum VerticalEdge {
        Top = 0,
        Bottom = 1,
    }
}

/// Apply `.containerBackground(for:alignment:content:)`.
pub fn container_background(
    view: &ViewHandle,
    placement: ContainerBackgroundPlacement,
    alignment: Alignment,
    content: &ViewHandle,
) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::container_background_placement_ma());
        let p = resilient_static(meta, placement.getter());
        let a = alignment.words();
        content_modifier(
            resolve::container_background_fn(),
            resolve::container_background_oret(),
            view,
            &[p.as_ptr() as u64, a[0], a[1]],
            content,
        )
    }
}

/// The edge, alignment and spacing the two safe-area modifiers share.
unsafe fn safe_area_args(
    edge: VerticalEdge,
    alignment: HorizontalAlignment,
    spacing: Option<f64>,
) -> Vec<u64> {
    unsafe {
        let e = abi::enum_argument(abi::metadata0(resolve::vertical_edge_ma()), edge.tag());
        let a = frozen_static(abi::metadata0(resolve::horizontal_alignment_ma()), alignment.getter());
        let mut ints = vec![e, a];
        ints.extend(opt_f64_words(spacing));
        ints
    }
}

/// Apply `.safeAreaInset(edge:alignment:spacing:content:)`.
pub fn safe_area_inset(
    view: &ViewHandle,
    edge: VerticalEdge,
    alignment: HorizontalAlignment,
    spacing: Option<f64>,
    content: &ViewHandle,
) -> ViewHandle {
    unsafe {
        let args = safe_area_args(edge, alignment, spacing);
        content_modifier(
            resolve::safe_area_inset_fn(),
            resolve::safe_area_inset_oret(),
            view,
            &args,
            content,
        )
    }
}

/// Apply `.safeAreaBar(edge:alignment:spacing:content:)`.
pub fn safe_area_bar(
    view: &ViewHandle,
    edge: VerticalEdge,
    alignment: HorizontalAlignment,
    spacing: Option<f64>,
    content: &ViewHandle,
) -> ViewHandle {
    unsafe {
        let args = safe_area_args(edge, alignment, spacing);
        content_modifier(
            resolve::safe_area_bar_fn(),
            resolve::safe_area_bar_oret(),
            view,
            &args,
            content,
        )
    }
}

/// Apply `.userActivity(_:isActive:_:)`.
pub fn user_activity(view: &ViewHandle, kind: &str, active: bool, action: impl Fn() + 'static) -> ViewHandle {
    unsafe {
        let s = abi::swift_string(kind);
        let c = ignoring_value_words(action);
        opaque_modifier(
            resolve::user_activity_fn(),
            resolve::user_activity_oret(),
            view,
            &[
                u64::from_le_bytes(s[..8].try_into().expect("lo")),
                u64::from_le_bytes(s[8..].try_into().expect("hi")),
                u64::from(active),
                c[0],
                c[1],
            ],
            [0.0; 4],
        )
    }
}

swift_statics! {
    /// A haptic or audible cue.
    pub enum SensoryFeedback {
        Success = c"$s7SwiftUI15SensoryFeedbackV7successACvgZ",
        Warning = c"$s7SwiftUI15SensoryFeedbackV7warningACvgZ",
        Error = c"$s7SwiftUI15SensoryFeedbackV5errorACvgZ",
        Selection = c"$s7SwiftUI15SensoryFeedbackV9selectionACvgZ",
        Impact = c"$s7SwiftUI15SensoryFeedbackV6impactACvgZ",
        Alignment = c"$s7SwiftUI15SensoryFeedbackV9alignmentACvgZ",
        Decrease = c"$s7SwiftUI15SensoryFeedbackV8decreaseACvgZ",
        Increase = c"$s7SwiftUI15SensoryFeedbackV8increaseACvgZ",
        LevelChange = c"$s7SwiftUI15SensoryFeedbackV11levelChangeACvgZ",
        PathComplete = c"$s7SwiftUI15SensoryFeedbackV12pathCompleteACvgZ",
        Start = c"$s7SwiftUI15SensoryFeedbackV5startACvgZ",
        Stop = c"$s7SwiftUI15SensoryFeedbackV4stopACvgZ",
    }
}

/// A byte buffer as the argument registers it occupies.
pub(crate) fn words(bytes: &[u8]) -> Vec<u64> {
    bytes
        .chunks(8)
        .map(|c| {
            let mut w = [0u8; 8];
            w[..c.len()].copy_from_slice(c);
            u64::from_le_bytes(w)
        })
        .collect()
}

swift_statics! {
    /// Where a search field is placed in the surrounding chrome.
    ///
    /// A struct rather than an enum, so each case is a static getter returning a
    /// value small enough to travel in a register.
    pub enum SearchFieldPlacement {
        Automatic = c"$s7SwiftUI20SearchFieldPlacementV9automaticACvgZ",
        ToolbarPrincipal = c"$s7SwiftUI20SearchFieldPlacementV16toolbarPrincipalACvgZ",
        NavigationColumn = c"$s7SwiftUI20SearchFieldPlacementV16navigationColumnACvgZ",
        /// Unavailable on macOS: SwiftUI ships a trap stub there, so
        /// reaching this aborts with "Unavailable code reached".
        #[cfg(not(target_os = "macos"))]
        NavigationBarDrawer = c"$s7SwiftUI20SearchFieldPlacementV19navigationBarDrawerACvgZ",
        Sidebar = c"$s7SwiftUI20SearchFieldPlacementV7sidebarACvgZ",
        Toolbar = c"$s7SwiftUI20SearchFieldPlacementV7toolbarACvgZ",
    }
}

/// Apply a modifier with *two* generic `View` parameters beyond `Self`.
///
/// Distinct from `generics::generic2_modifier_ints`, which is one generic
/// parameter carrying two conformances.
///
/// The tail is every metadata argument in generic-parameter order and then every
/// witness table in requirement order — not the two interleaved, which is what
/// repeating [`generic1_modifier_ints`] would give.
pub(crate) unsafe fn two_view_modifier(
    func: *const c_void,
    oret: *const c_void,
    view: &ViewHandle,
    leading: &[u64],
    a: &ViewHandle,
    b: &ViewHandle,
) -> ViewHandle {
    unsafe {
        // `Self`, then the two content views — which are passed as `AnyView`
        // words, so only the first of each triple is the receiver's.
        // Three distinct types: the receiver, and each of the two contents,
        // which `view_words` now hands back at its own type rather than boxed.
        let subst = [view.meta, a.meta, b.meta, view.wt, a.wt, b.wt];
        let (meta, wt, size) = opaque_result_type(oret, &subst);
        let mut ints = leading.to_vec();
        ints.extend_from_slice(&view_words(a));
        ints.extend_from_slice(&view_words(b));
        ints.extend_from_slice(&[view.meta as u64, a.meta as u64, b.meta as u64]);
        ints.extend_from_slice(&[view.wt as u64, a.wt as u64, b.wt as u64]);
        let r = abi::call_modifier_generic(func, view.value_ptr(), &ints, [0.0; 4], size);
        wrap_owned(r, meta, wt)
    }
}

swift_statics! {
    /// `SwiftUI.SearchSuggestionsPlacement.Set`, an option set.
    pub enum SearchSuggestionsPlacementSet {
        Menu = c"$s7SwiftUI26SearchSuggestionsPlacementV3SetV4menuAEvgZ",
        Content = c"$s7SwiftUI26SearchSuggestionsPlacementV3SetV7contentAEvgZ",
    }
}

swift_statics! {
    /// `SwiftUI.TextInputFormattingControlPlacement.Set`, an option set.
    pub enum TextInputFormattingControlPlacementSet {
        All = c"$s7SwiftUI35TextInputFormattingControlPlacementV3SetV3allAEvgZ",
        Default = c"$s7SwiftUI35TextInputFormattingControlPlacementV3SetV7defaultAEvgZ",
        ContextMenu = c"$s7SwiftUI35TextInputFormattingControlPlacementV3SetV11contextMenuAEvgZ",
        AccessoryBar = c"$s7SwiftUI35TextInputFormattingControlPlacementV3SetV12accessoryBarAEvgZ",
        /// Unavailable on macOS: SwiftUI ships a trap stub there, so
        /// reaching this aborts with "Unavailable code reached".
        #[cfg(not(target_os = "macos"))]
        InputAssistant = c"$s7SwiftUI35TextInputFormattingControlPlacementV3SetV14inputAssistantAEvgZ",
        FontPanel = c"$s7SwiftUI35TextInputFormattingControlPlacementV3SetV9fontPanelAEvgZ",
    }
}

swift_statics! {
    /// A Foundation `CharacterSet`, by the static that names it.
    ///
    /// `Whitespaces` and `Decimals` are the ones the parity suite compares.
    /// `.alphanumerics` is bound and correct, but it cannot be compared *across
    /// processes*: which concrete class backs it — a bitmap `NSCharacterSet` or
    /// a CF-bridged `__NSCFCharacterSet` — depends on what else in the process
    /// has touched Foundation, and `dump` prints the two differently. That is a
    /// property of Foundation's caching, not of the call.
    pub enum CharacterSetKind {
        Alphanumerics = c"$s10Foundation12CharacterSetV13alphanumericsACvgZ",
        Letters = c"$s10Foundation12CharacterSetV7lettersACvgZ",
        Decimals = c"$s10Foundation12CharacterSetV13decimalDigitsACvgZ",
        Whitespaces = c"$s10Foundation12CharacterSetV11whitespacesACvgZ",
    }
}

swift_statics! {
    /// Which phases of a key press to observe.
    pub enum KeyPressPhases {
        Down = c"$s7SwiftUI8KeyPressV6PhasesV4downAEvgZ",
        Up = c"$s7SwiftUI8KeyPressV6PhasesV2upAEvgZ",
        Repeat = c"$s7SwiftUI8KeyPressV6PhasesV6repeatAEvgZ",
        All = c"$s7SwiftUI8KeyPressV6PhasesV3allAEvgZ",
    }
}

/// Apply `.navigationTransition(_:)` with the automatic transition.
///
/// The static is declared on the *protocol*, in an extension constrained to
/// `Self == AutomaticNavigationTransition`, so reading it means naming that
/// concrete type — and the conformance comes from a runtime lookup rather than
/// an exported witness-table symbol.
pub fn navigation_transition(view: &ViewHandle) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::automatic_navigation_transition_ma());
        let wt = abi::get_view_wt_for_proto(meta, resolve::navigation_transition_proto());
        assert!(!wt.is_null(), "AutomaticNavigationTransition: NavigationTransition");
        let value = abi::static_out(
            resolve::navigation_transition_automatic(), meta, abi::type_bytes(meta));
        generic1_modifier_ints(
            resolve::navigation_transition_fn(),
            resolve::navigation_transition_oret(),
            view,
            meta,
            wt,
            &[value.as_ptr() as u64],
            [0.0; 4],
        )
    }
}

swift_statics! {
    /// A line height, as `AttributedString.LineHeight`'s statics name it.
    ///
    /// The initialiser taking an `NSParagraphStyle` is SwiftUI-internal, so the
    /// statics are the public way in — and `exact(points:)` and
    /// `multiple(factor:)` are the only two that take an argument.
    pub enum LineHeightKind {
        Variable = c"$s10Foundation16AttributedStringV8CoreTextE10LineHeightV8variableAFvgZ",
        Normal = c"$s10Foundation16AttributedStringV8CoreTextE10LineHeightV6normalAFvgZ",
        Tight = c"$s10Foundation16AttributedStringV8CoreTextE10LineHeightV5tightAFvgZ",
        Loose = c"$s10Foundation16AttributedStringV8CoreTextE10LineHeightV5looseAFvgZ",
    }
}

/// Apply `.lineHeight(_:)`.
///
/// `AttributedString.LineHeight` is nine bytes and resilient, so its static
/// getters write through x8 and the optional wrapping one goes to the modifier
/// by address. Passing `None` writes the optional's `.none` tag and leaves the
/// payload alone.
pub fn line_height(view: &ViewHandle, height: Option<LineHeightKind>) -> ViewHandle {
    unsafe {
        let payload = abi::metadata0(resolve::line_height_ma());
        let opt = abi::resolve_type_by_mangled_name(
            b"10Foundation16AttributedStringV8CoreTextE10LineHeightVSg");
        assert!(!opt.is_null(), "Optional<AttributedString.LineHeight>");
        let mut buf = vec![0u8; abi::type_bytes(opt)];
        if let Some(kind) = height {
            let v = resilient_static(payload, kind.getter());
            buf[..v.len()].copy_from_slice(&v);
        }
        abi::store_optional_tag(&mut buf, payload, height.is_some());
        opaque_modifier(
            resolve::line_height_fn(),
            resolve::line_height_oret(),
            view,
            &[buf.as_ptr() as u64],
            [0.0; 4],
        )
    }
}

/// Apply `.refreshable(action:)`.
///
/// The action is a Swift `async` closure built by [`crate::asyncfn`]: it runs
/// `action` and resumes immediately, never suspending.
pub fn refreshable(view: &ViewHandle, action: impl Fn() + Send + Sync + 'static) -> ViewHandle {
    unsafe {
        static mut RECORD: crate::asyncfn::FunctionPointer =
            crate::asyncfn::FunctionPointer::new();
        let closure = crate::asyncfn::prepare(
            crate::static_mut(&raw mut RECORD),
            0,
            action,
        );
        opaque_modifier(
            resolve::refreshable_fn(),
            resolve::refreshable_oret(),
            view,
            &closure,
            [0.0; 4],
        )
    }
}

/// [`generic1_modifier_ints`] for out-of-crate diagnostics.
#[doc(hidden)]
pub unsafe fn generic1_modifier_ints_for_test(
    func: *const c_void,
    oret: *const c_void,
    view: &ViewHandle,
    arg_meta: *const c_void,
    arg_wt: *const c_void,
    leading: &[u64],
) -> ViewHandle {
    unsafe { generic1_modifier_ints(func, oret, view, arg_meta, arg_wt, leading, [0.0; 4]) }
}

swift_statics! {
    /// How urgently a `task` should run.
    /// `.medium` is deliberately absent. The stdlib marks it
    /// `@_alwaysEmitIntoClient`, so unlike its neighbours it has no symbol to
    /// call — `dlsym` returns null for `$sScP6mediumScPvgZ` even with
    /// `libswift_Concurrency` loaded, and naming it could only panic.
    pub enum TaskPriority {
        High = c"$sScP4highScPvgZ",
        UserInitiated = c"$sScP13userInitiatedScPvgZ",
        Utility = c"$sScP7utilityScPvgZ",
        Low = c"$sScP3lowScPvgZ",
        Background = c"$sScP10backgroundScPvgZ",
    }
}

/// Apply `.task(id:priority:_:)`.
pub fn task(
    view: &ViewHandle,
    id: i64,
    priority: TaskPriority,
    file: &str,
    line: i64,
    action: impl Fn() + Send + Sync + 'static,
) -> ViewHandle {
    unsafe {
        static mut RECORD: crate::asyncfn::FunctionPointer =
            crate::asyncfn::FunctionPointer::new();
        let closure = crate::asyncfn::prepare(
            crate::static_mut(&raw mut RECORD),
            1,
            action,
        );
        let ctx = Box::leak(Box::new(abi::IsolatedContext::nonisolated()))
            as *mut abi::IsolatedContext;
        let pm = abi::metadata0(resolve::task_priority_ma());
        let p = resilient_static(pm, priority.getter());
        let name = abi::swift_string(&format!("View.task @ {file}:{line}"));
        let n0 = u64::from_le_bytes(name[..8].try_into().expect("name lo"));
        let n1 = u64::from_le_bytes(name[8..].try_into().expect("name hi"));
        let meta = resolve::int_meta();
        let wt = resolve::int_equatable_wt();
        let modifier = abi::generic_metadata2(resolve::task_modifier_ma(), meta, wt);
        assert!(!modifier.is_null(), "_TaskValueModifier2<Int> metadata");
        let mut value = vec![0u8; abi::type_bytes(modifier)];
        let mut boxed = id;
        core::arch::asm!(
            "sub sp, sp, #16",
            "stp {s0}, {s1}, [sp]",
            "blr {f}",
            "add sp, sp, #16",
            f = in(reg) resolve::task_modifier_init(),
            s0 = in(reg) meta, s1 = in(reg) wt,
            in("x0") &mut boxed as *mut i64,
            in("x1") n0, in("x2") n1,
            in("x3") 0u64, in("x4") 0u64,
            in("x5") p.as_ptr(),
            in("x6") closure[0], in("x7") ctx as u64,
            in("x8") value.as_mut_ptr(),
            lateout("x9") _, lateout("x10") _, lateout("x11") _, lateout("x12") _,
            lateout("x13") _, lateout("x14") _, lateout("x15") _, lateout("x16") _,
            lateout("x17") _, lateout("lr") _, lateout("x20") _, lateout("x21") _,
            clobber_abi("C"),
        );
        apply_modifier(view, modifier, &value)
    }
}

/// Apply `.task { … }` — the spelling with no `id:`.
///
/// A different modifier from [`task`], not a default-argument version of it:
/// that one builds `_TaskValueModifier2<ID>` and re-runs when the id changes,
/// this one builds `_TaskModifier2` and runs once. `_TaskModifier2` is not
/// generic, so there are no generic words to spill.
///
/// The `name` carries the call site — SwiftUI records `View.task @ file:line` —
/// so a value comparison against a reference only agrees if the caller passes
/// the reference's own file and line, which is why they are parameters.
pub fn task_once(
    view: &ViewHandle,
    priority: TaskPriority,
    file: &str,
    line: i64,
    action: impl Fn() + Send + Sync + 'static,
) -> ViewHandle {
    unsafe {
        static mut RECORD: crate::asyncfn::FunctionPointer =
            crate::asyncfn::FunctionPointer::new();
        let closure = crate::asyncfn::prepare(
            crate::static_mut(&raw mut RECORD),
            2,
            action,
        );
        let ctx = Box::leak(Box::new(abi::IsolatedContext::nonisolated()))
            as *mut abi::IsolatedContext;
        let pm = abi::metadata0(resolve::task_priority_ma());
        let p = resilient_static(pm, priority.getter());
        let name = abi::swift_string(&format!("View.task @ {file}:{line}"));
        let n0 = u64::from_le_bytes(name[..8].try_into().expect("name lo"));
        let n1 = u64::from_le_bytes(name[8..].try_into().expect("name hi"));

        let modifier = abi::metadata0(resolve::task_modifier2_ma());
        assert!(!modifier.is_null(), "_TaskModifier2 metadata");
        let mut value = vec![0u8; abi::type_bytes(modifier)];
        // init(name:executorPreference:priority:action:)
        //   x0/x1 = name, x2/x3 = TaskExecutor? existential (nil),
        //   x4 = &priority, x5 = action fn, x6 = action ctx, x8 = @out
        core::arch::asm!("blr {f}", f = in(reg) resolve::task_modifier2_init(),
            in("x0") n0, in("x1") n1,
            in("x2") 0u64, in("x3") 0u64,
            in("x4") p.as_ptr(),
            in("x5") closure[0], in("x6") ctx as u64,
            in("x8") value.as_mut_ptr(),
            lateout("x7") _, lateout("x9") _, lateout("x10") _, lateout("x11") _,
            lateout("x12") _, lateout("x13") _, lateout("x14") _, lateout("x15") _,
            lateout("x16") _, lateout("x17") _, lateout("lr") _, lateout("x20") _,
            lateout("x21") _, clobber_abi("C"),
        );
        apply_modifier(view, modifier, &value)
    }
}