waterui-ffi 0.5.1

FFI bindings for the WaterUI cross-platform UI framework
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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
use crate::components::text::WuiHorizontalAlignment;
use alloc::{boxed::Box, rc::Rc, vec::Vec};
use core::ffi::c_void;
use core::fmt;
use nami::{Signal, SignalExt};
use waterui_layout::{
    HorizontalAlignment, Layout, Point, ProposalSize, Rect, ScrollView, Size, Spacer, StretchAxis,
    SubView, SubviewPlacement, VerticalAlignment, ViewDimensions,
    container::{FixedContainer, LazyContainer},
    measure_layout,
    scroll::Axis,
    stack::LazyStackAxis,
    with_memoized_children,
};

use crate::views::WuiAnyViews;
use crate::{IntoFFI, IntoRust, WuiAnyView, array::WuiArray};

opaque!(WuiLayout, Box<dyn Layout>, layout);

/// C ABI mirror of [`FixedContainer`], a view that executes an arbitrary
/// [`Layout`] over an eagerly-collected, fixed set of child views.
#[repr(C)]
pub struct WuiFixedContainer {
    /// Owning handle to the boxed [`Layout`] implementation driving this container.
    pub layout: *mut WuiLayout,
    /// The container's child views, collected eagerly at construction time.
    pub contents: WuiArray<*mut WuiAnyView>,
}

impl fmt::Debug for WuiFixedContainer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WuiFixedContainer").finish_non_exhaustive()
    }
}

/// C ABI mirror of [`Spacer`], a flexible space that expands to fill
/// available space on the enclosing stack's main axis.
///
/// `min_length` is the floor the stack keeps under compression: per
/// `docs/layout-spec.md` §5/§6, a hosted spacer answers its minimum length on
/// the stack's main axis and zero on the cross axis, whatever the proposal.
#[repr(C)]
#[derive(Debug)]
pub struct WuiSpacer {
    /// The length this spacer never shrinks below on the stack's main axis.
    pub min_length: f32,
}

ffi_view!(Spacer, WuiSpacer, spacer);

impl IntoFFI for Spacer {
    type FFI = WuiSpacer;
    fn into_ffi(self) -> Self::FFI {
        WuiSpacer {
            min_length: self.min_length(),
        }
    }
}

ffi_view!(FixedContainer, WuiFixedContainer, fixed_container);

impl IntoFFI for FixedContainer {
    type FFI = WuiFixedContainer;
    fn into_ffi(self) -> Self::FFI {
        let (layout, contents) = self.into_inner();
        WuiFixedContainer {
            layout: layout.into_ffi(),
            contents: contents.into_ffi(),
        }
    }
}

/// C ABI mirror of [`LazyContainer`], a view that executes an arbitrary
/// [`Layout`] over a lazily reconstructed collection of child views.
#[repr(C)]
#[derive(Debug)]
pub struct WuiContainer {
    /// Owning handle to the boxed [`Layout`] implementation driving this container.
    pub layout: *mut WuiLayout,
    /// Handle to the lazily reconstructed child view collection.
    pub contents: *mut WuiAnyViews,
}

ffi_view!(LazyContainer, WuiContainer, layout_container);

impl IntoFFI for LazyContainer {
    type FFI = WuiContainer;
    fn into_ffi(self) -> Self::FFI {
        let (layout, contents) = self.into_inner();
        WuiContainer {
            layout: layout.into_ffi(),
            contents: contents.into_ffi(),
        }
    }
}

/// The stacking axis a layout advertises for lazy (virtualized) rendering,
/// as reported by [`waterui_layout_lazy_stack_axis`].
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WuiLazyStackAxis {
    /// The layout does not support lazy stacking (not a `VStackLayout`/`HStackLayout`).
    Unsupported = 0,
    /// The layout stacks children vertically (`VStackLayout`).
    Vertical = 1,
    /// The layout stacks children horizontally (`HStackLayout`).
    Horizontal = 2,
}

#[derive(Clone, Copy)]
struct LazyStackDescriptor {
    axis: WuiLazyStackAxis,
    spacing: f32,
    horizontal_alignment: WuiHorizontalAlignment,
    vertical_alignment: WuiVerticalAlignment,
}

fn lazy_stack_descriptor(layout: &dyn Layout) -> Option<LazyStackDescriptor> {
    waterui_layout::stack::lazy_stack_axis(layout).map(|axis| match axis {
        LazyStackAxis::Vertical { spacing, alignment } => LazyStackDescriptor {
            axis: WuiLazyStackAxis::Vertical,
            spacing: spacing.get(),
            horizontal_alignment: alignment.into_ffi(),
            vertical_alignment: VerticalAlignment::Center.into_ffi(),
        },
        LazyStackAxis::Horizontal { spacing, alignment } => LazyStackDescriptor {
            axis: WuiLazyStackAxis::Horizontal,
            spacing: spacing.get(),
            horizontal_alignment: HorizontalAlignment::Center.into_ffi(),
            vertical_alignment: alignment.into_ffi(),
        },
    })
}

fn required_lazy_stack_descriptor(layout: &dyn Layout) -> LazyStackDescriptor {
    lazy_stack_descriptor(layout)
        .unwrap_or_else(|| panic!("waterui_layout_lazy_stack_* called for unsupported layout"))
}

/// Native callback invoked when a reactive layout input changes.
pub type WuiLayoutInvalidationCallback = unsafe extern "C" fn(context: *mut c_void);

struct ForeignLayoutInvalidation {
    context: *mut c_void,
    invalidate: WuiLayoutInvalidationCallback,
    drop: WuiLayoutInvalidationCallback,
}

impl ForeignLayoutInvalidation {
    fn invalidate(&self) {
        // SAFETY: `invalidate` and `context` were registered together by the backend
        // and the context outlives this watcher.
        unsafe { (self.invalidate)(self.context) };
    }
}

