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
//! Accessibility, focus, lifecycle, gestures, geometry.
//!
//! * Accessibility attributes, traits, and focus

use super::*;
use crate::abi;
use crate::resolve;
use core::ffi::c_void;
use crate::mangle::{self, swift_type};

// ── Accessibility, focus, lifecycle, gestures, geometry ──

mangle::result_types! {
    /// `GeometryReader<AnyView>`
    pub(crate) GEOMETRY_T = ty("GeometryReader").of(vec![ty("AnyView")]);
}
mangle::modifier_types! {
    /// `ModifiedContent<AnyView, AccessibilityAttachmentModifier>`
    pub(crate) A11Y_T = ty("AccessibilityAttachmentModifier");
    /// `ModifiedContent<AnyView, _FocusableModifier>`
    pub(crate) FOCUSABLE_T = ty("_FocusableModifier");
    /// `ModifiedContent<AnyView, AddGestureModifier<LongPressGesture, DefaultGestureCombiner>>`
    pub(crate) LONG_PRESS_T = ty("AddGestureModifier").of(vec![ty("LongPressGesture"), ty("DefaultGestureCombiner")]);
}




/// Apply `.accessibilityLabel(_:)`.
pub fn accessibility_label(view: &ViewHandle, label: &str) -> ViewHandle {
    unsafe {
        let ss = abi::swift_string(label);
        let s0 = u64::from_le_bytes(ss[..8].try_into().unwrap());
        let s1 = u64::from_le_bytes(ss[8..].try_into().unwrap());
        let (k0, k1, k2, k3) = localized_string_key(s0, s1);
        let (_, _, size) = A11Y_T.applied_to(view.meta);
        let r = abi::call_modifier(resolve::a11y_label_fn(), view.value_ptr(), view.meta, view.wt, &[k0, k1, k2, k3], [0.0; 4], size);
        wrap_modified(r, &A11Y_T, view)
    }
}

/// Apply `.accessibilityHidden(_:)`.
pub fn accessibility_hidden(view: &ViewHandle, hidden: bool) -> ViewHandle {
    unsafe {
        let (_, _, size) = A11Y_T.applied_to(view.meta);
        let r =
            abi::call_modifier(resolve::a11y_hidden_fn(), view.value_ptr(), view.meta, view.wt, &[u64::from(hidden)], [0.0; 4], size);
        wrap_modified(r, &A11Y_T, view)
    }
}

/// Apply `.focusable(_:)`.
pub fn focusable(view: &ViewHandle, value: bool) -> ViewHandle {
    unsafe {
        let (_, _, size) = FOCUSABLE_T.applied_to(view.meta);
        let r =
            abi::call_modifier(resolve::focusable_fn(), view.value_ptr(), view.meta, view.wt, &[u64::from(value)], [0.0; 4], size);
        wrap_modified(r, &FOCUSABLE_T, view)
    }
}

/// Apply `.onDisappear(perform:)`.
pub fn on_disappear(view: &ViewHandle, action: impl Fn() + 'static) -> ViewHandle {
    unsafe {
        let ctx = Box::leak(Box::new(abi::ClosureCtx::new(
            invoke_action,
            boxed_ctx(Box::new(action) as Box<dyn Fn()>),
        ))) as *mut abi::ClosureCtx;
        let (_, _, size) = ON_APPEAR_T.applied_to(view.meta);
        let r = abi::call_modifier(resolve::on_disappear_fn(), view.value_ptr(), view.meta, view.wt,
            &[abi::swift_closure_thunk as *const () as u64, ctx as u64],
            [0.0; 4],
            size,
        );
        wrap_modified(r, &ON_APPEAR_T, view)
    }
}

/// Attach a `LongPressGesture` with `.gesture(_:including:)`.
pub fn long_press_gesture(view: &ViewHandle, duration: f64, max_distance: f64) -> ViewHandle {
    unsafe {
        let g_meta = abi::metadata0(resolve::long_press_ma());
        let mut gesture = vec![0u8; abi::type_bytes(g_meta)];
        // LongPressGesture.init(minimumDuration:maximumDistance:)
        core::arch::asm!("blr {f}", f = in(reg) resolve::long_press_init(),
            in("d0") duration, in("d1") max_distance,
            in("x8") gesture.as_mut_ptr(),
            in("x20") g_meta,
            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"),
        );

        let g_wt = abi::get_view_wt_for_proto(g_meta, resolve::gesture_proto());
        assert!(!g_wt.is_null(), "LongPressGesture: Gesture");

        let (_, _, size) = LONG_PRESS_T.applied_to(view.meta);
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        // gesture<G: Gesture>(_: G, including: GestureMask)
        //   x0 = @in gesture, x1 = GestureMask (.all == 3),
        //   x2 = Self.Type, x3 = G.Type, x4 = Self: View WT, x5 = G: Gesture WT
        core::arch::asm!("blr {f}", f = in(reg) resolve::gesture_fn(),
            in("x0") gesture.as_mut_ptr(),
            in("x1") 3u64,
            in("x2") view.meta,
            in("x3") g_meta,
            in("x4") view.wt,
            in("x5") g_wt,
            in("x8") result.as_mut_ptr(),
            in("x20") this,
            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"),
        );
        wrap_modified(result, &LONG_PRESS_T, view)
    }
}

