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
//! The last of Apple's own catalogue.
//!
//! `tools/xcode_catalog.py` reads the list Xcode's Library panel is built from —
//! 415 views and modifiers, each with Apple's canonical example — and reports
//! which of them this crate can build. These are the ones that were left, and
//! they are here together rather than scattered because what they have in common
//! is *why* they were last: each needed something the generated bindings cannot
//! express.
//!
//!   * `RenameButton` and `SettingsLink` take no arguments at all — their labels
//!     are fixed types — so there is nothing for a generator to read.
//!   * `HSplitView`/`VSplitView` are containers, not modifiers.
//!   * `ContentUnavailableView` has two initialisers of very different shapes:
//!     three view builders, or a title and an SF Symbol.
//!   * `ScrollViewReader` hands its closure a *proxy*, which is the only place in
//!     SwiftUI where a view builder takes an argument that is not a value the
//!     caller supplied.

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

/// `X<Content>` for a container generic over one `Content: View`.
///
/// Only `HSplitView` and `VSplitView` use this, and both are macOS-only.
///
/// # Safety
/// `ma` must be such a type's metadata accessor.
#[cfg(target_os = "macos")]
unsafe fn container_meta(
    ma: *const c_void,
    content: &ViewHandle,
) -> (*const c_void, *const c_void) {
    unsafe {
        let meta = abi::generic_metadata2(ma, content.meta, content.wt);
        assert!(!meta.is_null(), "container metadata instantiation failed");
        let wt = abi::get_view_wt(meta);
        assert!(!wt.is_null(), "{} !: View", crate::diag::type_name(meta));
        (meta, wt)
    }
}

/// A container built from `init(content:)` — one view builder and nothing else.
///
/// `HSplitView`, `VSplitView` and `Settings` all have this shape:
/// `(sret, closure fn, closure ctx, Content.Type, Content: View)`.
///
/// # Safety
/// `init` must be such an initialiser and `ma` its type's metadata accessor.
#[cfg(target_os = "macos")]
unsafe fn one_child_container(
    init: *const c_void,
    ma: *const c_void,
    content: &ViewHandle,
) -> ViewHandle {
    unsafe {
        let (meta, wt) = container_meta(ma, content);
        // Borrowed, not leaked: `init(content:)` takes its builder `@noescape`
        // and calls it before returning, so the child outlives the call.
        let child = content.clone();
        let kid = Child::new(&child, Content::Concrete);
        let handles = kid.element();
        let payload = TuplePayload { children: handles.as_ptr(), count: 1 };
        let mut ctx =
            abi::ClosureCtx::new(emit_tuple, &payload as *const TuplePayload as *mut c_void);

        let mut result = vec![0u8; abi::type_bytes(meta)];
        core::arch::asm!("blr {f}", f = in(reg) init,
            in("x0") abi::swift_closure_thunk as *const c_void,
            in("x1") &mut ctx as *mut abi::ClosureCtx,
            in("x2") content.meta,
            in("x3") content.wt,
            in("x8") result.as_mut_ptr(),
            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"),
        );
        wrap_owned(result, meta, wt)
    }
}

/// `HSplitView { content }` — a draggable divider between side-by-side panes.
///
/// macOS only. A split *view*, not a `NavigationSplitView`: the panes are
/// resizable by the user and there is no sidebar behaviour.
#[cfg(target_os = "macos")]
pub fn hsplit_view(content: &ViewHandle) -> ViewHandle {
    unsafe {
        one_child_container(resolve::hsplit_view_init(), resolve::hsplit_view_ma(), content)
    }
}

/// `VSplitView { content }` — the same, stacked.
#[cfg(target_os = "macos")]
pub fn vsplit_view(content: &ViewHandle) -> ViewHandle {
    unsafe {
        one_child_container(resolve::vsplit_view_init(), resolve::vsplit_view_ma(), content)
    }
}

