swiftui-native 0.0.1

SwiftUI from pure Rust — no Swift bridge, no shim, only swift-runtime calls
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
//! Layout and compositing modifiers.

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

// ── Layout and compositing modifiers ──

mangle::modifier_types! {
    /// `ModifiedContent<AnyView, _AspectRatioLayout>`
    pub(crate) ASPECT_T = ty("_AspectRatioLayout");
    /// `ModifiedContent<AnyView, _FixedSizeLayout>`
    pub(crate) FIXED_SIZE_T = ty("_FixedSizeLayout");
    /// `ModifiedContent<AnyView, _TraitWritingModifier<ZIndexTraitKey>>`
    pub(crate) Z_INDEX_T = ty("_TraitWritingModifier").of(vec![ty("ZIndexTraitKey")]);
    /// `ModifiedContent<AnyView, _EnvironmentKeyTransformModifier<Bool>>`
    pub(crate) DISABLED_T = ty("_EnvironmentKeyTransformModifier").of(vec![Type::Verbatim("Sb".into())]);
    /// `ModifiedContent<AnyView, _HiddenModifier>`
    pub(crate) HIDDEN_T = ty("_HiddenModifier");
    /// `ModifiedContent<AnyView, _BlendModeEffect>`
    pub(crate) BLEND_T = ty("_BlendModeEffect");
    /// `ModifiedContent<AnyView, _OverlayModifier<AnyView>>`
    pub(crate) OVERLAY_ANY_T = ty("_OverlayModifier").of(vec![ty("AnyView")]);
    /// `ModifiedContent<AnyView, _BackgroundModifier<AnyView>>`
    pub(crate) BACKGROUND_ANY_T = ty("_BackgroundModifier").of(vec![ty("AnyView")]);
    /// `ModifiedContent<AnyView, _MaskAlignmentEffect<AnyView>>`
    pub(crate) MASK_ANY_T = ty("_MaskAlignmentEffect").of(vec![ty("AnyView")]);
    /// `.clipShape(_:)` results, one per shape.
    /// `ModifiedContent<AnyView, _ClipEffect<Circle>>`
    pub(crate) CLIP_CIRCLE_T = ty("_ClipEffect").of(vec![ty("Circle")]);
    /// `ModifiedContent<AnyView, _ClipEffect<Capsule>>`
    pub(crate) CLIP_CAPSULE_T = ty("_ClipEffect").of(vec![ty("Capsule")]);
    /// `ModifiedContent<AnyView, _ClipEffect<Ellipse>>`
    pub(crate) CLIP_ELLIPSE_T = ty("_ClipEffect").of(vec![ty("Ellipse")]);
    /// `ModifiedContent<AnyView, _ClipEffect<RoundedRectangle>>`
    pub(crate) CLIP_RRECT_T = ty("_ClipEffect").of(vec![ty("RoundedRectangle")]);
}








/// `SwiftUI.ContentMode` — whether content fits inside its frame or fills it.
///
/// The enum `aspectRatio` and `Image.resizable` take. It is frozen and one byte,
/// so the case number *is* the ABI: `fit` is 0 and `fill` is 1, which is what
/// [`aspect_ratio`]'s `bool` has always passed. This gives it its name back,
/// because `aspect_ratio(&v, 1.5, true)` does not read as "fill".
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ContentMode {
    /// Scale to fit inside the frame, leaving empty space along one axis.
    #[default]
    Fit,
    /// Scale to fill the frame, cropping along one axis.
    Fill,
}

/// `SwiftUI.EdgeInsets` — four insets, one per edge.
///
/// Four `CGFloat`s and nothing else, which makes it a homogeneous float
/// aggregate: it travels in d0–d3 rather than by address, and comes back the
/// same way. That is why this is a `#[repr(C)]` struct of `f64` and not a
/// tuple — a Rust tuple is not `repr(C)` and would be returned through memory.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[repr(C)]
pub struct EdgeInsets {
    /// The inset from the top edge.
    pub top: f64,
    /// The inset from the leading edge — left in a left-to-right layout.
    pub leading: f64,
    /// The inset from the bottom edge.
    pub bottom: f64,
    /// The inset from the trailing edge.
    pub trailing: f64,
}

