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
//! Concrete arguments: optionals, resilient enums, transforms.

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

// ── Concrete arguments: optionals, resilient enums, transforms ──

/// [`opaque_modifier`] with one argument passed by address.
///
/// The fallback for everything a register cannot hold: a resilient type, whose
/// size the caller is not allowed to know, and a loadable one that explodes
/// into more than four registers — a `CGAffineTransform` is six doubles, and
/// six will not fit.
pub(crate) unsafe fn modifier_indirect(
    f: *const c_void,
    o: *const c_void,
    v: &ViewHandle,
    bytes: &[u8],
) -> ViewHandle {
    unsafe { opaque_modifier(f, o, v, &[bytes.as_ptr() as u64], [0.0; 4]) }
}

/// A resilient enum's case, in a buffer ready to pass by address.
pub(crate) unsafe fn enum_bytes(ma: *const c_void, tag: u32) -> Vec<u8> {
    unsafe {
        let meta = abi::metadata0(ma);
        let mut buf = vec![0u8; abi::type_bytes(meta)];
        abi::inject_enum_tag(&mut buf, meta, tag);
        buf
    }
}

/// `Optional<E>` for a resilient enum, in a buffer ready to pass by address.
pub(crate) unsafe fn opt_enum_bytes(ma: *const c_void, opt_mangled: &[u8], tag: Option<u32>) -> Vec<u8> {
    unsafe {
        let payload = abi::metadata0(ma);
        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)];
        if let Some(t) = tag {
            abi::inject_enum_tag(&mut buf[..abi::type_bytes(payload)], payload, t);
        }
        abi::store_optional_tag(&mut buf, payload, tag.is_some());
        buf
    }
}

/// An `Optional<T>` as the integer registers it travels in.
///
/// The payload is *not* destructured. `Optional<UnitPoint>` is two `CGFloat`s
/// and a discriminator, and the obvious reading — two float registers and an
/// integer one — faults: an optional is an enum, and an enum with a payload is
/// lowered to its raw storage rather than to its fields, so the whole seventeen
/// bytes travel as three integer registers. A `Double` inside an optional
/// reaches the callee in x0, not d0.
///
/// Payload bytes go in `bytes`, already laid out; `is_some` decides the tag.
/// Past four words the value would be passed by address instead, which is what
/// [`modifier_indirect`] is for.
pub(crate) unsafe fn optional_words(
    payload_meta: *const c_void,
    opt_meta: *const c_void,
    bytes: &[u8],
    is_some: bool,
) -> Vec<u64> {
    unsafe {
        let stride = abi::type_bytes(opt_meta);
        let mut buf = vec![0u8; stride.max(8)];
        if is_some {
            buf[..bytes.len()].copy_from_slice(bytes);
        }
        abi::store_optional_tag(&mut buf, payload_meta, is_some);
        let words = abi::type_size(opt_meta).div_ceil(8);
        (0..words)
            .map(|i| u64::from_le_bytes(buf[i * 8..i * 8 + 8].try_into().expect("word")))
            .collect()
    }
}

/// `Optional<Double>` as the two integer registers it travels in.
pub(crate) unsafe fn opt_f64_words(v: Option<f64>) -> Vec<u64> {
    unsafe {
        let payload = resolve::double_meta();
        let opt = abi::resolve_type_by_mangled_name(mangle::optional(mangle::DOUBLE).as_bytes());
        optional_words(payload, opt, &v.unwrap_or(0.0).to_le_bytes(), v.is_some())
    }
}

/// `Optional<UnitPoint>` as the three integer registers it travels in.
pub(crate) unsafe fn opt_unit_point_words(v: Option<(f64, f64)>) -> Vec<u64> {
    unsafe {
        let payload = crate::type_by_name!(swift_type!(SwiftUI.UnitPoint).as_bytes());
        let opt = crate::type_by_name!(swift_type!(opt SwiftUI.UnitPoint).as_bytes());
        let (x, y) = v.unwrap_or((0.0, 0.0));
        let mut bytes = [0u8; 16];
        bytes[..8].copy_from_slice(&x.to_le_bytes());
        bytes[8..].copy_from_slice(&y.to_le_bytes());
        optional_words(payload, opt, &bytes, v.is_some())
    }
}

