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
//! Option sets, variadic placements, resilient statics.

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

// ── Option sets, variadic placements, resilient statics ──

/// `Optional<T>` for a resilient `T`, in a buffer ready to pass by address.
pub(crate) unsafe fn opt_resilient_bytes(
    payload_meta: *const c_void,
    opt_mangled: &[u8],
    value: Option<&[u8]>,
) -> Vec<u8> {
    unsafe {
        let opt = abi::resolve_type_by_mangled_name(opt_mangled);
        assert!(!opt.is_null(), "{}", crate::diag::demangle_type(opt_mangled));
        let mut buf = vec![0u8; abi::type_bytes(opt).max(abi::type_bytes(payload_meta))];
        if let Some(v) = value {
            buf[..v.len()].copy_from_slice(v);
        }
        abi::store_optional_tag(&mut buf, payload_meta, value.is_some());
        buf
    }
}

/// A Swift `Array` of a resilient type, built from its static members.
///
/// A Swift variadic parameter is an `Array`, so `ToolbarPlacement...` is one
/// word at the call site no matter how many placements it holds.
pub(crate) unsafe fn static_array(ma: *const c_void, getters: &[&'static core::ffi::CStr]) -> u64 {
    unsafe {
        let meta = abi::metadata0(ma);
        let stride = abi::type_bytes(meta);
        let mut bytes = vec![0u8; stride * getters.len()];
        for (i, g) in getters.iter().enumerate() {
            let v = resilient_static(meta, g);
            bytes[i * stride..i * stride + v.len()].copy_from_slice(&v);
        }
        abi::swift_array(meta, getters.len(), &bytes)
    }
}

/// The union of an `OptionSet`'s members, as the one word it travels in.
///
/// SwiftUI's nested `.Set` types return from their static getters in a
/// register, unlike its other resilient structs, which return through x8. The
/// interface files do not say which is which — neither is marked `@frozen` —
/// so this follows the convention the existing, parity-checked bindings
/// established for `VerticalEdge.Set` and `Axis.Set`.
pub(crate) unsafe fn option_set_word(ma: *const c_void, getters: &[&'static core::ffi::CStr]) -> u64 {
    unsafe {
        let meta = abi::metadata0(ma);
        let mut acc = 0u64;
        for g in getters {
            let f = resolve::sym(g);
            assert!(!f.is_null(), "missing static: {}", crate::diag::symbol_name(g));
            let (w, _) = static_getter(f, meta);
            acc |= w;
        }
        acc
    }
}

swift_statics! {
    /// `SwiftUI.GestureMask` — which gestures still get a look in.
    ///
    /// The `including:` argument of `.gesture(_:including:)`. `All` is
    /// SwiftUI's default and what this crate passed as a bare `3` before the
    /// raw values were read from the framework.
    pub enum GestureMask {
        /// Neither this gesture nor the subviews' run.
        None = c"$s7SwiftUI11GestureMaskV4noneACvgZ",
        /// Only this gesture; the subviews' are disabled.
        Gesture = c"$s7SwiftUI11GestureMaskV7gestureACvgZ",
        /// Only the subviews'; this one is disabled.
        Subviews = c"$s7SwiftUI11GestureMaskV8subviewsACvgZ",
        /// Both, which is the default.
        All = c"$s7SwiftUI11GestureMaskV3allACvgZ",
    }
}

swift_statics! {
    /// A member of `SwiftUI.ToolbarPlacement`.
    pub enum ToolbarPlacement {
        Automatic = c"$s7SwiftUI16ToolbarPlacementV9automaticACvgZ",
        WindowToolbar = c"$s7SwiftUI16ToolbarPlacementV06windowC0ACvgZ",
        BottomBar = c"$s7SwiftUI16ToolbarPlacementV9bottomBarACvgZ",
        /// Unavailable on macOS: SwiftUI ships a trap stub there, so
        /// reaching this aborts with "Unavailable code reached".
        #[cfg(not(target_os = "macos"))]
        NavigationBar = c"$s7SwiftUI16ToolbarPlacementV13navigationBarACvgZ",
        /// Unavailable on macOS: SwiftUI ships a trap stub there, so
        /// reaching this aborts with "Unavailable code reached".
        #[cfg(not(target_os = "macos"))]
        TabBar = c"$s7SwiftUI16ToolbarPlacementV6tabBarACvgZ",
    }
}

swift_statics! {
    /// A member of `SwiftUI.Text.LineStyle.Pattern`.
    pub enum LinePattern {
        Solid = c"$s7SwiftUI4TextV9LineStyleV7PatternV5solidAGvgZ",
        Dot = c"$s7SwiftUI4TextV9LineStyleV7PatternV3dotAGvgZ",
        Dash = c"$s7SwiftUI4TextV9LineStyleV7PatternV4dashAGvgZ",
        DashDot = c"$s7SwiftUI4TextV9LineStyleV7PatternV7dashDotAGvgZ",
        DashDotDot = c"$s7SwiftUI4TextV9LineStyleV7PatternV07dashDotH0AGvgZ",
    }
}

swift_statics! {
    /// A member of `SwiftUI.SymbolRenderingMode`.
    pub enum SymbolRenderingMode {
        Monochrome = c"$s7SwiftUI19SymbolRenderingModeV10monochromeACvgZ",
        Multicolor = c"$s7SwiftUI19SymbolRenderingModeV10multicolorACvgZ",
        Hierarchical = c"$s7SwiftUI19SymbolRenderingModeV12hierarchicalACvgZ",
        Palette = c"$s7SwiftUI19SymbolRenderingModeV7paletteACvgZ",
    }
}

swift_statics! {
    /// A member of `SwiftUI.Font.Width`.
    pub enum FontWidth {
        Compressed = c"$s7SwiftUI4FontV5WidthV10compressedAEvgZ",
        Condensed = c"$s7SwiftUI4FontV5WidthV9condensedAEvgZ",
        Standard = c"$s7SwiftUI4FontV5WidthV8standardAEvgZ",
        Expanded = c"$s7SwiftUI4FontV5WidthV8expandedAEvgZ",
    }
}

swift_statics! {
    /// `SwiftUI.Text.Scale`.
    pub enum TextScale {
        Default = c"$s7SwiftUI4TextV5ScaleV7defaultAEvgZ",
        Secondary = c"$s7SwiftUI4TextV5ScaleV9secondaryAEvgZ",
    }
}

swift_statics! {
    /// `SwiftUI.ScrollEdgeEffectStyle`.
    pub enum ScrollEdgeEffectStyle {
        Automatic = c"$s7SwiftUI21ScrollEdgeEffectStyleV9automaticACvgZ",
        Soft = c"$s7SwiftUI21ScrollEdgeEffectStyleV4softACvgZ",
        Hard = c"$s7SwiftUI21ScrollEdgeEffectStyleV4hardACvgZ",
    }
}

swift_statics! {
    /// `SwiftUI.Alignment`, a frozen pair of alignment guides.
    pub enum Alignment {
        Center = c"$s7SwiftUI9AlignmentV6centerACvgZ",
        Leading = c"$s7SwiftUI9AlignmentV7leadingACvgZ",
        Trailing = c"$s7SwiftUI9AlignmentV8trailingACvgZ",
        Top = c"$s7SwiftUI9AlignmentV3topACvgZ",
        Bottom = c"$s7SwiftUI9AlignmentV6bottomACvgZ",
        TopLeading = c"$s7SwiftUI9AlignmentV10topLeadingACvgZ",
        TopTrailing = c"$s7SwiftUI9AlignmentV11topTrailingACvgZ",
        BottomLeading = c"$s7SwiftUI9AlignmentV13bottomLeadingACvgZ",
        BottomTrailing = c"$s7SwiftUI9AlignmentV14bottomTrailingACvgZ",
    }
}

impl Alignment {
    /// The two words an `Alignment` occupies: its horizontal and vertical guides.
    ///
    /// Returned in x0 and x1 rather than through x8. Reading it the other way
    /// leaves both alignment keys zero — a value SwiftUI accepts, stores, and
    /// then traps on at render time rather than at construction.
    pub(crate) unsafe fn words(self) -> [u64; 2] {
        unsafe {
            let f = resolve::sym(self.getter());
            assert!(!f.is_null(), "missing static: {}", crate::diag::symbol_name(self.getter()));
            let meta = abi::metadata0(resolve::alignment_ma());
            let r = abi::static_regs(f, meta);
            [r[0], r[1]]
        }
    }
}

/// Apply `.listRowSeparatorTint(_:edges:)`.
pub fn list_row_separator_tint(
    view: &ViewHandle,
    color: Option<crate::Color>,
    edges: &[VerticalEdgeSet],
) -> ViewHandle {
    unsafe {
        let c = color.map_or(0, |c| color_value(c.r, c.g, c.b, c.a));
        let g: Vec<&core::ffi::CStr> = edges.iter().map(|e| e.getter()).collect();
        let e = option_set_word(resolve::vertical_edge_set_ma(), &g);
        opaque_modifier(
            resolve::list_row_separator_tint_fn(),
            resolve::list_row_separator_tint_oret(),
            view,
            &[c, e],
            [0.0; 4],
        )
    }
}

/// Apply `.listSectionSeparatorTint(_:edges:)`.
pub fn list_section_separator_tint(
    view: &ViewHandle,
    color: Option<crate::Color>,
    edges: &[VerticalEdgeSet],
) -> ViewHandle {
    unsafe {
        let c = color.map_or(0, |c| color_value(c.r, c.g, c.b, c.a));
        let g: Vec<&core::ffi::CStr> = edges.iter().map(|e| e.getter()).collect();
        let e = option_set_word(resolve::vertical_edge_set_ma(), &g);
        opaque_modifier(
            resolve::list_section_separator_tint_fn(),
            resolve::list_section_separator_tint_oret(),
            view,
            &[c, e],
            [0.0; 4],
        )
    }
}

/// Apply `.strikethrough(_:pattern:color:)`.
pub fn strikethrough(
    view: &ViewHandle,
    active: bool,
    pattern: LinePattern,
    color: Option<crate::Color>,
) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::line_pattern_ma());
        let p = resilient_static(meta, pattern.getter());
        let c = color.map_or(0, |c| color_value(c.r, c.g, c.b, c.a));
        opaque_modifier(
            resolve::strikethrough_fn(),
            resolve::strikethrough_oret(),
            view,
            &[u64::from(active), p.as_ptr() as u64, c],
            [0.0; 4],
        )
    }
}

