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
//! Shapes, images, URLs, defaults.

use super::*;
use crate::abi;
use crate::resolve;
use core::ffi::c_void;
use crate::mangle::swift_type;

// ── Shapes, images, URLs, defaults ──

swift_cases! {
    /// `SwiftUI.AccessibilityLabeledPairRole`.
    pub enum LabeledPairRole {
        Label = 0,
        Content = 1,
    }
}

/// Apply `.accessibilityLabeledPair(role:id:in:)`.
pub fn accessibility_labeled_pair(
    view: &ViewHandle,
    role: LabeledPairRole,
    id: HashableValue<'_>,
) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::a11y_labeled_pair_role_ma());
        let r = abi::enum_argument(meta, role.tag());
        let (bytes, id_meta, wt) = id.parts();
        generic1_modifier_ints(
            resolve::a11y_labeled_pair_fn(),
            resolve::a11y_labeled_pair_oret(),
            view,
            id_meta,
            wt,
            &[r, bytes.as_ptr() as u64, namespace_id()],
            [0.0; 4],
        )
    }
}

/// Apply `.glassEffectID(_:in:)`.
pub fn glass_effect_id(view: &ViewHandle, id: Option<HashableValue<'_>>) -> ViewHandle {
    unsafe {
        let probe = id.unwrap_or(HashableValue::Int(0));
        let (bytes, meta, wt) = probe.parts();
        let opt = abi::generic_metadata1(resolve::optional_ma(), meta);
        let mut buf = vec![0u8; abi::type_bytes(opt)];
        if id.is_some() {
            buf[..bytes.len()].copy_from_slice(&bytes);
        }
        abi::store_optional_tag(&mut buf, meta, id.is_some());
        // `Sendable` is a marker protocol: it constrains the signature but
        // emits no witness table, so `Hashable`'s is the only one to pass.
        generic1_modifier_ints(
            resolve::glass_effect_id_fn(),
            resolve::glass_effect_id_oret(),
            view,
            meta,
            wt,
            &[buf.as_ptr() as u64, namespace_id()],
            [0.0; 4],
        )
    }
}

/// The one word a `SwiftUI.Image` occupies.
///
/// `Image` is frozen and wraps a single provider reference, so its initialiser
/// returns it in x0 rather than through x8.
pub(crate) unsafe fn image_word(name: &str) -> u64 {
    unsafe {
        let s = abi::swift_string(name);
        abi::call_regs(
            resolve::image_system_init(),
            abi::ints(&[
                u64::from_le_bytes(s[..8].try_into().expect("lo")),
                u64::from_le_bytes(s[8..].try_into().expect("hi")),
            ]),
            [0.0; 4],
            resolve::image_meta() as u64,
        )[0]
    }
}

/// The one word an `Image` built from a named asset occupies.
///
/// `Image(_ name: String, bundle: NSBundle?)`: the string in x0/x1, the bundle
/// in x2 with nil as a null reference, and the metatype in x20.
///
/// The name is looked up in the bundle's compiled asset catalogue —
/// `Assets.car` beside the executable for a plain binary. `NSImage.setName(_:)`
/// puts an image in AppKit's named cache and `NSImage(named:)` finds it there,
/// but SwiftUI does not consult that cache: an image registered that way
/// renders as nothing at all.
pub(crate) unsafe fn image_named_word(name: &str) -> u64 {
    unsafe {
        let s = abi::swift_string(name);
        abi::call_regs(
            resolve::image_named_init(),
            abi::ints(&[
                u64::from_le_bytes(s[..8].try_into().expect("lo")),
                u64::from_le_bytes(s[8..].try_into().expect("hi")),
                0, // bundle: nil — Bundle.main
            ]),
            [0.0; 4],
            resolve::image_meta() as u64,
        )[0]
    }
}

/// Build a `SwiftUI.Image` from a named asset in the main bundle.
pub fn image_named(name: &str) -> ViewHandle {
    unsafe {
        let word = image_named_word(name);
        ViewHandle::wrap(
            &word as *const u64 as *const c_void,
            resolve::image_meta(),
            resolve::image_wt(),
        )
    }
}

