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
//! The modifiers SwiftUI has only on iOS.
//!
//! Eight members declared `@available(macOS, unavailable)`. There is nothing to
//! resolve on a Mac — not a trap stub, as with
//! [`ContentToolbarPlacement`](super::ContentToolbarPlacement), but no symbol at
//! all — so the whole module is gated rather than left to fail at first use.
//!
//! What is worth reading here is the three argument conventions they span,
//! because each one is a place a binding could be wrong without looking wrong:
//!
//!   * `UIKeyboardType` and `UITextAutocapitalizationType` are
//!     `NS_ENUM(NSInteger)`, so they arrive as one `Int` in a register and their
//!     numbering is fixed by the UIKit header. That header is the source, and a
//!     test re-reads it and fails if the values here drift from it.
//!   * `NavigationBarItem.TitleDisplayMode` is a *resilient* Swift enum, so it
//!     travels by address and its case numbering is not something a caller may
//!     write down. The tag is read from reflection by case name, exactly as
//!     `GridItem.Size` is.
//!   * `TextInputAutocapitalization?` is an optional wrapping a resilient
//!     struct: the payload comes from the type's own static getter and the
//!     discriminator from `storeEnumTagSinglePayload`, on **the payload's**
//!     witness table.
//!
//! These are verified in a simulator by `examples/ios_parity.rs`, against the
//! same Swift the rest of the crate is held to — type, value and pixels.

use super::{
    enum_bytes, modifier_bool, modifier_i64, modifier_indirect, static_getter,
    static_getter_indirect, BoundState, EdgeSet, ViewHandle,
};
use crate::abi;
use crate::mangle::{self, swift_type};
use crate::resolve;
use core::ffi::c_void;

// ── fullScreenCover ──

/// `.fullScreenCover(isPresented:onDismiss:content:)` with a fixed flag.
///
/// As with [`super::sheet`], a constant binding is read-only: the cover cannot
/// dismiss itself, because there is nowhere for SwiftUI to write `false`. Use
/// [`full_screen_cover_bound`] for one the user can close.
pub fn full_screen_cover(view: &ViewHandle, content: &ViewHandle, presented: bool) -> ViewHandle {
    unsafe {
        let binding = super::constant_binding(
            &[u8::from(presented)],
            resolve::bool_meta(),
            mangle::bound(&swift_type!(SwiftUI.Binding), &[mangle::BOOL]).as_bytes(),
        );
        super::presenting_with_dismiss(
            view,
            content,
            &binding,
            [0, 0],
            resolve::full_screen_cover_fn(),
            resolve::full_screen_cover_oret(),
        )
    }
}

/// `.fullScreenCover` bound to Rust state, so dismissing it writes `false` back.
pub fn full_screen_cover_bound(
    view: &ViewHandle,
    content: &ViewHandle,
    state: &BoundState<bool>,
) -> ViewHandle {
    unsafe {
        let binding = super::bool_binding_of(state);
        super::presenting_with_dismiss(
            view,
            content,
            &binding,
            [0, 0],
            resolve::full_screen_cover_fn(),
            resolve::full_screen_cover_oret(),
        )
    }
}

/// `.fullScreenCover` with the `onDismiss:` closure spelled out.
pub fn full_screen_cover_bound_dismiss(
    view: &ViewHandle,
    content: &ViewHandle,
    state: &BoundState<bool>,
    on_dismiss: impl Fn() + 'static,
) -> ViewHandle {
    unsafe {
        let binding = super::bool_binding_of(state);
        let words = super::action_words(on_dismiss);
        super::presenting_with_dismiss(
            view,
            content,
            &binding,
            words,
            resolve::full_screen_cover_fn(),
            resolve::full_screen_cover_oret(),
        )
    }
}

// ── Bars ──