impl Drop for ForeignLayoutInvalidation {
    fn drop(&mut self) {
        // SAFETY: `drop` and `context` are one registration, and `Drop` runs once.
        unsafe { (self.drop)(self.context) };
    }
}

/// Retained native invalidation target and its precise signal subscriptions.
pub struct WuiLayoutWatcher {
    _guards: Vec<nami::watcher::BoxWatcherGuard>,
    _target: Rc<ForeignLayoutInvalidation>,
}

impl fmt::Debug for WuiLayoutWatcher {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WuiLayoutWatcher").finish_non_exhaustive()
    }
}

/// Watches the reactive fields used by a layout.
///
/// # Safety
///
/// `layout` and `context` must remain valid until the returned watcher is
/// dropped. Both callbacks must run on the layout's owning UI thread.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_layout_watch_invalidation(
    layout: *const WuiLayout,
    context: *mut c_void,
    invalidate: WuiLayoutInvalidationCallback,
    drop_callback: WuiLayoutInvalidationCallback,
) -> *mut WuiLayoutWatcher {
    // SAFETY: the caller contract requires `layout` to be a valid handle that stays
    // alive for this call; it is only borrowed.
    let layout = unsafe { crate::borrow_ffi(layout) };

    let target = Rc::new(ForeignLayoutInvalidation {
        context,
        invalidate,
        drop: drop_callback,
    });
    let callback_target = Rc::clone(&target);
    let guards = layout.0.watch_invalidation(Rc::new(move || {
        let target = Rc::clone(&callback_target);
        target.invalidate();
    }));
    Box::into_raw(Box::new(WuiLayoutWatcher {
        _guards: guards,
        _target: target,
    }))
}

/// Drops a layout invalidation watcher.
///
/// # Safety
///
/// `watcher` must be returned by [`waterui_layout_watch_invalidation`] and not
/// previously dropped.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_layout_watcher_drop(watcher: *mut WuiLayoutWatcher) {
    // SAFETY: the caller contract makes `watcher` an owning pointer from the
    // matching FFI constructor, so reclaiming the box frees it exactly once.
    unsafe { drop(Box::from_raw(watcher)) };
}

// ============================================================================
// ProposalSize FFI
// ============================================================================

/// C ABI mirror of [`ProposalSize`]: the size a parent layout suggests to a
/// child. Either axis may be unspecified, encoded here as `f32::NAN` to mean
/// "the child decides its own size along this axis".
#[derive(Clone, Default, Debug)]
#[repr(C)]
pub struct WuiProposalSize {
    width: f32, // May be f32::NAN for unspecified
    height: f32,
}

impl IntoRust for WuiProposalSize {
    type Rust = ProposalSize;
    unsafe fn into_rust(self) -> Self::Rust {
        ProposalSize {
            width: if self.width.is_nan() {
                None
            } else {
                Some(self.width)
            },
            height: if self.height.is_nan() {
                None
            } else {
                Some(self.height)
            },
        }
    }
}

impl IntoFFI for ProposalSize {
    type FFI = WuiProposalSize;
    fn into_ffi(self) -> Self::FFI {
        WuiProposalSize {
            width: self.width.unwrap_or(f32::NAN),
            height: self.height.unwrap_or(f32::NAN),
        }
    }
}

// ============================================================================
// StretchAxis FFI
// ============================================================================

/// FFI representation of `StretchAxis` enum.
///
/// Specifies which axis (or axes) a view stretches to fill available space.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WuiStretchAxis {
    /// No stretching - view uses its intrinsic size
    None = 0,
    /// Stretch horizontally only (expand width, use intrinsic height)
    Horizontal = 1,
    /// Stretch vertically only (expand height, use intrinsic width)
    Vertical = 2,
    /// Stretch in both directions (expand width and height)
    Both = 3,
    /// Stretch along the parent container's main axis (e.g., Spacer)
    MainAxis = 4,
    /// Stretch along the parent container's cross axis (e.g., Divider)
    CrossAxis = 5,
}

impl From<WuiStretchAxis> for StretchAxis {
    fn from(axis: WuiStretchAxis) -> Self {
        match axis {
            WuiStretchAxis::None => Self::None,
            WuiStretchAxis::Horizontal => Self::Horizontal,
            WuiStretchAxis::Vertical => Self::Vertical,
            WuiStretchAxis::Both => Self::Both,
            WuiStretchAxis::MainAxis => Self::MainAxis,
            WuiStretchAxis::CrossAxis => Self::CrossAxis,
        }
    }
}

impl From<StretchAxis> for WuiStretchAxis {
    fn from(axis: StretchAxis) -> Self {
        match axis {
            StretchAxis::None => Self::None,
            StretchAxis::Horizontal => Self::Horizontal,
            StretchAxis::Vertical => Self::Vertical,
            StretchAxis::Both => Self::Both,
            StretchAxis::MainAxis => Self::MainAxis,
            StretchAxis::CrossAxis => Self::CrossAxis,
        }
    }
}

// ============================================================================
// SubView FFI Proxy
// ============================================================================

/// `VTable` for `SubView` operations.
///
/// This structure contains function pointers that allow native code to implement
/// the `SubView` protocol. The native backend provides these callbacks to participate
/// in layout negotiation.
#[repr(C)]
#[derive(Debug)]
pub struct WuiSubViewVTable {
    /// Measures the child view given a size proposal.
    /// Called potentially multiple times with different proposals during layout.
    pub measure: unsafe extern "C" fn(
        context: *mut core::ffi::c_void,
        proposal: WuiProposalSize,
    ) -> WuiViewDimensions,
    /// Cleans up the context when the subview is no longer needed.
    /// Called when the `WuiSubView` is dropped.
    pub drop: unsafe extern "C" fn(context: *mut core::ffi::c_void),
}

