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
//! Search fields, file dialogs, and what a presentation offers.
//!
//! Grouped because they share an argument vocabulary — a `Binding` for what is
//! showing, a `Set` or an array of content types for what is allowed, and a
//! completion taking a `Result` the Rust side has to open.

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

/// Apply `.searchSelection(_:)`.
///
/// `Binding<TextSelection?>` is forty bytes — past the four registers a
/// loadable value gets — so it travels by address. The selection itself is
/// opaque to Rust, so the binding reports "no selection" and `changed` is told
/// whenever SwiftUI writes one back.
pub fn search_selection(view: &ViewHandle, changed: impl Fn() + 'static) -> ViewHandle {
    unsafe {
        let value_meta = crate::type_by_name!(swift_type!(opt SwiftUI.TextSelection).as_bytes());
        let payload = crate::type_by_name!(swift_type!(SwiftUI.TextSelection).as_bytes());
        let width = abi::type_bytes(value_meta);
        // Zeroing is not `nil`: `TextSelection` has no spare bit pattern that
        // reads as absent, so the discriminator has to be written explicitly.
        let mut none = vec![0u8; width];
        abi::store_optional_tag(&mut none, payload, false);
        let binding = binding_get_set(
            value_meta,
            mangle::ty("Binding")
                .of(vec![mangle::opt(mangle::ty("TextSelection"))])
                .mangle()
                .as_bytes(),
            Box::new(move |out| {
                core::ptr::copy_nonoverlapping(none.as_ptr(), out, width);
            }),
            Box::new(move |_| changed()),
        );
        modifier_indirect(
            resolve::search_selection_fn(),
            resolve::search_selection_oret(),
            view,
            &binding,
        )
    }
}

/// Which detent a sheet may rest at.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PresentationDetent {
    Medium,
    Large,
}

impl PresentationDetent {
    fn getter(self) -> &'static core::ffi::CStr {
        match self {
            PresentationDetent::Medium => c"$s7SwiftUI18PresentationDetentV6mediumACvgZ",
            PresentationDetent::Large => c"$s7SwiftUI18PresentationDetentV5largeACvgZ",
        }
    }
}

/// A `Set<String>` holding `items`.
pub(crate) unsafe fn string_set(items: &[&str]) -> u64 {
    unsafe {
        let meta = resolve::string_meta();
        let stride = abi::type_bytes(meta);
        let mut bytes = vec![0u8; stride * items.len()];
        for (i, s) in items.iter().enumerate() {
            bytes[i * stride..i * stride + 16].copy_from_slice(&abi::swift_string(s));
        }
        abi::swift_set(meta, resolve::string_hashable_wt(), items.len(), &bytes)
    }
}

/// Apply `.handlesExternalEvents(preferring:allowing:)`.
///
/// Both arguments are real `Set<String>`s built from the caller's strings.
pub fn handles_external_events(
    view: &ViewHandle,
    preferring: &[&str],
    allowing: &[&str],
) -> ViewHandle {
    unsafe {
        opaque_modifier(
            resolve::handles_external_events_fn(),
            resolve::handles_external_events_oret(),
            view,
            &[string_set(preferring), string_set(allowing)],
            [0.0; 4],
        )
    }
}

/// Apply `.presentationDetents(_:)`.
///
/// `PresentationDetent` exports no `Hashable` witness table, so the conformance
/// is looked up at run time the same way a `View` conformance is — which is the
/// only reason a `Set` of them can be built from outside SwiftUI at all.
pub fn presentation_detents(view: &ViewHandle, detents: &[PresentationDetent]) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::presentation_detent_ma());
        let wt = abi::get_view_wt_for_proto(meta, resolve::hashable_proto());
        assert!(!wt.is_null(), "PresentationDetent: Hashable");
        let stride = abi::type_bytes(meta);
        let mut bytes = vec![0u8; stride * detents.len()];
        for (i, d) in detents.iter().enumerate() {
            let v = resilient_static(meta, d.getter());
            bytes[i * stride..i * stride + v.len()].copy_from_slice(&v);
        }
        let set = abi::swift_set(meta, wt, detents.len(), &bytes);
        opaque_modifier(
            resolve::presentation_detents_fn(),
            resolve::presentation_detents_oret(),
            view,
            &[set],
            [0.0; 4],
        )
    }
}

