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
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
//! Compositing, 3D, and the rest of the gesture family.

use super::*;
use crate::abi;
use crate::resolve;
use core::ffi::c_void;
use crate::mangle::{self, swift_type};
mangle::modifier_types! {
    /// `.onChange(of:initial:_:)` over an `Int` adds two modifiers; these
    /// compose as `ModifiedContent<ModifiedContent<Receiver, inner>, outer>`.
    pub(crate) ON_CHANGE_INNER_T = ty("_ValueActionModifier2").of(vec![Type::Verbatim("Si".into())]);
    /// Watching a `String`.
    pub(crate) ON_CHANGE_STR_T = ty("_ValueActionModifier2").of(vec![Type::Verbatim("SS".into())]);
    /// Watching a `Bool`.
    pub(crate) ON_CHANGE_BOOL_T = ty("_ValueActionModifier2").of(vec![Type::Verbatim("Sb".into())]);
    /// Watching a `Double`.
    pub(crate) ON_CHANGE_F64_T = ty("_ValueActionModifier2").of(vec![Type::Verbatim("Sd".into())]);
    /// The outer half of `.onChange(of:initial:_:)`.
    pub(crate) ON_CHANGE_OUTER_T = ty("_AppearanceActionModifier");
}
mangle::modifier_types! {
    /// `ModifiedContent<AnyView, _ClipEffect<Rectangle>>`
    pub(crate) CLIPPED_T = ty("_ClipEffect").of(vec![ty("Rectangle")]);
    /// `ModifiedContent<AnyView, _CompositingGroupEffect>`
    pub(crate) COMPOSITING_T = ty("_CompositingGroupEffect");
    /// `ModifiedContent<AnyView, _DrawingGroupEffect>`
    pub(crate) DRAWING_GROUP_T = ty("_DrawingGroupEffect");
    /// `ModifiedContent<AnyView, _Rotation3DEffect>`
    pub(crate) ROTATION3D_T = ty("_Rotation3DEffect");
    /// `ModifiedContent<AnyView, AddGestureModifier<DragGesture, DefaultGestureCombiner>>`
    pub(crate) DRAG_T = ty("AddGestureModifier").of(vec![ty("DragGesture"), ty("DefaultGestureCombiner")]);
    /// `ModifiedContent<AnyView, AddGestureModifier<MagnifyGesture, DefaultGestureCombiner>>`
    pub(crate) MAGNIFY_T = ty("AddGestureModifier").of(vec![ty("MagnifyGesture"), ty("DefaultGestureCombiner")]);
    /// `ModifiedContent<AnyView, AddGestureModifier<RotateGesture, DefaultGestureCombiner>>`
    pub(crate) ROTATE_T = ty("AddGestureModifier").of(vec![ty("RotateGesture"), ty("DefaultGestureCombiner")]);
    /// `.popover(isPresented:content:)`
    /// `ModifiedContent<AnyView, PopoverPresentationModifier<PopoverConditionalStateProvider<AnyView>>>`
    pub(crate) POPOVER_T = ty("PopoverPresentationModifier").of(vec![ty("PopoverConditionalStateProvider").of(vec![ty("AnyView")])]);
}







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

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

/// Apply `.drawingGroup()` — render the subtree offscreen through Metal.
pub fn drawing_group(view: &ViewHandle) -> ViewHandle {
    unsafe {
        let (_, _, size) = DRAWING_GROUP_T.applied_to(view.meta);
        // `ColorRenderingMode` is a resilient enum, so it is address-only and
        // passed by pointer rather than by value.
        let mut mode = [0u8]; // .nonLinear
        let r = abi::call_modifier(resolve::drawing_group_fn(), view.value_ptr(), view.meta, view.wt,
            &[0, mode.as_mut_ptr() as u64],
            [0.0; 4],
            size,
        );
        wrap_modified(r, &DRAWING_GROUP_T, view)
    }
}

/// Apply `.rotation3DEffect(_:axis:)`.
pub fn rotation_3d(view: &ViewHandle, degrees: f64, ax: f64, ay: f64, az: f64) -> ViewHandle {
    unsafe {
        let (_, _, size) = ROTATION3D_T.applied_to(view.meta);
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        let radians = degrees * std::f64::consts::PI / 180.0;
        let (anchor_x, anchor_y) = (0.5f64, 0.5f64);
        // rotation3DEffect(_:axis:anchor:anchorZ:perspective:)
        //   every argument is a CGFloat or an Angle, so they all travel in
        //   d0-d7: angle, axis x/y/z, anchor x/y, anchorZ, perspective
        core::arch::asm!("blr {f}", f = in(reg) resolve::rotation3d_fn(),
            in("d0") radians,
            in("d1") ax, in("d2") ay, in("d3") az,
            in("d4") anchor_x, in("d5") anchor_y,
            in("d6") 0.0f64, in("d7") 1.0f64,
            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"),
        );
        wrap_modified(result, &ROTATION3D_T, view)
    }
}