/// `.statusBarHidden(_:)`.
///
/// Reached through `statusBar(hidden:)`. `statusBarHidden` is
/// `@_alwaysEmitIntoClient`, so it exports no symbol of its own — its body is
/// this call, which is what a Swift caller compiles to.
pub fn status_bar_hidden(view: &ViewHandle, hidden: bool) -> ViewHandle {
    unsafe {
        modifier_bool(
            resolve::status_bar_fn(),
            resolve::status_bar_oret(),
            view,
            hidden,
        )
    }
}

/// `.navigationBarHidden(_:)`.
pub fn navigation_bar_hidden(view: &ViewHandle, hidden: bool) -> ViewHandle {
    unsafe {
        modifier_bool(
            resolve::navigation_bar_hidden_fn(),
            resolve::navigation_bar_hidden_oret(),
            view,
            hidden,
        )
    }
}

/// How large a navigation bar draws its title — `NavigationBarItem.TitleDisplayMode`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TitleDisplayMode {
    /// Whatever the surrounding navigation stack decides.
    Automatic,
    /// Small, beside the bar's buttons.
    Inline,
    /// The large title that shrinks as the content scrolls under it.
    Large,
}

impl TitleDisplayMode {
    /// Swift's own name for the case, which is how its tag is looked up.
    fn case(self) -> &'static str {
        match self {
            Self::Automatic => "automatic",
            Self::Inline => "inline",
            Self::Large => "large",
        }
    }
}

/// `.navigationBarTitleDisplayMode(_:)`.
///
/// The mode is a resilient enum, so it goes by address and its tag is read from
/// reflection rather than written down — see [`abi::enum_case_index`].
pub fn navigation_bar_title_display_mode(
    view: &ViewHandle,
    mode: TitleDisplayMode,
) -> ViewHandle {
    unsafe {
        let ma = resolve::title_display_mode_ma();
        let meta = abi::metadata0(ma);
        assert!(!meta.is_null(), "NavigationBarItem.TitleDisplayMode metadata");
        let tag = abi::enum_case_index(meta, mode.case()).unwrap_or_else(|| {
            panic!("NavigationBarItem.TitleDisplayMode has no `{}` case", mode.case())
        });
        let bytes = enum_bytes(ma, tag as u32);
        modifier_indirect(
            resolve::nav_bar_title_display_mode_fn(),
            resolve::nav_bar_title_display_mode_oret(),
            view,
            &bytes,
        )
    }
}

// ── Text input ──

/// `UIKit.UIKeyboardType`, as the UIKit header numbers it.
///
/// An `NS_ENUM(NSInteger)`, so these are the ABI and not an ordering this crate
/// chose. `keyboard_header_values` in the tests re-reads
/// `UITextInputTraits.h` from the installed SDK and fails if the two disagree.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(i64)]
pub enum KeyboardType {
    /// The current input method's own keyboard.
    Default = 0,
    /// One that can reach every ASCII character.
    AsciiCapable = 1,
    /// Numbers and punctuation.
    NumbersAndPunctuation = 2,
    /// Optimised for URLs — `.` and `/` are prominent.
    Url = 3,
    /// Locale-appropriate digits only, for a PIN.
    NumberPad = 4,
    /// A phone keypad, letters under the digits.
    PhonePad = 5,
    /// A name or a phone number.
    NamePhonePad = 6,
    /// Optimised for e-mail — `@` and `.` are prominent.
    EmailAddress = 7,
    /// A number pad with a decimal point.
    DecimalPad = 8,
    /// Easy access to `@` and `#`.
    Twitter = 9,
    /// The default with a prominent space and `.`.
    WebSearch = 10,
    /// A number pad that is always ASCII digits.
    AsciiCapableNumberPad = 11,
}

/// `.keyboardType(_:)`.
pub fn keyboard_type(view: &ViewHandle, kind: KeyboardType) -> ViewHandle {
    unsafe {
        modifier_i64(
            resolve::keyboard_type_fn(),
            resolve::keyboard_type_oret(),
            view,
            kind as i64,
        )
    }
}

/// `UIKit.UITextAutocapitalizationType`, as the UIKit header numbers it.
///
/// See [`KeyboardType`] for where the values come from and what checks them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(i64)]
pub enum Autocapitalization {
    /// Capitalise nothing.
    None = 0,
    /// Every word.
    Words = 1,
    /// The first word of each sentence.
    Sentences = 2,
    /// Everything.
    AllCharacters = 3,
}