/// Build a `SwiftUI.Image` from an SF Symbol name.
pub fn image_system(name: &str) -> ViewHandle {
    unsafe {
        let word = image_word(name);
        ViewHandle::wrap(
            &word as *const u64 as *const c_void,
            resolve::image_meta(),
            resolve::image_wt(),
        )
    }
}

/// The bytes of an `Image` built from an SF Symbol name.
pub(crate) unsafe fn image_bytes(name: &str) -> Vec<u8> {
    unsafe { image_word(name).to_le_bytes().to_vec() }
}

/// Apply `.dialogIcon(_:)`.
pub fn dialog_icon(view: &ViewHandle, system_name: Option<&str>) -> ViewHandle {
    unsafe {
        // `Image` is one frozen word wrapping a provider reference, so
        // `Image?` is the same word and `nil` is a null one — a register, not
        // an address.
        let word = system_name.map_or(0, |n| {
            u64::from_le_bytes(image_bytes(n)[..8].try_into().expect("image word"))
        });
        opaque_modifier(
            resolve::dialog_icon_fn(),
            resolve::dialog_icon_oret(),
            view,
            &[word],
            [0.0; 4],
        )
    }
}

/// Apply `.defaultAppStorage(_:)` with `UserDefaults.standard`.
pub fn default_app_storage_standard(view: &ViewHandle) -> ViewHandle {
    unsafe {
        // `UserDefaults.standard` is an Objective-C class method, so it is a
        // message send rather than a Swift symbol.
        let cls = crate::objc::class_named(c"NSUserDefaults");
        type Send0 = unsafe extern "C" fn(*mut c_void, *const c_void) -> *mut c_void;
        let send: Send0 = core::mem::transmute(crate::objc::msg_send_addr());
        let defaults = send(cls, crate::objc::sel(c"standardUserDefaults"));
        assert!(!defaults.is_null(), "UserDefaults.standard");
        opaque_modifier(
            resolve::default_app_storage_fn(),
            resolve::default_app_storage_oret(),
            view,
            &[defaults as u64],
            [0.0; 4],
        )
    }
}

/// Apply `.defaultAppStorage(_:)` with a named suite.
///
/// The store every `@AppStorage` below this point reads and writes, when it
/// should not be the app's own defaults — a shared container between an app
/// and its extension is the usual reason.
///
/// Returns `None` if the suite cannot be opened. `UserDefaults(suiteName:)`
/// fails for a name that is the app's own bundle identifier or the global
/// domain, and returning nil is how it says so; a binding that unwrapped it
/// would hand SwiftUI a null store.
pub fn default_app_storage_suite(view: &ViewHandle, suite: &str) -> Option<ViewHandle> {
    unsafe {
        let cls = crate::objc::class_named(c"NSUserDefaults");
        type Alloc = unsafe extern "C" fn(*mut c_void, *const c_void) -> *mut c_void;
        type InitSuite =
            unsafe extern "C" fn(*mut c_void, *const c_void, *mut c_void) -> *mut c_void;
        let send_alloc: Alloc = core::mem::transmute(crate::objc::msg_send_addr());
        let send_init: InitSuite = core::mem::transmute(crate::objc::msg_send_addr());
        let raw = send_alloc(cls, crate::objc::sel(c"alloc"));
        let name = crate::objc::nsstring(suite);
        let defaults = send_init(raw, crate::objc::sel(c"initWithSuiteName:"), name);
        if defaults.is_null() {
            return None;
        }
        Some(opaque_modifier(
            resolve::default_app_storage_fn(),
            resolve::default_app_storage_oret(),
            view,
            &[defaults as u64],
            [0.0; 4],
        ))
    }
}