/// Attach a gesture value that is already built.
pub(crate) unsafe fn attach_gesture(
    view: &ViewHandle,
    gesture: &mut [u8],
    g_meta: *const c_void,
    modifier: &ModifierType,
) -> ViewHandle {
    unsafe {
        let g_wt = abi::get_view_wt_for_proto(g_meta, resolve::gesture_proto());
        assert!(!g_wt.is_null(), "gesture type: Gesture");
        let (_, _, size) = modifier.applied_to(view.meta);
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        core::arch::asm!("blr {f}", f = in(reg) resolve::gesture_fn(),
            in("x0") gesture.as_mut_ptr(),
            in("x1") 3u64, // GestureMask.all
            in("x2") view.meta,
            in("x3") g_meta,
            in("x4") view.wt,
            in("x5") g_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)
    }
}

/// Attach a `DragGesture`.
pub fn drag_gesture(view: &ViewHandle, minimum_distance: f64) -> ViewHandle {
    unsafe {
        let g_meta = abi::metadata0(resolve::drag_gesture_ma());
        let space_meta = abi::metadata0(resolve::local_space_ma());
        let mut gesture = vec![0u8; abi::type_bytes(g_meta)];
        // DragGesture.init<C: CoordinateSpaceProtocol>(minimumDistance:coordinateSpace:)
        //   d0 = distance, x0 = @in C (LocalCoordinateSpace is zero-size),
        //   x1 = C.Type, x2 = C: CoordinateSpaceProtocol WT, x8 = @out
        let mut space = [0u8; 8];
        core::arch::asm!("blr {f}", f = in(reg) resolve::drag_gesture_init(),
            in("d0") minimum_distance,
            in("x0") space.as_mut_ptr(),
            in("x1") space_meta,
            in("x2") resolve::local_space_wt(),
            in("x8") gesture.as_mut_ptr(),
            in("x20") g_meta,
            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"),
        );
        attach_gesture(view, &mut gesture, g_meta, &DRAG_T)
    }
}

/// Attach a `DragGesture` with an `onEnded` handler.
///
/// [`drag_gesture`] attaches a bare `DragGesture` with nothing listening, which
/// builds the same value Swift would but can never be seen to fire. This wires
/// the action SwiftUI calls when the drag ends, so the gesture is observable.
///
/// The result type is taken from `.gesture`'s opaque-result-type descriptor
/// rather than a hand-written mangling: the type is
/// `ModifiedContent<AnyView, AddGestureModifier<_EndedGesture<DragGesture>, _>>`,
/// and spelling that out by hand is how earlier bindings resolved to null.
pub fn on_drag_gesture(view: &ViewHandle, minimum_distance: f64, action: impl Fn() + 'static) -> ViewHandle {
    unsafe {
        drag_ended(
            view,
            minimum_distance,
            invoke_value_action,
            boxed_ctx(Box::new(action) as Box<dyn Fn()>),
        )
    }
}

/// The same, with the value SwiftUI delivered.
///
/// [`on_drag_gesture`]'s handler is told only *that* a drag ended. This one is
/// told where it started, where it finished and how fast it was going — see
/// [`DragValue`].
pub fn on_drag_ended_value(
    view: &ViewHandle,
    minimum_distance: f64,
    action: impl Fn(DragValue) + 'static,
) -> ViewHandle {
    unsafe {
        drag_ended(
            view,
            minimum_distance,
            invoke_drag_value,
            boxed_ctx(Box::new(action) as Box<dyn Fn(DragValue)>),
        )
    }
}

/// Build the gesture and attach it — the part both handlers share.
///
/// # Safety
/// `payload` must be what `body` expects.
unsafe fn drag_ended(
    view: &ViewHandle,
    minimum_distance: f64,
    body: unsafe extern "C" fn(*const u8, *mut c_void),
    payload: *mut c_void,
) -> ViewHandle {
    unsafe {
        let g_meta = abi::metadata0(resolve::drag_gesture_ma());
        let space_meta = abi::metadata0(resolve::local_space_ma());
        let mut gesture = vec![0u8; abi::type_bytes(g_meta)];
        let mut space = [0u8; 8];
        core::arch::asm!("blr {f}", f = in(reg) resolve::drag_gesture_init(),
            in("d0") minimum_distance,
            in("x0") space.as_mut_ptr(),
            in("x1") space_meta,
            in("x2") resolve::local_space_wt(),
            in("x8") gesture.as_mut_ptr(),
            in("x20") g_meta,
            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"),
        );
        gesture_ended(view, &mut gesture, g_meta, body, payload)
    }
}