/// The Rust side of a `GeometryReader` content closure, given the measured size.
pub(crate) type GeometryBuilder = Box<dyn Fn(f64, f64) -> ViewHandle>;

/// Read `GeometryProxy.size`.
///
/// `GeometryProxy` is 52 bytes and address-only, so it arrives by pointer; the
/// getter returns a `CGSize`, which is two doubles in d0/d1.
pub(crate) unsafe fn geometry_proxy_size(proxy: *const u8) -> (f64, f64) {
    let (w, h): (f64, f64);
    unsafe {
        core::arch::asm!("blr {f}", f = in(reg) resolve::geometry_proxy_size(),
            in("x20") proxy,
            lateout("d0") w, lateout("d1") h,
            lateout("x0") _, 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"),
        );
    }
    (w, h)
}

/// A builder together with the content type it was found to produce.
///
/// Swift knows a `GeometryReader`'s content type at compile time — the IR shows
/// the closure lowered to `(@out Text, @in GeometryProxy)`, with `Text` written
/// straight into the result — which is why the instantiation is
/// `GeometryReader<Text>` and not `GeometryReader<AnyView>`. A Rust closure
/// returning `ViewHandle` has no such type to read off, so it is *asked*: the
/// builder is run once while constructing, and whatever it produced fixes the
/// instantiation.
pub(crate) struct TypedBuilder {
    pub(crate) builder: GeometryBuilder,
    /// What the probe produced. Every later call has to agree.
    pub(crate) meta: *const c_void,
}

/// `(GeometryProxy) -> Content` — measure the proxy, then build from Rust.
pub(crate) unsafe extern "C" fn emit_geometry_view(out: *mut u8, proxy: i64, payload: *mut c_void) {
    let typed = unsafe { &*(payload as *const TypedBuilder) };
    let (w, h) = unsafe { geometry_proxy_size(proxy as *const u8) };
    let view = (typed.builder)(w, h);
    unsafe {
        if typed.meta.is_null() {
            // No type was promised, so the content is an `AnyView` and the box
            // is the value.
            *(out as *mut u64) = view.into_anyview_word();
            return;
        }
        // A type *was* promised, and SwiftUI has sized its storage for it.
        // Writing anything else would scribble past that, so this is checked
        // rather than assumed — the same rule Swift enforces at compile time by
        // making the closure's return type `some View`, i.e. exactly one type.
        assert_eq!(
            view.meta, typed.meta,
            "a GeometryReader's builder returned {} after returning {} — SwiftUI \
             sized the reader for the first. Use `view_if!` for a branch, which \
             builds a `_ConditionalContent` and so stays one type.",
            crate::diag::type_name(view.meta),
            crate::diag::type_name(typed.meta),
        );
        let vwt = &*swift_runtime_sys::SwiftABI::get_value_witness_table(view.meta);
        if vwt.size > 0 {
            (vwt.initialize_with_copy)(out as *mut c_void, view.value_ptr() as *mut c_void, view.meta);
        }
    }
}

/// `GeometryReader { size in … }`.
///
/// The builder receives the measured width and height, which is the whole point
/// of a `GeometryReader` — a version that discarded the proxy would just be a
/// container. The closure escapes, since SwiftUI re-runs it whenever the
/// geometry changes, so its context is leaked.
pub fn geometry_reader(builder: impl Fn(f64, f64) -> ViewHandle + 'static) -> ViewHandle {
    unsafe {
        let boxed: GeometryBuilder = Box::new(builder);
        // Ask the builder what it makes. A zero-sized proxy is what a reader is
        // handed before it has been laid out, so this is a call it will see
        // anyway — but it *is* an extra call, and a builder with side effects
        // will notice.
        let probe = boxed(0.0, 0.0);
        let (known_meta, known_wt, _) = result_type(&GEOMETRY_T);
        let typed = abi::generic_metadata_from(known_meta, &[probe.meta, probe.wt]);
        let typed_wt = if typed.is_null() { core::ptr::null() } else { abi::get_view_wt(typed) };
        let promised = if typed_wt.is_null() { core::ptr::null() } else { probe.meta };
        let (meta, wt) = if promised.is_null() {
            (known_meta, known_wt)
        } else {
            (typed, typed_wt)
        };
        let content_meta = if promised.is_null() { resolve::anyview_meta() } else { probe.meta };
        let content_wt = if promised.is_null() { resolve::anyview_wt() } else { probe.wt };
        drop(probe);

        let payload =
            Box::into_raw(Box::new(TypedBuilder { builder: boxed, meta: promised })) as *mut c_void;
        let ctx = Box::leak(Box::new(abi::IndexClosureCtx::new(emit_geometry_view, payload)))
            as *mut abi::IndexClosureCtx;

        // `GeometryReader<AnyView>` is sixteen bytes, so it comes back *in
        // registers* rather than through an indirect `x8` result. Supplying an
        // out-pointer here leaves the buffer untouched.
        let (r0, r1): (u64, u64);
        core::arch::asm!("blr {f}", f = in(reg) resolve::geometry_reader_init(),
            inout("x0") abi::index_closure_thunk as *const () as u64 => r0,
            inout("x1") ctx as u64 => r1,
            in("x2") content_meta,
            in("x3") content_wt,
            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("x20") _,
            lateout("x21") _, clobber_abi("C"),
        );
        let mut result = [0u8; 16];
        result[..8].copy_from_slice(&r0.to_le_bytes());
        result[8..].copy_from_slice(&r1.to_le_bytes());
        // An array on the stack, not a buffer the callee filled: this one has
        // to be copied into the handle.
        wrap_buf(&result, meta, wt)
    }
}