impl EdgeInsets {
    /// The same inset on all four edges.
    pub fn all(amount: f64) -> Self {
        Self { top: amount, leading: amount, bottom: amount, trailing: amount }
    }

    /// `EdgeInsets(top:leading:bottom:trailing:)`, built by SwiftUI itself.
    ///
    /// The four fields are laid out exactly as this struct is, so constructing
    /// one in Rust would give the same bytes — this calls the initialiser anyway,
    /// because "the same bytes" is an assumption about a resilient type's layout
    /// and the initialiser is the thing that is guaranteed.
    pub fn from_swift(top: f64, leading: f64, bottom: f64, trailing: f64) -> Self {
        unsafe {
            let (a, b, c, d): (f64, f64, f64, f64);
            core::arch::asm!("blr {f}", f = in(reg) resolve::edge_insets_init(),
                inlateout("d0") top => a,
                inlateout("d1") leading => b,
                inlateout("d2") bottom => c,
                inlateout("d3") trailing => d,
                lateout("x0") _, lateout("x1") _, lateout("x2") _, lateout("x3") _,
                lateout("x4") _, lateout("x5") _, lateout("x6") _, lateout("x7") _,
                lateout("x8") _, lateout("x9") _, lateout("x10") _, lateout("x11") _,
                lateout("x12") _, lateout("x13") _, lateout("x14") _, lateout("x15") _,
                lateout("x16") _, lateout("x17") _, lateout("lr") _,
                lateout("x20") _, lateout("x21") _, clobber_abi("C"),
            );
            Self { top: a, leading: b, bottom: c, trailing: d }
        }
    }
}

/// `.padding(_: EdgeInsets)` — a different inset per edge.
///
/// [`padding_set`] takes one length for a set of edges; this takes four. The
/// insets go in d0–d3, being a homogeneous float aggregate.
pub fn padding_insets(view: &ViewHandle, insets: EdgeInsets) -> ViewHandle {
    unsafe {
        let (meta, wt, size) = super::opaque_result_type(
            resolve::padding_insets_oret(),
            &[view.meta, view.wt],
        );
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        core::arch::asm!("blr {f}", f = in(reg) resolve::padding_insets_fn(),
            in("d0") insets.top,
            in("d1") insets.leading,
            in("d2") insets.bottom,
            in("d3") insets.trailing,
            in("x0") view.meta,
            in("x1") view.wt,
            in("x8") result.as_mut_ptr(),
            in("x20") this,
            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"),
        );
        super::wrap_owned(result, meta, wt)
    }
}

/// `.aspectRatio(_:contentMode:)` with the mode named rather than spelled as a
/// `bool`.
///
/// `None` for the ratio means "keep whatever the content already has", which is
/// not the same as `Some(1.0)`.
pub fn aspect_ratio_content_mode(
    view: &ViewHandle,
    ratio: Option<f64>,
    mode: ContentMode,
) -> ViewHandle {
    match ratio {
        Some(r) => aspect_ratio(view, r, mode == ContentMode::Fill),
        None => aspect_ratio_mode(view, mode == ContentMode::Fill),
    }
}

/// Apply `.aspectRatio(_:contentMode:)`. `fit` is case 0, `fill` is case 1.
pub fn aspect_ratio(view: &ViewHandle, ratio: f64, fill: bool) -> ViewHandle {
    unsafe {
        let (_, _, size) = ASPECT_T.applied_to(view.meta);
        // Optional<CGFloat>: raw bits then tag (0 == some), then ContentMode.
        let r = abi::call_modifier(resolve::aspect_ratio_fn(), view.value_ptr(), view.meta, view.wt,
            &[ratio.to_bits(), 0, u64::from(fill)],
            [0.0; 4],
            size,
        );
        wrap_modified(r, &ASPECT_T, view)
    }
}