/// Wrap any built gesture in `.onEnded(_:)` and attach it.
///
/// Nothing below is drag-specific: `Gesture.onEnded` is an extension on the
/// protocol, `_EndedGesture` takes whatever gesture it is given, and the result
/// type comes from `.gesture`'s own opaque-result-type descriptor. So magnify
/// and rotate get handlers by handing their gesture to this — they had none at
/// all, which made them the only gestures the DSL could attach but never hear
/// from.
///
/// # Safety
/// `gesture` must be a live value of type `g_meta`, and `payload` what `body`
/// expects.
pub(crate) unsafe fn gesture_ended(
    view: &ViewHandle,
    gesture: &mut [u8],
    g_meta: *const c_void,
    body: unsafe extern "C" fn(*const u8, *mut c_void),
    payload: *mut c_void,
) -> ViewHandle {
    unsafe {
        let g_wt = abi::get_view_wt_for_proto(g_meta, resolve::gesture_proto());
        assert!(!g_wt.is_null(), "gesture type: Gesture");

        // `_EndedGesture<Content: Gesture>`: one generic parameter and one
        // conformance requirement, so the accessor takes two key arguments.
        let ended_meta =
            abi::generic_metadata2(resolve::ended_gesture_ma(), g_meta, g_wt);
        let mut ended = vec![0u8; abi::type_bytes(ended_meta)];

        // The handler takes `DragGesture.Value` by pointer and returns nothing,
        // which is exactly the shape `value_closure_thunk` was written for.
        let ctx = Box::leak(Box::new(abi::ValueClosureCtx::new(body, payload)))
            as *mut abi::ValueClosureCtx;

        // Gesture.onEnded(_:) — x0/x1 = closure, x2 = Self.Type,
        // x3 = Self: Gesture WT, x8 = @out, x20 = @in_guaranteed self.
        core::arch::asm!("blr {f}", f = in(reg) resolve::gesture_on_ended(),
            in("x0") abi::value_closure_thunk as *const () as u64,
            in("x1") ctx as u64,
            in("x2") g_meta,
            in("x3") g_wt,
            in("x8") ended.as_mut_ptr(),
            in("x20") gesture.as_mut_ptr(),
            lateout("x4") _, lateout("x5") _, lateout("x6") _, lateout("x7") _,
            lateout("x9") _, lateout("x10") _, lateout("x11") _, lateout("x12") _,
            lateout("x13") _, lateout("x14") _, lateout("x15") _, lateout("x16") _,
            lateout("x17") _, lateout("lr") _, lateout("x21") _, clobber_abi("C"),
        );

        let ended_wt = abi::get_view_wt_for_proto(ended_meta, resolve::gesture_proto());
        assert!(!ended_wt.is_null(), "_EndedGesture<G>: Gesture");

        let subst = [
            view.meta,
            ended_meta,
            view.wt,
            ended_wt,
        ];
        let (meta, wt, size) = opaque_result_type(resolve::gesture_oret(), &subst);
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        core::arch::asm!("blr {f}", f = in(reg) resolve::gesture_fn(),
            in("x0") ended.as_mut_ptr(),
            in("x1") 3u64, // GestureMask.all
            in("x2") view.meta,
            in("x3") ended_meta,
            in("x4") view.wt,
            in("x5") ended_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_owned(result, meta, wt)
    }
}

/// Body for a `(Value) -> ()` handler that ignores the value.
pub(crate) unsafe extern "C" fn invoke_value_action(_value: *const u8, payload: *mut c_void) {
    let action = unsafe { boxed_ref::<dyn Fn()>(payload) };
    action();
}

/// Attach a `MagnifyGesture`.
pub fn magnify_gesture(view: &ViewHandle, minimum_scale_delta: f64) -> ViewHandle {
    unsafe {
        let g_meta = abi::metadata0(resolve::magnify_gesture_ma());
        let mut gesture = vec![0u8; abi::type_bytes(g_meta)];
        core::arch::asm!("blr {f}", f = in(reg) resolve::magnify_gesture_init(),
            in("d0") minimum_scale_delta,
            in("x8") gesture.as_mut_ptr(),
            in("x20") g_meta,
            lateout("x0") _, lateout("x1") _, 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"),
        );
        attach_gesture(view, &mut gesture, g_meta, &MAGNIFY_T)
    }
}

/// Attach a `RotateGesture`. The minimum delta is an `Angle`, i.e. radians.
pub fn rotate_gesture(view: &ViewHandle, minimum_degrees: f64) -> ViewHandle {
    unsafe {
        let g_meta = abi::metadata0(resolve::rotate_gesture_ma());
        let mut gesture = vec![0u8; abi::type_bytes(g_meta)];
        let radians = minimum_degrees * std::f64::consts::PI / 180.0;
        core::arch::asm!("blr {f}", f = in(reg) resolve::rotate_gesture_init(),
            in("d0") radians,
            in("x8") gesture.as_mut_ptr(),
            in("x20") g_meta,
            lateout("x0") _, lateout("x1") _, 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"),
        );
        attach_gesture(view, &mut gesture, g_meta, &ROTATE_T)
    }
}



/// The Rust side of an `onChange` handler.
pub(crate) type ChangeHandler = Box<dyn Fn(i64, i64)>;

pub(crate) unsafe extern "C" fn invoke_change(old: *const u8, new: *const u8, payload: *mut c_void) {
    let handler = unsafe { &*(payload as *const ChangeHandler) };
    unsafe { handler(*(old as *const i64), *(new as *const i64)) };
}

/// Apply `.onChange(of:initial:_:)`, watching an `Int`.
///
/// The handler is called with the old and new values. It is leaked, since
/// SwiftUI holds it for the lifetime of the view.
pub fn on_change(
    view: &ViewHandle,
    value: i64,
    handler: impl Fn(i64, i64) + 'static,
) -> ViewHandle {
    unsafe {
        let mut v = value;
        on_change_of(
            view,
            (&raw mut v).cast(),
            resolve::int_meta(),
            &ON_CHANGE_INNER_T,
            invoke_change,
            boxed_ctx(Box::new(handler) as Box<dyn Fn(i64, i64)>),
        )
    }
}

/// Apply `.onChange(of:initial:_:)`, watching a `String`.
///
/// `onChange` is one of the modifiers an application reaches for most, and it
/// could only ever watch an `Int` — a search field, a selected identifier, a
/// mode name all had to be turned into a number first. `V` is constrained to
/// `Equatable` and nothing else, so anything with a witness can be watched;
/// these are the three the standard library exports one for besides `Int`.
pub fn on_change_str(
    view: &ViewHandle,
    value: &str,
    handler: impl Fn(String, String) + 'static,
) -> ViewHandle {
    unsafe {
        // `of:` is `@in V`, which is *consumed* — the callee takes ownership,
        // so the string is handed over and not dropped here.
        let mut v = abi::swift_string(value);
        on_change_of(
            view,
            v.as_mut_ptr(),
            resolve::string_meta(),
            &ON_CHANGE_STR_T,
            invoke_change_str,
            boxed_ctx(Box::new(handler) as Box<dyn Fn(String, String)>),
        )
    }
}

/// Apply `.onChange(of:initial:_:)`, watching a `Bool`.
pub fn on_change_bool(
    view: &ViewHandle,
    value: bool,
    handler: impl Fn(bool, bool) + 'static,
) -> ViewHandle {
    unsafe {
        let mut v = u8::from(value);
        on_change_of(
            view,
            &raw mut v,
            resolve::bool_meta(),
            &ON_CHANGE_BOOL_T,
            invoke_change_bool,
            boxed_ctx(Box::new(handler) as Box<dyn Fn(bool, bool)>),
        )
    }
}

/// Apply `.onChange(of:initial:_:)`, watching a `Double`.
pub fn on_change_f64(
    view: &ViewHandle,
    value: f64,
    handler: impl Fn(f64, f64) + 'static,
) -> ViewHandle {
    unsafe {
        let mut v = value;
        on_change_of(
            view,
            (&raw mut v).cast(),
            resolve::double_meta(),
            &ON_CHANGE_F64_T,
            invoke_change_f64,
            boxed_ctx(Box::new(handler) as Box<dyn Fn(f64, f64)>),
        )
    }
}

pub(crate) unsafe extern "C" fn invoke_change_str(
    old: *const u8,
    new: *const u8,
    payload: *mut c_void,
) {
    unsafe {
        let f = boxed_ref::<dyn Fn(String, String)>(payload);
        let read = |p: *const u8| {
            let mut b = [0u8; 16];
            b.copy_from_slice(core::slice::from_raw_parts(p, 16));
            // A borrowed read: both strings belong to SwiftUI for the duration
            // of the call, so this copies out rather than taking ownership.
            abi::read_swift_string(b)
        };
        f(read(old), read(new));
    }
}

pub(crate) unsafe extern "C" fn invoke_change_bool(
    old: *const u8,
    new: *const u8,
    payload: *mut c_void,
) {
    unsafe {
        let f = boxed_ref::<dyn Fn(bool, bool)>(payload);
        f(*old & 1 != 0, *new & 1 != 0);
    }
}

pub(crate) unsafe extern "C" fn invoke_change_f64(
    old: *const u8,
    new: *const u8,
    payload: *mut c_void,
) {
    unsafe {
        let f = boxed_ref::<dyn Fn(f64, f64)>(payload);
        f(*(old as *const f64), *(new as *const f64));
    }
}

/// The half of `onChange` that does not depend on what is being watched.
///
/// `onChange<V: Equatable>` is generic, so everything type-specific is a
/// register: the value's address, its metadata, and the mangled name of the
/// `_ValueActionModifier2<V>` the result nests in.
///
/// # Safety
/// `value` must point at a live value of type `meta`, which the call consumes;
/// `inner` must be `_ValueActionModifier2` over that same type; and `payload`
/// must be what `body` expects.
unsafe fn on_change_of(
    view: &ViewHandle,
    value: *mut u8,
    meta: *const c_void,
    inner: &ModifierType,
    body: unsafe extern "C" fn(*const u8, *const u8, *mut c_void),
    payload: *mut c_void,
) -> ViewHandle {
    unsafe {
        let ctx = Box::leak(Box::new(abi::PairClosureCtx::new(body, payload)))
            as *mut abi::PairClosureCtx;

        let eq_wt = abi::get_view_wt_for_proto(meta, resolve::equatable_proto());
        assert!(!eq_wt.is_null(), "{}: Equatable", crate::diag::type_name(meta));

        let (inner_m, _, _) = inner.applied_to(view.meta);
        let (_, _, size) = ON_CHANGE_OUTER_T.applied_to(inner_m);
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        // onChange<V: Equatable>(of: V, initial: Bool, _: (V, V) -> ())
        //   x0 = @in V, x1 = initial, x2 = closure fn, x3 = closure ctx,
        //   x4 = Self.Type, x5 = V.Type, x6 = Self: View WT,
        //   x7 = V: Equatable WT, x8 = @out, x20 = self
        core::arch::asm!("blr {f}", f = in(reg) resolve::on_change_fn(),
            in("x0") value,
            in("x1") 0u64,
            in("x2") abi::pair_closure_thunk as *const c_void,
            in("x3") ctx,
            in("x4") view.meta,
            in("x5") meta,
            in("x6") view.wt,
            in("x7") eq_wt,
            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"),
        );
        // `onChange` adds two modifiers, so the result nests twice: the
        // value-action modifier over the receiver, then the appearance-action
        // modifier over that.
        let (nested, _, _) = inner.applied_to(view.meta);
        let (meta, wt, _) = ON_CHANGE_OUTER_T.applied_to(nested);
        wrap_owned(result, meta, wt)
    }
}



/// Apply `.popover(isPresented:content:)`.
///
/// The public `popover` is fully inlined — it has a symbol but nothing ever
/// calls it — so this goes through `popoverCore`, which is what Swift itself
/// ends up calling.
/// Shared tail of `popover` and `popover_bound`.
///
/// # Safety
/// `binding` must be a `Binding<Bool>`.
pub(crate) unsafe fn popover_with_binding(
    view: &ViewHandle,
    content: &ViewHandle,
    binding: &[u8],
) -> ViewHandle {
    unsafe {
        let b0 = u64::from_le_bytes(binding[0..8].try_into().unwrap());
        let b1 = u64::from_le_bytes(binding[8..16].try_into().unwrap());
        let b2 = binding[16] as u64;

        // PopoverAttachmentAnchor.rect(.bounds): the Source is one word, the
        // enum pads to sixteen and carries its tag in the seventeenth byte,
        // where `.rect` is case 0.
        let anchor_meta = abi::metadata0(resolve::popover_anchor_ma());
        let mut anchor = vec![0u8; abi::type_bytes(anchor_meta)];
        let source: u64;
        core::arch::asm!("blr {f}", f = in(reg) resolve::anchor_source_bounds(),
            lateout("x0") source,
            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"),
        );
        anchor[..8].copy_from_slice(&source.to_le_bytes());

        let ctx = Box::leak(Box::new(abi::ClosureCtx::new(
            emit_tuple,
            // `POPOVER_T` names
            // `PopoverPresentationModifier<PopoverConditionalStateProvider<AnyView>>`:
            // the content's type is part of the modifier's own name, so the
            // child stays erased until that name is composed per content.
            Child::leak(content, Content::Erased),
        ))) as *mut abi::ClosureCtx;

        let (_, _, size) = POPOVER_T.applied_to(view.meta);
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        // popoverCore(isPresented:attachmentAnchor:arrowEdges:isDetachable:content:)
        //   x0-x2 = Binding<Bool>, x3 = @in anchor,
        //   x4 = Edge.Set? (nil is 0x0100 — value then tag),
        //   x5 = isDetachable, x6 = content fn, x7 = content ctx,
        //   [sp] = Self.Type, [sp+8] = C.Type,
        //   [sp+16] = Self: View WT, [sp+24] = C: View WT
        core::arch::asm!(
            "sub sp, sp, #32",
            "stp {sm}, {cm}, [sp]",
            "stp {sw}, {cw}, [sp, #16]",
            "blr {f}",
            "add sp, sp, #32",
            f = in(reg) resolve::popover_core_fn(),
            sm = in(reg) view.meta,
            cm = in(reg) resolve::anyview_meta(),
            sw = in(reg) view.wt,
            cw = in(reg) resolve::anyview_wt(),
            in("x0") b0, in("x1") b1, in("x2") b2,
            in("x3") anchor.as_mut_ptr(),
            in("x4") 0x0100u64,
            in("x5") 0u64,
            in("x6") abi::swift_closure_thunk as *const c_void,
            in("x7") ctx,
            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_modified(result, &POPOVER_T, view)
    }
}

/// `popover` with a fixed flag. It cannot be dismissed: SwiftUI treats a
/// `Binding.constant` as read-only, so the presentation has no way to write
/// `false` back. Use [`popover_bound`] for one the user can close.
pub fn popover(view: &ViewHandle, content: &ViewHandle, presented: bool) -> ViewHandle {
    unsafe {
        let binding = constant_binding(
            &[u8::from(presented)],
            resolve::bool_meta(),
            mangle::bound(&swift_type!(SwiftUI.Binding), &[mangle::BOOL]).as_bytes(),
        );
        popover_with_binding(view, content, &binding)
    }
}

/// `popover` bound to Rust state, so dismissing it writes `false` back.
pub fn popover_bound(view: &ViewHandle, content: &ViewHandle, state: &BoundState<bool>) -> ViewHandle {
    unsafe {
        let binding = bool_binding_of(state);
        popover_with_binding(view, content, &binding)
    }
}


// ── What a drag delivered ───────────────────────────────────────────────────

/// A `DragGesture.Value`, read out of the struct SwiftUI hands the handler.
///
/// `on_drag_gesture` used to throw this away — the handler was `() -> ()` and
/// the value went into `invoke_value_action`, which ignores its argument. A
/// drag handler that cannot see where the drag went is not much of a drag
/// handler: it can tell you that something was dragged and nothing else.
///
/// The fields come from the struct's own layout rather than from accessors,
/// because SwiftUI exports exactly one — `translation` — and none of the
/// others:
///
/// ```text
///   +0   time           Date            (seconds from the 2001 epoch)
///   +8   location       CGPoint
///   +24  startLocation  CGPoint
///   +40  _velocity      _Velocity<CGSize>
///   +56  platform       (empty)
/// ```
///
/// That layout is read from the metadata at run time rather than trusted: a
/// field added in front of `location` in a later SwiftUI would otherwise turn
/// every drag into silent nonsense. If the shape is not the five fields above,
/// the reader hands back zeroes rather than reading somewhere it should not.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DragValue {
    /// Where the drag is now, in the gesture's coordinate space.
    pub location: (f64, f64),
    /// Where it began.
    pub start_location: (f64, f64),
    /// How fast it was moving, in points per second.
    ///
    /// `_Velocity<CGSize>` wraps a single `CGSize` and nothing else — checked
    /// by following the field record's symbolic reference to the descriptor,
    /// which reports one stored field — so the two doubles at the field's own
    /// offset are the velocity, with no wrapper to step over.
    pub velocity: (f64, f64),
    /// Seconds since Apple's reference date (1 January 2001), which is what a
    /// `Date` stores. Useful for comparing two values, not as a wall clock.
    pub time: f64,
}

impl DragValue {
    /// `location - startLocation`, which is what Swift's `translation`
    /// computes. Cross-checked against SwiftUI's own getter in the tests.
    pub fn translation(&self) -> (f64, f64) {
        (self.location.0 - self.start_location.0, self.location.1 - self.start_location.1)
    }
}

/// The offsets of `DragGesture.Value`'s stored fields, from its metadata.
///
/// Read rather than hardcoded: this is a resilient struct in a system
/// framework, and a field added in front of `location` would otherwise turn
/// every drag into silent nonsense. Five fields at these offsets is what this
/// build of SwiftUI has; a different shape returns `None` and the reader hands
/// back zeroes rather than reading somewhere it should not.
fn drag_value_offsets() -> Option<&'static [usize; 4]> {
    static CACHE: std::sync::OnceLock<Option<[usize; 4]>> = std::sync::OnceLock::new();
    CACHE
        .get_or_init(|| unsafe {
            let meta = abi::metadata0(resolve::drag_value_ma());
            let offs = abi::struct_field_offsets(meta)?;
            // time, location, startLocation, _velocity, platform.
            if offs.len() != 5 {
                return None;
            }
            Some([offs[0], offs[1], offs[2], offs[3]])
        })
        .as_ref()
}