/// A view whose initialiser takes nothing but the result slot.
///
/// # Safety
/// `init` must be a no-argument initialiser and `named` its result type's
/// mangled name.
unsafe fn no_argument_view(init: *const c_void, named: &str) -> ViewHandle {
    unsafe {
        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 mut result = vec![0u8; abi::type_bytes(meta)];
        core::arch::asm!("blr {f}", f = in(reg) init,
            in("x8") result.as_mut_ptr(),
            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("x20") _, lateout("x21") _,
            clobber_abi("C"),
        );
        wrap_owned(result, meta, wt)
    }
}

/// `RenameButton()` — the button a `.renameAction` puts in a context menu.
///
/// It takes no arguments: the label is always `Label<Text, Image>`, and what it
/// does comes from the `renameAction` in the environment rather than from a
/// closure here.
pub fn rename_button() -> ViewHandle {
    unsafe {
        let label = mangle::bound(
            &swift_type!(SwiftUI.Label),
            &[&swift_type!(SwiftUI.Text), &swift_type!(SwiftUI.Image)],
        );
        let named = mangle::bound(&swift_type!(SwiftUI.RenameButton), &[&label]);
        no_argument_view(resolve::rename_button_init(), &named)
    }
}

/// `SettingsLink()` — a button that opens the app's `Settings` scene.
///
/// macOS only, and the counterpart to [`crate::scene::settings`]: that builds
/// the window, this is how a view opens it without the user reaching for ⌘,.
#[cfg(target_os = "macos")]
pub fn settings_link() -> ViewHandle {
    unsafe {
        let named = mangle::bound(
            &swift_type!(SwiftUI.SettingsLink),
            &[&swift_type!(SwiftUI.DefaultSettingsLinkLabel)],
        );
        no_argument_view(resolve::settings_link_init(), &named)
    }
}

/// `ContentUnavailableView(title, systemImage:description:)` — the placeholder
/// for an empty list, a failed search, a screen with nothing on it yet.
///
/// The shorthand initialiser, whose three generic parameters are all fixed:
/// `Label<Text, Image>` for the label, `Text?` for the description and
/// `EmptyView` for the actions. `description` is optional — `None` is a genuine
/// `nil`, not an empty string, and draws no second line at all.
pub fn content_unavailable(title: &str, system_image: &str, description: Option<&str>) -> ViewHandle {
    unsafe {
        let label = mangle::bound(
            &swift_type!(SwiftUI.Label),
            &[&swift_type!(SwiftUI.Text), &swift_type!(SwiftUI.Image)],
        );
        let named = mangle::bound(
            &swift_type!(SwiftUI.ContentUnavailableView),
            &[
                &label,
                &mangle::optional(&swift_type!(SwiftUI.Text)),
                &swift_type!(SwiftUI.EmptyView),
            ],
        );
        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 (k0, k1, k2, k3) = lsk_words(title);
        let img = abi::swift_string(system_image);
        let i0 = u64::from_le_bytes(img[..8].try_into().expect("image lo"));
        let i1 = u64::from_le_bytes(img[8..].try_into().expect("image hi"));
        // `Text?` is four words; `nil` is all four zero, since a `Text`'s first
        // word is a reference and a null one is what the optional's spare-bit
        // representation uses.
        let text = match description {
            Some(s) => text_value(s),
            None => [0u64; 4],
        };

        let mut result = vec![0u8; abi::type_bytes(meta)];
        // x0-x3 = LocalizedStringKey, x4/x5 = the systemImage String,
        // x6/x7 + two stack words = the `Text?`, x8 = @out.
        core::arch::asm!(
            "sub sp, sp, #16",
            "stp {t2}, {t3}, [sp]",
            "blr {f}",
            "add sp, sp, #16",
            f = in(reg) resolve::content_unavailable_system_init(),
            t2 = in(reg) text[2],
            t3 = in(reg) text[3],
            in("x0") k0, in("x1") k1, in("x2") k2, in("x3") k3,
            in("x4") i0, in("x5") i1,
            in("x6") text[0], in("x7") text[1],
            in("x8") result.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"),
        );
        wrap_owned(result, meta, wt)
    }
}