/// Apply `.searchable(text:isPresented:placement:prompt:)`.
///
/// The widest modifier bound here: four words of `Binding<String>`, three of
/// `Binding<Bool>`, one of placement and four of `LocalizedStringKey` — twelve
/// argument words before the two type arguments, so eight of them spill onto
/// the stack.
pub fn searchable(
    view: &ViewHandle,
    text: &BoundState<String>,
    presented: &BoundState<bool>,
    placement: SearchFieldPlacement,
    prompt: &str,
) -> ViewHandle {
    unsafe {
        let t = text_binding(text);
        let p = bool_binding(presented);
        // One byte wide, but resilient: the getter writes it through x8 and the
        // modifier takes it by address, so reading x0 gets a register that was
        // never written.
        let meta = abi::metadata0(resolve::search_field_placement_ma());
        let place = resilient_static(meta, placement.getter());
        let (k0, k1, k2, k3) = lsk_words(prompt);
        let mut ints: Vec<u64> = words(&t);
        ints.extend(words(&p));
        ints.push(place.as_ptr() as u64);
        ints.extend_from_slice(&[k0, k1, k2, k3]);
        let subst = [view.meta, view.wt];
        let (m, wt, size) = opaque_result_type(resolve::searchable_oret(), &subst);
        let r = abi::call_modifier(resolve::searchable_fn(), view.value_ptr(), view.meta, view.wt, &ints, [0.0; 4], size);
        wrap_owned(r, m, wt)
    }
}

/// Apply `.searchSuggestions(_:for:)`.
pub fn search_suggestions(
    view: &ViewHandle,
    visibility: Visibility,
    placements: SearchSuggestionsPlacementSet,
) -> ViewHandle {
    unsafe {
        // `Visibility` travels *in* a register; the option set does not.
        // `Edge.Set` and friends are frozen and come back from their getters in
        // x0, but these two are resilient — the getter writes through x8, and a
        // getter's convention and a parameter's are the same question.
        let vm = abi::metadata0(resolve::visibility_ma());
        let sm = abi::metadata0(resolve::search_suggestions_placement_set_ma());
        let p = resilient_static(sm, placements.getter());
        opaque_modifier(
            resolve::search_suggestions_fn(),
            resolve::search_suggestions_oret(),
            view,
            &[abi::enum_argument(vm, visibility as u32), p.as_ptr() as u64],
            [0.0; 4],
        )
    }
}

/// Apply `.textInputFormattingControlVisibility(_:for:)`.
pub fn text_input_formatting_control_visibility(
    view: &ViewHandle,
    visibility: Visibility,
    placements: TextInputFormattingControlPlacementSet,
) -> ViewHandle {
    unsafe {
        // Resilient, so by address — see [`search_suggestions`].
        let vm = abi::metadata0(resolve::visibility_ma());
        let sm = abi::metadata0(resolve::text_input_formatting_set_ma());
        let p = resilient_static(sm, placements.getter());
        opaque_modifier(
            resolve::text_input_formatting_fn(),
            resolve::text_input_formatting_oret(),
            view,
            &[abi::enum_argument(vm, visibility as u32), p.as_ptr() as u64],
            [0.0; 4],
        )
    }
}

/// Apply `.dismissalConfirmationDialog(_:shouldPresent:actions:message:)`.
pub fn dismissal_confirmation_dialog(
    view: &ViewHandle,
    title: &str,
    should_present: bool,
    actions: &ViewHandle,
    message: &ViewHandle,
) -> ViewHandle {
    unsafe {
        let (k0, k1, k2, k3) = lsk_words(title);
        two_view_modifier(
            resolve::dismissal_dialog_fn(),
            resolve::dismissal_dialog_oret(),
            view,
            &[k0, k1, k2, k3, u64::from(should_present)],
            actions,
            message,
        )
    }
}