/// Apply `.confirmationDialog(_:isPresented:titleVisibility:actions:)`.
///
/// Like `alert`, the actions builder escapes, and the generic arguments spill:
/// the title, binding and visibility fill all eight registers.
/// Shared tail of `confirmation_dialog` and `confirmation_dialog_bound`.
///
/// # Safety
/// `binding` must be a `Binding<Bool>`.
pub(crate) unsafe fn confirmation_dialog_with_binding(
    view: &ViewHandle,
    title: &str, actions: &ViewHandle,
    binding: &[u8],
) -> ViewHandle {
    unsafe {
        let ss = abi::swift_string(title);
        let s0 = u64::from_le_bytes(ss[..8].try_into().unwrap());
        let s1 = u64::from_le_bytes(ss[8..].try_into().unwrap());
        let (k0, k1, k2, k3) = localized_string_key(s0, s1);
        let b0 = u64::from_le_bytes(binding[0..8].try_into().unwrap());
        let b1 = u64::from_le_bytes(binding[8..16].try_into().unwrap());
        let b2 = binding[16] as u64;

        let ctx = Box::leak(Box::new(abi::ClosureCtx::new(
            emit_tuple,
            Child::leak(actions, Content::Concrete),
        ))) as *mut abi::ClosureCtx;

        let subst = [
            view.meta,                        // Self.Type — the concrete receiver
            actions.meta,          // content — the closure emits AnyView
            view.wt,                          // Self: View
            actions.wt,            // content: View
        ];
        let (meta, wt, size) = opaque_result_type(resolve::confirm_oret(), &subst);
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        // confirmationDialog(_:isPresented:titleVisibility:actions:)
        //   x0-x3 = key, x4-x6 = Binding<Bool>, x7 = Visibility (.automatic == 0),
        //   [sp] = actions fn, [sp+8] = actions ctx, [sp+16] = Self.Type,
        //   [sp+24] = A.Type, [sp+32] = Self: View WT, [sp+40] = A: View WT
        core::arch::asm!(
            "sub sp, sp, #48",
            "stp {fnp}, {cx}, [sp]",
            "stp {sm}, {am}, [sp, #16]",
            "stp {sw}, {aw}, [sp, #32]",
            "blr {f}",
            "add sp, sp, #48",
            f = in(reg) resolve::confirm_fn(),
            fnp = in(reg) abi::swift_closure_thunk as *const c_void,
            cx = in(reg) ctx,
            sm = in(reg) view.meta,
            am = in(reg) actions.meta,
            sw = in(reg) view.wt,
            aw = in(reg) actions.wt,
            in("x0") k0, in("x1") k1, in("x2") k2, in("x3") k3,
            in("x4") b0, in("x5") b1, in("x6") b2,
            in("x7") 0u64,
            in("x8") result.as_mut_ptr(),
            in("x20") this,
            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"),
        );
        wrap_owned(result, meta, wt)
    }
}

/// `confirmationDialog(_:isPresented:titleVisibility:actions:message:)`.
///
/// The message is the explanatory line under the title, and on a sheet-style
/// dialog it is often the only place the consequence is stated — "This will
/// delete 12 items" under a bare "Delete". Only the title-and-buttons overload
/// was bound.
///
/// # Safety
/// `binding` must be a live `Binding<Bool>`.
pub(crate) unsafe fn confirmation_message_with_binding(
    view: &ViewHandle,
    title: &str,
    actions: &ViewHandle,
    message: &ViewHandle,
    binding: &[u8],
) -> ViewHandle {
    unsafe {
        let ss = abi::swift_string(title);
        let s0 = u64::from_le_bytes(ss[..8].try_into().expect("title lo"));
        let s1 = u64::from_le_bytes(ss[8..].try_into().expect("title hi"));
        let (k0, k1, k2, k3) = super::primitives::localized_string_key(s0, s1);
        let b0 = u64::from_le_bytes(binding[0..8].try_into().expect("binding 0"));
        let b1 = u64::from_le_bytes(binding[8..16].try_into().expect("binding 1"));
        let b2 = binding[16] as u64;

        let actions_ctx = Box::leak(Box::new(abi::ClosureCtx::new(
            emit_tuple,
            Child::leak(actions, Content::Concrete),
        ))) as *mut abi::ClosureCtx;
        let message_ctx = Box::leak(Box::new(abi::ClosureCtx::new(
            emit_tuple,
            Child::leak(message, Content::Concrete),
        ))) as *mut abi::ClosureCtx;

        let subst = [view.meta, actions.meta, message.meta, view.wt, actions.wt, message.wt];
        let (meta, wt, size) = opaque_result_type(resolve::confirm_msg_oret(), &subst);
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        // confirmationDialog(_:isPresented:titleVisibility:actions:message:)
        //   x0-x3 = key, x4-x6 = Binding<Bool>, x7 = Visibility (.automatic),
        //   [sp]    = actions fn,  [sp+8]  = actions ctx,
        //   [sp+16] = message fn,  [sp+24] = message ctx,
        //   [sp+32] = Self.Type,   [sp+40] = A.Type,    [sp+48] = B.Type,
        //   [sp+56] = Self: View,  [sp+64] = A: View,   [sp+72] = B: View
        core::arch::asm!(
            "sub sp, sp, #80",
            "stp {af}, {ac}, [sp]",
            "stp {mf}, {mc}, [sp, #16]",
            "stp {sm}, {am}, [sp, #32]",
            "stp {mm}, {sw}, [sp, #48]",
            "stp {aw}, {mw}, [sp, #64]",
            "blr {f}",
            "add sp, sp, #80",
            f = in(reg) resolve::confirm_msg_fn(),
            af = in(reg) abi::swift_closure_thunk as *const c_void,
            ac = in(reg) actions_ctx,
            mf = in(reg) abi::swift_closure_thunk as *const c_void,
            mc = in(reg) message_ctx,
            sm = in(reg) subst[0],
            am = in(reg) subst[1],
            mm = in(reg) subst[2],
            sw = in(reg) subst[3],
            aw = in(reg) subst[4],
            mw = in(reg) subst[5],
            in("x0") k0, in("x1") k1, in("x2") k2, in("x3") k3,
            in("x4") b0, in("x5") b1, in("x6") b2,
            in("x7") 0u64,
            in("x8") result.as_mut_ptr(),
            in("x20") this,
            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"),
        );
        wrap_owned(result, meta, wt)
    }
}