// ── ScrollViewReader ──

/// The `ScrollViewProxy` a [`scroll_view_reader`]'s closure is handed.
///
/// An owned copy, not a borrow, because that is how SwiftUI means it to be used:
///
/// ```text
/// ScrollViewReader { proxy in
///     Button("go") { proxy.scrollTo(10) }   // captured, used later
/// }
/// ```
///
/// Calling `scroll_to` *during* the build instead traps —
/// `ScrollViewProxy may not be accessed during view updates`, which is SwiftUI's
/// own check and was measured by doing it. So the proxy has to outlive the
/// closure, and a borrow would not let it.
///
/// `ScrollViewProxy` is resilient, so it reaches the closure by address and its
/// size is not something a caller may assume: the bytes are copied through its
/// own value witness rather than read as a word. It happens to be eight POD
/// bytes today, which is exactly the kind of fact a resilient type is allowed to
/// change.
pub struct ScrollProxy {
    bytes: Vec<u8>,
    meta: *const c_void,
}

impl Clone for ScrollProxy {
    fn clone(&self) -> Self {
        unsafe {
            let vwt = &*swift_runtime_sys::SwiftABI::get_value_witness_table(self.meta);
            let mut bytes = vec![0u8; self.bytes.len()];
            (vwt.initialize_with_copy)(
                bytes.as_mut_ptr() as *mut c_void,
                self.bytes.as_ptr() as *mut c_void,
                self.meta,
            );
            Self { bytes, meta: self.meta }
        }
    }
}

impl Drop for ScrollProxy {
    fn drop(&mut self) {
        unsafe {
            let vwt = &*swift_runtime_sys::SwiftABI::get_value_witness_table(self.meta);
            if vwt.size > 0 {
                (vwt.destroy)(self.bytes.as_mut_ptr() as *mut c_void, self.meta);
            }
        }
    }
}

impl ScrollProxy {
    /// Copy the proxy SwiftUI handed the closure.
    ///
    /// # Safety
    /// `raw` must address a live `ScrollViewProxy`.
    unsafe fn copy_from(raw: *mut c_void) -> Self {
        unsafe {
            let meta = abi::metadata0(resolve::scroll_view_proxy_ma());
            assert!(!meta.is_null(), "ScrollViewProxy metadata");
            let vwt = &*swift_runtime_sys::SwiftABI::get_value_witness_table(meta);
            let mut bytes = vec![0u8; abi::type_bytes(meta)];
            (vwt.initialize_with_copy)(bytes.as_mut_ptr() as *mut c_void, raw, meta);
            Self { bytes, meta }
        }
    }

    /// `proxy.scrollTo(id)` — bring the view with that `.id(_:)` into view.
    ///
    /// `Int` ids only, which is what `ForEach(0..<n)` and `.id(i)` produce. A
    /// `String` id would need its own `Hashable` witness passed, and nothing in
    /// this crate produces one yet.
    pub fn scroll_to(&self, id: i64) {
        unsafe { self.scroll(id, None) }
    }

    /// `proxy.scrollTo(id, anchor: UnitPoint(x:y:))`.
    pub fn scroll_to_anchor(&self, id: i64, anchor: (f64, f64)) {
        unsafe { self.scroll(id, Some(anchor)) }
    }

    /// # Safety
    /// `self.bytes` must hold a live `ScrollViewProxy`.
    unsafe fn scroll(&self, id: i64, anchor: Option<(f64, f64)>) {
        unsafe {
            let mut value = id;
            // `UnitPoint?` is two `CGFloat`s and a tag, and it travels as *three
            // integer registers*: an optional is an enum, and an enum with a
            // payload is lowered to its raw storage rather than to its fields,
            // so the two doubles arrive in x1/x2 and not in d0/d1.
            let (x, y, tag) = match anchor {
                Some((x, y)) => (x.to_bits(), y.to_bits(), 0u64),
                None => (0, 0, 1),
            };
            core::arch::asm!("blr {f}", f = in(reg) resolve::scroll_to_fn(),
                in("x0") &mut value as *mut i64,
                in("x1") x, in("x2") y, in("x3") tag,
                in("x4") resolve::int_meta(),
                in("x5") resolve::int_hashable_wt(),
                in("x20") self.bytes.as_ptr(),
                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"),
            );
        }
    }
}