/// Read the value at `p`, which SwiftUI passed by address.
///
/// # Safety
/// `p` must point at a live `DragGesture.Value`.
pub(crate) unsafe fn read_drag_value(p: *const u8) -> DragValue {
    let Some(&[time, location, start, velocity]) = drag_value_offsets() else {
        return DragValue {
            location: (0.0, 0.0),
            start_location: (0.0, 0.0),
            velocity: (0.0, 0.0),
            time: 0.0,
        };
    };
    unsafe {
        let point = |at: usize| {
            let f = p.add(at) as *const f64;
            (*f, *f.add(1))
        };
        let v = DragValue {
            time: *(p.add(time) as *const f64),
            location: point(location),
            start_location: point(start),
            velocity: point(velocity),
        };
        debug_assert_eq!(
            v.translation(),
            swift_translation(p),
            "computed translation disagrees with SwiftUI's own getter — the \
             field offsets have moved"
        );
        v
    }
}

/// What SwiftUI's own `translation` getter says, for checking against
/// [`DragValue::translation`].
///
/// Only the one accessor is exported: `velocity`, `predictedEndLocation` and
/// `predictedEndTranslation` resolve to nothing, so they are computed here or
/// not at all. This is the one crosscheck available, and it covers `location`
/// and `startLocation` between them — which are the fields a wrong offset
/// would corrupt.
///
/// # Safety
/// `p` must point at a live `DragGesture.Value`.
unsafe fn swift_translation(p: *const u8) -> (f64, f64) {
    unsafe {
        let (w, h): (f64, f64);
        // A getter on a 56-byte struct: self is `@in_guaranteed` in x20, and
        // `CGSize` comes back in d0/d1.
        core::arch::asm!("blr {f}", f = in(reg) resolve::drag_value_translation(),
            in("x20") p,
            lateout("d0") w, lateout("d1") h,
            lateout("x0") _, lateout("x1") _, 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"),
        );
        (w, h)
    }
}