/// A `Foundation.URL` for a file path.
///
/// None of `URL`'s initialisers are exported — they are all emitted into the
/// client — so the value comes from an `NSURL` through Foundation's bridging
/// entry point, which is exported.
///
/// `NSURL` stats the path: give it an existing directory and it appends a
/// trailing slash where Swift's own initialiser does not, and the two URLs
/// stop comparing equal.
pub(crate) unsafe fn file_url(path: &str) -> Vec<u8> {
    unsafe {
        let ns_string = crate::objc::class_named(c"NSString");
        type Send1<T> = unsafe extern "C" fn(*mut c_void, *const c_void, T) -> *mut c_void;
        let send: Send1<*const i8> = core::mem::transmute(crate::objc::msg_send_addr());
        let cpath = std::ffi::CString::new(path).expect("path");
        let s = send(ns_string, crate::objc::sel(c"stringWithUTF8String:"), cpath.as_ptr());
        let ns_url = crate::objc::class_named(c"NSURL");
        let send_obj: Send1<*mut c_void> = core::mem::transmute(crate::objc::msg_send_addr());
        let url = send_obj(ns_url, crate::objc::sel(c"fileURLWithPath:"), s);
        assert!(!url.is_null(), "NSURL for {path}");

        let meta = crate::type_by_name!(swift_type!(Foundation.URL).as_bytes());
        let mut out = vec![0u8; abi::type_bytes(meta)];
        abi::call_out(
            resolve::url_bridge_from_objc(),
            abi::ints(&[url as u64]),
            [0.0; 4],
            meta as u64,
            out.as_mut_ptr(),
        );
        out
    }
}

/// Apply `.fileDialogDefaultDirectory(_:)`.
pub fn file_dialog_default_directory(view: &ViewHandle, path: Option<&str>) -> ViewHandle {
    unsafe {
        let payload = crate::type_by_name!(swift_type!(Foundation.URL).as_bytes());
        let v = path.map(|p| file_url(p));
        let b = opt_resilient_bytes(payload, swift_type!(opt Foundation.URL).as_bytes(), v.as_deref());
        modifier_indirect(
            resolve::file_dialog_default_directory_fn(),
            resolve::file_dialog_default_directory_oret(),
            view,
            &b,
        )
    }
}

/// Apply `.previewDevice(_:)`.
pub fn preview_device(view: &ViewHandle, name: Option<&str>) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::preview_device_ma());
        let mut buf = vec![0u8; abi::type_bytes(meta)];
        if let Some(n) = name {
            let s = abi::swift_string(n);
            abi::call_out(
                resolve::preview_device_init(),
                abi::ints(&[
                    u64::from_le_bytes(s[..8].try_into().expect("lo")),
                    u64::from_le_bytes(s[8..].try_into().expect("hi")),
                ]),
                [0.0; 4],
                meta as u64,
                buf.as_mut_ptr(),
            );
        }
        let b = opt_resilient_bytes(meta, swift_type!(opt SwiftUI.PreviewDevice).as_bytes(), name.map(|_| &buf[..]));
        modifier_indirect(resolve::preview_device_fn(), resolve::preview_device_oret(), view, &b)
    }
}

#[cfg(test)]
mod url_tests {
    use super::*;

    /// A bridged `URL` carries the right path even though its storage differs
    /// from the one Swift source builds — `NSURL`-backed rather than
    /// `_SwiftURL`-backed — which is why the parity suite only covers the
    /// `nil` case of `fileDialogDefaultDirectory`.
    #[test]
    fn bridged_file_url_round_trips() {
        unsafe {
            let meta = crate::type_by_name!(swift_type!(Foundation.URL).as_bytes());
            let mut bytes = file_url("/tmp/rswift-parity");
            let d = crate::diag::dump_any(bytes.as_mut_ptr().cast(), meta, 1);
            assert!(d.contains("file:///tmp/rswift-parity"), "bridged URL was {d}");
        }
    }

    #[test]
    fn file_dialog_default_directory_builds_either_way() {
        let _ = file_dialog_default_directory(&text("Fx"), Some("/tmp/rswift-parity"));
        let _ = file_dialog_default_directory(&text("Fx"), None);
    }
}

/// A member of `AppKit`'s `NSTextContentType`.
///
/// These are `NSString` constants rather than Swift statics, so each is a
/// *variable* the loader exports: `dlsym` gives its address and the string is
/// one dereference further in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TextContentKind {
    Username,
    Password,
    OneTimeCode,
}