/// Apply `.aspectRatio(contentMode:)` — the spelling with no ratio.
///
/// Same entry point as [`aspect_ratio`] with the `Optional<CGFloat>` set to
/// `nil`: tag 1, payload ignored. It means "keep whatever ratio the content
/// already has", which is not the same as passing 1.0.
pub fn aspect_ratio_mode(view: &ViewHandle, fill: bool) -> ViewHandle {
    unsafe {
        let (_, _, size) = ASPECT_T.applied_to(view.meta);
        let r = abi::call_modifier(resolve::aspect_ratio_fn(), view.value_ptr(), view.meta, view.wt,
            &[0, 1, u64::from(fill)],
            [0.0; 4],
            size,
        );
        wrap_modified(r, &ASPECT_T, view)
    }
}

/// Apply `.fixedSize(horizontal:vertical:)`.
pub fn fixed_size(view: &ViewHandle, horizontal: bool, vertical: bool) -> ViewHandle {
    unsafe {
        let (_, _, size) = FIXED_SIZE_T.applied_to(view.meta);
        let r = abi::call_modifier(resolve::fixed_size_fn(), view.value_ptr(), view.meta, view.wt,
            &[u64::from(horizontal), u64::from(vertical)],
            [0.0; 4],
            size,
        );
        wrap_modified(r, &FIXED_SIZE_T, view)
    }
}

/// Apply `.zIndex(_:)`.
pub fn z_index(view: &ViewHandle, value: f64) -> ViewHandle {
    unsafe {
        let (_, _, size) = Z_INDEX_T.applied_to(view.meta);
        let r = abi::call_modifier(resolve::z_index_fn(), view.value_ptr(), view.meta, view.wt, &[], [value, 0.0, 0.0, 0.0], size);
        wrap_modified(r, &Z_INDEX_T, view)
    }
}

/// Apply `.disabled(_:)`.
pub fn disabled(view: &ViewHandle, value: bool) -> ViewHandle {
    unsafe {
        let (_, _, size) = DISABLED_T.applied_to(view.meta);
        let r =
            abi::call_modifier(resolve::disabled_fn(), view.value_ptr(), view.meta, view.wt, &[u64::from(value)], [0.0; 4], size);
        wrap_modified(r, &DISABLED_T, view)
    }
}

/// Apply `.hidden()`.
pub fn hidden(view: &ViewHandle) -> ViewHandle {
    unsafe {
        let (_, _, size) = HIDDEN_T.applied_to(view.meta);
        let r = abi::call_modifier(resolve::hidden_fn(), view.value_ptr(), view.meta, view.wt, &[], [0.0; 4], size);
        wrap_modified(r, &HIDDEN_T, view)
    }
}

/// Apply `.blendMode(_:)`. The cases follow `SwiftUI.BlendMode`'s declaration order.
///
/// `BlendMode` is a resilient enum, so it is address-only and passed by pointer.
pub fn blend_mode(view: &ViewHandle, mode: u8) -> ViewHandle {
    unsafe {
        let (_, _, size) = BLEND_T.applied_to(view.meta);
        let mut buf = [mode];
        let r = abi::call_modifier(resolve::blend_mode_fn(), view.value_ptr(), view.meta, view.wt,
            &[buf.as_mut_ptr() as u64],
            [0.0; 4],
            size,
        );
        wrap_modified(r, &BLEND_T, view)
    }
}






/// Apply `.clipShape(_:style:)`.
///
/// `shape_bytes` is the shape value, `shape_mangled` names its type, and
/// `modifier` is the `_ClipEffect` the result wraps the receiver in.
pub(crate) unsafe fn clip_shape_impl(
    view: &ViewHandle,
    shape_bytes: &[u8],
    shape_mangled: &[u8],
    modifier: &ModifierType,
) -> ViewHandle {
    unsafe {
        let shape_meta = abi::resolve_type_by_mangled_name(shape_mangled);
        assert!(!shape_meta.is_null(), "shape metadata");
        let shape_wt = abi::get_view_wt_for_proto(shape_meta, resolve::shape_proto());
        assert!(!shape_wt.is_null(), "shape: Shape");

        let mut shape_buf = vec![0u8; abi::type_bytes(shape_meta)];
        shape_buf[..shape_bytes.len()].copy_from_slice(shape_bytes);

        let (_, _, size) = modifier.applied_to(view.meta);
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        // clipShape<S: Shape>(_: S, style: FillStyle)
        //   x0 = @in shape, x1 = FillStyle (both flags packed into one word:
        //        low byte isEOFilled, next byte isAntialiased),
        //   x2 = Self.Type, x3 = S.Type, x4 = Self: View WT, x5 = S: Shape WT
        core::arch::asm!("blr {f}", f = in(reg) resolve::clip_shape_fn(),
            in("x0") shape_buf.as_mut_ptr(),
            in("x1") 0x0100u64, // eoFill: false, antialiased: true
            in("x2") view.meta,
            in("x3") shape_meta,
            in("x4") view.wt,
            in("x5") shape_wt,
            in("x8") result.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"),
        );
        wrap_modified(result, modifier, view)
    }
}