/// FFI representation of a `SubView` proxy.
///
/// This allows native code to participate in the layout negotiation protocol
/// by providing callbacks that can be called multiple times with different proposals.
///
/// # Memory Management
///
/// The `context` pointer is owned by this struct. When the `WuiSubView` is dropped,
/// the `vtable.drop` function will be called to clean up the context.
#[repr(C)]
#[derive(Debug)]
pub struct WuiSubView {
    /// Opaque context pointer (e.g., child view reference, cached data)
    pub context: *mut core::ffi::c_void,
    /// `VTable` containing measure and drop functions
    pub vtable: WuiSubViewVTable,
    /// Which axis this view stretches to fill available space
    pub stretch_axis: WuiStretchAxis,
    /// Layout priority (higher = measured first, gets space preference)
    pub priority: i32,
}

impl Drop for WuiSubView {
    fn drop(&mut self) {
        // SAFETY: the vtable was registered with this `context`, and `Drop` runs once.
        unsafe { (self.vtable.drop)(self.context) }
    }
}

impl SubView for WuiSubView {
    fn measure(&self, proposal: ProposalSize) -> ViewDimensions {
        // SAFETY: the vtable was registered with this `context`, which is alive for as
        // long as `self`; the proposal is passed by value into backend ownership.
        let result = unsafe { (self.vtable.measure)(self.context, proposal.into_ffi()) };
        // SAFETY: the caller contract makes `result` an owning handle from the
        // matching FFI constructor; it is consumed here and not observed
        // again.
        unsafe { result.into_rust() }
    }

    fn stretch_axis(&self) -> StretchAxis {
        self.stretch_axis.into()
    }

    fn priority(&self) -> i32 {
        self.priority
    }
}

// ============================================================================
// Geometry Types
// ============================================================================

into_ffi! {Point,
    pub struct WuiPoint {
        x: f32,
        y: f32,
    }
}

impl IntoRust for WuiPoint {
    type Rust = Point;
    unsafe fn into_rust(self) -> Self::Rust {
        Point {
            x: self.x,
            y: self.y,
        }
    }
}

into_ffi! {Size,
    pub struct WuiSize {
        width: f32,
        height: f32,
    }
}

impl IntoRust for WuiSize {
    type Rust = Size;
    unsafe fn into_rust(self) -> Self::Rust {
        Size {
            width: self.width,
            height: self.height,
        }
    }
}

#[cfg(feature = "c-api")]
crate::ffi_computed!(Size, WuiSize, size);

/// C ABI mirror of [`VerticalAlignment`], a named vertical alignment guide
/// used for stack cross-axis alignment and explicit view dimension guides.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WuiVerticalAlignment {
    /// Aligns to the top edge.
    Top = 0,
    /// Aligns to the vertical center.
    #[default]
    Center = 1,
    /// Aligns to the bottom edge.
    Bottom = 2,
    /// Aligns to the first line's text baseline.
    FirstBaseline = 3,
    /// Aligns to the last line's text baseline.
    LastBaseline = 4,
}

impl IntoFFI for VerticalAlignment {
    type FFI = WuiVerticalAlignment;

    fn into_ffi(self) -> Self::FFI {
        if self == Self::Top {
            WuiVerticalAlignment::Top
        } else if self == Self::Bottom {
            WuiVerticalAlignment::Bottom
        } else if self == Self::FirstBaseline {
            WuiVerticalAlignment::FirstBaseline
        } else if self == Self::LastBaseline {
            WuiVerticalAlignment::LastBaseline
        } else {
            WuiVerticalAlignment::Center
        }
    }
}

impl IntoRust for WuiVerticalAlignment {
    type Rust = VerticalAlignment;

    unsafe fn into_rust(self) -> Self::Rust {
        match self {
            Self::Top => VerticalAlignment::Top,
            Self::Center => VerticalAlignment::Center,
            Self::Bottom => VerticalAlignment::Bottom,
            Self::FirstBaseline => VerticalAlignment::FirstBaseline,
            Self::LastBaseline => VerticalAlignment::LastBaseline,
        }
    }
}

/// C ABI mirror of one explicit horizontal alignment guide entry from
/// [`ViewDimensions`], pairing a named alignment with its measured offset.
#[derive(Clone, Copy, Default, Debug)]
#[repr(C)]
pub struct WuiHorizontalGuide {
    alignment: WuiHorizontalAlignment,
    value: f32,
}

impl IntoRust for WuiHorizontalGuide {
    type Rust = (HorizontalAlignment, f32);

    unsafe fn into_rust(self) -> Self::Rust {
        // SAFETY: the caller contract makes `alignment` an owning handle from the
        // matching FFI constructor; it is consumed here and not observed
        // again.
        (unsafe { self.alignment.into_rust() }, self.value)
    }
}

/// C ABI mirror of one explicit vertical alignment guide entry from
/// [`ViewDimensions`], pairing a named alignment with its measured offset.
#[derive(Clone, Copy, Default, Debug)]
#[repr(C)]
pub struct WuiVerticalGuide {
    alignment: WuiVerticalAlignment,
    value: f32,
}

impl IntoRust for WuiVerticalGuide {
    type Rust = (VerticalAlignment, f32);

    unsafe fn into_rust(self) -> Self::Rust {
        // SAFETY: the caller contract makes `alignment` an owning handle from the
        // matching FFI constructor; it is consumed here and not observed
        // again.
        (unsafe { self.alignment.into_rust() }, self.value)
    }
}

/// C ABI mirror of [`ViewDimensions`]: a measured size together with any
/// explicit horizontal/vertical alignment guides the view exposes to its
/// parent layout.
#[repr(C)]
pub struct WuiViewDimensions {
    size: WuiSize,
    horizontal_guides: WuiArray<WuiHorizontalGuide>,
    vertical_guides: WuiArray<WuiVerticalGuide>,
}