/// Apply `.underline(_:pattern:color:)`.
pub fn underline(
    view: &ViewHandle,
    active: bool,
    pattern: LinePattern,
    color: Option<crate::Color>,
) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::line_pattern_ma());
        let p = resilient_static(meta, pattern.getter());
        let c = color.map_or(0, |c| color_value(c.r, c.g, c.b, c.a));
        opaque_modifier(
            resolve::underline_fn(),
            resolve::underline_oret(),
            view,
            &[u64::from(active), p.as_ptr() as u64, c],
            [0.0; 4],
        )
    }
}

/// The `Visibility` case and the placement array these four share.
pub(crate) unsafe fn toolbar_args(visibility: Visibility, placements: &[ToolbarPlacement]) -> (u64, u64) {
    unsafe {
        // `Visibility` travels *in* a register here. Handing over its address
        // instead is not a crash: SwiftUI stores the pointer as if it were a
        // case number and `dump` reports `Visibility.()`, a case that does not
        // exist.
        let meta = abi::metadata0(resolve::visibility_ma());
        let v = abi::enum_argument(meta, visibility as u32);
        let g: Vec<&core::ffi::CStr> = placements.iter().map(|p| p.getter()).collect();
        (v, static_array(resolve::toolbar_placement_ma(), &g))
    }
}