/// `.autocapitalization(_:)`.
///
/// Deprecated in SwiftUI in favour of
/// [`text_input_autocapitalization`], and bound because Apple's catalogue still
/// lists it and a caller targeting an older iOS has nothing else.
pub fn autocapitalization(view: &ViewHandle, style: Autocapitalization) -> ViewHandle {
    unsafe {
        modifier_i64(
            resolve::autocapitalization_fn(),
            resolve::autocapitalization_oret(),
            view,
            style as i64,
        )
    }
}

swift_statics! {
    /// `SwiftUI.TextInputAutocapitalization` — the modern spelling.
    ///
    /// A resilient struct with four static properties rather than an enum, so
    /// each case is a getter returning indirectly.
    pub enum TextInputCapitalization {
        Never = c"$s7SwiftUI27TextInputAutocapitalizationV5neverACvgZ",
        Words = c"$s7SwiftUI27TextInputAutocapitalizationV5wordsACvgZ",
        Sentences = c"$s7SwiftUI27TextInputAutocapitalizationV9sentencesACvgZ",
        Characters = c"$s7SwiftUI27TextInputAutocapitalizationV10charactersACvgZ",
    }
}

/// `.textInputAutocapitalization(_:)`. `None` means `nil` — defer to the field.
///
/// The argument is `TextInputAutocapitalization?`, an optional wrapping a
/// resilient struct. The payload is whatever the static getter writes; the
/// discriminator goes in through `storeEnumTagSinglePayload` on the *payload's*
/// witness table, which is the rule [`abi::store_optional_tag`] exists to keep.
pub fn text_input_autocapitalization(
    view: &ViewHandle,
    style: Option<TextInputCapitalization>,
) -> ViewHandle {
    unsafe {
        let payload = abi::metadata0(resolve::text_input_autocapitalization_ma());
        assert!(!payload.is_null(), "TextInputAutocapitalization metadata");
        let opt = abi::resolve_type_by_mangled_name(
            swift_type!(opt SwiftUI.TextInputAutocapitalization).as_bytes(),
        );
        assert!(!opt.is_null(), "Optional<TextInputAutocapitalization> metadata");

        let mut buf = vec![0u8; abi::type_bytes(opt)];
        if let Some(s) = style {
            let value = static_getter_indirect(s.resolved(), payload, 0);
            buf[..value.len()].copy_from_slice(&value);
        }
        abi::store_optional_tag(&mut buf, payload, style.is_some());

        modifier_indirect(
            resolve::text_input_autocapitalization_fn(),
            resolve::text_input_autocapitalization_oret(),
            view,
            &buf,
        )
    }
}

// ── Gestures ──

/// `.defersSystemGestures(on:)` — hold off the home indicator and Control Centre
/// swipes on the named edges.
///
/// `Edge.Set` is an option set over one byte, read out of SwiftUI's own static
/// rather than written as a bitmask.
pub fn defers_system_gestures(view: &ViewHandle, edges: EdgeSet) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::edge_set_ma());
        let (bits, _) = static_getter(edges.resolved(), meta);
        modifier_i64(
            resolve::defers_system_gestures_fn(),
            resolve::defers_system_gestures_oret(),
            view,
            bits as i64,
        )
    }
}

// ── MultiDatePicker ──

/// One calendar day, as a `Foundation.DateComponents`.
///
/// Only the three fields a date picker reads. `DateComponents` has seventeen
/// optionals and no initialiser that defaults them from outside its module, so a
/// value is built as an `NSDateComponents` through the Objective-C runtime and
/// bridged across — documented API in both directions, and not a guess about the
/// layout of a resilient 283-byte struct.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Day {
    /// The year, as the calendar counts it.
    pub year: i64,
    /// The month, 1–12.
    pub month: i64,
    /// The day of the month, from 1.
    pub day: i64,
}