/// What the reader's content closure needs.
struct ProxyPayload {
    builder: Box<dyn Fn(ScrollProxy) -> ViewHandle>,
}

/// Build the content, handing the proxy through.
///
/// # Safety
/// Reached through [`abi::index_closure_thunk`], which puts the proxy in the
/// second argument; `payload` must be a live [`ProxyPayload`].
unsafe extern "C" fn emit_with_proxy(out: *mut u8, proxy: i64, payload: *mut c_void) {
    let p = unsafe { &*(payload as *const ProxyPayload) };
    let view = (p.builder)(unsafe { ScrollProxy::copy_from(proxy as *mut c_void) });
    unsafe { *(out as *mut u64) = view.into_anyview_word() };
}

/// `ScrollViewReader { proxy in content }` — a scroll view that can be scrolled
/// from code.
///
/// The one view builder in SwiftUI that takes an argument the caller did not
/// supply. It is also *escaping* — `…Vc` in the mangling, not `…VXE` — so both
/// the closure and its context are leaked rather than borrowed: SwiftUI keeps
/// them and calls back long after this returns.
pub fn scroll_view_reader(
    content: impl Fn(ScrollProxy) -> ViewHandle + 'static,
) -> ViewHandle {
    unsafe {
        let meta = abi::generic_metadata2(
            resolve::scroll_view_reader_ma(),
            resolve::anyview_meta(),
            resolve::anyview_wt(),
        );
        assert!(!meta.is_null(), "ScrollViewReader metadata");
        let wt = abi::get_view_wt(meta);
        assert!(!wt.is_null(), "{} !: View", crate::diag::type_name(meta));

        let payload = Box::leak(Box::new(ProxyPayload { builder: Box::new(content) }))
            as *mut ProxyPayload as *mut c_void;
        let ctx = Box::leak(Box::new(abi::IndexClosureCtx::new(emit_with_proxy, payload)))
            as *mut abi::IndexClosureCtx;

        // The initialiser returns its two words *in registers*, not through x8:
        // `ScrollViewReader<Content>` is loadable and small enough. The assert is
        // the check that it still is — a third word would arrive somewhere this
        // does not look.
        let stride = abi::type_bytes(meta);
        assert_eq!(stride, 16, "ScrollViewReader is no longer two words");
        let (w0, w1): (u64, u64);
        core::arch::asm!("blr {f}", f = in(reg) resolve::scroll_view_reader_init(),
            in("x0") abi::index_closure_thunk as *const c_void,
            in("x1") ctx,
            in("x2") resolve::anyview_meta(),
            in("x3") resolve::anyview_wt(),
            lateout("x0") w0, lateout("x1") w1,
            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("x20") _, lateout("x21") _,
            clobber_abi("C"),
        );
        let mut result = vec![0u8; stride];
        result[..8].copy_from_slice(&w0.to_le_bytes());
        result[8..16].copy_from_slice(&w1.to_le_bytes());
        wrap_owned(result, meta, wt)
    }
}

// ── PasteButton ──

/// `PasteButton(supportedContentTypes:payloadAction:)` — a button that pastes.
///
/// Not generic: its label is fixed, so there is no content type to pass. What
/// arrives in the action is the pasteboard's item providers, the same shape
/// `on_paste_command` receives.
pub fn paste_button(
    kinds: &[ContentType],
    paste: impl Fn(&[ItemProvider]) + 'static,
) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::paste_button_ma());
        assert!(!meta.is_null(), "PasteButton metadata");
        let wt = abi::get_view_wt(meta);
        assert!(!wt.is_null(), "{} !: View", crate::diag::type_name(meta));

        let types = content_types(kinds);
        let c = wide_words(observe_providers, provider_payload(0, None, Some(Box::new(paste))));
        let mut result = vec![0u8; abi::type_bytes(meta)];
        core::arch::asm!("blr {f}", f = in(reg) resolve::paste_button_init(),
            in("x0") types,
            in("x1") c[0],
            in("x2") c[1],
            in("x8") result.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"),
        );
        wrap_owned(result, meta, wt)
    }
}