/// Apply `.toolbarVisibility(_:for:)`.
pub fn toolbar_visibility(
    view: &ViewHandle,
    visibility: Visibility,
    placements: &[ToolbarPlacement],
) -> ViewHandle {
    unsafe {
        let (v, arr) = toolbar_args(visibility, placements);
        opaque_modifier(
            resolve::toolbar_visibility_fn(),
            resolve::toolbar_visibility_oret(),
            view,
            &[v, arr],
            [0.0; 4],
        )
    }
}

/// Apply `.toolbarBackgroundVisibility(_:for:)`.
pub fn toolbar_background_visibility(
    view: &ViewHandle,
    visibility: Visibility,
    placements: &[ToolbarPlacement],
) -> ViewHandle {
    unsafe {
        let (v, arr) = toolbar_args(visibility, placements);
        opaque_modifier(
            resolve::toolbar_background_visibility_fn(),
            resolve::toolbar_background_visibility_oret(),
            view,
            &[v, arr],
            [0.0; 4],
        )
    }
}

/// Apply `.toolbarBackground(_:in:)`.
pub fn toolbar_background(
    view: &ViewHandle,
    visibility: Visibility,
    placements: &[ToolbarPlacement],
) -> ViewHandle {
    unsafe {
        let (v, arr) = toolbar_args(visibility, placements);
        opaque_modifier(
            resolve::toolbar_background_fn(),
            resolve::toolbar_background_oret(),
            view,
            &[v, arr],
            [0.0; 4],
        )
    }
}