/// The outcome of a file dialog, as much of it as Rust can read.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FileOutcome {
    /// The user chose this URL, given as its absolute string.
    Picked(String),
    /// The dialog failed. The `Error` is an existential this cannot open.
    Failed,
}

/// `(Result<URL, Error>) -> ()`.
///
/// `Result` carries an `Error` existential, which puts it well past four words,
/// so it arrives by address. Its cases are `success` then `failure` and neither
/// is empty, so the tags are the declaration order — but the tag is read through
/// the enum's own witness rather than off a fixed byte, because a payload case
/// stores its discriminator wherever the payload leaves room.
pub(crate) unsafe extern "C" fn invoke_file_result(
    a0: u64,
    _a1: u64,
    _a2: u64,
    payload: *mut c_void,
) {
    unsafe {
        let f = boxed_ref::<dyn Fn(FileOutcome)>(payload);
        let meta = abi::resolve_type_by_mangled_name(mangle::bound(&swift_type!(stdlib enum Result), &[&swift_type!(Foundation.URL), &mangle::existential("s5Error")]).as_bytes());
        if meta.is_null() {
            f(FileOutcome::Failed);
            return;
        }
        if abi::read_enum_tag(a0 as *const u8, meta) != 0 {
            f(FileOutcome::Failed);
            return;
        }
        // The payload sits at offset zero; `absoluteString` is the one accessor
        // that turns a resilient `URL` back into something Rust can read.
        let (s0, s1): (u64, u64);
        core::arch::asm!("blr {f}", f = in(reg) resolve::url_absolute_string(),
            in("x20") a0,
            lateout("x0") s0, lateout("x1") s1,
            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("x21") _, clobber_abi("C"),
        );
        let mut raw = [0u8; 16];
        raw[..8].copy_from_slice(&s0.to_le_bytes());
        raw[8..].copy_from_slice(&s1.to_le_bytes());
        f(FileOutcome::Picked(abi::read_swift_string(raw)));
    }
}

/// Apply `.fileImporter(isPresented:allowedContentTypes:onCompletion:)`.
pub fn file_importer(
    view: &ViewHandle,
    state: &BoundState<bool>,
    kinds: &[ContentType],
    completion: impl Fn(FileOutcome) + 'static,
) -> ViewHandle {
    unsafe {
        let mut b = bool_binding(state);
        let w = binding_words(&mut b);
        let c = wide_words(invoke_file_result, boxed_ctx(Box::new(completion) as Box<dyn Fn(FileOutcome)>));
        opaque_modifier(
            resolve::file_importer_fn(),
            resolve::file_importer_oret(),
            view,
            &[w[0], w[1], w[2], content_types(kinds), c[0], c[1]],
            [0.0; 4],
        )
    }
}

/// Apply `.searchScopes(_:scopes:)` with `A == Int`.
///
/// Two generic parameters carrying *different* constraints — `Hashable` on the
/// binding's value and `View` on the builder's result — so the tail is three
/// metadata arguments and three witness tables, in requirement order.
pub fn search_scopes(
    view: &ViewHandle,
    scope: &BoundState<i64>,
    scopes: &ViewHandle,
) -> ViewHandle {
    unsafe {
        // `Binding<A>` with `A` *generic* is address-only however small the
        // caller's choice of `A` turns out to be — the callee cannot know its
        // layout. So a pointer, where `searchable`'s concrete `Binding<String>`
        // travels in registers.
        let b = i64_binding(scope);
        // `Self` is the concrete receiver; the trailing type is the content
        // the closure emits, which `view_words` erases to an `AnyView`.
        let av = scopes.meta;
        let aw = scopes.wt;
        let im = resolve::int_meta();
        let ih = resolve::int_hashable_wt();
        let subst = [view.meta, im, av, view.wt, ih, aw];
        let (meta, wt, size) = opaque_result_type(resolve::search_scopes_oret(), &subst);
        let mut ints = vec![b.as_ptr() as u64];
        ints.extend_from_slice(&view_words(scopes));
        ints.extend_from_slice(&[view.meta as u64, im as u64, av as u64]);
        ints.extend_from_slice(&[view.wt as u64, ih as u64, aw as u64]);
        let r = abi::call_modifier_generic(resolve::search_scopes_fn(), view.value_ptr(), &ints, [0.0; 4], size);
        wrap_owned(r, meta, wt)
    }
}

