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
//! Scenes and commands — what an app is, above its views.
//!
//! [`crate::app::run`] builds one `WindowGroup` and stops there. A real macOS
//! app is several scenes: the window group, the preferences window `Settings`
//! puts behind ⌘, — a menu-bar item, a second window — and a menu bar described
//! by `Commands`. This module builds each of them, and the tuples that hold
//! several at once, so [`crate::app::run_scene`] can be given a whole app rather
//! than one window.
//!
//! ```no_run
//! use swiftui_native::{app, scene, views};
//!
//! app::run_scene(|| {
//!     scene::commands(
//!         scene::group(vec![
//!             scene::window_group(|| views::text("main")),
//!             scene::settings(|| views::text("preferences")),
//!             scene::menu_bar_extra("Status", "star", || views::text("menu")),
//!         ]),
//!         vec![scene::command_menu("Extras", || views::button("Do it", || {}))],
//!     )
//! });
//! ```
//!
//! # Why the content closures are borrowed
//!
//! Every initialiser here takes its content as `@noescape` — `xyXE` in the
//! mangling, not `yc` — so it calls the closure before returning and keeps the
//! *value*, not the closure. A borrowed [`crate::abi::ClosureCtx`] on the stack
//! is therefore correct, and leaking one (as a `sheet`'s content must be) would
//! leak once per read of `App.body`, which SwiftUI does repeatedly.
//!
//! # What is synthesised and what is SwiftUI's
//!
//! Nothing here is a Swift wrapper: each scene is SwiftUI's own type,
//! instantiated by calling its own initialiser with the arguments in the
//! registers its ABI names. `_TupleScene` and `TupleCommandContent` are what
//! `SceneBuilder` and `CommandsBuilder` build — those builders are
//! `@_alwaysEmitIntoClient` and export no symbol, so the binding calls what
//! their bodies call.

use crate::abi;
// Only `menu_bar_extra` names a type by hand, and it is macOS-only.
#[cfg(target_os = "macos")]
use crate::mangle::{self, swift_type};
use crate::resolve;
use crate::view::IntoView;
use crate::views::{self, ViewHandle};
use core::ffi::c_void;

/// A Swift value with its type and one protocol conformance.
///
/// The same shape as [`ViewHandle`], and for the same reason: the type is only
/// known at run time, so the bytes travel with the metadata that describes them
/// and the witness table that says what they are. Both [`SceneHandle`] and
/// [`CommandsHandle`] are this — distinct types at the Rust level so that
/// `commands(_:)` cannot be handed a scene, which is the one thing the
/// conformance itself would not catch.
struct Value {
    bytes: Vec<u8>,
    meta: *const c_void,
    wt: *const c_void,
}

impl Value {
    /// Take ownership of a `+1` value the caller has just built.
    ///
    /// # Safety
    /// `bytes` must hold an initialised value of `meta`'s type whose single
    /// reference is being handed over.
    unsafe fn wrap(bytes: Vec<u8>, meta: *const c_void, wt: *const c_void) -> Self {
        debug_assert!(!meta.is_null() && !wt.is_null(), "a value needs a type and a witness");
        Self { bytes, meta, wt }
    }

    fn ptr(&self) -> *const c_void {
        self.bytes.as_ptr() as *const c_void
    }

    /// Move the value into `out` and give up ownership of it.
    ///
    /// For `App.body`, whose result slot SwiftUI supplies: copying and then
    /// letting `Drop` run would destroy the reference just handed over, and
    /// SwiftUI would read freed storage on the next frame.
    ///
    /// # Safety
    /// `out` must have room for the type's stride.
    unsafe fn move_into(self, out: *mut u8) {
        let me = core::mem::ManuallyDrop::new(self);
        unsafe { core::ptr::copy_nonoverlapping(me.bytes.as_ptr(), out, me.bytes.len()) };
    }
}

impl Drop for Value {
    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);
            }
        }
    }
}

/// A value conforming to SwiftUI's `Scene` — a window, a settings pane, a
/// menu-bar item, or a tuple of them.
pub struct SceneHandle(Value);

/// A value conforming to SwiftUI's `Commands` — one menu, or a tuple of them.
pub struct CommandsHandle(Value);

impl SceneHandle {
    /// The Swift type of the scene, as the runtime spells it.
    pub fn type_name(&self) -> String {
        crate::diag::type_name(self.0.meta)
    }