// ── onInsert ──

/// `.onInsert(of:perform:)` — accept a drop into a `ForEach`'s rows.
///
/// A modifier on `DynamicViewContent`, not on `View`: the receiver has to be a
/// `ForEach`, because what the action is told is *where* in the collection the
/// drop landed. Handing it anything else fails loudly rather than rendering
/// something that ignores drops — the conformance lookup is the check.
///
/// The action is `(Int, [NSItemProvider]) -> Void`: the index first, then what
/// was dropped.
pub fn on_insert(
    content: &ViewHandle,
    kinds: &[ContentType],
    action: impl Fn(i64, &[ItemProvider]) + 'static,
) -> ViewHandle {
    unsafe {
        let dvc = abi::get_view_wt_for_proto(content.meta, resolve::dynamic_view_content_proto());
        assert!(
            !dvc.is_null(),
            "{} !: DynamicViewContent — `on_insert` needs a ForEach, not any view",
            crate::diag::type_name(content.meta),
        );

        let types = content_types(kinds);
        let c = pair_words(
            insert_at_index,
            Box::leak(Box::new(InsertPayload { action: Box::new(action) })) as *mut InsertPayload
                as *mut c_void,
        );

        let (meta, _dvc_out, size) =
            super::opaque_result_type(resolve::on_insert_oret(), &[content.meta, dvc]);
        // The opaque type's *first* conformance is `DynamicViewContent`, since
        // that is what the signature promises. A handle needs the `View` one,
        // which the same type also has.
        let wt = abi::get_view_wt(meta);
        assert!(!wt.is_null(), "{} !: View", crate::diag::type_name(meta));

        let mut result = vec![0u8; size];
        let this = content.value_ptr();
        // x0 = [UTType], x1/x2 = the action, x3 = Self.Type,
        // x4 = Self: DynamicViewContent, x8 = @out, x20 = self.
        core::arch::asm!("blr {f}", f = in(reg) resolve::on_insert_fn(),
            in("x0") types,
            in("x1") c[0],
            in("x2") c[1],
            in("x3") content.meta,
            in("x4") dvc,
            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"),
        );
        wrap_owned(result, meta, wt)
    }
}

/// `(Int, [NSItemProvider]) -> Void` as a Rust callback.
type InsertAction = Box<dyn Fn(i64, &[ItemProvider])>;

/// What [`insert_at_index`] calls.
struct InsertPayload {
    action: InsertAction,
}

/// `(Int, [NSItemProvider]) -> Void`, as Rust.
///
/// # Safety
/// Reached through [`abi::pair_closure_thunk`]; `payload` must be a live
/// [`InsertPayload`], `index` an `Int` and `providers` a Swift array of
/// `NSItemProvider`.
unsafe extern "C" fn insert_at_index(index: *const u8, providers: *const u8, payload: *mut c_void) {
    let p = unsafe { &*(payload as *const InsertPayload) };
    let items = unsafe { read_provider_array(providers as u64) };
    (p.action)(index as i64, &items);
}

// ── SubscriptionView ──