/// `Optional<Foundation.URL>` in a buffer, ready to pass by address.
///
/// `URL.init?(string:)` is the only exported way in — `init(fileURLWithPath:)`
/// has no symbol at all — and its parameter is `__shared String`, which is why
/// the mangling ends `SSh_` rather than `SS_`. It is failable, so what comes
/// back through x8 is already the optional the modifier wants.
pub(crate) unsafe fn optional_url(spec: Option<&str>) -> Vec<u8> {
    unsafe {
        let payload = abi::metadata0(resolve::url_ma());
        let opt = crate::type_by_name!(swift_type!(opt Foundation.URL).as_bytes());
        assert!(!opt.is_null(), "Optional<URL>");
        let mut buf = vec![0u8; abi::type_bytes(opt)];
        match spec {
            Some(s) => {
                let ss = abi::swift_string(s);
                let s0 = u64::from_le_bytes(ss[..8].try_into().expect("url lo"));
                let s1 = u64::from_le_bytes(ss[8..].try_into().expect("url hi"));
                core::arch::asm!("blr {f}", f = in(reg) resolve::url_string_init(),
                    in("x0") s0, in("x1") s1,
                    in("x8") buf.as_mut_ptr(), in("x20") payload,
                    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"),
                );
            }
            None => abi::store_optional_tag(&mut buf, payload, false),
        }
        buf
    }
}

/// Apply `.fileMover(isPresented:file:onCompletion:)`.
pub fn file_mover(
    view: &ViewHandle,
    state: &BoundState<bool>,
    file: Option<&str>,
    completion: impl Fn(FileOutcome) + 'static,
) -> ViewHandle {
    unsafe {
        let mut b = bool_binding(state);
        let w = binding_words(&mut b);
        let url = optional_url(file);
        let c = wide_words(invoke_file_result, boxed_ctx(Box::new(completion) as Box<dyn Fn(FileOutcome)>));
        opaque_modifier(
            resolve::file_mover_fn(),
            resolve::file_mover_oret(),
            view,
            &[w[0], w[1], w[2], url.as_ptr() as u64, c[0], c[1]],
            [0.0; 4],
        )
    }
}

/// Apply `.fileExporter(isPresented:item:contentTypes:defaultFilename:onCompletion:onCancellation:)`
/// with `Item == String`.
///
/// `String` is the one `Transferable` reachable without declaring a type, so it
/// is what gets exported; the item is `Optional<String>`, which is two words and
/// a tag and so travels in registers.
pub fn file_exporter(
    view: &ViewHandle,
    state: &BoundState<bool>,
    item: Option<&str>,
    kinds: &[ContentType],
    default_filename: Option<&str>,
    completion: impl Fn(FileOutcome) + 'static,
    cancellation: impl Fn() + 'static,
) -> ViewHandle {
    unsafe {
        let mut b = bool_binding(state);
        let w = binding_words(&mut b);
        let meta = resolve::string_meta();
        let opt = abi::resolve_type_by_mangled_name(mangle::optional(mangle::STRING).as_bytes());
        // `Optional<Item>` with `Item` *generic* is address-only, however small
        // the caller's choice turns out to be — the same rule that puts a
        // generic `Binding` behind a pointer. `defaultFilename` beside it is a
        // concrete `Optional<String>` and does travel in registers.
        let mut boxed = vec![0u8; abi::type_bytes(opt)];
        if let Some(s) = item {
            boxed[..16].copy_from_slice(&abi::swift_string(s));
        }
        abi::store_optional_tag(&mut boxed, meta, item.is_some());
        let name = optional_words(
            meta,
            opt,
            &default_filename.map(|s| abi::swift_string(s)).unwrap_or([0u8; 16]),
            default_filename.is_some(),
        );
        let done = wide_words(invoke_file_result, boxed_ctx(Box::new(completion) as Box<dyn Fn(FileOutcome)>));
        let cancel = action_words(cancellation);
        let mut ints = w.to_vec();
        ints.push(boxed.as_ptr() as u64);
        ints.push(content_types(kinds));
        ints.extend_from_slice(&name);
        ints.extend_from_slice(&done);
        ints.extend_from_slice(&cancel);
        generic1_modifier_ints(
            resolve::file_exporter_fn(),
            resolve::file_exporter_oret(),
            view,
            meta,
            {
                // `String: Transferable` is not an exported witness table; the
                // conformance is found the same way a `View` one is.
                let wt = abi::get_view_wt_for_proto(meta, resolve::transferable_proto());
                assert!(!wt.is_null(), "String: Transferable");
                wt
            },
            &ints,
            [0.0; 4],
        )
    }
}