/// `Optional<String>` as the two words it travels in.
///
/// A `String` has spare bits, so `nil` is a bit pattern inside the existing
/// sixteen rather than a byte alongside them.
pub(crate) unsafe fn opt_string_words(v: Option<&str>) -> [u64; 2] {
    unsafe {
        let payload = resolve::string_meta();
        let mut buf = [0u8; 16];
        if let Some(s) = v {
            buf.copy_from_slice(&abi::swift_string(s));
        }
        abi::store_optional_tag(&mut buf, payload, v.is_some());
        [
            u64::from_le_bytes(buf[..8].try_into().expect("string lo")),
            u64::from_le_bytes(buf[8..].try_into().expect("string hi")),
        ]
    }
}

swift_cases! {
    /// `SwiftUI.Image.Scale`.
    pub enum ImageScale {
        Small = 0,
        Medium = 1,
        Large = 2,
    }
}

swift_cases! {
    /// `SwiftUI.Text.TruncationMode`.
    pub enum TruncationMode {
        Head = 0,
        Tail = 1,
        Middle = 2,
    }
}

swift_cases! {
    /// `SwiftUI.Text.Case`.
    pub enum TextCase {
        Uppercase = 0,
        Lowercase = 1,
    }
}

swift_statics! {
    /// `SwiftUI.HorizontalAlignment`, a frozen word-sized value.
    pub enum HorizontalAlignment {
        Leading = c"$s7SwiftUI19HorizontalAlignmentV7leadingACvgZ",
        Center = c"$s7SwiftUI19HorizontalAlignmentV6centerACvgZ",
        Trailing = c"$s7SwiftUI19HorizontalAlignmentV8trailingACvgZ",
        ListRowSeparatorLeading = c"$s7SwiftUI19HorizontalAlignmentV23listRowSeparatorLeadingACvgZ",
        ListRowSeparatorTrailing = c"$s7SwiftUI19HorizontalAlignmentV24listRowSeparatorTrailingACvgZ",
    }
}

swift_statics! {
    /// `SwiftUI.VerticalAlignment`, a frozen word-sized value.
    ///
    /// What an `HStack` aligns its children on, the mirror of
    /// [`HorizontalAlignment`] for a `VStack`. The two baseline cases align on
    /// text rather than on the box: `FirstTextBaseline` lines up the first
    /// lines of each child, which is what makes a row of differently-sized
    /// labels read as one line.
    pub enum VerticalAlignment {
        Top = c"$s7SwiftUI17VerticalAlignmentV3topACvgZ",
        Center = c"$s7SwiftUI17VerticalAlignmentV6centerACvgZ",
        Bottom = c"$s7SwiftUI17VerticalAlignmentV6bottomACvgZ",
        FirstTextBaseline = c"$s7SwiftUI17VerticalAlignmentV17firstTextBaselineACvgZ",
        LastTextBaseline = c"$s7SwiftUI17VerticalAlignmentV16lastTextBaselineACvgZ",
    }
}

swift_statics! {
    /// `SwiftUI.ScrollAnchorRole`.
    pub enum ScrollAnchorRole {
        Alignment = c"$s7SwiftUI16ScrollAnchorRoleV9alignmentACvgZ",
        SizeChanges = c"$s7SwiftUI16ScrollAnchorRoleV11sizeChangesACvgZ",
        InitialOffset = c"$s7SwiftUI16ScrollAnchorRoleV13initialOffsetACvgZ",
    }
}

/// Apply `.accentColor(_:)`.
pub fn accent_color(view: &ViewHandle, color: Option<crate::Color>) -> ViewHandle {
    unsafe {
        modifier_opt_color(resolve::accent_color_fn(), resolve::accent_color_oret(), view, color)
    }
}