    /// Move the scene into `out`, giving up ownership.
    ///
    /// # Safety
    /// `out` must have room for the type's stride.
    pub(crate) unsafe fn move_into(self, out: *mut u8) {
        unsafe { self.0.move_into(out) }
    }

    pub(crate) fn meta(&self) -> *const c_void {
        self.0.meta
    }

    pub(crate) fn wt(&self) -> *const c_void {
        self.0.wt
    }
}

impl CommandsHandle {
    /// The Swift type of the commands, as the runtime spells it.
    pub fn type_name(&self) -> String {
        crate::diag::type_name(self.0.meta)
    }
}

// ── The content closure ──

/// What a scene's or menu's `@ViewBuilder content:` closure needs.
struct Content<'a> {
    builder: &'a dyn Fn() -> ViewHandle,
}

/// Emit the builder's view, erased into an `AnyView`.
///
/// A Rust closure's result type is decided at run time, so the content type is
/// `AnyView` — the same trade every closure-valued binding in this crate makes.
///
/// # Safety
/// Reached through [`abi::swift_closure_thunk`]; `payload` must be a [`Content`].
unsafe extern "C" fn emit_content(out: *mut u8, payload: *mut c_void) {
    let p = unsafe { &*(payload as *const Content<'_>) };
    let view = (p.builder)();
    unsafe { *(out as *mut u64) = view.into_anyview_word() };
}

/// A type's conformance to `proto`, or a panic naming what failed.
///
/// `name` is only for the message: a protocol descriptor carries its name, but
/// not anywhere a caller can read it without walking the descriptor, and the
/// caller already knows which one it asked for.
///
/// # Safety
/// `meta` must be valid metadata and `proto` a protocol descriptor.
unsafe fn conformance(
    meta: *const c_void,
    proto: *const c_void,
    name: &str,
) -> *const c_void {
    let wt = unsafe { abi::get_view_wt_for_proto(meta, proto) };
    assert!(!wt.is_null(), "{} !: {name}", crate::diag::type_name(meta));
    wt
}

/// `X<AnyView>` for a type generic over one `Content: View`.
///
/// # Safety
/// `ma` must be such a type's metadata accessor.
unsafe fn over_anyview(ma: *const c_void) -> *const c_void {
    let meta = unsafe {
        abi::generic_metadata2(ma, resolve::anyview_meta(), resolve::anyview_wt())
    };
    assert!(!meta.is_null(), "metadata instantiation failed");
    meta
}

/// An initialiser whose whole argument list is one `@ViewBuilder content:`.
///
/// `WindowGroup.init(content:)`, `Settings.init(content:)` and
/// `CommandMenu`'s content have this shape — `(sret, closure fn, closure ctx,
/// Content.Type, Content: View)` — so one body serves all of them.
///
/// # Safety
/// `init` must be such an initialiser and `meta` the result's metadata.
unsafe fn build_from_content(
    init: *const c_void,
    meta: *const c_void,
    builder: &dyn Fn() -> ViewHandle,
) -> Vec<u8> {
    unsafe {
        let payload = Content { builder };
        let mut ctx = abi::ClosureCtx::new(
            emit_content,
            &payload as *const Content<'_> as *mut c_void,
        );
        let mut bytes = 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") resolve::anyview_meta(),
            in("x3") resolve::anyview_wt(),
            in("x8") bytes.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"),
        );
        bytes
    }
}

/// An initialiser taking four words of label, two of string, then the content.
///
/// `Window` and `MenuBarExtra` are the only two, and both are macOS-only.
///
/// `Window(_:id:content:)` and `MenuBarExtra(_:systemImage:content:)` both look
/// like this. Eight integer registers is all there are, so the two generic
/// arguments go on the stack.
///
/// # Safety
/// `init` must be such an initialiser and `meta` the result's metadata.
#[cfg(target_os = "macos")]
unsafe fn build_from_key_string_content(
    init: *const c_void,
    meta: *const c_void,
    key: &str,
    string: &str,
    builder: &dyn Fn() -> ViewHandle,
) -> Vec<u8> {
    unsafe {
        let (k0, k1, k2, k3) = views::lsk_words(key);
        let s = abi::swift_string(string);
        let s0 = u64::from_le_bytes(s[..8].try_into().expect("string lo"));
        let s1 = u64::from_le_bytes(s[8..].try_into().expect("string hi"));
        let payload = Content { builder };
        let mut ctx = abi::ClosureCtx::new(
            emit_content,
            &payload as *const Content<'_> as *mut c_void,
        );
        let mut bytes = vec![0u8; abi::type_bytes(meta)];
        // x0-x3 = LocalizedStringKey, x4/x5 = the String, x6/x7 = the closure,
        // [sp] = Content.Type, [sp+8] = Content: View.
        core::arch::asm!(
            "sub sp, sp, #16",
            "stp {cm}, {cw}, [sp]",
            "blr {f}",
            "add sp, sp, #16",
            f = in(reg) init,
            cm = in(reg) resolve::anyview_meta(),
            cw = in(reg) resolve::anyview_wt(),
            in("x0") k0, in("x1") k1, in("x2") k2, in("x3") k3,
            in("x4") s0, in("x5") s1,
            in("x6") abi::swift_closure_thunk as *const c_void,
            in("x7") &mut ctx as *mut abi::ClosureCtx,
            in("x8") bytes.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"),
        );
        bytes
    }
}

// ── Scenes ──

/// `WindowGroup { content }` — the app's main window, and as many more as the
/// user opens.
pub fn window_group<V: IntoView>(content: impl Fn() -> V) -> SceneHandle {
    let content = move || content().into_view().into_handle();
    unsafe {
        let meta = over_anyview(resolve::windowgroup_ma());
        let bytes = build_from_content(resolve::windowgroup_content_init(), meta, &content);
        SceneHandle(Value::wrap(bytes, meta, conformance(meta, resolve::scene_proto(), "Scene")))
    }
}

/// `Settings { content }` — the window behind ⌘, on macOS.
#[cfg(target_os = "macos")]
pub fn settings<V: IntoView>(content: impl Fn() -> V) -> SceneHandle {
    let content = move || content().into_view().into_handle();
    unsafe {
        let meta = over_anyview(resolve::settings_ma());
        let bytes = build_from_content(resolve::settings_content_init(), meta, &content);
        SceneHandle(Value::wrap(bytes, meta, conformance(meta, resolve::scene_proto(), "Scene")))
    }
}

/// `Window(title, id: id) { content }` — a single window, not a group.
///
/// Unlike a `WindowGroup` the user cannot open a second one; `id` is what
/// `openWindow` names it by.
#[cfg(target_os = "macos")]
pub fn window<V: IntoView>(title: &str, id: &str, content: impl Fn() -> V) -> SceneHandle {
    let content = move || content().into_view().into_handle();
    unsafe {
        let meta = over_anyview(resolve::window_ma());
        let bytes =
            build_from_key_string_content(resolve::window_init(), meta, title, id, &content);
        SceneHandle(Value::wrap(bytes, meta, conformance(meta, resolve::scene_proto(), "Scene")))
    }
}

/// `MenuBarExtra(title, systemImage: image) { content }` — an item in the
/// system menu bar, with a menu of its own.
///
/// The `Label == Label<Text, Image>` overload, the one that takes a title and an
/// SF Symbol. Its `Label` type argument is concrete, so the metadata is resolved
/// by name rather than through the accessor — the accessor would want
/// `Label<Text, Image>`'s own metadata and both of its `View` conformances first,
/// which is three more lookups to reach the same answer.
#[cfg(target_os = "macos")]
pub fn menu_bar_extra<V: IntoView>(
    title: &str,
    system_image: &str,
    content: impl Fn() -> V,
) -> SceneHandle {
    let content = move || content().into_view().into_handle();
    unsafe {
        let label = mangle::bound(
            &swift_type!(SwiftUI.Label),
            &[&swift_type!(SwiftUI.Text), &swift_type!(SwiftUI.Image)],
        );
        let named = mangle::bound(
            &swift_type!(SwiftUI.MenuBarExtra),
            &[&label, &swift_type!(SwiftUI.AnyView)],
        );
        let meta = abi::resolve_type_by_mangled_name(named.as_bytes());
        assert!(!meta.is_null(), "{}", mangle::demangle(&named));
        let bytes = build_from_key_string_content(
            resolve::menu_bar_extra_init(),
            meta,
            title,
            system_image,
            &content,
        );
        SceneHandle(Value::wrap(bytes, meta, conformance(meta, resolve::scene_proto(), "Scene")))
    }
}

/// Several scenes as one — `_TupleScene<(A, B, …)>`.
///
/// What `SceneBuilder`'s variadic `buildBlock` returns, so this is what writing
/// four scenes one after another inside `var body: some Scene` reduces to. A
/// single scene is returned unchanged, as the one-element `buildBlock` does.
pub fn group(scenes: Vec<SceneHandle>) -> SceneHandle {
    assert!(!scenes.is_empty(), "a scene group needs at least one scene");
    if scenes.len() == 1 {
        return scenes.into_iter().next().expect("one scene");
    }
    unsafe {
        SceneHandle(tuple_of(
            scenes.into_iter().map(|s| s.0).collect(),
            resolve::tuple_scene_ma(),
            resolve::tuple_scene_init(),
            resolve::scene_proto(),
            "Scene",
        ))
    }
}

/// Build `Wrapper<(A, B, …)>` from a list of values of mixed types.
///
/// Shared by `_TupleScene` and `TupleCommandContent`, which have the same shape:
/// one unconstrained generic parameter, an initialiser taking the tuple `@in`
/// plus `T.Type`, and an unconditional conformance.
///
/// The elements' *own* types go into the tuple, not an erased stand-in: a
/// `_TupleScene<(WindowGroup<AnyView>, Settings<AnyView>)>` is what Swift
/// builds, and the runtime finds each element's conformance by reflecting over
/// that tuple — an erased tuple would render and be the wrong type.
///
/// # Safety
/// `ma` and `init` must be the wrapper's accessor and initialiser, and `proto`
/// the protocol the wrapper is being used for.
unsafe fn tuple_of(
    parts: Vec<Value>,
    ma: *const c_void,
    init: *const c_void,
    proto: *const c_void,
    name: &str,
) -> Value {
    unsafe {
        let elements: Vec<*const c_void> = parts.iter().map(|p| p.meta).collect();
        let tuple_meta = abi::tuple_metadata(&elements);
        assert!(!tuple_meta.is_null(), "tuple metadata instantiation failed");
        // The runtime chose the layout; asking it is the only way to know it.
        let offsets = abi::tuple_element_offsets(tuple_meta, parts.len());
        let mut tuple = vec![0u8; abi::type_bytes(tuple_meta)];
        for (part, &offset) in parts.iter().zip(&offsets) {
            let vwt = &*swift_runtime_sys::SwiftABI::get_value_witness_table(part.meta);
            if vwt.size > 0 {
                (vwt.initialize_with_copy)(
                    tuple.as_mut_ptr().add(offset) as *mut c_void,
                    part.ptr() as *mut c_void,
                    part.meta,
                );
            }
        }

        let meta = abi::generic_metadata1(ma, tuple_meta);
        assert!(!meta.is_null(), "tuple wrapper metadata instantiation failed");
        let mut bytes = vec![0u8; abi::type_bytes(meta)];
        // x0 = @in the tuple, x1 = T.Type, x8 = @out.
        core::arch::asm!("blr {f}", f = in(reg) init,
            in("x0") tuple.as_mut_ptr(),
            in("x1") tuple_meta,
            in("x8") bytes.as_mut_ptr(),
            lateout("x2") _, lateout("x3") _, lateout("x4") _, lateout("x5") _,
            lateout("x6") _, lateout("x7") _,
            lateout("x9") _, lateout("x10") _, lateout("x11") _, lateout("x12") _,
            lateout("x13") _, lateout("x14") _, lateout("x15") _, lateout("x16") _,
            lateout("x17") _, lateout("lr") _, lateout("x20") _, lateout("x21") _,
            clobber_abi("C"),
        );
        // The initialiser consumed the tuple, which held a copy of each part;
        // the parts themselves are still ours, and dropping them destroys those.
        drop(parts);
        Value::wrap(bytes, meta, conformance(meta, proto, name))
    }
}

// ── Commands — the menu bar ──

/// `CommandMenu(title) { content }` — a whole new menu in the menu bar.
pub fn command_menu<V: IntoView>(title: &str, content: impl Fn() -> V) -> CommandsHandle {
    let content = move || content().into_view().into_handle();
    unsafe {
        let meta = over_anyview(resolve::command_menu_ma());
        let builder: &dyn Fn() -> ViewHandle = &content;
        let (k0, k1, k2, k3) = views::lsk_words(title);
        let payload = Content { builder };
        let mut ctx = abi::ClosureCtx::new(
            emit_content,
            &payload as *const Content<'_> as *mut c_void,
        );
        let mut bytes = vec![0u8; abi::type_bytes(meta)];
        // x0-x3 = LocalizedStringKey, x4/x5 = the closure,
        // x6 = Content.Type, x7 = Content: View, x8 = @out.
        core::arch::asm!("blr {f}", f = in(reg) resolve::command_menu_init(),
            in("x0") k0, in("x1") k1, in("x2") k2, in("x3") k3,
            in("x4") abi::swift_closure_thunk as *const c_void,
            in("x5") &mut ctx as *mut abi::ClosureCtx,
            in("x6") resolve::anyview_meta(),
            in("x7") resolve::anyview_wt(),
            in("x8") bytes.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"),
        );
        CommandsHandle(Value::wrap(
            bytes,
            meta,
            conformance(meta, resolve::commands_proto(), "Commands"),
        ))
    }
}

swift_statics! {
    /// Where in the standard menu bar a [`command_group`] goes.
    ///
    /// The twenty-one placements SwiftUI exports, each a static property of
    /// `CommandGroupPlacement` read through its own getter rather than a number
    /// written down — the type is resilient and its layout is not API.
    pub enum CommandPlacement {
        AppInfo = c"$s7SwiftUI21CommandGroupPlacementV7appInfoACvgZ",
        AppSettings = c"$s7SwiftUI21CommandGroupPlacementV11appSettingsACvgZ",
        AppShortcuts = c"$s7SwiftUI21CommandGroupPlacementV12appShortcutsACvgZ",
        AppSpecificSettings = c"$s7SwiftUI21CommandGroupPlacementV11appSettingsACvgZ",
        AppTermination = c"$s7SwiftUI21CommandGroupPlacementV14appTerminationACvgZ",
        AppVisibility = c"$s7SwiftUI21CommandGroupPlacementV13appVisibilityACvgZ",
        Help = c"$s7SwiftUI21CommandGroupPlacementV4helpACvgZ",
        ImportExport = c"$s7SwiftUI21CommandGroupPlacementV12importExportACvgZ",
        NewItem = c"$s7SwiftUI21CommandGroupPlacementV7newItemACvgZ",
        Pasteboard = c"$s7SwiftUI21CommandGroupPlacementV10pasteboardACvgZ",
        PrintItem = c"$s7SwiftUI21CommandGroupPlacementV9printItemACvgZ",
        SaveItem = c"$s7SwiftUI21CommandGroupPlacementV8saveItemACvgZ",
        Sidebar = c"$s7SwiftUI21CommandGroupPlacementV7sidebarACvgZ",
        SingleWindowList = c"$s7SwiftUI21CommandGroupPlacementV16singleWindowListACvgZ",
        SystemServices = c"$s7SwiftUI21CommandGroupPlacementV14systemServicesACvgZ",
        TextEditing = c"$s7SwiftUI21CommandGroupPlacementV11textEditingACvgZ",
        TextFormatting = c"$s7SwiftUI21CommandGroupPlacementV14textFormattingACvgZ",
        Toolbar = c"$s7SwiftUI21CommandGroupPlacementV7toolbarACvgZ",
        UndoRedo = c"$s7SwiftUI21CommandGroupPlacementV8undoRedoACvgZ",
        WindowArrangement = c"$s7SwiftUI21CommandGroupPlacementV17windowArrangementACvgZ",
        WindowList = c"$s7SwiftUI21CommandGroupPlacementV10windowListACvgZ",
        WindowSize = c"$s7SwiftUI21CommandGroupPlacementV10windowSizeACvgZ",
    }
}

/// Where a group sits relative to the placement it names.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Relative {
    /// Take the standard group's place entirely.
    Replacing,
    /// Add after it.
    After,
    /// Add before it.
    Before,
}