impl fmt::Debug for WuiViewDimensions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WuiViewDimensions")
            .field("size", &self.size)
            .finish_non_exhaustive()
    }
}

impl IntoFFI for ViewDimensions {
    type FFI = WuiViewDimensions;

    fn into_ffi(self) -> Self::FFI {
        let horizontal_guides = self
            .explicit_horizontal_guides()
            .map(|(alignment, value)| WuiHorizontalGuide {
                alignment: alignment.into_ffi(),
                value,
            })
            .collect::<Vec<_>>();
        let vertical_guides = self
            .explicit_vertical_guides()
            .map(|(alignment, value)| WuiVerticalGuide {
                alignment: alignment.into_ffi(),
                value,
            })
            .collect::<Vec<_>>();

        WuiViewDimensions {
            size: self.size.into_ffi(),
            horizontal_guides: WuiArray::new(horizontal_guides),
            vertical_guides: WuiArray::new(vertical_guides),
        }
    }
}

impl IntoRust for WuiViewDimensions {
    type Rust = ViewDimensions;

    unsafe fn into_rust(self) -> Self::Rust {
        // SAFETY: the caller contract makes `size` an owning handle from the
        // matching FFI constructor; it is consumed here and not observed
        // again.
        let mut dimensions = ViewDimensions::new(unsafe { self.size.into_rust() });
        // SAFETY: the caller contract makes `horizontal_guides` an owning handle
        // from the matching FFI constructor; it is consumed here and not
        // observed again.
        for (alignment, value) in unsafe { self.horizontal_guides.into_rust() } {
            dimensions.set_horizontal(alignment, value);
        }
        // SAFETY: the caller contract makes `vertical_guides` an owning handle from
        // the matching FFI constructor; it is consumed here and not observed
        // again.
        for (alignment, value) in unsafe { self.vertical_guides.into_rust() } {
            dimensions.set_vertical(alignment, value);
        }
        dimensions
    }
}

/// C ABI mirror of [`Rect`]: an axis-aligned rectangle expressed as an
/// origin point and a size, relative to its parent's coordinate space.
#[repr(C)]
#[derive(Debug)]
pub struct WuiRect {
    origin: WuiPoint,
    size: WuiSize,
}

impl IntoRust for WuiRect {
    type Rust = Rect;
    unsafe fn into_rust(self) -> Self::Rust {
        // SAFETY: the caller contract makes `origin` an owning handle from the
        // matching FFI constructor; it is consumed here and not observed
        // again.
        unsafe { Rect::new(self.origin.into_rust(), self.size.into_rust()) }
    }
}

impl IntoFFI for Rect {
    type FFI = WuiRect;
    fn into_ffi(self) -> Self::FFI {
        WuiRect {
            origin: self.origin().into_ffi(),
            size: (*self.size()).into_ffi(),
        }
    }
}

#[cfg(feature = "c-api")]
crate::ffi_binding!(Rect, WuiRect, rect);
crate::ffi_watcher!(Rect, WuiRect, rect);

/// C ABI mirror of [`SubviewPlacement`]: a child's resolved frame together
/// with the size proposal that was selected to measure and recursively place
/// it.
#[repr(C)]
#[derive(Debug)]
pub struct WuiSubviewPlacement {
    /// The child frame in the parent layout's coordinate space.
    frame: WuiRect,
    /// The proposal used to measure and recursively place the child; it is
    /// not inferred from the frame.
    proposal: WuiProposalSize,
}

impl IntoFFI for SubviewPlacement {
    type FFI = WuiSubviewPlacement;
    fn into_ffi(self) -> Self::FFI {
        WuiSubviewPlacement {
            frame: self.frame.into_ffi(),
            proposal: self.proposal.into_ffi(),
        }
    }
}

// ============================================================================
// Layout API Functions
// ============================================================================

/// Calculates the size required by the layout given a proposal and child proxies.
///
/// This function implements the new SubView-based negotiation protocol where
/// layouts can query children multiple times with different proposals.
///
/// # Safety
///
/// - The `layout` pointer must be valid and point to a properly initialized `WuiLayout`.
/// - The `children` array must contain valid `WuiSubView` entries.
/// - The measure callbacks in each child must be safe to call.
/// - The `children` array will be consumed and dropped after this call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_layout_measure(
    layout: *mut WuiLayout,
    proposal: WuiProposalSize,
    mut children: WuiArray<WuiSubView>,
) -> WuiViewDimensions {
    // SAFETY: the caller contract requires `layout` to be a valid handle whose boxed
    // `dyn Layout` stays alive for this call; it is only borrowed.
    let layout: &dyn Layout = unsafe { &*(*layout).0 };
    // SAFETY: the caller contract makes `proposal` an owning handle from the
    // matching FFI constructor; it is consumed here and not observed again.
    let proposal = unsafe { proposal.into_rust() };
    let children_slice = children.as_mut_slice();
    let subview_refs: Vec<&dyn SubView> =
        children_slice.iter().map(|s| s as &dyn SubView).collect();
    let dimensions = measure_layout(layout, proposal, &subview_refs);
    children.consume();
    dimensions.into_ffi()
}