/// `SubscriptionView(content:publisher:action:)` — `onReceive` as a view.
///
/// The same thing [`super::on_receive`] does as a modifier, and with the same
/// publisher: `Combine.Empty<Int, Never>`, which is the one publisher that can be
/// built without a Foundation object behind it. `complete_immediately` is
/// `Empty`'s only stored property — `true` finishes at once, `false` never
/// publishes anything.
///
/// `PublisherType` comes *first* in `SubscriptionView<PublisherType, Content>`,
/// so the metadata and witness tables go in that order too. The labels read
/// `content:publisher:` and the arguments follow the labels, which is the
/// opposite order from the generic parameters — worth getting from the IR rather
/// than from the signature.
pub fn subscription_view(
    content: &ViewHandle,
    complete_immediately: bool,
    action: impl Fn(i64) + 'static,
) -> ViewHandle {
    unsafe {
        let empty = mangle::bound("7Combine5EmptyV", &[mangle::INT, mangle::NEVER]);
        let publisher = abi::resolve_type_by_mangled_name(empty.as_bytes());
        assert!(!publisher.is_null(), "{}", mangle::demangle(&empty));
        let pub_wt = abi::get_view_wt_for_proto(publisher, resolve::publisher_proto());
        assert!(!pub_wt.is_null(), "Empty<Int, Never> !: Combine.Publisher");

        let named = mangle::bound(
            &swift_type!(SwiftUI.SubscriptionView),
            &[&empty, &swift_type!(SwiftUI.AnyView)],
        );
        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 mut value = vec![u8::from(complete_immediately); abi::type_bytes(publisher).max(1)];
        // The content is erased, because the closure that produced it could have
        // returned anything; `AnyView` is one word.
        let mut erased_word = content.to_anyview_word().to_le_bytes();

        let ctx = Box::leak(Box::new(abi::ValueClosureCtx::new(
            super::saw_published_int,
            super::boxed_ctx(Box::new(action) as Box<dyn Fn(i64)>),
        ))) as *mut abi::ValueClosureCtx;

        let mut result = vec![0u8; abi::type_bytes(meta)];
        // x0 = @in content, x1 = @in publisher, x2/x3 = the action,
        // x4 = PublisherType.Type, x5 = Content.Type,
        // x6 = PublisherType: Publisher, x7 = Content: View, x8 = @out.
        core::arch::asm!("blr {f}", f = in(reg) resolve::subscription_view_init(),
            in("x0") erased_word.as_mut_ptr(),
            in("x1") value.as_mut_ptr(),
            in("x2") abi::value_closure_thunk as *const c_void,
            in("x3") ctx,
            in("x4") publisher,
            in("x5") resolve::anyview_meta(),
            in("x6") pub_wt,
            in("x7") resolve::anyview_wt(),
            in("x8") result.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"),
        );
        wrap_owned(result, meta, wt)
    }
}

// ── Sign in with Apple ──
//
// The last entry in Apple's catalogue, and the only one that is not in SwiftUI:
// `SignInWithAppleButton` lives in `_AuthenticationServices_SwiftUI`, a
// cross-import overlay that depends on SwiftUI rather than being depended on by
// it. Nothing in the process has loaded it, so `resolve::sym` cannot see it and
// these go through [`resolve::sym_in`], which loads the image first.
//
// The button renders anywhere. *Authorising* needs the Sign in with Apple
// entitlement, which is a signing matter and not a binding one — what is bound
// here is the button, its two callbacks and its style.

/// Which words `SignInWithAppleButton` draws.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AppleButtonLabel {
    /// "Sign in with Apple".
    SignIn,
    /// "Sign up with Apple".
    SignUp,
    /// "Continue with Apple".
    Continue,
}

impl AppleButtonLabel {
    fn getter(self) -> &'static core::ffi::CStr {
        match self {
            Self::SignIn => c"$s31_AuthenticationServices_SwiftUI21SignInWithAppleButtonV5LabelV04signF0AEvgZ",
            Self::SignUp => c"$s31_AuthenticationServices_SwiftUI21SignInWithAppleButtonV5LabelV6signUpAEvgZ",
            Self::Continue => c"$s31_AuthenticationServices_SwiftUI21SignInWithAppleButtonV5LabelV8continueAEvgZ",
        }
    }
}

/// How `SignInWithAppleButton` is painted.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AppleButtonStyle {
    /// Black on white.
    Black,
    /// White on black.
    White,
    /// White with a black outline, for light backgrounds.
    WhiteOutline,
}