/// Apply `.foregroundColor(_:)`, the deprecated environment-writing one.
///
/// Not [`foreground_style_color`]: this produces
/// `_EnvironmentKeyWritingModifier<Color?>` and that produces
/// `_ForegroundStyleModifier<Color>`. They render the same.
/// Apply `.foregroundColor(_:)` to a `Color` that is already built.
///
/// For one of SwiftUI's named colours, which no set of components can spell.
/// See [`super::system_color`].
pub fn foreground_color_value(view: &ViewHandle, color: u64) -> ViewHandle {
    unsafe {
        opaque_modifier(
            resolve::foreground_color_fn(),
            resolve::foreground_color_oret(),
            view,
            &[color],
            [0.0; 4],
        )
    }
}

/// Apply `.foregroundColor(_:)`.
pub fn foreground_color(view: &ViewHandle, color: Option<crate::Color>) -> ViewHandle {
    unsafe {
        modifier_opt_color(
            resolve::foreground_color_fn(),
            resolve::foreground_color_oret(),
            view,
            color,
        )
    }
}

/// Apply `.colorMultiply(_:)`.
pub fn color_multiply(view: &ViewHandle, color: crate::Color) -> ViewHandle {
    unsafe {
        let word = color_value(color.r, color.g, color.b, color.a);
        opaque_modifier(
            resolve::color_multiply_fn(),
            resolve::color_multiply_oret(),
            view,
            &[word],
            [0.0; 4],
        )
    }
}

/// Apply `.allowsWindowActivationEvents(_:)`.
pub fn allows_window_activation_events(view: &ViewHandle, allows: Option<bool>) -> ViewHandle {
    unsafe {
        modifier_opt_bool(
            resolve::allows_window_activation_fn(),
            resolve::allows_window_activation_oret(),
            view,
            allows,
        )
    }
}

/// Apply `.dialogPreventsAppTermination(_:)`.
pub fn dialog_prevents_app_termination(view: &ViewHandle, prevents: Option<bool>) -> ViewHandle {
    unsafe {
        modifier_opt_bool(
            resolve::dialog_prevents_termination_fn(),
            resolve::dialog_prevents_termination_oret(),
            view,
            prevents,
        )
    }
}

/// Apply `.disableAutocorrection(_:)`.
pub fn disable_autocorrection(view: &ViewHandle, disable: Option<bool>) -> ViewHandle {
    unsafe {
        modifier_opt_bool(
            resolve::disable_autocorrection_fn(),
            resolve::disable_autocorrection_oret(),
            view,
            disable,
        )
    }
}

/// Apply `.presentationPreventsAppTermination(_:)`.
pub fn presentation_prevents_app_termination(
    view: &ViewHandle,
    prevents: Option<bool>,
) -> ViewHandle {
    unsafe {
        modifier_opt_bool(
            resolve::presentation_prevents_termination_fn(),
            resolve::presentation_prevents_termination_oret(),
            view,
            prevents,
        )
    }
}

/// Apply `.previewDisplayName(_:)`.
pub fn preview_display_name(view: &ViewHandle, name: Option<&str>) -> ViewHandle {
    unsafe {
        let w = opt_string_words(name);
        opaque_modifier(
            resolve::preview_display_name_fn(),
            resolve::preview_display_name_oret(),
            view,
            &w,
            [0.0; 4],
        )
    }
}

/// Apply `.hueRotation(_:)`, in radians.
///
/// An `Angle` stores radians and nothing else, so it is one frozen double and
/// travels in d0 rather than by address.
pub fn hue_rotation(view: &ViewHandle, radians: f64) -> ViewHandle {
    unsafe {
        modifier_f64(resolve::hue_rotation_fn(), resolve::hue_rotation_oret(), view, radians)
    }
}

/// Apply `.gridCellAnchor(_:)`.
pub fn grid_cell_anchor(view: &ViewHandle, x: f64, y: f64) -> ViewHandle {
    unsafe {
        opaque_modifier(
            resolve::grid_cell_anchor_fn(),
            resolve::grid_cell_anchor_oret(),
            view,
            &[],
            [x, y, 0.0, 0.0],
        )
    }
}