impl TextContentKind {
    fn constant(self) -> &'static core::ffi::CStr {
        match self {
            Self::Username => c"NSTextContentTypeUsername",
            Self::Password => c"NSTextContentTypePassword",
            Self::OneTimeCode => c"NSTextContentTypeOneTimeCode",
        }
    }
}

/// Apply `.textContentType(_:)`.
pub fn text_content_type(view: &ViewHandle, kind: Option<TextContentKind>) -> ViewHandle {
    unsafe {
        // `NSTextContentType` is a typed `NSString`, so the optional is one
        // reference and `nil` is a null word.
        let word = kind.map_or(0, |k| {
            let slot = resolve::sym(k.constant());
            assert!(!slot.is_null(), "missing constant: {:?}", k.constant());
            *(slot as *const u64)
        });
        opaque_modifier(
            resolve::text_content_type_fn(),
            resolve::text_content_type_oret(),
            view,
            &[word],
            [0.0; 4],
        )
    }
}

// ── Images kept as images ───────────────────────────────────────────────────

/// An `Image` value, not yet erased to a view.
///
/// The same reason [`super::Shape`] exists: `Image.resizable(_:_:)` and
/// `.renderingMode(_:)` are methods on `Image` that *return* an `Image`, so
/// they are not view modifiers and an `AnyView` cannot be their receiver. An
/// `Image` is one word, so it travels in a register both ways.
#[derive(Clone, Copy)]
pub struct Image(u64);

/// `Image.ResizingMode`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResizingMode {
    Tile,
    Stretch,
}

impl ResizingMode {
    /// The case descriptor the framework exports, which holds the tag.
    fn descriptor(self) -> &'static core::ffi::CStr {
        match self {
            Self::Tile => c"$s7SwiftUI5ImageV12ResizingModeO4tileyA2EmFWC",
            Self::Stretch => c"$s7SwiftUI5ImageV12ResizingModeO7stretchyA2EmFWC",
        }
    }
}

/// `Image.Interpolation` — how a scaled image is resampled.
///
/// Resilient, so the case numbering is not something a caller may write down:
/// each variant names the `…WC` global SwiftUI exports for it, which holds the
/// tag, and the binding reads it from there.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Interpolation {
    /// No smoothing — nearest neighbour, so pixels stay square.
    None,
    /// The cheapest smoothing.
    Low,
    /// Between `Low` and `High`.
    Medium,
    /// The best smoothing, and the default.
    High,
}

impl Interpolation {
    /// The case descriptor the framework exports, which holds the tag.
    fn descriptor(self) -> &'static core::ffi::CStr {
        match self {
            Self::None => c"$s7SwiftUI5ImageV13InterpolationO4noneyA2EmFWC",
            Self::Low => c"$s7SwiftUI5ImageV13InterpolationO3lowyA2EmFWC",
            Self::Medium => c"$s7SwiftUI5ImageV13InterpolationO6mediumyA2EmFWC",
            Self::High => c"$s7SwiftUI5ImageV13InterpolationO4highyA2EmFWC",
        }
    }
}

/// `Image.TemplateRenderingMode`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TemplateRenderingMode {
    Template,
    Original,
}

impl TemplateRenderingMode {
    fn descriptor(self) -> &'static core::ffi::CStr {
        match self {
            Self::Template => c"$s7SwiftUI5ImageV21TemplateRenderingModeO8templateyA2EmFWC",
            Self::Original => c"$s7SwiftUI5ImageV21TemplateRenderingModeO8originalyA2EmFWC",
        }
    }
}

impl Image {
    /// `Image(systemName:)`
    pub fn system(name: &str) -> Self {
        Self(unsafe { image_word(name) })
    }