/// Apply `.toolbarColorScheme(_:in:)`.
pub fn toolbar_color_scheme(
    view: &ViewHandle,
    scheme: Option<ColorScheme>,
    placements: &[ToolbarPlacement],
) -> ViewHandle {
    unsafe {
        let s = opt_enum_bytes(
            resolve::color_scheme_ma(),
            swift_type!(opt enum SwiftUI.ColorScheme).as_bytes(),
            scheme.map(|s| s as u32),
        );
        let g: Vec<&core::ffi::CStr> = placements.iter().map(|p| p.getter()).collect();
        let arr = static_array(resolve::toolbar_placement_ma(), &g);
        opaque_modifier(
            resolve::toolbar_color_scheme_fn(),
            resolve::toolbar_color_scheme_oret(),
            view,
            &[s.as_ptr() as u64, arr],
            [0.0; 4],
        )
    }
}

/// Apply `.containerRelativeFrame(_:alignment:)`.
pub fn container_relative_frame(
    view: &ViewHandle,
    axes: &[AxisSet],
    alignment: Alignment,
) -> ViewHandle {
    unsafe {
        let g: Vec<&core::ffi::CStr> = axes.iter().map(|a| a.getter()).collect();
        let a = option_set_word(resolve::axis_set_ma(), &g);
        let al = alignment.words();
        opaque_modifier(
            resolve::container_relative_frame_fn(),
            resolve::container_relative_frame_oret(),
            view,
            &[a, al[0], al[1]],
            [0.0; 4],
        )
    }
}

/// Apply `.symbolRenderingMode(_:)`.
pub fn symbol_rendering_mode(view: &ViewHandle, mode: Option<SymbolRenderingMode>) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::symbol_rendering_mode_ma());
        let v = mode.map(|m| resilient_static(meta, m.getter()));
        let b = opt_resilient_bytes(meta, swift_type!(opt SwiftUI.SymbolRenderingMode).as_bytes(), v.as_deref());
        modifier_indirect(
            resolve::symbol_rendering_mode_fn(),
            resolve::symbol_rendering_mode_oret(),
            view,
            &b,
        )
    }
}

/// Apply `.fontWidth(_:)`.
pub fn font_width(view: &ViewHandle, width: Option<FontWidth>) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::font_width_ma());
        let v = width.map(|w| resilient_static(meta, w.getter()));
        let b = opt_resilient_bytes(meta, swift_type!(opt SwiftUI.Font.Width).as_bytes(), v.as_deref());
        modifier_indirect(resolve::font_width_fn(), resolve::font_width_oret(), view, &b)
    }
}

/// Apply `.listItemTint(_:)` with the monochrome tint or none.
pub fn list_item_tint_monochrome(view: &ViewHandle, tinted: bool) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::list_item_tint_ma());
        let v = tinted.then(|| resilient_static(meta, c"$s7SwiftUI12ListItemTintV10monochromeACvgZ"));
        let b = opt_resilient_bytes(meta, swift_type!(opt SwiftUI.ListItemTint).as_bytes(), v.as_deref());
        modifier_indirect(resolve::list_item_tint_fn(), resolve::list_item_tint_oret(), view, &b)
    }
}

/// Which `ListItemTint` a row uses.
///
/// The two colour cases are static *functions*, not `static var`s, which is
/// why only `.monochrome` appears in the statics report — there is nothing
/// for a plain getter to return when the case takes an argument.
// `Color` is not `PartialEq` here, so neither is this — the colour cases
// carry one and comparing tints is not something the crate needs.
#[derive(Clone, Copy, Debug)]
pub enum ListItemTint {
    /// Tint with the list's own monochrome treatment.
    Monochrome,
    /// This colour, always.
    Fixed(crate::Color),
    /// This colour unless the user's accent colour overrides it.
    Preferred(crate::Color),
}