/// Apply `.clipShape(Circle())`.
pub fn clip_circle(view: &ViewHandle) -> ViewHandle {
    unsafe { clip_shape_impl(view, &[], swift_type!(SwiftUI.Circle).as_bytes(), &CLIP_CIRCLE_T) }
}

/// Apply `.clipShape(Ellipse())`.
pub fn clip_ellipse(view: &ViewHandle) -> ViewHandle {
    unsafe { clip_shape_impl(view, &[], swift_type!(SwiftUI.Ellipse).as_bytes(), &CLIP_ELLIPSE_T) }
}

/// Apply `.clipShape(Capsule())`.
pub fn clip_capsule(view: &ViewHandle) -> ViewHandle {
    clip_capsule_styled(view, true)
}

/// `.clipShape(Capsule(style:))`.
///
/// `continuous` is what `.clipShape(.capsule)` means in Swift source — the same
/// default `Capsule()` has, and case **1** of `RoundedCornerStyle`, not case 0.
/// [`clip_capsule`] wrote case 0 until a listing needed the natural spelling;
/// its parity case had been written to say `Capsule(style: .circular)` to suit,
/// so nothing had ever disagreed.
pub fn clip_capsule_styled(view: &ViewHandle, continuous: bool) -> ViewHandle {
    unsafe {
        clip_shape_impl(
            view,
            &[u8::from(continuous)],
            swift_type!(SwiftUI.Capsule).as_bytes(),
            &CLIP_CAPSULE_T,
        )
    }
}

/// Apply `.clipShape(RoundedRectangle(cornerRadius:))`.
pub fn clip_rounded_rect(view: &ViewHandle, radius: f64) -> ViewHandle {
    clip_rounded_rect_styled(view, radius, true)
}

/// Apply `.clipShape(RoundedRectangle(cornerRadius:style:))`.
///
/// As with [`super::rounded_rectangle_styled`], the style is not optional here
/// even though Swift source can leave it out: leaving it out means
/// `.continuous`, and writing case 0 builds the other shape.
pub fn clip_rounded_rect_styled(view: &ViewHandle, radius: f64, continuous: bool) -> ViewHandle {
    let mut buf = [0u8; 17];
    buf[..8].copy_from_slice(&radius.to_le_bytes());
    buf[8..16].copy_from_slice(&radius.to_le_bytes());
    buf[16] = u8::from(continuous);
    unsafe { clip_shape_impl(view, &buf, swift_type!(SwiftUI.RoundedRectangle).as_bytes(), &CLIP_RRECT_T) }
}