/// Apply `.navigationDocument(_:)` with a `URL`.
///
/// The non-generic overload — `URL` is resilient, so it goes by address, and the
/// optional the initialiser hands back is unwrapped by pointing past its tag:
/// a `.some` payload starts at offset zero.
pub fn navigation_document_url(view: &ViewHandle, spec: &str) -> ViewHandle {
    unsafe {
        let url = optional_url(Some(spec));
        opaque_modifier(
            resolve::navigation_document_url_fn(),
            resolve::navigation_document_url_oret(),
            view,
            &[url.as_ptr() as u64],
            [0.0; 4],
        )
    }
}

/// Apply `.navigationDocument(_:)` with a `Transferable` item.
///
/// `String` is the one `Transferable` reachable without declaring a type. The
/// item is a bare generic parameter, so it travels by address.
pub fn navigation_document(view: &ViewHandle, item: &str) -> ViewHandle {
    unsafe {
        let meta = resolve::string_meta();
        let wt = abi::get_view_wt_for_proto(meta, resolve::transferable_proto());
        assert!(!wt.is_null(), "String: Transferable");
        let s = abi::swift_string(item);
        generic1_modifier_ints(
            resolve::navigation_document_item_fn(),
            resolve::navigation_document_item_oret(),
            view,
            meta,
            wt,
            &[s.as_ptr() as u64],
            [0.0; 4],
        )
    }
}

/// Apply `.fileDialogURLEnabled(_:)`.
///
/// The argument is a `Foundation.Predicate<Pack{URL}>`, which the `#Predicate`
/// macro normally builds from an expression tree at compile time. `Predicate`
/// also exposes `.true` and `.false` as statics, and those are values rather
/// than syntax — so they are reachable from here, where an arbitrary predicate
/// is not.
///
/// The type is generic over a *parameter pack*, whose mangling closes with
/// `_QP` rather than directly; see [`crate::mangle::pack`].
pub fn file_dialog_url_enabled(view: &ViewHandle, enabled: bool) -> ViewHandle {
    unsafe {
        let meta = abi::resolve_type_by_mangled_name(
            mangle::pack(
                mangle::Type::Nominal {
                    module: "Foundation",
                    path: vec!["Predicate"],
                    kind: mangle::Kind::Struct,
                },
                vec![mangle::Type::Nominal {
                    module: "Foundation",
                    path: vec!["URL"],
                    kind: mangle::Kind::Struct,
                }],
            )
            .mangle()
            .as_bytes(),
        );
        assert!(!meta.is_null(), "Predicate<Pack{{URL}}> metadata");
        let getter = if enabled { resolve::predicate_true() } else { resolve::predicate_false() };
        let value = abi::static_out(getter, meta, abi::type_bytes(meta));
        opaque_modifier(
            resolve::file_dialog_url_enabled_fn(),
            resolve::file_dialog_url_enabled_oret(),
            view,
            &[value.as_ptr() as u64],
            [0.0; 4],
        )
    }
}