/// A `DateComponents` value for `day`, in a buffer.
///
/// # Safety
/// Calls into Foundation.
unsafe fn date_components(day: Day) -> Vec<u8> {
    unsafe {
        let cls = crate::objc::class(c"OBJC_CLASS_$_NSDateComponents");
        assert!(!cls.is_null(), "NSDateComponents class");
        let obj = crate::objc::send(cls, crate::objc::sel(c"alloc"));
        let obj = crate::objc::send(obj, crate::objc::sel(c"init"));
        assert!(!obj.is_null(), "NSDateComponents init");
        crate::objc::send_i64(obj, crate::objc::sel(c"setYear:"), day.year);
        crate::objc::send_i64(obj, crate::objc::sel(c"setMonth:"), day.month);
        crate::objc::send_i64(obj, crate::objc::sel(c"setDay:"), day.day);

        let meta = abi::metadata0(resolve::date_components_ma());
        assert!(!meta.is_null(), "DateComponents metadata");
        let mut out = vec![0u8; abi::type_bytes(meta)];
        // `_unconditionallyBridgeFromObjectiveC(_:)` — the class instance as one
        // word in x0 (an `NSDateComponents?`, and a non-null one), the struct
        // through x8. A concrete static, so there is no `Self.Type` to pass.
        core::arch::asm!("blr {f}", f = in(reg) resolve::date_components_from_ns(),
            in("x0") obj,
            in("x8") out.as_mut_ptr(),
            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("x20") _, lateout("x21") _,
            clobber_abi("C"),
        );
        out
    }
}

/// `MultiDatePicker(title, selection: .constant(days))` — pick several dates.
///
/// iOS only. The selection is a **constant** binding, so the days shown are the
/// ones passed and the user's taps do not come back: SwiftUI treats
/// `Binding.constant` as read-only. A writable form needs a
/// [`BoundState`]`<Set<DateComponents>>`, and `BoundState` does not yet carry a
/// Foundation collection — that is the missing piece, not the picker.
pub fn multi_date_picker(title: &str, days: &[Day]) -> ViewHandle {
    unsafe {
        let named = mangle::bound(
            &swift_type!(SwiftUI.MultiDatePicker),
            &[&swift_type!(SwiftUI.Text)],
        );
        let meta = abi::resolve_type_by_mangled_name(named.as_bytes());
        assert!(!meta.is_null(), "{}", mangle::demangle(&named));
        let wt = abi::get_view_wt(meta);
        assert!(!wt.is_null(), "{} !: View", crate::diag::type_name(meta));

        let dc_meta = abi::metadata0(resolve::date_components_ma());
        assert!(!dc_meta.is_null(), "DateComponents metadata");
        // `DateComponents: Hashable` is looked up rather than named: the
        // conformance is in Foundation and its witness-table symbol is not
        // something this crate should depend on when the runtime will find it.
        let hashable = abi::get_view_wt_for_proto(dc_meta, resolve::hashable_proto());
        assert!(!hashable.is_null(), "DateComponents !: Hashable");

        let stride = abi::type_bytes(dc_meta);
        let mut bytes = vec![0u8; stride * days.len()];
        for (i, d) in days.iter().enumerate() {
            let v = date_components(*d);
            bytes[i * stride..i * stride + v.len()].copy_from_slice(&v);
        }
        let set = abi::swift_set(dc_meta, hashable, days.len(), &bytes);

        let set_named = mangle::set(&swift_type!(Foundation.DateComponents));
        let set_meta = abi::resolve_type_by_mangled_name(set_named.as_bytes());
        assert!(!set_meta.is_null(), "{}", mangle::demangle(&set_named));
        let binding = super::constant_binding(
            &set.to_le_bytes(),
            set_meta,
            mangle::bound(&swift_type!(SwiftUI.Binding), &[&set_named]).as_bytes(),
        );
        // `Binding<Set<…>>` is three words: the location, the transaction, and
        // the cached value — which for a `Set` is one word, not a byte, so all
        // three are read as words.
        let b0 = u64::from_le_bytes(binding[0..8].try_into().expect("binding lo"));
        let b1 = u64::from_le_bytes(binding[8..16].try_into().expect("binding mid"));
        let b2 = u64::from_le_bytes(binding[16..24].try_into().expect("binding hi"));

        let (k0, k1, k2, k3) = super::lsk_words(title);
        let mut result = vec![0u8; abi::type_bytes(meta)];
        core::arch::asm!("blr {f}", f = in(reg) resolve::multi_date_picker_init(),
            in("x0") k0, in("x1") k1, in("x2") k2, in("x3") k3,
            in("x4") b0, in("x5") b1, in("x6") b2,
            in("x8") result.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"),
        );
        super::wrap_owned(result, meta, wt)
    }
}