/// Apply `.presentationCornerRadius(_:)`.
pub fn presentation_corner_radius(view: &ViewHandle, radius: Option<f64>) -> ViewHandle {
    unsafe {
        let w = opt_f64_words(radius);
        opaque_modifier(
            resolve::presentation_corner_radius_fn(),
            resolve::presentation_corner_radius_oret(),
            view,
            &w,
            [0.0; 4],
        )
    }
}

/// Apply `.imageScale(_:)`.
pub fn image_scale(view: &ViewHandle, scale: ImageScale) -> ViewHandle {
    unsafe {
        let b = enum_bytes(resolve::image_scale_ma(), scale.tag());
        modifier_indirect(resolve::image_scale_fn(), resolve::image_scale_oret(), view, &b)
    }
}

/// Apply `.truncationMode(_:)`.
pub fn truncation_mode(view: &ViewHandle, mode: TruncationMode) -> ViewHandle {
    unsafe {
        let b = enum_bytes(resolve::truncation_mode_ma(), mode.tag());
        modifier_indirect(resolve::truncation_mode_fn(), resolve::truncation_mode_oret(), view, &b)
    }
}

/// Apply `.textCase(_:)`.
pub fn text_case(view: &ViewHandle, case: Option<TextCase>) -> ViewHandle {
    unsafe {
        let b = opt_enum_bytes(
            resolve::text_case_ma(),
            swift_type!(opt enum SwiftUI.Text.Case).as_bytes(),
            case.map(TextCase::tag),
        );
        modifier_indirect(resolve::text_case_fn(), resolve::text_case_oret(), view, &b)
    }
}

/// Apply `.gridColumnAlignment(_:)`.
pub fn grid_column_alignment(view: &ViewHandle, alignment: HorizontalAlignment) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::horizontal_alignment_ma());
        let a = frozen_static(meta, alignment.getter());
        opaque_modifier(
            resolve::grid_column_alignment_fn(),
            resolve::grid_column_alignment_oret(),
            view,
            &[a],
            [0.0; 4],
        )
    }
}

/// Apply `.transformEffect(_:)` with a `CGAffineTransform`'s six components.
pub fn transform_effect(
    view: &ViewHandle,
    a: f64,
    b: f64,
    c: f64,
    d: f64,
    tx: f64,
    ty: f64,
) -> ViewHandle {
    unsafe {
        let mut bytes = [0u8; 48];
        for (i, v) in [a, b, c, d, tx, ty].iter().enumerate() {
            bytes[i * 8..(i + 1) * 8].copy_from_slice(&v.to_le_bytes());
        }
        modifier_indirect(
            resolve::transform_effect_fn(),
            resolve::transform_effect_oret(),
            view,
            &bytes,
        )
    }
}

/// Apply `.projectionEffect(_:)` with a 3×3 matrix in row-major order.
pub fn projection_effect(view: &ViewHandle, m: [f64; 9]) -> ViewHandle {
    unsafe {
        let mut bytes = [0u8; 72];
        for (i, v) in m.iter().enumerate() {
            bytes[i * 8..(i + 1) * 8].copy_from_slice(&v.to_le_bytes());
        }
        modifier_indirect(
            resolve::projection_effect_fn(),
            resolve::projection_effect_oret(),
            view,
            &bytes,
        )
    }
}

/// Apply `.listRowInsets(_:)`.
pub fn list_row_insets(view: &ViewHandle, insets: Option<[f64; 4]>) -> ViewHandle {
    unsafe {
        let payload = abi::metadata0(resolve::edge_insets_ma());
        let opt = crate::type_by_name!(swift_type!(opt SwiftUI.EdgeInsets).as_bytes());
        let mut bytes = vec![0u8; abi::type_bytes(opt)];
        if let Some(v) = insets {
            for (i, x) in v.iter().enumerate() {
                bytes[i * 8..(i + 1) * 8].copy_from_slice(&x.to_le_bytes());
            }
        }
        abi::store_optional_tag(&mut bytes, payload, insets.is_some());
        modifier_indirect(resolve::list_row_insets_fn(), resolve::list_row_insets_oret(), view, &bytes)
    }
}