/// `CommandGroup(replacing:/after:/before: placement) { content }` — items
/// added to, or in place of, one of the standard menu groups.
pub fn command_group<V: IntoView>(
    placement: CommandPlacement,
    where_: Relative,
    content: impl Fn() -> V,
) -> CommandsHandle {
    let content = move || content().into_view().into_handle();
    unsafe {
        let meta = over_anyview(resolve::command_group_ma());
        let placement_meta = abi::metadata0(resolve::command_group_placement_ma());
        assert!(!placement_meta.is_null(), "CommandGroupPlacement metadata");
        // Resilient, so it travels by address and its stride is asked for.
        let mut place =
            views::static_getter_indirect(placement.resolved(), placement_meta, 0);

        let init = match where_ {
            Relative::Replacing => resolve::command_group_replacing_init(),
            Relative::After => resolve::command_group_after_init(),
            Relative::Before => resolve::command_group_before_init(),
        };
        let builder: &dyn Fn() -> ViewHandle = &content;
        let payload = Content { builder };
        let mut ctx = abi::ClosureCtx::new(
            emit_content,
            &payload as *const Content<'_> as *mut c_void,
        );
        let mut bytes = vec![0u8; abi::type_bytes(meta)];
        // x0 = @in placement, x1/x2 = the closure,
        // x3 = Content.Type, x4 = Content: View, x8 = @out.
        core::arch::asm!("blr {f}", f = in(reg) init,
            in("x0") place.as_mut_ptr(),
            in("x1") abi::swift_closure_thunk as *const c_void,
            in("x2") &mut ctx as *mut abi::ClosureCtx,
            in("x3") resolve::anyview_meta(),
            in("x4") resolve::anyview_wt(),
            in("x8") bytes.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"),
        );
        CommandsHandle(Value::wrap(
            bytes,
            meta,
            conformance(meta, resolve::commands_proto(), "Commands"),
        ))
    }
}