/// Body for a `(DragGesture.Value) -> ()` handler that reads the value.
pub(crate) unsafe extern "C" fn invoke_drag_value(value: *const u8, payload: *mut c_void) {
    let f = unsafe { boxed_ref::<dyn Fn(DragValue)>(payload) };
    f(unsafe { read_drag_value(value) });
}

// ── What a magnify or a rotate delivered ────────────────────────────────────

/// A `MagnifyGesture.Value`.
///
/// `magnify_gesture` attaches the gesture and listens to nothing — it was the
/// only kind of gesture the DSL could add but never hear from. The layout is
/// the same shape as the drag's and read the same way:
///
/// ```text
///   +0   time           Date
///   +8   magnification  CGFloat
///   +16  velocity       CGFloat
///   +24  startAnchor    UnitPoint
///   +40  startLocation  CGPoint
///   +56  platform       (empty)
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MagnifyValue {
    /// How far the pinch has scaled, as a multiplier — 1.0 is no change.
    pub magnification: f64,
    /// How fast it is scaling, in multiples per second.
    pub velocity: f64,
    /// Where the pinch is centred, in unit space — (0.5, 0.5) is the middle.
    pub start_anchor: (f64, f64),
    /// Where it began, in the gesture's coordinate space.
    pub start_location: (f64, f64),
    /// Seconds since Apple's reference date.
    pub time: f64,
}