impl AppleButtonStyle {
    fn getter(self) -> &'static core::ffi::CStr {
        match self {
            Self::Black => c"$s31_AuthenticationServices_SwiftUI21SignInWithAppleButtonV5StyleV5blackAEvgZ",
            Self::White => c"$s31_AuthenticationServices_SwiftUI21SignInWithAppleButtonV5StyleV5whiteAEvgZ",
            Self::WhiteOutline => c"$s31_AuthenticationServices_SwiftUI21SignInWithAppleButtonV5StyleV12whiteOutlineAEvgZ",
        }
    }
}

/// The `ASAuthorizationAppleIDRequest` the `onRequest` callback is handed.
///
/// A borrowed Objective-C object: configure it and return. The one thing worth
/// configuring is what to ask for, which is why that is the method here; `raw`
/// is for anything else, reachable through [`crate::objc`].
pub struct AppleIDRequest<'a> {
    raw: *mut c_void,
    marker: core::marker::PhantomData<&'a ()>,
}

impl AppleIDRequest<'_> {
    /// `request.requestedScopes = [.fullName, .email]`.
    ///
    /// The two scopes Sign in with Apple offers. Set through the Objective-C
    /// runtime because `ASAuthorizationScope` is a string constant in the
    /// framework's headers, not a Swift enum with a getter.
    pub fn request_full_name_and_email(&self) {
        unsafe {
            let full_name = crate::objc::nsstring("fullName");
            let email = crate::objc::nsstring("email");
            let items = [full_name, email];
            let array_cls = crate::objc::class(c"OBJC_CLASS_$_NSArray");
            assert!(!array_cls.is_null(), "NSArray class");
            type WithObjects =
                unsafe extern "C" fn(*mut c_void, *const c_void, *const *mut c_void, u64) -> *mut c_void;
            let f: WithObjects =
                core::mem::transmute(crate::objc::msg_send_addr());
            let array = f(
                array_cls,
                crate::objc::sel(c"arrayWithObjects:count:"),
                items.as_ptr(),
                2,
            );
            crate::objc::send_id(self.raw, crate::objc::sel(c"setRequestedScopes:"), array);
        }
    }

    /// The object itself, for anything [`request_full_name_and_email`] does not
    /// cover.
    ///
    /// [`request_full_name_and_email`]: Self::request_full_name_and_email
    pub fn raw(&self) -> *mut c_void {
        self.raw
    }
}

/// What the button's two callbacks are.
struct ApplePayload {
    on_request: Box<dyn Fn(AppleIDRequest<'_>)>,
    on_completion: Box<dyn Fn(bool)>,
    result_meta: *const c_void,
}

/// `onRequest: (ASAuthorizationAppleIDRequest) -> Void`.
///
/// A class reference, so x0 *is* the object rather than a pointer to it.
///
/// # Safety
/// Reached through [`abi::value_closure_thunk`]; `payload` must be a live
/// [`ApplePayload`].
unsafe extern "C" fn apple_on_request(request: *const u8, payload: *mut c_void) {
    let p = unsafe { &*(payload as *const ApplePayload) };
    (p.on_request)(AppleIDRequest {
        raw: request as *mut c_void,
        marker: core::marker::PhantomData,
    });
}

/// `onCompletion: (Result<ASAuthorization, any Error>) -> Void`.
///
/// `Result` with an existential failure is address-only, so x0 is the address of
/// the value. Which case it holds is read from the enum's own `getEnumTag`
/// witness — case 0 is `.success` — rather than from the bytes, because a
/// multi-payload enum's discriminator is not at a fixed offset.
///
/// # Safety
/// As [`apple_on_request`].
unsafe extern "C" fn apple_on_completion(result: *const u8, payload: *mut c_void) {
    let p = unsafe { &*(payload as *const ApplePayload) };
    let tag = unsafe { abi::enum_tag(result as *const c_void, p.result_meta) };
    (p.on_completion)(tag == 0);
}

/// `SignInWithAppleButton(label, onRequest:onCompletion:)`.
///
/// `on_request` is called before the sheet appears, to say what to ask for;
/// `on_completion` is told whether the authorisation succeeded.
pub fn sign_in_with_apple_button(
    label: AppleButtonLabel,
    on_request: impl Fn(AppleIDRequest<'_>) + 'static,
    on_completion: impl Fn(bool) + 'static,
) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::siwa_button_ma());
        assert!(!meta.is_null(), "SignInWithAppleButton metadata");
        let wt = abi::get_view_wt(meta);
        assert!(!wt.is_null(), "{} !: View", crate::diag::type_name(meta));