    /// `Image(systemName:variableValue:)` — a symbol drawn at a fill level.
    ///
    /// The `Double?` does not travel in a float register. It goes as its raw
    /// bits in an integer register with the tag in the next one, which is what
    /// the IR spells: `(i64, ptr, i64, i8)` for a `String` and an
    /// `Optional<Double>`.
    pub fn system_variable(name: &str, value: Option<f64>) -> Self {
        unsafe {
            let s = abi::swift_string(name);
            let (bits, tag) = match value {
                Some(v) => (v.to_bits(), 0u64),
                None => (0, 1),
            };
            Self(
                abi::call_regs(
                    resolve::image_sysname_variable_init(),
                    abi::ints(&[
                        u64::from_le_bytes(s[..8].try_into().expect("lo")),
                        u64::from_le_bytes(s[8..].try_into().expect("hi")),
                        bits,
                        tag,
                    ]),
                    [0.0; 4],
                    resolve::image_meta() as u64,
                )[0],
            )
        }
    }

    /// `.allowedDynamicRange(_:)` with `.high`.
    ///
    /// `Image.DynamicRange` is a resilient *struct*, so its size is a run-time
    /// question and `.high` is handed back through x8 rather than in a
    /// register. The `Optional` wrapper is the struct's own bytes in a buffer
    /// the optional's size — zeroed, which is `.some` for a payload with spare
    /// inhabitants — and it travels by address with the image beside it.
    pub fn allowed_dynamic_range_high(self) -> Self {
        unsafe {
            let inner = abi::metadata0(resolve::image_dynamic_range_ma());
            assert!(!inner.is_null(), "Image.DynamicRange metadata");
            let value = super::static_getter_indirect(
                resolve::image_dynamic_range_high(),
                inner,
                abi::type_bytes(inner),
            );

            let mut opt = vec![0u8; abi::type_bytes(inner) + 8];
            opt[..value.len()].copy_from_slice(&value);
            let out: u64;
            core::arch::asm!("blr {f}", f = in(reg) resolve::image_dynamic_range_fn(),
                in("x0") opt.as_mut_ptr(),
                in("x1") self.0,
                lateout("x0") out,
                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"),
            );
            Self(out)
        }
    }

    /// `Image(_:)` — a named asset from the main bundle's catalogue.
    pub fn named(name: &str) -> Self {
        Self(unsafe { image_named_word(name) })
    }

    /// `.resizable(capInsets:resizingMode:)`, with the zero cap insets Swift
    /// source gets from the bare `.resizable()`.
    ///
    /// `EdgeInsets` is four `CGFloat`s and nothing else, which makes it a
    /// homogeneous float aggregate: it travels in d0–d3 rather than by address.
    /// The resizing mode does *not* travel in a register, though — see
    /// [`Image::rendering_mode`].
    pub fn resizable(self, mode: ResizingMode) -> Self {
        unsafe {
            let mut buf = resilient_case(
                RESIZING_MODE,
                mode.descriptor(),
            );
            let out: u64;
            core::arch::asm!("blr {f}", f = in(reg) resolve::image_resizable_fn(),
                in("d0") 0.0f64, in("d1") 0.0f64, in("d2") 0.0f64, in("d3") 0.0f64,
                in("x0") buf.as_mut_ptr(),
                in("x1") self.0,
                lateout("x0") out,
                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"),
            );
            Self(out)
        }
    }

    /// `.interpolation(_:)` — how the image is resampled when scaled.
    ///
    /// The same argument convention as [`Image::resizable`]: the mode by address
    /// in x0, the image itself as a plain second argument in x1 rather than in
    /// x20, and the new image back in x0. Not what a method on a struct usually
    /// looks like, which is why it is read out of the IR rather than assumed.
    pub fn interpolation(self, mode: Interpolation) -> Self {
        unsafe {
            let mut buf = resilient_case(INTERPOLATION, mode.descriptor());
            let out: u64;
            core::arch::asm!("blr {f}", f = in(reg) resolve::image_interpolation_fn(),
                in("x0") buf.as_mut_ptr(),
                in("x1") self.0,
                lateout("x0") out,
                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"),
            );
            Self(out)
        }
    }