/// A `RotateGesture.Value`.
///
/// The same layout as [`MagnifyValue`] with `rotation`/`velocity` as `Angle`,
/// which stores radians and nothing else.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RotateValue {
    /// How far it has turned, in radians. `Angle` stores radians; the degrees
    /// are computed, so the conversion is here rather than through an accessor.
    pub radians: f64,
    /// How fast it is turning, in radians per second.
    pub velocity: f64,
    /// Where the rotation is centred, in unit space.
    pub start_anchor: (f64, f64),
    /// Where it began, in the gesture's coordinate space.
    pub start_location: (f64, f64),
    /// Seconds since Apple's reference date.
    pub time: f64,
}

impl RotateValue {
    /// The rotation in degrees, which is what `Angle.degrees` reports.
    pub fn degrees(&self) -> f64 {
        self.radians.to_degrees()
    }
}

/// The offsets shared by `MagnifyGesture.Value` and `RotateGesture.Value`.
///
/// Both are six fields at 0, 8, 16, 24, 40, 56 in this build of SwiftUI, read
/// from the metadata for the same reason the drag's are: a field inserted in
/// front of `magnification` would otherwise be read as the magnification.
fn pinch_value_offsets(accessor: *const c_void) -> Option<[usize; 5]> {
    unsafe {
        let offs = abi::struct_field_offsets(abi::metadata0(accessor))?;
        // time, amount, velocity, startAnchor, startLocation, platform.
        if offs.len() != 6 {
            return None;
        }
        Some([offs[0], offs[1], offs[2], offs[3], offs[4]])
    }
}