/// Apply `.listItemTint(_:)`.
///
/// `None` clears the tint, which is the `nil` the modifier's `ListItemTint?`
/// parameter takes.
pub fn list_item_tint(view: &ViewHandle, tint: Option<ListItemTint>) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::list_item_tint_ma());
        let v = tint.map(|t| match t {
            ListItemTint::Monochrome => {
                resilient_static(meta, c"$s7SwiftUI12ListItemTintV10monochromeACvgZ")
            }
            ListItemTint::Fixed(c) => list_item_tint_of(resolve::list_item_tint_fixed(), meta, c),
            ListItemTint::Preferred(c) => {
                list_item_tint_of(resolve::list_item_tint_preferred(), meta, c)
            }
        });
        let b = opt_resilient_bytes(meta, swift_type!(opt SwiftUI.ListItemTint).as_bytes(), v.as_deref());
        modifier_indirect(resolve::list_item_tint_fn(), resolve::list_item_tint_oret(), view, &b)
    }
}

/// Call `ListItemTint.fixed(_:)` or `.preferred(_:)`.
///
/// `(sret, ptr)` — the `Color` is a single reference, so it travels in x0 by
/// value rather than by address; the tint is resilient and comes back through
/// x8.
///
/// # Safety
/// `f` must be one of those two statics and `meta` `ListItemTint`'s metadata.
unsafe fn list_item_tint_of(
    f: *const c_void,
    meta: *const c_void,
    color: crate::Color,
) -> Vec<u8> {
    unsafe {
        let word = super::color_value(color.r, color.g, color.b, color.a);
        let mut out = vec![0u8; abi::type_bytes(meta)];
        core::arch::asm!("blr {f}", f = in(reg) f,
            in("x0") word,
            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
    }
}

/// Apply `.typeSelectEquivalent(_:)`.
pub fn type_select_equivalent(view: &ViewHandle, text: Option<&str>) -> ViewHandle {
    unsafe {
        let payload = resolve::lsk_meta();
        let key = text.map(|t| {
            let (k0, k1, k2, k3) = lsk_words(t);
            let mut b = [0u8; 32];
            b[..8].copy_from_slice(&k0.to_le_bytes());
            b[8..16].copy_from_slice(&k1.to_le_bytes());
            b[16..24].copy_from_slice(&k2.to_le_bytes());
            b[24..].copy_from_slice(&k3.to_le_bytes());
            b
        });
        // Four words in four registers, not by address. A
        // `LocalizedStringKey` already travels that way everywhere else in this
        // file, and thirty-two bytes is exactly the four-register limit, so its
        // optional travels the same way.
        let opt = crate::type_by_name!(swift_type!(opt SwiftUI.LocalizedStringKey).as_bytes());
        let w = optional_words(payload, opt, key.as_ref().map_or(&[][..], |k| &k[..]), key.is_some());
        opaque_modifier(
            resolve::type_select_equivalent_fn(),
            resolve::type_select_equivalent_oret(),
            view,
            &w,
            [0.0; 4],
        )
    }
}

swift_cases! {
    /// `SwiftUI.PreviewLayout`'s cases without payloads.
    ///
    /// The tags are not the declaration order. Swift numbers an enum's *payload*
    /// cases first, and `PreviewLayout` has two of them — `fixed` and `fixed3D` —
    /// so the empty cases start at two. Guessing zero and one lands on `fixed3D`
    /// with a zeroed payload, which dumps as a real case and renders as nothing.
    pub enum PreviewLayout {
        Device = 2,
        SizeThatFits = 3,
    }
}

/// Apply `.previewLayout(_:)`.
pub fn preview_layout(view: &ViewHandle, layout: PreviewLayout) -> ViewHandle {
    unsafe {
        let b = enum_bytes(resolve::preview_layout_ma(), layout.tag());
        modifier_indirect(resolve::preview_layout_fn(), resolve::preview_layout_oret(), view, &b)
    }
}

/// Apply `.textScale(_:isEnabled:)`.
pub fn text_scale(view: &ViewHandle, scale: TextScale, enabled: bool) -> ViewHandle {
    unsafe {
        let s = resilient_static(abi::metadata0(resolve::text_scale_ma()), scale.getter());
        opaque_modifier(
            resolve::text_scale_fn(),
            resolve::text_scale_oret(),
            view,
            &[s.as_ptr() as u64, u64::from(enabled)],
            [0.0; 4],
        )
    }
}

/// Apply `.scrollEdgeEffectStyle(_:for:)`.
pub fn scroll_edge_effect_style(
    view: &ViewHandle,
    style: Option<ScrollEdgeEffectStyle>,
    edges: &[EdgeSetMember],
) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::scroll_edge_effect_style_ma());
        let v = style.map(|s| resilient_static(meta, s.getter()));
        let b = opt_resilient_bytes(meta, swift_type!(opt SwiftUI.ScrollEdgeEffectStyle).as_bytes(), v.as_deref());
        let g: Vec<&core::ffi::CStr> = edges.iter().map(|e| e.getter()).collect();
        let e = option_set_word(resolve::edge_set_ma(), &g);
        opaque_modifier(
            resolve::scroll_edge_effect_style_fn(),
            resolve::scroll_edge_effect_style_oret(),
            view,
            &[b.as_ptr() as u64, e],
            [0.0; 4],
        )
    }
}