/// Places child views within the specified bounds under the given proposal.
///
/// Returns an array of [`WuiSubviewPlacement`] values — each child's frame
/// paired with the proposal that was selected to measure it. The `proposal`
/// argument is the selected measurement input, the same one passed to
/// [`waterui_layout_measure`]; it is not derived from `bounds`.
///
/// # Safety
///
/// - The `layout` pointer must be valid and point to a properly initialized `WuiLayout`.
/// - The `children` array must contain valid `WuiSubView` entries.
/// - The measure callbacks in each child must be safe to call.
/// - The `children` array will be consumed and dropped after this call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_layout_place_subviews(
    layout: *mut WuiLayout,
    bounds: WuiRect,
    proposal: WuiProposalSize,
    mut children: WuiArray<WuiSubView>,
) -> WuiArray<WuiSubviewPlacement> {
    // SAFETY: the caller contract requires `layout` to be a valid handle whose boxed
    // `dyn Layout` stays alive for this call; it is only borrowed.
    let layout: &dyn Layout = unsafe { &*(*layout).0 };
    // SAFETY: the caller contract makes `bounds` an owning handle from the matching
    // FFI constructor; it is consumed here and not observed again.
    let bounds = unsafe { bounds.into_rust() };
    // SAFETY: the caller contract makes `proposal` an owning handle from the
    // matching FFI constructor; it is consumed here and not observed again.
    let proposal = unsafe { proposal.into_rust() };

    // Get slice of WuiSubView and create trait object references
    let children_slice = children.as_mut_slice();
    let subview_refs: Vec<&dyn SubView> =
        children_slice.iter().map(|s| s as &dyn SubView).collect();

    let placements =
        with_memoized_children(&subview_refs, |refs| layout.place(bounds, proposal, refs));

    children.consume();

    placements.into_ffi()
}

/// Queries a layout's live stretch behavior using its current child axes.
///
/// # Safety
///
/// `layout` must be a live layout handle on its owning thread. `children` must
/// be a valid array and is consumed by this call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_layout_stretch_axis(
    layout: *const WuiLayout,
    children: WuiArray<WuiStretchAxis>,
) -> WuiStretchAxis {
    // SAFETY: the caller keeps the layout handle alive for this shared borrow.
    let layout = unsafe { crate::borrow_ffi(layout) };
    let axes: Vec<StretchAxis> = children
        .as_slice()
        .iter()
        .copied()
        .map(Into::into)
        .collect();
    let result = layout.0.stretch_axis(&axes);
    children.consume();
    result.into()
}

/// Returns the lazy-stack axis the layout advertises, if any.
///
/// # Safety
///
/// The `layout` pointer must be valid and point to a properly initialized `WuiLayout`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_layout_lazy_stack_axis(
    layout: *mut WuiLayout,
) -> WuiLazyStackAxis {
    // SAFETY: the caller contract requires `layout` to be a valid handle whose boxed
    // `dyn Layout` stays alive for this call; it is only borrowed.
    let layout: &dyn Layout = unsafe { &*(*layout).0 };
    lazy_stack_descriptor(layout)
        .map_or(WuiLazyStackAxis::Unsupported, |descriptor| descriptor.axis)
}

/// Returns the lazy-stack inter-item spacing the layout requires.
///
/// # Safety
///
/// The `layout` pointer must be valid and point to a properly initialized `WuiLayout`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_layout_lazy_stack_spacing(layout: *mut WuiLayout) -> f32 {
    // SAFETY: the caller contract requires `layout` to be a valid handle whose boxed
    // `dyn Layout` stays alive for this call; it is only borrowed.
    let layout: &dyn Layout = unsafe { &*(*layout).0 };
    required_lazy_stack_descriptor(layout).spacing
}

/// Returns the lazy-stack cross-axis horizontal alignment the layout requires.
///
/// # Safety
///
/// The `layout` pointer must be valid and point to a properly initialized `WuiLayout`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_layout_lazy_stack_horizontal_alignment(
    layout: *mut WuiLayout,
) -> WuiHorizontalAlignment {
    // SAFETY: the caller contract requires `layout` to be a valid handle whose boxed
    // `dyn Layout` stays alive for this call; it is only borrowed.
    let layout: &dyn Layout = unsafe { &*(*layout).0 };
    required_lazy_stack_descriptor(layout).horizontal_alignment
}

/// Returns the lazy-stack cross-axis vertical alignment the layout requires.
///
/// # Safety
///
/// The `layout` pointer must be valid and point to a properly initialized `WuiLayout`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_layout_lazy_stack_vertical_alignment(
    layout: *mut WuiLayout,
) -> WuiVerticalAlignment {
    // SAFETY: the caller contract requires `layout` to be a valid handle whose boxed
    // `dyn Layout` stays alive for this call; it is only borrowed.
    let layout: &dyn Layout = unsafe { &*(*layout).0 };
    required_lazy_stack_descriptor(layout).vertical_alignment
}

// ============================================================================
// ScrollView
// ============================================================================

into_ffi! {Axis, non_exhaustive,
    pub enum WuiAxis {
        Horizontal,
        Vertical,
        All,
    }
}

/// C ABI mirror of [`ScrollView`], a container that scrolls content larger
/// than its own frame along one or both axes.
#[repr(C)]
#[derive(Debug)]
pub struct WuiScrollView {
    /// The axis (or axes) along which this scroll view allows scrolling.
    pub axis: WuiAxis,
    /// The scrollable content view.
    pub content: *mut WuiAnyView,
    /// Read-only signal for the horizontal scroll target requested via
    /// `ScrollController::scroll_to`, or null if no controller is attached.
    pub target_x: *mut crate::reactive::WuiComputed<f32>,
    /// Read-only signal for the vertical scroll target requested via
    /// `ScrollController::scroll_to`, or null if no controller is attached.
    pub target_y: *mut crate::reactive::WuiComputed<f32>,
    /// Monotonically increasing generation that changes each time a new
    /// scroll request is issued, letting the backend detect a repeated
    /// request to the same target. Null if no controller is attached.
    pub scroll_generation: *mut crate::reactive::WuiComputed<i32>,
}