/// `confirmationDialog(…actions:message:)` with a fixed flag, which cannot be
/// dismissed — see [`confirmation_dialog`].
pub fn confirmation_message(
    view: &ViewHandle,
    title: &str,
    actions: &ViewHandle,
    message: &ViewHandle,
    presented: bool,
) -> ViewHandle {
    unsafe {
        let binding = constant_binding(
            &[u8::from(presented)],
            resolve::bool_meta(),
            mangle::bound(&swift_type!(SwiftUI.Binding), &[mangle::BOOL]).as_bytes(),
        );
        confirmation_message_with_binding(view, title, actions, message, &binding)
    }
}

/// `confirmationDialog(…actions:message:)` bound to Rust state.
pub fn confirmation_message_bound(
    view: &ViewHandle,
    title: &str,
    actions: &ViewHandle,
    message: &ViewHandle,
    state: &BoundState<bool>,
) -> ViewHandle {
    unsafe {
        let binding = bool_binding_of(state);
        confirmation_message_with_binding(view, title, actions, message, &binding)
    }
}

/// `confirmation_dialog` with a fixed flag. It cannot be dismissed: SwiftUI treats a
/// `Binding.constant` as read-only, so the presentation has no way to write
/// `false` back. Use [`confirmation_dialog_bound`] for one the user can close.
pub fn confirmation_dialog(view: &ViewHandle, title: &str, actions: &ViewHandle, presented: bool) -> ViewHandle {
    unsafe {
        let binding = constant_binding(
            &[u8::from(presented)],
            resolve::bool_meta(),
            mangle::bound(&swift_type!(SwiftUI.Binding), &[mangle::BOOL]).as_bytes(),
        );
        confirmation_dialog_with_binding(view, title, actions, &binding)
    }
}

/// `confirmation_dialog` bound to Rust state, so dismissing it writes `false` back.
pub fn confirmation_dialog_bound(view: &ViewHandle, title: &str, actions: &ViewHandle, state: &BoundState<bool>) -> ViewHandle {
    unsafe {
        let binding = bool_binding_of(state);
        confirmation_dialog_with_binding(view, title, actions, &binding)
    }
}


// ── Accessibility attributes, traits, and focus ──

//
// This family returns `ModifiedContent<Self, AccessibilityAttachmentModifier>`
// outright rather than `some View`, so there is no opaque descriptor to consult
// and the result type is the same for all of them: [`&A11Y_T`].

/// Apply an accessibility modifier, whose result type never varies.
pub(crate) unsafe fn a11y_modifier(
    f: *const c_void,
    v: &ViewHandle,
    ints: &[u64],
    floats: [f64; 4],
) -> ViewHandle {
    unsafe {
        let (_, _, size) = A11Y_T.applied_to(v.meta);
        let r = abi::call_modifier(f, v.value_ptr(), v.meta, v.wt, ints, floats, size);
        wrap_modified(r, &A11Y_T, v)
    }
}

/// Read a resilient type's `static var`, which returns through x8.
///
/// `AccessibilityTraits` and its neighbours are public but not `@frozen`, so
/// their size is not known to a caller compiled against the SDK and every one
/// of them travels by address. That applies to the static members as much as to
/// the arguments: the getter takes the metatype in x20 and writes the value
/// into the buffer x8 points at.
pub(crate) unsafe fn resilient_static(meta: *const c_void, getter: &'static core::ffi::CStr) -> Vec<u8> {
    unsafe {
        let f = resolve::sym(getter);
        assert!(!f.is_null(), "missing static: {}", crate::diag::symbol_name(getter));
        abi::static_out(f, meta, abi::type_bytes(meta))
    }
}