    /// `.symbolRenderingMode(_:)` — the overload on `Image`, which returns
    /// `Image`.
    ///
    /// Its `View` neighbour writes the environment and wraps the image in a
    /// `ModifiedContent`; Apple's own listings reach this one, so a chain that
    /// went through the environment rendered the same and typed differently.
    /// Same shape as [`Image::rendering_mode`]: the mode is address-only and
    /// `self` is an ordinary second argument, not a `swiftself`.
    pub fn symbol_rendering_mode(self, mode: Option<super::SymbolRenderingMode>) -> Self {
        unsafe {
            let meta = abi::metadata0(resolve::symbol_rendering_mode_ma());
            let v = mode.map(|m| super::resilient_static(meta, m.getter()));
            let mut buf = super::opt_resilient_bytes(
                meta,
                swift_type!(opt SwiftUI.SymbolRenderingMode).as_bytes(),
                v.as_deref(),
            );
            let out: u64;
            core::arch::asm!("blr {f}", f = in(reg) resolve::image_symbol_rendering_mode_fn(),
                in("x0") buf.as_mut_ptr(),
                in("x1") self.0,
                lateout("x0") out,
                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"),
            );
            Self(out)
        }
    }

    /// `.antialiased(_:)`
    pub fn antialiased(self, on: bool) -> Self {
        unsafe {
            let out: u64;
            core::arch::asm!("blr {f}", f = in(reg) resolve::image_antialiased_fn(),
                in("x0") u64::from(on),
                in("x1") self.0,
                lateout("x0") out,
                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"),
            );
            Self(out)
        }
    }

    /// `.renderingMode(_:)`
    ///
    /// Neither of these two takes its enum in a register, and neither takes
    /// `self` in x20. `Image.TemplateRenderingMode` is not `@frozen`, so its
    /// size is only known at run time and the argument is address-only; and the
    /// IR shows plain pointers rather than a `swiftself`, so the receiver is an
    /// ordinary second argument. Passing the case number in x0 and the image in
    /// x20 — which is what every *view* modifier in this crate wants — faults
    /// inside the runtime.
    pub fn rendering_mode(self, mode: Option<TemplateRenderingMode>) -> Self {
        unsafe {
            let mangled = TEMPLATE_RENDERING_MODE;
            let mut buf = match mode {
                Some(m) => resilient_case(mangled, m.descriptor()),
                None => {
                    // `nil` is an extra inhabitant of the payload, so it is
                    // written by the *optional's* witness rather than injected.
                    let mut opt = mangled.to_vec();
                    opt.extend_from_slice(b"Sg");
                    let meta = abi::resolve_type_by_mangled_name(&opt);
                    assert!(!meta.is_null(), "Optional<TemplateRenderingMode>");
                    let mut buf = vec![0u8; abi::type_bytes(meta).max(1)];
                    abi::inject_enum_tag(&mut buf, meta, 1);
                    buf
                }
            };
            let out: u64;
            core::arch::asm!("blr {f}", f = in(reg) resolve::image_rendering_mode_fn(),
                in("x0") buf.as_mut_ptr(),
                in("x1") self.0,
                lateout("x0") out,
                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"),
            );
            Self(out)
        }
    }

    /// The image as a view.
    pub fn view(self) -> ViewHandle {
        unsafe {
            ViewHandle::wrap(
                &self.0 as *const u64 as *const c_void,
                resolve::image_meta(),
                resolve::image_wt(),
            )
        }
    }
}

/// `SwiftUI.Image.ResizingMode` and `SwiftUI.Image.TemplateRenderingMode`.
///
/// Written out rather than built, because both are *enums* nested in a struct
/// and the `O` suffix is what says so — `swift_type!` spells a nominal type as
/// a struct, and `...ModeV` resolves to nothing at all.
const RESIZING_MODE: &[u8] = b"7SwiftUI5ImageV12ResizingModeO";
const INTERPOLATION: &[u8] = b"7SwiftUI5ImageV13InterpolationO";
const TEMPLATE_RENDERING_MODE: &[u8] = b"7SwiftUI5ImageV21TemplateRenderingModeO";