// ── actionSheet ──

/// Which of the three `Alert.Button` constructors a button is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum AlertButtonKind {
    Cancel,
    Default,
    Destructive,
}

/// One button in an [`action_sheet`].
///
/// `Alert.Button`, which the action sheet shares with the deprecated `Alert`.
/// `.cancel()` has no title of its own — the system supplies "Cancel" — so its
/// title is ignored rather than passed.
pub struct AlertButton<'a> {
    kind: AlertButtonKind,
    title: &'a str,
    action: [u64; 2],
}

impl<'a> AlertButton<'a> {
    /// `.cancel()` — dismisses the sheet.
    pub fn cancel() -> Self {
        Self { kind: AlertButtonKind::Cancel, title: "", action: [0, 0] }
    }

    /// `.default(Text(title))`.
    pub fn default(title: &'a str) -> Self {
        Self { kind: AlertButtonKind::Default, title, action: [0, 0] }
    }

    /// `.destructive(Text(title))` — drawn in red.
    pub fn destructive(title: &'a str) -> Self {
        Self { kind: AlertButtonKind::Destructive, title, action: [0, 0] }
    }

    /// What to run when it is tapped. Without this the action is `nil`, which is
    /// what Swift's defaulted argument passes.
    pub fn on_tap(mut self, action: impl Fn() + 'static) -> Self {
        self.action = super::action_words(action);
        self
    }