/// Apply `.overlay(alignment:content:)` or `.mask(alignment:_:)`.
pub(crate) unsafe fn overlay_or_mask(
    view: &ViewHandle,
    content: &ViewHandle,
    func: *const c_void,
    modifier: &ModifierType,
    alignment: super::Alignment,
) -> ViewHandle {
    unsafe {
        let (_, _, size) = modifier.applied_to_content(view.meta, content.meta, content.wt);
        let mut result = vec![0u8; size];
        let this = view.value_ptr();

        let kid_handles = Child::new(content, Content::Concrete);
        let handles = kid_handles.element();
        let payload = TuplePayload { children: handles.as_ptr(), count: 1 };
        let mut ctx = abi::ClosureCtx::new(emit_tuple, &payload as *const TuplePayload as *mut c_void);

        let [ah, av] = alignment.words();
        // overlay<V: View>(alignment: Alignment, content: () -> V)
        //   x0/x1 = Alignment, x2 = closure fn, x3 = closure ctx,
        //   x4 = Self.Type, x5 = V.Type, x6 = Self: View WT, x7 = V: View WT
        core::arch::asm!("blr {f}", f = in(reg) func,
            in("x0") ah, in("x1") av,
            in("x2") abi::swift_closure_thunk as *const c_void,
            in("x3") &mut ctx as *mut abi::ClosureCtx,
            in("x4") view.meta,                  // Self.Type
            in("x5") content.meta,               // V.Type
            in("x6") view.wt,                    // Self: View
            in("x7") content.wt,                 // V: View
            in("x8") result.as_mut_ptr(),
            in("x20") this,
            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 (meta, wt, _) = modifier.applied_to_content(view.meta, content.meta, content.wt);
        wrap_owned(result, meta, wt)
    }
}

/// Apply `.overlay(alignment:content:)`.
pub fn overlay_aligned(
    view: &ViewHandle,
    content: &ViewHandle,
    alignment: super::Alignment,
) -> ViewHandle {
    unsafe { overlay_or_mask(view, content, resolve::overlay_fn(), &OVERLAY_ANY_T, alignment) }
}

/// Apply `.overlay(alignment: .center) { content }`.
pub fn overlay(view: &ViewHandle, content: &ViewHandle) -> ViewHandle {
    overlay_aligned(view, content, super::Alignment::Center)
}

/// Apply `.background(alignment:content:)`.
///
/// The same call as `.overlay(alignment:content:)` with a different symbol:
/// an `Alignment` in x0/x1, the content closure and its context in x2/x3, four
/// generic words after that. The colour-taking `background` next door is a
/// different overload entirely — that one is generic over `ShapeStyle`, this
/// one over `View`.
pub fn background_content(
    view: &ViewHandle,
    content: &ViewHandle,
    alignment: super::Alignment,
) -> ViewHandle {
    unsafe {
        overlay_or_mask(
            view,
            content,
            resolve::background_content_fn(),
            &BACKGROUND_ANY_T,
            alignment,
        )
    }
}

/// Apply `.mask(alignment:_:)`.
pub fn mask_aligned(
    view: &ViewHandle,
    content: &ViewHandle,
    alignment: super::Alignment,
) -> ViewHandle {
    unsafe { overlay_or_mask(view, content, resolve::mask_fn(), &MASK_ANY_T, alignment) }
}

/// Apply `.mask(alignment: .center) { content }`.
pub fn mask(view: &ViewHandle, content: &ViewHandle) -> ViewHandle {
    mask_aligned(view, content, super::Alignment::Center)
}

/// Apply `.background(_:in:fillStyle:)` — a style drawn behind, in a shape.
///
/// Identical in shape to [`overlay_style_in_shape`], which is the point: both
/// take a `ShapeStyle` and a `Shape`, so both spill exactly one of their six
/// generic words.
/// # Safety
/// `style` must hold an initialised value of the type `style_meta` describes,
/// and `style_wt` must be that type's `ShapeStyle` conformance. Nothing here
/// checks either, and a mismatched pair is read as the type named.
pub unsafe fn background_style_in_shape(
    view: &ViewHandle,
    style: &[u8],
    style_meta: *const c_void,
    style_wt: *const c_void,
    shape: &super::Shape,
) -> ViewHandle {
    unsafe {
        style_in_shape(
            resolve::background_style_in_fn(),
            resolve::background_style_in_oret(),
            view,
            style,
            style_meta,
            style_wt,
            shape,
        )
    }
}

/// Apply `.background(_:in:fillStyle:)` where the shape is `InsettableShape`.
///
/// A second overload with the same spelling. Swift picks *this* one whenever the
/// shape conforms — a `Capsule` does — and it builds
/// `_InsettableBackgroundShapeModifier` rather than `_BackgroundShapeModifier`.
/// The two render identically, so only a type or value comparison tells them
/// apart. The witness table has to be the `InsettableShape` one, not the
/// `Shape` one the [`super::Shape`] value carries.
/// # Safety
/// `style` must hold an initialised value of the type `style_meta` describes,
/// and `style_wt` must be that type's `ShapeStyle` conformance. Nothing here
/// checks either, and a mismatched pair is read as the type named.
pub unsafe fn background_style_in_insettable(
    view: &ViewHandle,
    style: &[u8],
    style_meta: *const c_void,
    style_wt: *const c_void,
    shape: &super::Shape,
) -> ViewHandle {
    unsafe {
        let (bytes, meta, _) = shape.parts();
        let insettable = abi::get_view_wt_for_proto(meta, resolve::insettable_shape_proto());
        assert!(!insettable.is_null(), "{} !: InsettableShape", crate::diag::type_name(meta));
        style_in_shape_with(
            resolve::background_style_in_insettable_fn(),
            resolve::background_style_in_insettable_oret(),
            view,
            style,
            style_meta,
            style_wt,
            &bytes,
            meta,
            insettable,
        )
    }
}

/// Apply `.overlay(_:in:fillStyle:)` — a style drawn inside a shape.
///
/// Two generic parameters: the style and the shape. From the IR,
/// `(sret, ptr style, ptr shape, i16 fillStyle, Self.Type, S.Type, Shape.Type,
/// Self:View, S:ShapeStyle, Shape:Shape, swiftself)`. The `FillStyle` sits
/// between the two addresses and the generic words, which leaves x3 through x7
/// — five registers for six words, so exactly one spills.
/// # Safety
/// `style` must hold an initialised value of the type `style_meta` describes,
/// and `style_wt` must be that type's `ShapeStyle` conformance. Nothing here
/// checks either, and a mismatched pair is read as the type named.
pub unsafe fn overlay_style_in_shape(
    view: &ViewHandle,
    style: &[u8],
    style_meta: *const c_void,
    style_wt: *const c_void,
    shape: &super::Shape,
) -> ViewHandle {
    unsafe {
        style_in_shape(
            resolve::overlay_in_fn(),
            resolve::overlay_in_oret(),
            view,
            style,
            style_meta,
            style_wt,
            shape,
        )
    }
}

/// The body `overlay(_:in:)` and `background(_:in:)` share.
#[allow(clippy::too_many_arguments)]
unsafe fn style_in_shape(
    func: *const c_void,
    oret: *const c_void,
    view: &ViewHandle,
    style: &[u8],
    style_meta: *const c_void,
    style_wt: *const c_void,
    shape: &super::Shape,
) -> ViewHandle {
    let (b, m, w) = shape.parts();
    unsafe { style_in_shape_with(func, oret, view, style, style_meta, style_wt, &b, m, w) }
}

/// As [`style_in_shape`], with the shape's bytes, metadata and witness given
/// directly — so the witness can be `InsettableShape` rather than `Shape`.
#[allow(clippy::too_many_arguments)]
unsafe fn style_in_shape_with(
    func: *const c_void,
    oret: *const c_void,
    view: &ViewHandle,
    style: &[u8],
    style_meta: *const c_void,
    style_wt: *const c_void,
    shape_bytes: &[u8],
    shape_meta: *const c_void,
    shape_wt: *const c_void,
) -> ViewHandle {
    unsafe {
        let shape_bytes = shape_bytes.to_vec();
        let subst = [
            view.meta,
            style_meta,
            shape_meta,
            view.wt,
            style_wt,
            shape_wt,
        ];
        let (meta, wt, size) = super::opaque_result_type(oret, &subst);

        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        let mut style_arg = style.to_vec();
        let mut shape_arg = shape_bytes;
        shape_arg.push(0);
        core::arch::asm!(
            "sub sp, sp, #16",
            "str {a}, [sp]",
            "blr {f}",
            "add sp, sp, #16",
            f = in(reg) func,
            a = in(reg) subst[5],
            in("x0") style_arg.as_mut_ptr(),
            in("x1") shape_arg.as_mut_ptr(),
            in("x2") FILL_STYLE_DEFAULT_WORD,
            in("x3") subst[0],
            in("x4") subst[1],
            in("x5") subst[2],
            in("x6") subst[3],
            in("x7") subst[4],
            in("x8") result.as_mut_ptr(),
            in("x20") this,
            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)
    }
}

/// `FillStyle()` — `isEOFilled` false, `isAntialiased` true.
const FILL_STYLE_DEFAULT_WORD: u64 = 0x0100;

/// Apply `.padding()` — every edge, at whatever length the system picks.
///
/// Not `padding(_ length: CGFloat)`. A bare `.padding()` in Swift is
/// `padding(.all, nil)`, and the `nil` is the point: it asks for the system's
/// own inset rather than for zero.
pub fn padding_default(view: &ViewHandle) -> ViewHandle {
    unsafe {
        let (meta, wt, size) = super::opaque_result_type(
            resolve::padding_edges_oret(),
            &[view.meta, view.wt],
        );
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        // x0 = Edge.Set (.all is every bit of a four-bit option set),
        // x1/x2 = Optional<CGFloat> payload and tag, then the generic words.
        core::arch::asm!("blr {f}", f = in(reg) resolve::padding_edges_fn(),
            in("x0") 0x0fu64,
            in("x1") 0u64, in("x2") 1u64,
            in("x3") view.meta,
            in("x4") view.wt,
            in("x8") result.as_mut_ptr(),
            in("x20") this,
            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"),
        );
        wrap_owned(result, meta, wt)
    }
}

/// Apply `.padding(_:_:)` — chosen edges, an explicit length.
///
/// `edges` is an `Edge.Set` bit pattern: 1 top, 2 leading, 4 bottom, 8 trailing,
/// so `.vertical` is 5 and `.all` is 15. A `None` length means the system's own
/// inset, as in [`padding_default`].
/// `.padding(_:_:)` with the edges named rather than spelled as a bitmask.
///
/// [`padding_edges`] takes the raw option-set bits, which a caller has to know;
/// this reads the member out of SwiftUI's own `Edge.Set` instead.
pub fn padding_set(view: &ViewHandle, edges: super::EdgeSet, length: Option<f64>) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::edge_set_ma());
        let (bits, _) = super::static_getter(edges.resolved(), meta);
        padding_edges(view, bits, length)
    }
}