/// A member of `SwiftUI.AccessibilityTraits`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AccessibilityTrait {
    IsButton,
    IsHeader,
    IsLink,
    IsImage,
    IsModal,
    IsSwitch,
    IsTabBar,
    IsToggle,
    IsSelected,
    PlaysSound,
    IsTabButton,
    IsBackButton,
    IsStaticText,
    IsKeyboardKey,
    IsSearchField,
    CausesPageTurn,
    IsMathEquation,
    IsSummaryElement,
    UpdatesFrequently,
    StartsMediaSession,
    AllowsDirectInteraction,
}

impl AccessibilityTrait {
    /// The static property getter that produces this trait.
    pub(crate) fn getter(self) -> &'static core::ffi::CStr {
        match self {
            Self::IsButton => c"$s7SwiftUI19AccessibilityTraitsV8isButtonACvgZ",
            Self::IsHeader => c"$s7SwiftUI19AccessibilityTraitsV8isHeaderACvgZ",
            Self::IsLink => c"$s7SwiftUI19AccessibilityTraitsV6isLinkACvgZ",
            Self::IsImage => c"$s7SwiftUI19AccessibilityTraitsV7isImageACvgZ",
            Self::IsModal => c"$s7SwiftUI19AccessibilityTraitsV7isModalACvgZ",
            Self::IsSwitch => c"$s7SwiftUI19AccessibilityTraitsV8isSwitchACvgZ",
            Self::IsTabBar => c"$s7SwiftUI19AccessibilityTraitsV8isTabBarACvgZ",
            Self::IsToggle => c"$s7SwiftUI19AccessibilityTraitsV8isToggleACvgZ",
            Self::IsSelected => c"$s7SwiftUI19AccessibilityTraitsV10isSelectedACvgZ",
            Self::PlaysSound => c"$s7SwiftUI19AccessibilityTraitsV10playsSoundACvgZ",
            Self::IsTabButton => c"$s7SwiftUI19AccessibilityTraitsV11isTabButtonACvgZ",
            Self::IsBackButton => c"$s7SwiftUI19AccessibilityTraitsV12isBackButtonACvgZ",
            Self::IsStaticText => c"$s7SwiftUI19AccessibilityTraitsV12isStaticTextACvgZ",
            Self::IsKeyboardKey => c"$s7SwiftUI19AccessibilityTraitsV13isKeyboardKeyACvgZ",
            Self::IsSearchField => c"$s7SwiftUI19AccessibilityTraitsV13isSearchFieldACvgZ",
            Self::CausesPageTurn => c"$s7SwiftUI19AccessibilityTraitsV14causesPageTurnACvgZ",
            Self::IsMathEquation => c"$s7SwiftUI19AccessibilityTraitsV14isMathEquationACvgZ",
            Self::IsSummaryElement => c"$s7SwiftUI19AccessibilityTraitsV16isSummaryElementACvgZ",
            Self::UpdatesFrequently => c"$s7SwiftUI19AccessibilityTraitsV17updatesFrequentlyACvgZ",
            Self::StartsMediaSession => c"$s7SwiftUI19AccessibilityTraitsV18startsMediaSessionACvgZ",
            Self::AllowsDirectInteraction => {
                c"$s7SwiftUI19AccessibilityTraitsV23allowsDirectInteractionACvgZ"
            }
        }
    }
}

/// Build an `AccessibilityTraits` set from its members.
///
/// The all-zero pattern is the empty set, so an empty slice needs no call and
/// each trait is folded in with `formUnion` — a mutating method, which takes
/// the receiver by address in x20 like any other resilient `self`.
pub(crate) unsafe fn traits_value(traits: &[AccessibilityTrait]) -> Vec<u8> {
    unsafe {
        let meta = abi::metadata0(resolve::a11y_traits_ma());
        let mut acc = vec![0u8; abi::type_bytes(meta)];
        let union = resolve::a11y_traits_form_union();
        for t in traits {
            let one = resilient_static(meta, t.getter());
            abi::call_out(
                union,
                abi::ints(&[one.as_ptr() as u64]),
                [0.0; 4],
                acc.as_mut_ptr() as u64,
                core::ptr::null_mut(),
            );
        }
        acc
    }
}

swift_cases! {
    /// `SwiftUI.AccessibilityHeadingLevel`, a frozen enum that fits in a register.
    pub enum HeadingLevel {
        Unspecified = 0,
        H1 = 1,
        H2 = 2,
        H3 = 3,
        H4 = 4,
        H5 = 5,
        H6 = 6,
    }
}

swift_statics! {
    /// A member of `SwiftUI.AccessibilityTextContentType`.
    pub enum TextContentType {
        Plain = c"$s7SwiftUI28AccessibilityTextContentTypeV5plainACvgZ",
        Console = c"$s7SwiftUI28AccessibilityTextContentTypeV7consoleACvgZ",
        FileSystem = c"$s7SwiftUI28AccessibilityTextContentTypeV10fileSystemACvgZ",
        Messaging = c"$s7SwiftUI28AccessibilityTextContentTypeV9messagingACvgZ",
        Narrative = c"$s7SwiftUI28AccessibilityTextContentTypeV9narrativeACvgZ",
        SourceCode = c"$s7SwiftUI28AccessibilityTextContentTypeV10sourceCodeACvgZ",
        Spreadsheet = c"$s7SwiftUI28AccessibilityTextContentTypeV11spreadsheetACvgZ",
        WordProcessing = c"$s7SwiftUI28AccessibilityTextContentTypeV14wordProcessingACvgZ",
    }
}