/// `.commands { … }` on a scene — the app's menu bar.
///
/// The menus are combined into a `TupleCommandContent`, which is what
/// `CommandsBuilder.buildBlock` builds. An empty list is rejected rather than
/// silently producing a scene with no menus: `commands` with nothing in it is a
/// mistake, not a shorthand.
pub fn commands(scene: SceneHandle, menus: Vec<CommandsHandle>) -> SceneHandle {
    assert!(!menus.is_empty(), "`commands` needs at least one menu");
    unsafe {
        let content = if menus.len() == 1 {
            menus.into_iter().next().expect("one menu").0
        } else {
            tuple_of(
                menus.into_iter().map(|m| m.0).collect(),
                resolve::tuple_commands_ma(),
                resolve::tuple_commands_init(),
                resolve::commands_proto(),
                "Commands",
            )
        };

        // The content closure here returns `Commands`, not a view, so it cannot
        // go through `emit_content`: what it emits is the tuple built above.
        let payload = EmitValue { value: content.ptr(), meta: content.meta };
        let mut ctx = abi::ClosureCtx::new(
            emit_value,
            &payload as *const EmitValue as *mut c_void,
        );

        let subst = [scene.meta(), content.meta, scene.wt(), content.wt];
        let (meta, wt, size) =
            views::opaque_result_type(resolve::scene_commands_oret(), &subst);
        let mut bytes = vec![0u8; size];
        let this = scene.0.ptr();
        // x0/x1 = the content closure, x2 = Self.Type, x3 = C.Type,
        // x4 = Self: Scene, x5 = C: Commands, x8 = @out, x20 = self.
        core::arch::asm!("blr {f}", f = in(reg) resolve::scene_commands_fn(),
            in("x0") abi::swift_closure_thunk as *const c_void,
            in("x1") &mut ctx as *mut abi::ClosureCtx,
            in("x2") scene.meta(),
            in("x3") content.meta,
            in("x4") scene.wt(),
            in("x5") content.wt,
            in("x8") bytes.as_mut_ptr(),
            in("x20") this,
            lateout("x6") _, lateout("x7") _,
            lateout("x9") _, lateout("x10") _, lateout("x11") _, lateout("x12") _,
            lateout("x13") _, lateout("x14") _, lateout("x15") _, lateout("x16") _,
            lateout("x17") _, lateout("lr") _, lateout("x21") _, clobber_abi("C"),
        );
        SceneHandle(Value::wrap(bytes, meta, wt))
    }
}

/// What [`emit_value`] copies.
#[repr(C)]
struct EmitValue {
    value: *const c_void,
    meta: *const c_void,
}

/// A closure body that emits an already-built value of any type.
///
/// `.commands(content:)`'s closure returns `some Commands`, so the result is a
/// value of a type only the payload knows — copied through its own witness
/// rather than written as a word, the way an `AnyView` can be.
///
/// # Safety
/// Reached through [`abi::swift_closure_thunk`]; `payload` must be an
/// [`EmitValue`] whose `value` is live.
unsafe extern "C" fn emit_value(out: *mut u8, payload: *mut c_void) {
    let p = unsafe { &*(payload as *const EmitValue) };
    unsafe {
        let vwt = &*swift_runtime_sys::SwiftABI::get_value_witness_table(p.meta);
        if vwt.size > 0 {
            (vwt.initialize_with_copy)(out as *mut c_void, p.value as *mut c_void, p.meta);
        }
    }
}