pub fn padding_edges(view: &ViewHandle, edges: u64, length: Option<f64>) -> ViewHandle {
    unsafe {
        let (meta, wt, size) = super::opaque_result_type(
            resolve::padding_edges_oret(),
            &[view.meta, view.wt],
        );
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        let (bits, tag) = match length {
            Some(v) => (v.to_bits(), 0u64),
            None => (0u64, 1u64),
        };
        core::arch::asm!("blr {f}", f = in(reg) resolve::padding_edges_fn(),
            in("x0") edges,
            in("x1") bits, in("x2") tag,
            in("x3") view.meta,
            in("x4") view.wt,
            in("x8") result.as_mut_ptr(),
            in("x20") this,
            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"),
        );
        wrap_owned(result, meta, wt)
    }
}

/// Apply `.background(in:fillStyle:)` — the background style, clipped to a shape.
///
/// The shape must be `InsettableShape`, not merely `Shape`, so its witness is a
/// different table from the one [`super::Shape`] carries.
pub fn background_in_circle(view: &ViewHandle) -> ViewHandle {
    unsafe {
        let shape = super::Shape::circle();
        let (mut bytes, shape_meta, _) = shape.parts();
        bytes.push(0);
        let shape_wt = resolve::circle_wt();
        let subst = [view.meta, shape_meta, view.wt, shape_wt];
        let (meta, wt, size) =
            super::opaque_result_type(resolve::background_in_oret(), &subst);
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        core::arch::asm!("blr {f}", f = in(reg) resolve::background_in_fn(),
            in("x0") bytes.as_mut_ptr(),
            in("x1") 0x0100u64,           // FillStyle()
            in("x2") subst[0], in("x3") subst[1], in("x4") subst[2], in("x5") subst[3],
            in("x8") result.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"),
        );
        wrap_owned(result, meta, wt)
    }
}