swift_statics! {
    /// A member of `SwiftUI.AccessibilityDirectTouchOptions`.
    pub enum DirectTouchOption {
        SilentOnTouch = c"$s7SwiftUI31AccessibilityDirectTouchOptionsV08silentOnE0ACvgZ",
        RequiresActivation = c"$s7SwiftUI31AccessibilityDirectTouchOptionsV18requiresActivationACvgZ",
    }
}

/// Apply `.accessibility(identifier:)`, the pre-`accessibilityIdentifier` name.
pub fn accessibility_deprecated_identifier(view: &ViewHandle, id: &str) -> ViewHandle {
    unsafe {
        let s = abi::swift_string(id);
        let w0 = u64::from_le_bytes(s[..8].try_into().expect("string lo"));
        let w1 = u64::from_le_bytes(s[8..].try_into().expect("string hi"));
        a11y_modifier(resolve::a11y_deprecated_identifier_fn(), view, &[w0, w1], [0.0; 4])
    }
}

/// Apply `.accessibilityIdentifier(_:)`.
pub fn accessibility_identifier(view: &ViewHandle, id: &str) -> ViewHandle {
    unsafe {
        let s = abi::swift_string(id);
        let w0 = u64::from_le_bytes(s[..8].try_into().expect("string lo"));
        let w1 = u64::from_le_bytes(s[8..].try_into().expect("string hi"));
        a11y_modifier(resolve::a11y_identifier_fn(), view, &[w0, w1], [0.0; 4])
    }
}

/// Apply `.accessibilitySortPriority(_:)`.
pub fn accessibility_sort_priority(view: &ViewHandle, priority: f64) -> ViewHandle {
    unsafe { a11y_modifier(resolve::a11y_sort_priority_fn(), view, &[], [priority, 0.0, 0.0, 0.0]) }
}

/// Apply `.accessibilityValue(_:isEnabled:)`.
pub fn accessibility_value(view: &ViewHandle, value: &str, enabled: bool) -> ViewHandle {
    unsafe {
        let (k0, k1, k2, k3) = lsk_words(value);
        a11y_modifier(resolve::a11y_value_fn(), view, &[k0, k1, k2, k3, u64::from(enabled)], [0.0; 4])
    }
}

/// Apply `.accessibilityRespondsToUserInteraction(_:)`.
pub fn accessibility_responds_to_user_interaction(view: &ViewHandle, responds: bool) -> ViewHandle {
    unsafe {
        a11y_modifier(resolve::a11y_responds_fn(), view, &[u64::from(responds)], [0.0; 4])
    }
}

/// Apply `.accessibilityHint(_:)`.
pub fn accessibility_hint(view: &ViewHandle, hint: &str) -> ViewHandle {
    unsafe {
        let (k0, k1, k2, k3) = lsk_words(hint);
        a11y_modifier(resolve::a11y_hint_fn(), view, &[k0, k1, k2, k3], [0.0; 4])
    }
}

/// Apply `.accessibilityScrollStatus(_:isEnabled:)`.
pub fn accessibility_scroll_status(view: &ViewHandle, status: &str, enabled: bool) -> ViewHandle {
    unsafe {
        let (k0, k1, k2, k3) = lsk_words(status);
        a11y_modifier(
            resolve::a11y_scroll_status_fn(),
            view,
            &[k0, k1, k2, k3, u64::from(enabled)],
            [0.0; 4],
        )
    }
}

/// Apply `.accessibilityActivationPoint(_:)`.
///
/// A `UnitPoint` is two `CGFloat`s and frozen, so it arrives in d0 and d1
/// rather than by address.
pub fn accessibility_activation_point(view: &ViewHandle, x: f64, y: f64) -> ViewHandle {
    unsafe { a11y_modifier(resolve::a11y_activation_point_fn(), view, &[], [x, y, 0.0, 0.0]) }
}

/// Apply `.accessibilityDragPoint(_:description:isEnabled:)`.
pub fn accessibility_drag_point(
    view: &ViewHandle,
    x: f64,
    y: f64,
    description: &str,
    enabled: bool,
) -> ViewHandle {
    unsafe {
        let (k0, k1, k2, k3) = lsk_words(description);
        a11y_modifier(
            resolve::a11y_drag_point_fn(),
            view,
            &[k0, k1, k2, k3, u64::from(enabled)],
            [x, y, 0.0, 0.0],
        )
    }
}

/// Apply `.accessibilityDropPoint(_:description:isEnabled:)`.
pub fn accessibility_drop_point(
    view: &ViewHandle,
    x: f64,
    y: f64,
    description: &str,
    enabled: bool,
) -> ViewHandle {
    unsafe {
        let (k0, k1, k2, k3) = lsk_words(description);
        a11y_modifier(
            resolve::a11y_drop_point_fn(),
            view,
            &[k0, k1, k2, k3, u64::from(enabled)],
            [x, y, 0.0, 0.0],
        )
    }
}

/// Apply `.accessibilityAddTraits(_:)`.
pub fn accessibility_add_traits(view: &ViewHandle, traits: &[AccessibilityTrait]) -> ViewHandle {
    unsafe {
        let v = traits_value(traits);
        a11y_modifier(resolve::a11y_add_traits_fn(), view, &[v.as_ptr() as u64], [0.0; 4])
    }
}