/// Read the five readable fields, which both gestures share.
///
/// # Safety
/// `p` must point at a live value of the type `accessor` names.
unsafe fn read_pinch_value(p: *const u8, accessor: *const c_void) -> [f64; 7] {
    let Some([time, amount, velocity, anchor, start]) = pinch_value_offsets(accessor) else {
        return [0.0; 7];
    };
    unsafe {
        let at = |o: usize| *(p.add(o) as *const f64);
        let pair = |o: usize| (at(o), at(o + 8));
        let (ax, ay) = pair(anchor);
        let (sx, sy) = pair(start);
        [at(amount), at(velocity), ax, ay, sx, sy, at(time)]
    }
}

/// Body for a `(MagnifyGesture.Value) -> ()` handler.
unsafe extern "C" fn invoke_magnify_value(value: *const u8, payload: *mut c_void) {
    let f = unsafe { boxed_ref::<dyn Fn(MagnifyValue)>(payload) };
    let v = unsafe { read_pinch_value(value, resolve::magnify_value_ma()) };
    f(MagnifyValue {
        magnification: v[0],
        velocity: v[1],
        start_anchor: (v[2], v[3]),
        start_location: (v[4], v[5]),
        time: v[6],
    });
}

/// Body for a `(RotateGesture.Value) -> ()` handler.
unsafe extern "C" fn invoke_rotate_value(value: *const u8, payload: *mut c_void) {
    let f = unsafe { boxed_ref::<dyn Fn(RotateValue)>(payload) };
    let v = unsafe { read_pinch_value(value, resolve::rotate_value_ma()) };
    f(RotateValue {
        radians: v[0],
        velocity: v[1],
        start_anchor: (v[2], v[3]),
        start_location: (v[4], v[5]),
        time: v[6],
    });
}