swift_statics! {
    /// A member of `SwiftUI.Edge.Set`.
    pub enum EdgeSetMember {
        Top = c"$s7SwiftUI4EdgeO3SetV3topAEvgZ",
        Leading = c"$s7SwiftUI4EdgeO3SetV7leadingAEvgZ",
        Bottom = c"$s7SwiftUI4EdgeO3SetV6bottomAEvgZ",
        Trailing = c"$s7SwiftUI4EdgeO3SetV8trailingAEvgZ",
        All = c"$s7SwiftUI4EdgeO3SetV3allAEvgZ",
        Horizontal = c"$s7SwiftUI4EdgeO3SetV10horizontalAEvgZ",
        Vertical = c"$s7SwiftUI4EdgeO3SetV8verticalAEvgZ",
    }
}

crate::thunk::runtime_thunk! {
    /// A `(CGFloat, Axis) -> CGFloat` closure, as `containerRelativeFrame` wants.
    ///
    /// Swift hands a closure its context in x20 and its arguments in the
    /// ordinary registers — here the length in d0 and the axis in x0. Moving
    /// x20 into x1 makes the whole thing addressable from a plain
    /// `extern "C" fn(u64, *mut c_void, f64) -> f64`: integers in x0 and x1,
    /// the float in d0, the result in d0. It is the only closure shape in this
    /// crate that returns a value rather than writing one through x8.
    fn container_length_thunk = "rswift_container_length" via RSWIFT_CONTAINER_LENGTH {
        prologue: ["mov x1, x20"],
        branch: "br",
        epilogue: [],
    }
}

/// The body behind [`container_length_thunk`]: a third of the length down the
/// vertical axis, a fifth across.
///
/// `Axis` is frozen — `.horizontal` is 0 and `.vertical` is 1.
unsafe extern "C" fn container_length(axis: u64, _ctx: *mut c_void, length: f64) -> f64 {
    if axis == 1 { length / 3.0 } else { length / 5.0 }
}

/// Apply `.containerRelativeFrame(_:alignment:_:)` with the documentation's
/// length function.
pub fn container_relative_frame_thirds(
    view: &ViewHandle,
    axes: &[AxisSet],
    alignment: Alignment,
) -> ViewHandle {
    unsafe {
        RSWIFT_CONTAINER_LENGTH = container_length as *const c_void;
        let g: Vec<&core::ffi::CStr> = axes.iter().map(|a| a.getter()).collect();
        let set = option_set_word(resolve::axis_set_ma(), &g);
        let [ah, av] = alignment.words();
        let (meta, wt, size) = super::opaque_result_type(
            resolve::container_relative_frame_closure_oret(),
            &[view.meta, view.wt],
        );
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        // Leaked, not a stack local. The content closures elsewhere in this
        // crate run *during* the call that takes them, so a local outlives
        // them; this one is stored in the modifier and called at layout time,
        // by which point the frame that held it is long gone. The body never
        // reads it — the closure captures nothing — but SwiftUI retains and
        // releases it, and `ClosureCtx`'s immortal refcount makes both no-ops.
        let ctx = Box::leak(Box::new(abi::ClosureCtx::new(
            noop_closure_body,
            core::ptr::null_mut(),
        )));
        core::arch::asm!("blr {f}", f = in(reg) resolve::container_relative_frame_closure_fn(),
            in("x0") set,
            in("x1") ah, in("x2") av,
            in("x3") container_length_thunk as *const c_void,
            in("x4") ctx as *mut abi::ClosureCtx,
            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"),
        );
        wrap_owned(result, meta, wt)
    }
}

unsafe extern "C" fn noop_closure_body(_out: *mut u8, _payload: *mut c_void) {}