        let label_meta = abi::metadata0(resolve::siwa_label_ma());
        assert!(!label_meta.is_null(), "SignInWithAppleButton.Label metadata");
        let getter = resolve::sym_in(resolve::AUTH_SWIFTUI, label.getter());
        assert!(!getter.is_null(), "{:?}", label.getter());
        let mut label_value = static_getter_indirect(getter, label_meta, 0);

        let result_named = mangle::bound(
            "s6ResultO",
            &["So15ASAuthorizationC", "s5Error_p"],
        );
        let result_meta = abi::resolve_type_by_mangled_name(result_named.as_bytes());
        assert!(!result_meta.is_null(), "{}", mangle::demangle(&result_named));

        // Both callbacks escape — SwiftUI keeps the button and calls them when
        // the user taps it — so the payload and both contexts are leaked.
        let payload = Box::leak(Box::new(ApplePayload {
            on_request: Box::new(on_request),
            on_completion: Box::new(on_completion),
            result_meta,
        })) as *mut ApplePayload as *mut c_void;
        let req_ctx = Box::leak(Box::new(abi::ValueClosureCtx::new(apple_on_request, payload)))
            as *mut abi::ValueClosureCtx;
        let done_ctx =
            Box::leak(Box::new(abi::ValueClosureCtx::new(apple_on_completion, payload)))
                as *mut abi::ValueClosureCtx;

        let mut result = vec![0u8; abi::type_bytes(meta)];
        // x0 = @in Label, x1/x2 = onRequest, x3/x4 = onCompletion, x8 = @out.
        core::arch::asm!("blr {f}", f = in(reg) resolve::siwa_button_init(),
            in("x0") label_value.as_mut_ptr(),
            in("x1") abi::value_closure_thunk as *const c_void,
            in("x2") req_ctx,
            in("x3") abi::value_closure_thunk as *const c_void,
            in("x4") done_ctx,
            in("x8") result.as_mut_ptr(),
            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"),
        );
        wrap_owned(result, meta, wt)
    }
}

/// `.signInWithAppleButtonStyle(_:)`.
///
/// Declared on `View` in the overlay, so its mangled name says `SwiftUI.View`
/// with the overlay as the extension's module — which is why it resolves in the
/// overlay's image and not in SwiftUI's.
pub fn sign_in_with_apple_button_style(
    view: &ViewHandle,
    style: AppleButtonStyle,
) -> ViewHandle {
    unsafe {
        let style_meta = abi::metadata0(resolve::siwa_style_ma());
        assert!(!style_meta.is_null(), "SignInWithAppleButton.Style metadata");
        let getter = resolve::sym_in(resolve::AUTH_SWIFTUI, style.getter());
        assert!(!getter.is_null(), "{:?}", style.getter());
        let mut value = static_getter_indirect(getter, style_meta, 0);

        let (meta, wt, size) =
            super::opaque_result_type(resolve::siwa_style_oret(), &[view.meta, view.wt]);
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        // x0 = @in Style, x1 = Self.Type, x2 = Self: View, x8 = @out, x20 = self.
        core::arch::asm!("blr {f}", f = in(reg) resolve::siwa_style_fn(),
            in("x0") value.as_mut_ptr(),
            in("x1") view.meta,
            in("x2") view.wt,
            in("x8") result.as_mut_ptr(),
            in("x20") this,
            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"),
        );
        wrap_owned(result, meta, wt)
    }
}