/// `.backgroundStyle(_:)` with a `Color`.
///
/// [`background_style_of`] takes the style as raw bytes and a witness, which
/// is what an arbitrary `ShapeStyle` needs and what nothing can call without
/// building one first. These three name the styles that have a Rust spelling,
/// so the modifier is reachable the way the documentation writes it.
///
/// Not `.background(_:)`: that draws behind *this* view, while this says what
/// style the views *inside* should use for their own backgrounds.
pub fn background_style_color(view: &ViewHandle, r: f64, g: f64, b: f64, a: f64) -> ViewHandle {
    background_style_value(view, unsafe { super::color_value(r, g, b, a) })
}

/// `.backgroundStyle(_:)` with an already-resolved `Color` word.
pub fn background_style_value(view: &ViewHandle, color: u64) -> ViewHandle {
    // SAFETY: a resolved `Color` word beside `Color`'s own metadata and its
    // `ShapeStyle` conformance — the three come from one place and match.
    unsafe {
        background_style_of(
            view,
            &color.to_le_bytes(),
            resolve::color_meta(),
            resolve::color_shapestyle_wt(),
        )
    }
}

/// `.backgroundStyle(_:)` with one of the hierarchical levels.
pub fn background_style_hierarchical(view: &ViewHandle, level: super::Hierarchical) -> ViewHandle {
    // SAFETY: `hierarchical_style` returns a value with its own metadata and
    // conformance, so the three agree by construction.
    let (style, meta, wt) = super::hierarchical_style(level);
    unsafe { background_style_of(view, &style, meta, wt) }
}