/// Apply `.windowResizeAnchor(_:)`.
pub fn window_resize_anchor(view: &ViewHandle, anchor: Option<(f64, f64)>) -> ViewHandle {
    unsafe {
        let w = opt_unit_point_words(anchor);
        opaque_modifier(
            resolve::window_resize_anchor_fn(),
            resolve::window_resize_anchor_oret(),
            view,
            &w,
            [0.0; 4],
        )
    }
}

/// Apply `.defaultScrollAnchor(_:for:)`.
pub fn default_scroll_anchor(
    view: &ViewHandle,
    anchor: Option<(f64, f64)>,
    role: ScrollAnchorRole,
) -> ViewHandle {
    unsafe {
        let mut w = opt_unit_point_words(anchor);
        let meta = abi::metadata0(resolve::scroll_anchor_role_ma());
        let r = resilient_static(meta, role.getter());
        w.push(r.as_ptr() as u64);
        opaque_modifier(
            resolve::default_scroll_anchor_fn(),
            resolve::default_scroll_anchor_oret(),
            view,
            &w,
            [0.0; 4],
        )
    }
}

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

    /// An optional's payload is not destructured into float registers.
    ///
    /// This is the rule that four modifiers faulted on. `Optional<UnitPoint>`
    /// is seventeen bytes of `CGFloat`, `CGFloat`, tag — and it arrives as
    /// three *integer* registers, because an enum with a payload is lowered to
    /// its raw storage rather than to the payload's fields.
    #[test]
    fn optional_payloads_travel_as_raw_words() {
        unsafe {
            let w = opt_unit_point_words(Some((0.3, 0.6)));
            assert_eq!(w.len(), 3, "Optional<UnitPoint> is three words");
            assert_eq!(w[0], 0.3f64.to_bits(), "x is raw bits, not a float register");
            assert_eq!(w[1], 0.6f64.to_bits(), "y is raw bits, not a float register");
            assert_eq!(w[2] & 0xff, 0, "some");

            let n = opt_unit_point_words(None);
            assert_eq!(n.len(), 3);
            assert_ne!(n[2] & 0xff, 0, "none");

            let d = opt_f64_words(Some(12.0));
            assert_eq!(d.len(), 2, "Optional<Double> is two words");
            assert_eq!(d[0], 12.0f64.to_bits());
        }
    }

    /// `Optional<Bool>` spends one of a byte's spare values on `nil`, so the
    /// whole thing is one register rather than a payload plus a tag.
    #[test]
    fn optional_bool_is_one_byte() {
        unsafe {
            let m = abi::resolve_type_by_mangled_name(mangle::optional(mangle::BOOL).as_bytes());
            assert_eq!(abi::type_bytes(m), 1);
            let mut buf = [0u8; 1];
            buf[0] = 1;
            abi::store_optional_tag(&mut buf, resolve::bool_meta(), true);
            assert_eq!(buf[0], 1, "Some(true)");
            abi::store_optional_tag(&mut buf, resolve::bool_meta(), false);
            assert!(buf[0] > 1, "nil is a value a Bool cannot hold");
        }
    }

    /// `Color` is `@frozen` and one word, so it is passed by value. Sending its
    /// address instead is what the first draft of this did, and it faulted.
    #[test]
    fn color_is_one_frozen_word() {
        unsafe {
            let m = crate::type_by_name!(swift_type!(SwiftUI.Color).as_bytes());
            assert_eq!(abi::type_bytes(m), 8);
            let o = crate::type_by_name!(swift_type!(opt SwiftUI.Color).as_bytes());
            assert_eq!(abi::type_bytes(o), 8, "a null reference is already nil");
        }
    }
}