/// A buffer holding one case of a resilient enum.
///
/// The case *number* is not the declaration order and is not knowable here:
/// the compiler loads it from a per-case descriptor the framework exports
/// (`...WC`), then hands it to the enum's own `destructiveInjectEnumTag`. Both
/// steps are needed — the size comes from the value witness table too.
unsafe fn resilient_case(mangled: &[u8], case_descriptor: &'static core::ffi::CStr) -> Vec<u8> {
    unsafe {
        let meta = abi::resolve_type_by_mangled_name(mangled);
        assert!(!meta.is_null(), "{}", crate::diag::demangle_type(mangled));
        let tag = resolve::sym(case_descriptor) as *const u32;
        assert!(!tag.is_null(), "enum case descriptor: {case_descriptor:?}");
        let mut buf = vec![0u8; abi::type_bytes(meta).max(1)];
        abi::inject_enum_tag(&mut buf, meta, tag.read());
        buf
    }
}

/// `AsyncImage(url:scale:)` — the `Content == Image` form.
///
/// The `Optional<URL>` travels by address in x0 and the scale in d0, with the
/// metatype in x20. A URL that does not resolve leaves the default placeholder
/// on screen, which is what both sides show in a test with no network.
pub fn async_image(spec: Option<&str>, scale: f64) -> ViewHandle {
    unsafe {
        let ty = crate::mangle::ty("AsyncImage").of(vec![crate::mangle::ty("Image")]).mangle();
        let meta = abi::resolve_type_by_mangled_name(ty.as_bytes());
        assert!(!meta.is_null(), "AsyncImage<Image> metadata");
        let mut url = super::optional_url(spec);
        let mut value = vec![0u8; abi::type_bytes(meta)];
        core::arch::asm!("blr {f}", f = in(reg) resolve::async_image_init(),
            in("x0") url.as_mut_ptr(),
            in("d0") scale,
            in("x8") value.as_mut_ptr(),
            in("x20") meta,
            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 wt = abi::get_view_wt(meta);
        assert!(!wt.is_null(), "AsyncImage !: View");
        wrap_buf(&value, meta, wt)
    }
}

/// `ShareLink(item:)` for a URL.
///
/// The initialiser is `ShareLink(item:subject:message:)` with both trailing
/// arguments defaulted to nil, and a nil `Text?` is simply four zero words —
/// eight in total for the pair, of which seven fit in x1 through x7 and one
/// spills. The item itself goes by address in x0: a `CollectionOfOne<URL>` is
/// laid out as the `URL` it holds, so the payload of the optional this builds
/// serves directly.
pub fn share_link_url(spec: &str) -> ViewHandle {
    unsafe {
        let ty = crate::mangle::ty("ShareLink")
            .of(vec![
                crate::mangle::Type::Verbatim("s15CollectionOfOneVy10Foundation3URLVG".into()),
                crate::mangle::Type::Verbatim("s5NeverO".into()),
                crate::mangle::Type::Verbatim("s5NeverO".into()),
                crate::mangle::ty("DefaultShareLinkLabel"),
            ])
            .mangle();
        let meta = abi::resolve_type_by_mangled_name(ty.as_bytes());
        assert!(!meta.is_null(), "ShareLink metadata: {ty}");

        let mut url = super::optional_url(Some(spec));
        let mut value = vec![0u8; abi::type_bytes(meta)];
        core::arch::asm!(
            "str xzr, [sp, #-16]!",
            "blr {f}",
            "add sp, sp, #16",
            f = in(reg) resolve::share_link_url_init(),
            in("x0") url.as_mut_ptr(),
            in("x1") 0u64, in("x2") 0u64, in("x3") 0u64, in("x4") 0u64,
            in("x5") 0u64, in("x6") 0u64, in("x7") 0u64,
            in("x8") value.as_mut_ptr(),
            lateout("x9") _, lateout("x10") _, lateout("x11") _, lateout("x12") _,
            lateout("x13") _, lateout("x14") _, lateout("x15") _, lateout("x16") _,
            lateout("x17") _, lateout("lr") _, lateout("x20") _, lateout("x21") _,
            clobber_abi("C"),
        );
        let wt = abi::get_view_wt(meta);
        assert!(!wt.is_null(), "ShareLink !: View");
        wrap_buf(&value, meta, wt)
    }
}