/// Apply `.backgroundStyle(_:)` with any `ShapeStyle`.
/// # Safety
/// `style` must hold an initialised value of the type `style_meta` describes,
/// and `style_wt` must be that type's `ShapeStyle` conformance. Nothing here
/// checks either, and a mismatched pair is read as the type named.
pub unsafe fn background_style_of(
    view: &ViewHandle,
    style: &[u8],
    style_meta: *const c_void,
    style_wt: *const c_void,
) -> ViewHandle {
    unsafe {
        let subst = [view.meta, style_meta, view.wt, style_wt];
        let (meta, wt, size) =
            super::opaque_result_type(resolve::background_style_oret(), &subst);
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        let mut arg = style.to_vec();
        core::arch::asm!("blr {f}", f = in(reg) resolve::background_style_fn(),
            in("x0") arg.as_mut_ptr(),
            in("x1") subst[0], in("x2") subst[1], in("x3") subst[2], in("x4") subst[3],
            in("x8") result.as_mut_ptr(),
            in("x20") this,
            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"),
        );
        wrap_owned(result, meta, wt)
    }
}

/// `.mask(_:)` — the alignment-free overload, which builds a `_MaskEffect`.
///
/// SwiftUI has two masks and they are different types: `.mask(alignment:_:)`
/// gives `_MaskAlignmentEffect` and is what [`mask`] reaches, while the older
/// `.mask(_:)` gives `_MaskEffect`. The second is deprecated and inlined, so it
/// exports no function — but `_MaskEffect<Mask>` is a newtype over the mask
/// itself (measured: both eight bytes for the same mask), its descriptor is
/// exported, and `View.modifier(_:)` composes anything that conforms to
/// `ViewModifier`. So the modifier is built rather than called.
///
/// Falls back to [`mask`] if the instantiation does not take.
pub fn mask_plain(view: &ViewHandle, content: &ViewHandle) -> ViewHandle {
    unsafe {
        let desc = resolve::mask_effect_desc();
        if desc.is_null() {
            return mask(view, content);
        }
        let effect = abi::generic_metadata_from_descriptor(desc, &[content.meta, content.wt]);
        if effect.is_null() {
            return mask(view, content);
        }
        // A newtype over the mask: one stored property, at offset zero. The
        // metadata says so rather than being inferred from the size matching,
        // which two different layouts can also do.
        if abi::struct_field_offsets(effect).as_deref() != Some(&[0][..]) {
            return mask(view, content);
        }
        if abi::type_bytes(effect) != abi::type_bytes(content.meta) {
            return mask(view, content);
        }
        if !crate::diag::type_name(effect).starts_with("SwiftUI._MaskEffect<") {
            return mask(view, content);
        }
        let bytes =
            core::slice::from_raw_parts(content.value_ptr() as *const u8, abi::type_bytes(effect));
        super::apply_modifier(view, effect, bytes)
    }
}