impl IntoFFI for ScrollView {
    type FFI = WuiScrollView;
    fn into_ffi(self) -> Self::FFI {
        let (axis, content, controller) = self.into_inner();
        let (target_x, target_y, scroll_generation) = controller.map_or_else(
            || {
                (
                    core::ptr::null_mut(),
                    core::ptr::null_mut(),
                    core::ptr::null_mut(),
                )
            },
            |controller| {
                let target = controller.target();
                (
                    target.clone().map(|point| point.x).computed().into_ffi(),
                    target.map(|point| point.y).computed().into_ffi(),
                    controller.generation().into_ffi(),
                )
            },
        );
        WuiScrollView {
            axis: axis.into_ffi(),
            content: content.into_ffi(),
            target_x,
            target_y,
            scroll_generation,
        }
    }
}

ffi_view!(ScrollView, WuiScrollView, scroll_view);

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;
    use core::cell::{Cell, RefCell};
    use nami::{Computed, SignalExt, binding};
    use waterui_layout::frame::FrameLayout;
    use waterui_layout::stack::{HStackLayout, VStackLayout};

    #[cfg(feature = "c-api")]
    #[test]
    fn layout_priority_metadata_preserves_values_and_content_ownership() {
        use crate::{
            waterui_force_as_metadata_layout_priority, waterui_metadata_layout_priority_id,
            waterui_view_id,
        };
        use waterui_core::layout::LayoutPriority;
        use waterui_core::{AnyView, Environment, Metadata, View};

        struct DropProbe(Rc<Cell<usize>>);

        impl Drop for DropProbe {
            fn drop(&mut self) {
                self.0.set(self.0.get() + 1);
            }
        }

        impl View for DropProbe {
            fn body(self, _env: &Environment) -> impl View {}
        }

        for priority in [i32::MIN, -3, 0, 5, i32::MAX] {
            let drops = Rc::new(Cell::new(0));
            let view = AnyView::new(Metadata::new(
                DropProbe(Rc::clone(&drops)),
                LayoutPriority::new(priority),
            ))
            .into_ffi();
            // SAFETY: `view` is the live owning handle created above.
            let view_id = unsafe { waterui_view_id(view) };
            assert_eq!(view_id, waterui_metadata_layout_priority_id());
            // SAFETY: the handle contains Metadata<LayoutPriority> and is consumed once.
            let metadata = unsafe { waterui_force_as_metadata_layout_priority(view) };
            assert_eq!(metadata.value, priority);
            assert_eq!(drops.get(), 0);
            // SAFETY: extraction transferred the live content handle, consumed once here.
            unsafe { drop(metadata.content.into_rust()) };
            assert_eq!(drops.get(), 1);
        }
    }

    #[cfg(feature = "c-api")]
    #[test]
    #[expect(
        clippy::float_cmp,
        reason = "min_length is copied verbatim across FFI with no intervening arithmetic, so exact equality is the correct assertion"
    )]
    fn spacer_crosses_ffi_with_its_minimum_length() {
        use crate::waterui_view_id;
        use waterui_core::{AnyView, Native};

        let view = AnyView::new(Native::new(Spacer::new(40.0))).into_ffi();
        // SAFETY: `view` is the live owning handle created above.
        let view_id = unsafe { waterui_view_id(view) };
        assert_eq!(view_id, waterui_spacer_id());
        // SAFETY: the handle contains a `Native<Spacer>` and is consumed once.
        let spacer = unsafe { waterui_force_as_spacer(view) };
        assert_eq!(spacer.min_length, 40.0);
    }

    #[test]
    fn layout_stretch_queries_follow_current_children() {
        let check = |layout: *mut WuiLayout, main, cross| {
            for (axes, expected) in [
                (vec![], WuiStretchAxis::None),
                (vec![WuiStretchAxis::MainAxis], main),
                (vec![WuiStretchAxis::CrossAxis], cross),
                (vec![WuiStretchAxis::Both], WuiStretchAxis::Both),
                (vec![], WuiStretchAxis::None),
            ] {
                // SAFETY: with_layout owns the live handle and this array is consumed once.
                let actual = unsafe { waterui_layout_stretch_axis(layout, WuiArray::new(axes)) };
                assert_eq!(actual, expected);
            }
        };
        with_layout(HStackLayout::default(), |layout| {
            check(layout, WuiStretchAxis::Horizontal, WuiStretchAxis::Vertical);
        });
        with_layout(VStackLayout::default(), |layout| {
            check(layout, WuiStretchAxis::Vertical, WuiStretchAxis::Horizontal);
        });
    }

    fn with_layout(layout: impl Layout + 'static, f: impl FnOnce(*mut WuiLayout)) {
        let mut layout = WuiLayout(Box::new(layout));
        f(&raw mut layout);
    }

    #[test]
    #[expect(
        clippy::float_cmp,
        reason = "spacing is copied verbatim across FFI from a Computed::constant with no intervening arithmetic, so exact equality is the correct assertion"
    )]
    fn lazy_stack_queries_report_vstack_configuration() {
        with_layout(
            VStackLayout {
                alignment: HorizontalAlignment::Trailing,
                spacing: Computed::constant(12.0),
            },
            // SAFETY: the harness hands the closure a pointer to the live layout
            // handle it just built.
            |layout| unsafe {
                assert_eq!(
                    waterui_layout_lazy_stack_axis(layout),
                    WuiLazyStackAxis::Vertical
                );
                assert_eq!(waterui_layout_lazy_stack_spacing(layout), 12.0);
                assert_eq!(
                    waterui_layout_lazy_stack_horizontal_alignment(layout),
                    WuiHorizontalAlignment::Trailing
                );
            },
        );
    }

    #[test]
    #[expect(
        clippy::float_cmp,
        reason = "spacing is copied verbatim across FFI from a Computed::constant with no intervening arithmetic, so exact equality is the correct assertion"
    )]
    fn lazy_stack_queries_report_hstack_configuration() {
        with_layout(
            HStackLayout {
                alignment: VerticalAlignment::Bottom,
                spacing: Computed::constant(7.0),
            },
            // SAFETY: the harness hands the closure a pointer to the live layout
            // handle it just built.
            |layout| unsafe {
                assert_eq!(
                    waterui_layout_lazy_stack_axis(layout),
                    WuiLazyStackAxis::Horizontal
                );
                assert_eq!(waterui_layout_lazy_stack_spacing(layout), 7.0);
                assert_eq!(
                    waterui_layout_lazy_stack_vertical_alignment(layout),
                    WuiVerticalAlignment::Bottom
                );
            },
        );
    }

    #[test]
    #[expect(
        clippy::float_cmp,
        reason = "spacing is copied verbatim across FFI from a Computed::constant with no intervening arithmetic, so exact equality is the correct assertion"
    )]
    fn layout_watcher_forwards_precise_signal_invalidation() {
        struct Target(Rc<Cell<usize>>);

        unsafe extern "C" fn invalidate(context: *mut c_void) {
            // SAFETY: the test registers this callback with a pointer to its own
            // live `Target`.
            let target = unsafe { &*(context as *const Target) };
            target.0.set(target.0.get() + 1);
        }

        unsafe extern "C" fn drop_target(context: *mut c_void) {
            // SAFETY: `context` is the boxed `Target` this callback was registered
            // with, and the drop entry runs once.
            unsafe { drop(Box::from_raw(context.cast::<Target>())) };
        }

        let spacing = binding(4.0_f32);
        let mut layout = WuiLayout(Box::new(VStackLayout {
            alignment: HorizontalAlignment::Center,
            spacing: spacing.computed(),
        }));
        let invalidations = Rc::new(Cell::new(0));
        let context = Box::into_raw(Box::new(Target(Rc::clone(&invalidations)))).cast();
        // SAFETY: `layout` is a live local, and `context`/`invalidate`/`drop_target`
        // are one registration built just above.
        let watcher = unsafe {
            waterui_layout_watch_invalidation(&raw const layout, context, invalidate, drop_target)
        };

        spacing.set(12.0);
        assert_eq!(invalidations.get(), 1);
        assert_eq!(
            // SAFETY: `layout` is a live local for the duration of the call.
            unsafe { waterui_layout_lazy_stack_spacing(&raw mut layout) },
            12.0
        );

        // SAFETY: `watcher` is the owning handle returned above, dropped once here.
        unsafe { waterui_layout_watcher_drop(watcher) };
    }

    fn proposal_cases() -> [Option<f32>; 4] {
        [None, Some(0.0), Some(48.0), Some(f32::INFINITY)]
    }

    #[test]
    fn proposal_round_trip_preserves_each_axis_probe() {
        for width in proposal_cases() {
            for height in proposal_cases() {
                let proposal = ProposalSize::new(width, height);
                // SAFETY: the decoded value is the FFI mirror produced by
                // `into_ffi` from `proposal` itself, satisfying the `into_rust`
                // contract.
                let decoded = unsafe { proposal.into_ffi().into_rust() };
                assert_eq!(decoded, proposal);
            }
        }
    }

    #[test]
    fn proposal_decodes_nan_as_unspecified_without_losing_infinity() {
        for bits in [f32::NAN.to_bits(), 0x7fc0_0001, 0xffc0_0042] {
            // SAFETY: `WuiProposalSize` mirrors `ProposalSize` bit for bit on
            // each axis, so decoding a value with arbitrary `f32` payloads is
            // the contract `into_rust` defines.
            let decoded = unsafe {
                WuiProposalSize {
                    width: f32::from_bits(bits),
                    height: f32::INFINITY,
                }
                .into_rust()
            };
            assert_eq!(decoded, ProposalSize::new(None, Some(f32::INFINITY)));
        }
        // SAFETY: the decoded value is the FFI mirror produced by `into_ffi`
        // from this pair, satisfying the `into_rust` contract.
        let decoded = unsafe {
            ProposalSize::new(Some(-0.0), Some(0.0))
                .into_ffi()
                .into_rust()
        };
        assert_eq!(decoded.width.unwrap().to_bits(), (-0.0_f32).to_bits());
        assert_eq!(decoded.height.unwrap().to_bits(), 0.0_f32.to_bits());
    }

    fn probe_extent(proposed: Option<f32>, minimum: f32, ideal: f32, maximum: f32) -> f32 {
        proposed.map_or(ideal, |value| value.clamp(minimum, maximum))
    }

    #[derive(Debug)]
    struct ProbeView;

    impl SubView for ProbeView {
        fn measure(&self, proposal: ProposalSize) -> ViewDimensions {
            ViewDimensions::new(Size::new(
                probe_extent(proposal.width, 8.0, 24.0, 96.0),
                probe_extent(proposal.height, 12.0, 36.0, 144.0),
            ))
            .with_horizontal(HorizontalAlignment::Leading, 3.0)
            .with_vertical(VerticalAlignment::FirstBaseline, 5.0)
        }

        fn stretch_axis(&self) -> StretchAxis {
            StretchAxis::Both
        }

        fn priority(&self) -> i32 {
            7
        }
    }

    struct ProbeContext {
        proposals: Rc<RefCell<Vec<ProposalSize>>>,
        drops: Rc<Cell<usize>>,
    }

    unsafe extern "C" fn measure_probe(
        context: *mut c_void,
        proposal: WuiProposalSize,
    ) -> WuiViewDimensions {
        // SAFETY: the test registers this callback with a live `ProbeContext`
        // created by `foreign_probe`, which outlives every measure call.
        let context = unsafe { &*context.cast::<ProbeContext>() };
        // Decode independently of `IntoRust`: the callback models a foreign
        // backend, so it must not reuse the Rust-side decoder under test.
        let decoded = ProposalSize::new(
            (!proposal.width.is_nan()).then_some(proposal.width),
            (!proposal.height.is_nan()).then_some(proposal.height),
        );
        context.proposals.borrow_mut().push(decoded);
        ProbeView.measure(decoded).into_ffi()
    }

    unsafe extern "C" fn drop_probe(context: *mut c_void) {
        // SAFETY: `context` is the boxed `ProbeContext` this callback was
        // registered with, and the drop entry runs once.
        let context = unsafe { Box::from_raw(context.cast::<ProbeContext>()) };
        context.drops.set(context.drops.get() + 1);
    }

    fn foreign_probe(
        proposals: Rc<RefCell<Vec<ProposalSize>>>,
        drops: Rc<Cell<usize>>,
    ) -> WuiSubView {
        WuiSubView {
            context: Box::into_raw(Box::new(ProbeContext { proposals, drops })).cast(),
            vtable: WuiSubViewVTable {
                measure: measure_probe,
                drop: drop_probe,
            },
            stretch_axis: WuiStretchAxis::Both,
            priority: 7,
        }
    }

    const WIDTH_EXTENTS: [(Option<f32>, f32); 4] = [
        (None, 24.0),
        (Some(0.0), 8.0),
        (Some(48.0), 48.0),
        (Some(f32::INFINITY), 96.0),
    ];
    const HEIGHT_EXTENTS: [(Option<f32>, f32); 4] = [
        (None, 36.0),
        (Some(0.0), 12.0),
        (Some(48.0), 48.0),
        (Some(f32::INFINITY), 144.0),
    ];

    fn expected_extent(table: [(Option<f32>, f32); 4], probe: Option<f32>) -> f32 {
        table
            .into_iter()
            .find_map(|(proposal, extent)| (proposal == probe).then_some(extent))
            .expect("the tables cover every `proposal_cases` entry")
    }

    #[test]
    fn layout_measure_preserves_probes_through_foreign_callbacks() {
        for width in proposal_cases() {
            for height in proposal_cases() {
                let proposal = ProposalSize::new(width, height);
                let expected_size = Size::new(
                    expected_extent(WIDTH_EXTENTS, width),
                    expected_extent(HEIGHT_EXTENTS, height),
                );
                let direct = measure_layout(&FrameLayout::default(), proposal, &[&ProbeView]);
                let proposals = Rc::new(RefCell::new(Vec::new()));
                let drops = Rc::new(Cell::new(0));
                with_layout(
                    FrameLayout::default(),
                    // SAFETY: the harness hands the closure a pointer to the live
                    // layout handle it just built; each `WuiArray` is an owning
                    // handle the FFI call consumes once, and each returned FFI
                    // value is decoded once and never observed again.
                    |layout| unsafe {
                        let measured = waterui_layout_measure(
                            layout,
                            proposal.into_ffi(),
                            WuiArray::new(vec![foreign_probe(
                                Rc::clone(&proposals),
                                Rc::clone(&drops),
                            )]),
                        )
                        .into_rust();
                        assert_eq!(measured.size, expected_size);
                        assert_eq!(measured.size, direct.size);
                        assert_eq!(
                            measured.explicit_horizontal(HorizontalAlignment::Leading),
                            Some(3.0)
                        );
                        assert_eq!(
                            measured.explicit_vertical(VerticalAlignment::FirstBaseline),
                            Some(5.0)
                        );
                        assert_eq!(proposals.borrow().first(), Some(&proposal));
                        assert_eq!(drops.get(), 1);

                        let bounds = Rect::new(Point::new(13.0, -9.0), expected_size);
                        let placed = waterui_layout_place_subviews(
                            layout,
                            bounds.into_ffi(),
                            proposal.into_ffi(),
                            WuiArray::new(vec![foreign_probe(
                                Rc::clone(&proposals),
                                Rc::clone(&drops),
                            )]),
                        );
                        let rects: Vec<Rect> = placed
                            .as_slice()
                            .iter()
                            .map(|placement| {
                                let frame = &placement.frame;
                                Rect::new(
                                    Point::new(frame.origin.x, frame.origin.y),
                                    Size::new(frame.size.width, frame.size.height),
                                )
                            })
                            .collect();
                        for placement in placed.as_slice() {
                            // SAFETY: `placement.proposal` is the FFI mirror this
                            // very call produced; decoding it here is the
                            // `into_rust` contract.
                            let returned = placement.proposal.clone().into_rust();
                            assert_eq!(returned, proposal);
                        }
                        placed.consume();
                        assert_eq!(rects, vec![bounds]);
                        let direct: Vec<Rect> = FrameLayout::default()
                            .place(bounds, proposal, &[&ProbeView])
                            .into_iter()
                            .map(|placement| placement.frame)
                            .collect();
                        assert_eq!(rects, direct);
                        assert_eq!(drops.get(), 2);
                    },
                );
            }
        }
    }

    #[test]
    fn foreign_subview_preserves_metadata_and_measurement() {
        let proposals = Rc::new(RefCell::new(Vec::new()));
        let drops = Rc::new(Cell::new(0));
        {
            let subview = foreign_probe(Rc::clone(&proposals), Rc::clone(&drops));
            assert_eq!(subview.priority(), 7);
            assert_eq!(subview.stretch_axis(), StretchAxis::Both);
            let proposal = ProposalSize::new(Some(f32::INFINITY), None);
            let measured = subview.measure(proposal);
            assert_eq!(measured.size, Size::new(96.0, 36.0));
            assert_eq!(
                measured.explicit_horizontal(HorizontalAlignment::Leading),
                Some(3.0)
            );
            assert_eq!(
                measured.explicit_vertical(VerticalAlignment::FirstBaseline),
                Some(5.0)
            );
            assert_eq!(proposals.borrow().first(), Some(&proposal));
        }
        assert_eq!(drops.get(), 1);
    }
}