    /// The button's value, in a buffer.
    ///
    /// # Safety
    /// Calls into SwiftUI.
    unsafe fn value(&self) -> Vec<u8> {
        unsafe {
            let meta = abi::metadata0(resolve::alert_button_ma());
            assert!(!meta.is_null(), "Alert.Button metadata");
            let mut out = vec![0u8; abi::type_bytes(meta)];
            match self.kind {
                // `cancel(_ action: (() -> Void)?)` — two words and nothing else.
                AlertButtonKind::Cancel => {
                    core::arch::asm!("blr {f}", f = in(reg) resolve::alert_button_cancel(),
                        in("x0") self.action[0], in("x1") self.action[1],
                        in("x8") out.as_mut_ptr(),
                        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("x20") _, lateout("x21") _,
                        clobber_abi("C"),
                    );
                }
                // `default(_: Text, action:)` and `destructive(_:action:)` — a
                // four-word `Text` then the optional closure.
                kind => {
                    let f = if kind == AlertButtonKind::Default {
                        resolve::alert_button_default()
                    } else {
                        resolve::alert_button_destructive()
                    };
                    let t = super::text_value(self.title);
                    core::arch::asm!("blr {f}", f = in(reg) f,
                        in("x0") t[0], in("x1") t[1], in("x2") t[2], in("x3") t[3],
                        in("x4") self.action[0], in("x5") self.action[1],
                        in("x8") out.as_mut_ptr(),
                        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
        }
    }
}

/// What [`emit_action_sheet`] builds.
struct SheetPayload {
    title: [u64; 4],
    message: [u64; 4],
    buttons: u64,
    meta: *const c_void,
}

/// The `() -> ActionSheet` closure's body.
///
/// It returns a value of a concrete type rather than a view, so the result is
/// copied through the type's own witness rather than written as a word.
///
/// # Safety
/// Reached through [`abi::swift_closure_thunk`]; `payload` must be a live
/// [`SheetPayload`].
unsafe extern "C" fn emit_action_sheet(out: *mut u8, payload: *mut c_void) {
    let p = unsafe { &*(payload as *const SheetPayload) };
    unsafe {
        // `ActionSheet(title:message:buttons:)` — x0-x3 the title `Text`,
        // x4-x7 the `Text?` message, [sp] the `[Alert.Button]` array.
        core::arch::asm!(
            "sub sp, sp, #16",
            "str {b}, [sp]",
            "blr {f}",
            "add sp, sp, #16",
            f = in(reg) resolve::action_sheet_init(),
            b = in(reg) p.buttons,
            in("x0") p.title[0], in("x1") p.title[1],
            in("x2") p.title[2], in("x3") p.title[3],
            in("x4") p.message[0], in("x5") p.message[1],
            in("x6") p.message[2], in("x7") p.message[3],
            in("x8") out,
            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 _ = p.meta;
}

/// `.actionSheet(isPresented:content:)` — the iOS sheet of choices.
///
/// Deprecated by Apple in favour of `confirmationDialog`, and bound because the
/// catalogue still lists it and an app targeting an older iOS has nothing else.
///
/// `presented` is a constant, so the sheet cannot dismiss itself; use
/// [`action_sheet_bound`] for one the user can close.
pub fn action_sheet(
    view: &ViewHandle,
    title: &str,
    message: Option<&str>,
    buttons: Vec<AlertButton<'_>>,
) -> ViewHandle {
    unsafe {
        let binding = super::constant_binding(
            &[1u8],
            resolve::bool_meta(),
            mangle::bound(&swift_type!(SwiftUI.Binding), &[mangle::BOOL]).as_bytes(),
        );
        sheet_of_actions(view, title, message, buttons, &binding)
    }
}

/// `.actionSheet` bound to Rust state, so dismissing it writes `false` back.
pub fn action_sheet_bound(
    view: &ViewHandle,
    title: &str,
    message: Option<&str>,
    buttons: Vec<AlertButton<'_>>,
    state: &BoundState<bool>,
) -> ViewHandle {
    unsafe {
        let binding = super::bool_binding_of(state);
        sheet_of_actions(view, title, message, buttons, &binding)
    }
}

/// # Safety
/// `binding` must be a live `Binding<Bool>`.
unsafe fn sheet_of_actions(
    view: &ViewHandle,
    title: &str,
    message: Option<&str>,
    buttons: Vec<AlertButton<'_>>,
    binding: &[u8],
) -> ViewHandle {
    unsafe {
        assert!(!buttons.is_empty(), "an action sheet needs at least one button");
        let btn_meta = abi::metadata0(resolve::alert_button_ma());
        assert!(!btn_meta.is_null(), "Alert.Button metadata");
        let stride = abi::type_bytes(btn_meta);
        let mut bytes = vec![0u8; stride * buttons.len()];
        for (i, b) in buttons.iter().enumerate() {
            let v = b.value();
            bytes[i * stride..i * stride + v.len()].copy_from_slice(&v);
        }
        let array = abi::swift_array(btn_meta, buttons.len(), &bytes);

        let sheet_meta = abi::metadata0(resolve::action_sheet_ma());
        assert!(!sheet_meta.is_null(), "ActionSheet metadata");
        // The closure escapes in practice — SwiftUI builds the sheet when it is
        // presented, not when the modifier is applied — so the payload is leaked.
        let payload = Box::leak(Box::new(SheetPayload {
            title: super::text_value(title),
            message: match message {
                Some(m) => super::text_value(m),
                None => [0; 4],
            },
            buttons: array,
            meta: sheet_meta,
        })) as *mut SheetPayload as *mut c_void;
        let ctx = Box::leak(Box::new(abi::ClosureCtx::new(emit_action_sheet, payload)))
            as *mut abi::ClosureCtx;

        let b0 = u64::from_le_bytes(binding[0..8].try_into().expect("binding lo"));
        let b1 = u64::from_le_bytes(binding[8..16].try_into().expect("binding mid"));
        let b2 = binding[16] as u64;

        let (meta, wt, size) =
            super::opaque_result_type(resolve::action_sheet_oret(), &[view.meta, view.wt]);
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        // x0-x2 = Binding<Bool>, x3/x4 = the content closure,
        // x5 = Self.Type, x6 = Self: View, x8 = @out, x20 = self.
        core::arch::asm!("blr {f}", f = in(reg) resolve::action_sheet_fn(),
            in("x0") b0, in("x1") b1, in("x2") b2,
            in("x3") abi::swift_closure_thunk as *const c_void,
            in("x4") ctx,
            in("x5") view.meta,
            in("x6") view.wt,
            in("x8") result.as_mut_ptr(),
            in("x20") this,
            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"),
        );
        super::wrap_owned(result, meta, wt)
    }
}

// ── indexViewStyle ──

swift_statics! {
    /// `PageIndexViewStyle.BackgroundDisplayMode` — when the dots get a backdrop.
    pub enum IndexBackground {
        Always = c"$s7SwiftUI18PageIndexViewStyleV21BackgroundDisplayModeV6alwaysAEvgZ",
        Automatic = c"$s7SwiftUI18PageIndexViewStyleV21BackgroundDisplayModeV9automaticAEvgZ",
        Interactive = c"$s7SwiftUI18PageIndexViewStyleV21BackgroundDisplayModeV11interactiveAEvgZ",
        Never = c"$s7SwiftUI18PageIndexViewStyleV21BackgroundDisplayModeV5neverAEvgZ",
    }
}

/// `.indexViewStyle(PageIndexViewStyle(backgroundDisplayMode:))` — the page dots
/// under a paged `TabView`.
///
/// iOS only. `PageIndexViewStyle` is the only `IndexViewStyle` SwiftUI ships, so
/// there is nothing to choose between — what there *is* to choose is when the
/// dots get a backdrop, which is the argument.
pub fn index_view_style_page(view: &ViewHandle, background: IndexBackground) -> ViewHandle {
    unsafe {
        let bg_meta = abi::metadata0(resolve::page_index_background_ma());
        assert!(!bg_meta.is_null(), "PageIndexViewStyle.BackgroundDisplayMode metadata");
        let mut bg = static_getter_indirect(background.resolved(), bg_meta, 0);

        let style_meta = abi::metadata0(resolve::page_index_style_ma());
        assert!(!style_meta.is_null(), "PageIndexViewStyle metadata");
        let style_wt =
            abi::get_view_wt_for_proto(style_meta, resolve::index_view_style_proto());
        assert!(!style_wt.is_null(), "PageIndexViewStyle !: IndexViewStyle");

        let mut style = vec![0u8; abi::type_bytes(style_meta)];
        // `PageIndexViewStyle(backgroundDisplayMode:)` — the mode by address in
        // x0, the style through x8. Both are resilient, so both go indirect.
        core::arch::asm!("blr {f}", f = in(reg) resolve::page_index_style_init(),
            in("x0") bg.as_mut_ptr(),
            in("x8") style.as_mut_ptr(),
            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("x20") _, lateout("x21") _,
            clobber_abi("C"),
        );

        let subst = [view.meta, style_meta, view.wt, style_wt];
        let (meta, wt, size) =
            super::opaque_result_type(resolve::index_view_style_oret(), &subst);
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        // The same shape as every other style modifier: x0 = @in style,
        // x1 = Self.Type, x2 = S.Type, x3 = Self: View, x4 = S: IndexViewStyle.
        core::arch::asm!("blr {f}", f = in(reg) resolve::index_view_style_fn(),
            in("x0") style.as_mut_ptr(),
            in("x1") view.meta,
            in("x2") style_meta,
            in("x3") view.wt,
            in("x4") style_wt,
            in("x8") result.as_mut_ptr(),
            in("x20") this,
            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"),
        );
        super::wrap_owned(result, meta, wt)
    }
}