/// Apply `.accessibilityRemoveTraits(_:)`.
pub fn accessibility_remove_traits(view: &ViewHandle, traits: &[AccessibilityTrait]) -> ViewHandle {
    unsafe {
        let v = traits_value(traits);
        a11y_modifier(resolve::a11y_remove_traits_fn(), view, &[v.as_ptr() as u64], [0.0; 4])
    }
}

/// Apply `.accessibilityHeading(_:)`.
pub fn accessibility_heading(view: &ViewHandle, level: HeadingLevel) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::a11y_heading_level_ma());
        let arg = abi::enum_argument(meta, level.tag());
        a11y_modifier(resolve::a11y_heading_fn(), view, &[arg], [0.0; 4])
    }
}

/// Apply `.accessibilityTextContentType(_:)`.
pub fn accessibility_text_content_type(view: &ViewHandle, kind: TextContentType) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::a11y_text_content_type_ma());
        let v = resilient_static(meta, kind.getter());
        a11y_modifier(
            resolve::a11y_text_content_type_fn(),
            view,
            &[v.as_ptr() as u64],
            [0.0; 4],
        )
    }
}

/// Apply `.accessibilityInputLabels(_:isEnabled:)`.
/// Box a `Hashable` value into a `Swift.AnyHashable`.
///
/// Forty bytes, written through x8; the value goes in by address with its
/// metadata and `Hashable` witness beside it. `AnyHashable` is not something
/// this crate can lay out by hand — the box stores a copy made through the
/// value's own witness table, which is what `_convertToAnyHashable` is for.
///
/// # Safety
/// `bytes` must be a live value of type `meta`, conforming through `wt`.
pub(crate) unsafe fn any_hashable(
    bytes: &[u8],
    meta: *const c_void,
    wt: *const c_void,
) -> Vec<u8> {
    unsafe {
        let any_meta = abi::metadata0(resolve::any_hashable_ma());
        assert!(!any_meta.is_null(), "AnyHashable metadata");
        let mut out = vec![0u8; abi::type_bytes(any_meta)];
        core::arch::asm!("blr {f}", f = in(reg) resolve::convert_to_any_hashable(),
            in("x0") bytes.as_ptr(),
            in("x1") meta,
            in("x2") wt,
            in("x8") out.as_mut_ptr(),
            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("x20") _,
            lateout("x21") _, clobber_abi("C"),
        );
        out
    }
}

/// `.accessibility(selectionIdentifier:)` — which item of a selectable group
/// this is, for assistive technologies.
///
/// Deprecated in Swift, with no modern replacement — `accessibilityIdentifier`
/// is a different thing (a test hook). Bound because it is the one member of
/// that family the crate could not otherwise reach.
///
/// The argument is `AnyHashable`, which is three words: the boxed value, its
/// metadata and its `Hashable` witness.
pub fn accessibility_selection_identifier(
    view: &ViewHandle,
    id: super::HashableValue<'_>,
) -> ViewHandle {
    unsafe {
        let (bytes, meta, wt) = id.parts();
        let any = any_hashable(&bytes, meta, wt);
        a11y_modifier(resolve::a11y_selection_identifier_fn(), view, &[any.as_ptr() as u64], [0.0; 4])
    }
}

pub fn accessibility_input_labels(
    view: &ViewHandle,
    labels: &[&str],
    enabled: bool,
) -> ViewHandle {
    unsafe {
        let meta = resolve::lsk_meta();
        let stride = abi::type_bytes(meta);
        let mut bytes = vec![0u8; stride * labels.len()];
        for (i, l) in labels.iter().enumerate() {
            let (k0, k1, k2, k3) = lsk_words(l);
            let at = &mut bytes[i * stride..];
            at[..8].copy_from_slice(&k0.to_le_bytes());
            at[8..16].copy_from_slice(&k1.to_le_bytes());
            at[16..24].copy_from_slice(&k2.to_le_bytes());
            at[24..32].copy_from_slice(&k3.to_le_bytes());
        }
        let array = abi::swift_array(meta, labels.len(), &bytes);
        a11y_modifier(
            resolve::a11y_input_labels_fn(),
            view,
            &[array, u64::from(enabled)],
            [0.0; 4],
        )
    }
}

/// Apply `.accessibilityDirectTouch(_:options:)`.
pub fn accessibility_direct_touch(
    view: &ViewHandle,
    enabled: bool,
    options: &[DirectTouchOption],
) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::a11y_direct_touch_options_ma());
        let mut v = vec![0u8; abi::type_bytes(meta)];
        // An `OptionSet` is its `rawValue`, so members combine by bitwise or
        // without going through `formUnion`.
        for o in options {
            let one = resilient_static(meta, o.getter());
            for (dst, src) in v.iter_mut().zip(one.iter()) {
                *dst |= *src;
            }
        }
        a11y_modifier(
            resolve::a11y_direct_touch_fn(),
            view,
            &[u64::from(enabled), v.as_ptr() as u64],
            [0.0; 4],
        )
    }
}