/// Attach a `MagnifyGesture` with an `onEnded` handler.
pub fn on_magnify_ended(
    view: &ViewHandle,
    minimum_scale_delta: f64,
    action: impl Fn(MagnifyValue) + 'static,
) -> ViewHandle {
    unsafe {
        let g_meta = abi::metadata0(resolve::magnify_gesture_ma());
        let mut gesture = vec![0u8; abi::type_bytes(g_meta)];
        core::arch::asm!("blr {f}", f = in(reg) resolve::magnify_gesture_init(),
            in("d0") minimum_scale_delta,
            in("x8") gesture.as_mut_ptr(),
            in("x20") g_meta,
            lateout("x0") _, lateout("x1") _, 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"),
        );
        gesture_ended(
            view,
            &mut gesture,
            g_meta,
            invoke_magnify_value,
            boxed_ctx(Box::new(action) as Box<dyn Fn(MagnifyValue)>),
        )
    }
}

/// Attach a `RotateGesture` with an `onEnded` handler.
pub fn on_rotate_ended(
    view: &ViewHandle,
    minimum_degrees: f64,
    action: impl Fn(RotateValue) + 'static,
) -> ViewHandle {
    unsafe {
        let g_meta = abi::metadata0(resolve::rotate_gesture_ma());
        let mut gesture = vec![0u8; abi::type_bytes(g_meta)];
        // `minimumAngleDelta` is an `Angle`, which stores radians — the same
        // conversion `rotate_gesture` does, and the reason this is spelled out
        // rather than left to look like a plain float argument.
        let radians = minimum_degrees * std::f64::consts::PI / 180.0;
        core::arch::asm!("blr {f}", f = in(reg) resolve::rotate_gesture_init(),
            in("d0") radians,
            in("x8") gesture.as_mut_ptr(),
            in("x20") g_meta,
            lateout("x0") _, lateout("x1") _, 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"),
        );
        gesture_ended(
            view,
            &mut gesture,
            g_meta,
            invoke_rotate_value,
            boxed_ctx(Box::new(action) as Box<dyn Fn(RotateValue)>),
        )
    }
}

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

    /// The pinch readers pick the right field out of a real layout.
    ///
    /// A synthetic magnify or rotate event is not something AppKit will build —
    /// there is no public constructor for one — so unlike the drag, these
    /// readers cannot be driven end to end. What *can* be checked is the part
    /// that would be wrong if the offsets moved: a buffer is filled with a
    /// distinct value at each of the offsets the metadata reports, and the
    /// reader has to come back with them in the right order.
    ///
    /// This is a weaker check than the drag's behavioural one and worth saying
    /// so: it proves the reader agrees with the metadata, not that SwiftUI puts
    /// the magnification where its metadata says. The drag case covers that for
    /// the shared mechanism.
    #[test]
    fn pinch_reader_matches_the_live_layout() {
        for accessor in [resolve::magnify_value_ma(), resolve::rotate_value_ma()] {
            let offsets = pinch_value_offsets(accessor).expect("six stored fields");
            let [time, amount, velocity, anchor, start] = offsets;

            // A distinct value per field, so a swapped pair cannot pass.
            let size = unsafe { abi::type_bytes(abi::metadata0(accessor)) };
            let mut buf = vec![0u8; size];
            let put = |b: &mut [u8], at: usize, v: f64| {
                b[at..at + 8].copy_from_slice(&v.to_le_bytes());
            };
            put(&mut buf, time, 11.0);
            put(&mut buf, amount, 22.0);
            put(&mut buf, velocity, 33.0);
            put(&mut buf, anchor, 44.0);
            put(&mut buf, anchor + 8, 55.0);
            put(&mut buf, start, 66.0);
            put(&mut buf, start + 8, 77.0);

            let got = unsafe { read_pinch_value(buf.as_ptr(), accessor) };
            assert_eq!(got, [22.0, 33.0, 44.0, 55.0, 66.0, 77.0, 11.0]);
        }
    }

    /// `Angle` stores radians, so the degrees are computed.
    #[test]
    fn rotate_value_converts_to_degrees() {
        let v = RotateValue {
            radians: std::f64::consts::FRAC_PI_2,
            velocity: 0.0,
            start_anchor: (0.5, 0.5),
            start_location: (0.0, 0.0),
            time: 0.0,
        };
        assert!((v.degrees() - 90.0).abs() < 1e-9);
    }

    /// A drag's translation is the difference of its two points.
    #[test]
    fn drag_value_translation_is_the_difference() {
        let v = DragValue {
            location: (142.0, 40.0),
            start_location: (70.0, 40.0),
            velocity: (164.0, 0.0),
            time: 0.0,
        };
        assert_eq!(v.translation(), (72.0, 0.0));
    }
}