/// A `LocalizedStringKey`'s four words.
pub(crate) unsafe fn lsk_words(s: &str) -> (u64, u64, u64, u64) {
    unsafe {
        let ss = abi::swift_string(s);
        localized_string_key(
            u64::from_le_bytes(ss[..8].try_into().expect("string lo")),
            u64::from_le_bytes(ss[8..].try_into().expect("string hi")),
        )
    }
}

/// How prominent a piece of custom accessibility content is.
///
/// An imported Objective-C `NS_ENUM`, so it is a plain integer in a register
/// rather than a Swift enum with a witness table.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CustomContentImportance {
    Default = 0,
    High = 1,
}

/// Apply `.accessibilityCustomContent(_:_:importance:)`.
///
/// The key is built first, through `AccessibilityCustomContentKey.init(_:id:)`
/// — four words of `LocalizedStringKey` and two of `String`, returning the key
/// through x8 because it is resilient. The modifier then takes that key by
/// address, its own label as another `LocalizedStringKey`, and the importance
/// in a register.
pub fn accessibility_custom_content(
    view: &ViewHandle,
    key_label: &str,
    id: &str,
    value: &str,
    importance: CustomContentImportance,
) -> ViewHandle {
    unsafe {
        let (kk0, kk1, kk2, kk3) = lsk_words(key_label);
        let ids = abi::swift_string(id);
        let i0 = u64::from_le_bytes(ids[..8].try_into().expect("id lo"));
        let i1 = u64::from_le_bytes(ids[8..].try_into().expect("id hi"));
        let key_meta = abi::metadata0(resolve::a11y_custom_content_key_ma());
        let mut key = vec![0u8; abi::type_bytes(key_meta)];
        core::arch::asm!("blr {f}", f = in(reg) resolve::a11y_custom_content_key_init(),
            in("x0") kk0, in("x1") kk1, in("x2") kk2, in("x3") kk3,
            in("x4") i0, in("x5") i1,
            in("x8") key.as_mut_ptr(), in("x20") key_meta,
            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"),
        );
        let (v0, v1, v2, v3) = lsk_words(value);
        let (_, _, size) = A11Y_T.applied_to(view.meta);
        let r = abi::call_modifier(resolve::a11y_custom_content_fn(), view.value_ptr(), view.meta, view.wt,
            &[key.as_ptr() as u64, v0, v1, v2, v3, importance as u64],
            [0.0; 4],
            size,
        );
        wrap_modified(r, &A11Y_T, view)
    }
}

/// One end of a `String`, as a `String.Index`.
///
/// A `String` is sixteen bytes, which is more than the one register Swift pins
/// `self` to — so a method on it takes `self` *indirectly*, with the address in
/// x20. The index itself is one word and comes back in x0.
unsafe fn string_bound(text: &str, getter: *const c_void) -> u64 {
    unsafe {
        let s = abi::swift_string(text);
        let index: u64;
        core::arch::asm!("blr {f}", f = in(reg) getter,
            in("x20") s.as_ptr(),
            lateout("x0") index,
            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"),
        );
        index
    }
}

/// Apply `.accessibilityRotor(_:textRanges:)`.
///
/// The ranges are real `Range<String.Index>` values taken from `text` — one
/// spanning the whole string. `Range` is frozen and its two bounds are stored
/// back to back, so the array elements are built directly rather than through an
/// initialiser.
pub fn accessibility_rotor(view: &ViewHandle, label: &str, text: &str) -> ViewHandle {
    unsafe {
        let lower = string_bound(text, resolve::string_start_index());
        let upper = string_bound(text, resolve::string_end_index());
        let range = abi::resolve_type_by_mangled_name(mangle::range(&mangle::nested(mangle::STRING, "Index", mangle::Kind::Struct)).as_bytes());
        assert!(!range.is_null(), "Range<String.Index>");
        let stride = abi::type_bytes(range);
        let mut bytes = vec![0u8; stride];
        bytes[..8].copy_from_slice(&lower.to_le_bytes());
        bytes[8..16].copy_from_slice(&upper.to_le_bytes());
        let array = abi::swift_array(range, 1, &bytes);
        let (k0, k1, k2, k3) = lsk_words(label);
        let subst = [view.meta, view.wt];
        let (m, wt, size) = opaque_result_type(resolve::a11y_rotor_oret(), &subst);
        let r = abi::call_modifier(resolve::a11y_rotor_fn(), view.value_ptr(), view.meta, view.wt,
            &[k0, k1, k2, k3, array],
            [0.0; 4],
            size,
        );
        wrap_owned(r, m, wt)
    }
}

/// Apply `.accessibilityChartDescriptor(_:)` with a synthesized representable.
///
/// No public SwiftUI type conforms to `AXChartDescriptorRepresentable` — the
/// protocol exists for applications to adopt — so the conformance is built at
/// run time and hung on `EdgeInsets`, which the reference can name too.
pub fn accessibility_chart_descriptor(view: &ViewHandle) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::edge_insets_ma());
        let wt = crate::conformance::chart_descriptor_representable().witness_table();
        let value = vec![0u8; abi::type_bytes(meta)];
        generic1_modifier_ints(
            resolve::a11y_chart_descriptor_fn(),
            resolve::a11y_chart_descriptor_oret(),
            view,
            meta,
            wt,
            &[value.as_ptr() as u64],
            [0.0; 4],
        )
    }
}