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
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
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
//! Deterministic offscreen rendering — the basis of the visual parity tests.
//!
//! Everything here is pinned so that two runs, or a Rust run and a Swift run,
//! produce byte-identical output:
//!
//! - the bitmap is created explicitly at 1 pixel per point, so the result does
//!   not depend on the attached display's backing scale factor;
//! - the appearance is forced to Aqua, so it does not depend on the host's
//!   light/dark setting;
//! - the view is hosted in an offscreen window, so layout matches what an
//!   on-screen window would produce.

use crate::hosting::HostingView;
use crate::objc::{self};
// Every use of `NSRect` here is in an AppKit path, so on iOS the name has
// nothing to refer to.
#[cfg(target_os = "macos")]
use crate::objc::NSRect;
use crate::views::ViewHandle;
use core::ffi::c_void;

/// A rendered bitmap: 8-bit RGBA, row-major, no padding.
pub struct Rendered {
    pub width: u32,
    pub height: u32,
    pub pixels: Vec<u8>,
}

impl Rendered {
    /// Number of pixels differing from `other` by more than `tolerance` in any
    /// channel. `u32::MAX` if the dimensions differ.
    pub fn diff_count(&self, other: &Rendered, tolerance: u8) -> u32 {
        if self.width != other.width || self.height != other.height {
            return u32::MAX;
        }
        // Almost every comparison in a passing sweep is of two identical images,
        // and that case is one `memcmp` rather than a walk over four bytes per
        // pixel through nested iterators. Slice equality lowers to `memcmp`.
        if self.pixels == other.pixels {
            return 0;
        }
        // Exact comparison is a word compare per pixel, not four byte compares.
        if tolerance == 0 {
            return self
                .pixels
                .chunks_exact(4)
                .zip(other.pixels.chunks_exact(4))
                .filter(|(a, b)| a != b)
                .count() as u32;
        }
        let mut n = 0;
        for (a, b) in self.pixels.chunks_exact(4).zip(other.pixels.chunks_exact(4)) {
            if a.iter().zip(b).any(|(x, y)| x.abs_diff(*y) > tolerance) {
                n += 1;
            }
        }
        n
    }

    /// How many distinct RGBA values the bitmap contains.
    ///
    /// A render that came out blank has one; a case whose diff is zero *and*
    /// whose colour count is one proved nothing, so the harness reports both.
    pub fn distinct(&self) -> usize {
        // An open-addressed table with a multiply-shift hash, not `HashSet` and
        // not a sort. Every pixel of every render goes through here: `HashSet`'s
        // SipHash costs more per pixel than the whole image is worth, and
        // sorting pays O(n log n) to answer a question that only needs
        // membership. A render has a few hundred distinct colours out of tens of
        // thousands of pixels, so the table stays small and cache-resident and
        // almost every probe hits an existing entry on the first try.
        //
        // Reusing one scratch buffer across calls was tried under the sorting
        // version and measured no faster: the cost was never the allocation.
        let pixels = self.pixels.chunks_exact(4);
        // Power of two, so the mask is the modulo. Start well above the couple
        // of hundred colours a typical render has, and grow if a gradient or a
        // photograph blows past it.
        let mut bits = 12;
        let mut table = vec![u32::MAX; 1 << bits];
        // `u32::MAX` marks an empty slot, so a genuine white-opaque pixel needs
        // somewhere else to live.
        let mut has_sentinel = false;
        let mut count = 0usize;
        for px in pixels {
            let key = u32::from_le_bytes([px[0], px[1], px[2], px[3]]);
            if key == u32::MAX {
                if !has_sentinel {
                    has_sentinel = true;
                    count += 1;
                }
                continue;
            }
            // Fibonacci hashing: one multiply, then take the high bits, which
            // mixes far better than masking the low ones for pixel values that
            // differ only in their top byte.
            let mut i = ((key as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> (64 - bits)) as usize;
            loop {
                let slot = table[i];
                if slot == key {
                    break;
                }
                if slot == u32::MAX {
                    table[i] = key;
                    count += 1;
                    // Grow past half full, where linear probing starts to cluster.
                    if count > (1 << bits) / 2 {
                        bits += 1;
                        let mut bigger = vec![u32::MAX; 1 << bits];
                        for &v in table.iter().filter(|&&v| v != u32::MAX) {
                            let mut j = ((v as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
                                >> (64 - bits)) as usize;
                            while bigger[j] != u32::MAX {
                                j = (j + 1) & ((1 << bits) - 1);
                            }
                            bigger[j] = v;
                        }
                        table = bigger;
                    }
                    break;
                }
                i = (i + 1) & ((1 << bits) - 1);
            }
        }
        count
    }

    /// Write a PNG for eyeballing.
    ///
    /// `NSBitmapImageRep` on the Mac, so the file matches what the macOS
    /// capture paths produced byte for byte; CoreGraphics and ImageIO
    /// elsewhere, which are the same API on every Apple platform.
    #[cfg(target_os = "macos")]
    pub fn write_png(&self, path: &str) -> bool {
        unsafe {
            let rep = new_bitmap(self.width, self.height);
            let data = objc::send_ret_ptr(rep, objc::sel(c"bitmapData")) as *mut u8;
            let row = objc::send_ret_u64(rep, objc::sel(c"bytesPerRow")) as usize;
            for y in 0..self.height as usize {
                let src = &self.pixels[y * self.width as usize * 4..][..self.width as usize * 4];
                core::ptr::copy_nonoverlapping(src.as_ptr(), data.add(y * row), src.len());
            }
            let ok = write_rep_png(rep, path);
            objc::send(rep, objc::sel(c"release"));
            ok
        }
    }

    /// Write a PNG for eyeballing.
    #[cfg(not(target_os = "macos"))]
    pub fn write_png(&self, path: &str) -> bool {
        crate::cg::write_png(self.width, self.height, &self.pixels, path)
    }
}

/// Render a view offscreen at exactly `width` x `height` pixels.
#[cfg(target_os = "macos")]
pub fn render(view: &ViewHandle, width: u32, height: u32) -> Rendered {
    let hv = HostingView::new(view);
    let out = render_hosting(&hv, width, height);
    // Tear the hosting view down and let AppKit finish the job before
    // returning. Draining *after* the capture, so nothing the run loop does can
    // change what was captured.
    drop(hv);
    drain();
    out
}

/// Let AppKit and SwiftUI finish work they have deferred to the run loop.
///
/// Closing a window and releasing a hosting view does not free them: both are
/// torn down on the next turn of the run loop, and a capture loop that never
/// turns it accumulates every frame it has taken — about fifty kilobytes each,
/// which is a hundred megabytes over a couple of thousand frames.
///
/// An application has a run loop and never needs this. [`render`] calls it for
/// the view it owns. Anything driving [`render_hosting`] over a hosting view of
/// its own should call it too, at whatever interval suits: once every dozen
/// frames is enough to keep memory flat, and costs less overall than not doing
/// it at all.
pub fn drain() {
    pump(0.0);
}

/// Render an existing hosting view — used when the root is swapped between frames.
#[cfg(target_os = "macos")]
pub fn render_hosting(hv: &HostingView, width: u32, height: u32) -> Rendered {
    unsafe {
        let _pool = objc::AutoreleasePool::new();
        let app = objc::shared_app();
        let _ = app;

        // The window belongs to the hosting view and lives as long as it does.
        let _ = offscreen_window_for(hv, width, height);
        hv.set_frame(width as f64, height as f64);
        capture_view(hv.as_ptr(), width, height)
    }
}

/// The hosting view's own offscreen window, sized for this capture.
#[cfg(target_os = "macos")]
unsafe fn offscreen_window_for(hv: &HostingView, width: u32, height: u32) -> *mut c_void {
    unsafe { hv.offscreen(width as f64, height as f64) }
}

/// Capture any `NSView` into a `width` x `height` bitmap.
///
/// Some things SwiftUI draws never reach a hosting view's own layer — a
/// `.toolbar` is installed into the window's titlebar, which is a sibling of the
/// content view — so verifying them means capturing a different view than the
/// one the root was set on. See [`capture_window`].
///
/// # Safety
/// `view` must be a live `NSView`.
#[cfg(target_os = "macos")]
pub unsafe fn capture_view(view: *mut c_void, width: u32, height: u32) -> Rendered {
    unsafe {
        let _pool = objc::AutoreleasePool::new();
        let bounds = NSRect::new(0.0, 0.0, width as f64, height as f64);
        // A bitmap we create ourselves is exactly width x height pixels, so the
        // output never picks up the display's 2x backing scale.
        let rep = new_bitmap(width, height);
        objc::send_rect_id(
            view,
            objc::sel(c"cacheDisplayInRect:toBitmapImageRep:"),
            bounds,
            rep,
        );

        let data = objc::send_ret_ptr(rep, objc::sel(c"bitmapData"));
        let row = objc::send_ret_u64(rep, objc::sel(c"bytesPerRow")) as usize;
        let mut pixels = vec![0u8; (width * height * 4) as usize];
        for y in 0..height as usize {
            core::ptr::copy_nonoverlapping(
                data.add(y * row),
                pixels.as_mut_ptr().add(y * width as usize * 4),
                width as usize * 4,
            );
        }
        objc::send(rep, objc::sel(c"release"));
        Rendered { width, height, pixels }
    }
}

/// Capture a window including its titlebar, at `width` x `height`.
///
/// The titlebar is drawn by the window's *frame view*, the private superview of
/// the content view. Capturing that is the only way to see a `.toolbar` from a
/// test.
///
/// # Safety
/// `window` must be a live `NSWindow`.
#[cfg(target_os = "macos")]
pub unsafe fn capture_window(window: *mut c_void, width: u32, height: u32) -> Rendered {
    unsafe {
        let content = objc::send(window, objc::sel(c"contentView"));
        let frame_view = objc::send(content, objc::sel(c"superview"));
        let target = if frame_view.is_null() { content } else { frame_view };
        capture_view(target, width, height)
    }
}

/// Build a real titled window around `view`, sized so its **frame** — titlebar
/// included — is exactly `width` x `height`, and capture the whole thing.
///
/// A macOS `.toolbar` is installed into the window's titlebar, which is a
/// sibling of the content view, so it is invisible to every offscreen capture.
/// This is the path that can see it.
///
/// The window is ordered in without being made key, and the app stays an
/// accessory, so running this does not steal focus from whatever is in front.
#[cfg(target_os = "macos")]
pub fn render_chrome(view: &ViewHandle, width: u32, height: u32) -> Rendered {
    unsafe {
        let _pool = objc::AutoreleasePool::new();
        // Reusing one titled window across captures was tried: it saved nothing
        // — building the window is not where the time goes — and 36 variants
        // came back different, so each capture gets its own.
        let win = titled_window(view, width, height);
        pump_until(0.45, || objc::send_ret_bool(win, objc::sel(c"isVisible")));
        let out = capture_window(win, width, height);
        objc::send(win, objc::sel(c"close"));
        // A closed window is torn down on the next turn of the run loop, not on
        // the call — but that is one turn, not fifty milliseconds of them. The
        // memory pass at the end of a sweep is what would notice if it were not
        // enough.
        pump(0.01);
        out
    }
}

/// Present `view` in a real window and capture the **sheet it puts up**, not the
/// window itself.
///
/// `.alert`, `.sheet` and `.confirmationDialog` on macOS present into a separate
/// child window attached to the parent. Capturing the parent shows only that it
/// dimmed; capturing the sheet shows the dialog SwiftUI actually built, which is
/// what the modifier is for.
///
/// Returns a single flat pixel if nothing was presented, so a case that silently
/// stopped presenting shows up as flat rather than passing.
#[cfg(target_os = "macos")]
pub fn render_sheet(view: &ViewHandle, win_w: u32, win_h: u32, w: u32, h: u32) -> Rendered {
    unsafe {
        let _pool = objc::AutoreleasePool::new();
        let win = titled_window(view, win_w, win_h);
        pump_until(0.7, || !objc::send(win, objc::sel(c"attachedSheet")).is_null());
        let sheet = objc::send(win, objc::sel(c"attachedSheet"));
        let out = if sheet.is_null() {
            Rendered { width: w, height: h, pixels: vec![0; (w * h * 4) as usize] }
        } else {
            capture_window(sheet, w, h)
        };
        objc::send(win, objc::sel(c"close"));
        // A closed window is torn down on the next turn of the run loop, not on
        // the call — but that is one turn, not fifty milliseconds of them. The
        // memory pass at the end of a sweep is what would notice if it were not
        // enough.
        pump(0.01);
        out
    }
}

/// Render `view` in a real window and capture it **as the window server
/// composited it**, rather than as its own layers draw.
///
/// This is the only path that shows Liquid Glass. `.glassEffect` and
/// `.buttonStyle(.glass)` are resolved by the compositor, not by the view's
/// layer tree, so `cacheDisplayInRect` renders them away and `ImageRenderer`
/// drops the subtree — through either one a glass case passes without the glass
/// ever existing.
///
/// Asks for nominal resolution so the result is in points and does not pick up
/// the display's backing scale.
#[cfg(target_os = "macos")]
pub fn render_composited(view: &ViewHandle, width: u32, height: u32) -> Rendered {
    unsafe {
        let _pool = objc::AutoreleasePool::new();
        let win = titled_window(view, width, height);
        pump_until(0.7, || objc::send_ret_bool(win, objc::sel(c"isVisible")));
        let out = capture_composited(win, width, height);
        objc::send(win, objc::sel(c"close"));
        // A closed window is torn down on the next turn of the run loop, not on
        // the call — but that is one turn, not fifty milliseconds of them. The
        // memory pass at the end of a sweep is what would notice if it were not
        // enough.
        pump(0.01);
        out
    }
}

/// Run the run loop until `ready` holds, or `limit` seconds have passed.
///
/// The capture paths used to sleep a fixed 0.45–0.7s each, long enough for the
/// slowest case. Most are ready in a fraction of that, and with sixty on-screen
/// variants in the suite the difference is most of a minute. The timeout keeps
/// the old behaviour as the worst case rather than the every case.
#[cfg(target_os = "macos")]
pub fn pump_until(limit: f64, mut ready: impl FnMut() -> bool) {
    // 5ms, not 20: the step is the granularity of the answer, and a window that
    // becomes visible after 3ms was being noticed at 20 and charged 40 with the
    // settling turn. The settle stays at 20ms — it is there to let the frame that
    // satisfied the condition draw, which is a property of the frame rather than
    // of how often we look.
    let step = 0.005;
    let mut waited = 0.0;
    while waited < limit {
        pump(step);
        waited += step;
        if ready() {
            // One more turn so the frame that satisfied the condition is drawn.
            pump(0.02);
            return;
        }
    }
}

/// Ask the window server for a window's composited contents.
///
/// # Safety
/// `window` must be a live, on-screen `NSWindow`.
#[cfg(target_os = "macos")]
pub unsafe fn capture_composited(window: *mut c_void, width: u32, height: u32) -> Rendered {
        let _pool = objc::AutoreleasePool::new();
    unsafe extern "C" {
        fn CGWindowListCreateImage(
            bounds: objc::NSRect,
            list_option: u32,
            window_id: u32,
            image_option: u32,
        ) -> *mut c_void;
    }
    unsafe {
        let id = objc::send_ret_u64(window, objc::sel(c"windowNumber")) as u32;
        // CGRectNull bounds: use the window's own. optionIncludingWindow (1<<3),
        // boundsIgnoreFraming (1<<0) | nominalResolution (1<<4).
        let cg = CGWindowListCreateImage(
            // `CGRectInfinite`: the whole screen.
            objc::NSRect::new(f64::INFINITY, f64::INFINITY, 0.0, 0.0),
            1 << 3,
            id,
            (1 << 4) | 1,
        );
        if cg.is_null() {
            return Rendered { width, height, pixels: vec![0; (width * height * 4) as usize] };
        }
        let rep = objc::send_id(
            objc::send(objc::class(c"OBJC_CLASS_$_NSBitmapImageRep"), objc::sel(c"alloc")),
            objc::sel(c"initWithCGImage:"),
            cg,
        );
        let got_w = objc::send_ret_u64(rep, objc::sel(c"pixelsWide")) as usize;
        let got_h = objc::send_ret_u64(rep, objc::sel(c"pixelsHigh")) as usize;
        let row = objc::send_ret_u64(rep, objc::sel(c"bytesPerRow")) as usize;
        let data = objc::send_ret_ptr(rep, objc::sel(c"bitmapData"));

        // Copy whatever overlaps the requested size, so a window the server
        // sized slightly differently still lines up at the origin instead of
        // reading past the buffer.
        let mut pixels = vec![0u8; (width * height * 4) as usize];
        let copy_w = got_w.min(width as usize);
        for y in 0..got_h.min(height as usize) {
            core::ptr::copy_nonoverlapping(
                data.add(y * row),
                pixels.as_mut_ptr().add(y * width as usize * 4),
                copy_w * 4,
            );
        }
        Rendered { width, height, pixels }
    }
}

/// Present `view` in a real window and capture the **popover it puts up**.
///
/// A `.popover` is not an attached sheet — it gets its own `_NSPopoverWindow`,
/// which is why [`render_sheet`] cannot see it. This finds that window among the
/// application's and captures it.
///
/// Returns a single flat pixel if no popover appeared.
#[cfg(target_os = "macos")]
pub fn render_popover(view: &ViewHandle, win_w: u32, win_h: u32, w: u32, h: u32) -> Rendered {
    unsafe {
        let _pool = objc::AutoreleasePool::new();
        let win = titled_window(view, win_w, win_h);
        // Wait for the popover to exist rather than for a fixed 0.8s. Its
        // neighbours were converted to `pump_until` and this one was not, which
        // made it the most expensive capture in the suite by an order of
        // magnitude — 0.92s a variant, nearly all of it sleeping past the point
        // the window was already there.
        pump_until(0.8, || !find_window(|name| name.contains("Popover")).is_null());
        let popover = find_window(|name| name.contains("Popover"));
        let out = if popover.is_null() {
            Rendered { width: w, height: h, pixels: vec![0; (w * h * 4) as usize] }
        } else {
            capture_window(popover, w, h)
        };
        objc::send(win, objc::sel(c"close"));
        // Closing the parent leaves the popover's own window behind, and a
        // stray borderless window stays key and swallows the mouse events a
        // later test posts. Take it down explicitly.
        if !popover.is_null() {
            objc::send_id(popover, objc::sel(c"orderOut:"), core::ptr::null_mut());
            objc::send(popover, objc::sel(c"close"));
        }
        pump(0.01);
        out
    }
}

/// The first application window whose class name satisfies `pred`, or null.
#[cfg(target_os = "macos")]
unsafe fn find_window(pred: impl Fn(&str) -> bool) -> *mut c_void {
    unsafe {
        let wins = objc::send(objc::shared_app(), objc::sel(c"windows"));
        if wins.is_null() {
            return core::ptr::null_mut();
        }
        let n = objc::send_ret_u64(wins, objc::sel(c"count"));
        for i in 0..n {
            let w = objc::send_u64_id(wins, objc::sel(c"objectAtIndex:"), i, core::ptr::null_mut());
            let cls = objc::send(w, objc::sel(c"className"));
            let p = objc::send_ret_ptr(cls, objc::sel(c"UTF8String"));
            if p.is_null() {
                continue;
            }
            let name = core::ffi::CStr::from_ptr(p as *const i8).to_string_lossy();
            if pred(&name) {
                return w;
            }
        }
        core::ptr::null_mut()
    }
}

/// A titled window whose *frame* is `width` x `height`, shown without taking focus.
#[cfg(target_os = "macos")]
unsafe fn titled_window(view: &ViewHandle, width: u32, height: u32) -> *mut c_void {
    unsafe {
        let app = objc::shared_app();
        // `.accessory`, not `.regular`: the windows appear but never steal focus.
        objc::send_i64(app, objc::sel(c"setActivationPolicy:"), 1);
        // A bare executable has no bundle identifier, so AppKit cannot key its
        // window-tab index and faults the second time a titled, resizable window
        // is registered. Nothing here wants tabbing anyway.
        objc::send_bool(
            objc::class(c"OBJC_CLASS_$_NSWindow"),
            objc::sel(c"setAllowsAutomaticWindowTabbing:"),
            false,
        );

        let hosting = HostingView::new(view);
        let bounds = NSRect::new(0.0, 0.0, width as f64, height as f64);
        let win = objc::send(objc::class(c"OBJC_CLASS_$_NSWindow"), objc::sel(c"alloc"));
        type InitWin =
            unsafe extern "C" fn(*mut c_void, *const c_void, NSRect, u64, u64, bool) -> *mut c_void;
        let init: InitWin = core::mem::transmute(objc::msg_send_addr());
        // titled | closable | miniaturizable | resizable
        let win = init(win, objc::sel(c"initWithContentRect:styleMask:backing:defer:"), bounds, 15, 2, false);

        let name = objc::nsstring("NSAppearanceNameAqua");
        let appearance = objc::send_id(
            objc::class(c"OBJC_CLASS_$_NSAppearance"),
            objc::sel(c"appearanceNamed:"),
            name,
        );
        if !appearance.is_null() {
            objc::send_id(win, objc::sel(c"setAppearance:"), appearance);
        }
        objc::send_i64(win, objc::sel(c"setTabbingMode:"), 2); // .disallowed
        // `.none`, so AppKit does not animate the window in or a sheet down. The
        // capture paths wait for the window to be on screen and a sheet to be
        // attached, and with the animation running that wait is the animation's
        // duration — a third of a second per sheet, which is most of what a
        // sheet variant costs.
        objc::send_i64(win, objc::sel(c"setAnimationBehavior:"), 2);
        objc::send_id(win, objc::sel(c"setTitle:"), objc::nsstring("parity"));
        objc::send_id(win, objc::sel(c"setContentView:"), hosting.as_ptr());
        // Setting the *frame* (not the content rect) makes the frame view exactly
        // width x height, so the captured bitmap lines up with what was asked for
        // however tall the titlebar turns out to be.
        type SetFrame = unsafe extern "C" fn(*mut c_void, *const c_void, NSRect, bool);
        let set_frame: SetFrame = core::mem::transmute(objc::msg_send_addr());
        set_frame(win, objc::sel(c"setFrame:display:"), bounds, true);
        objc::send_id(win, objc::sel(c"orderFront:"), core::ptr::null_mut());
        // `setContentView:` retained it; the window owns it from here.
        drop(hosting);
        win
    }
}

/// Run `body` once, `delay` seconds from now, *inside* whatever loop is running.
///
/// A context menu, a drag or a modal sheet does not return to the caller: AppKit
/// enters its own event loop in `NSEventTrackingRunLoopMode` and stays there
/// until the user dismisses it. [`pump_events`] never gets a turn while that is
/// happening, which is why anything that opens a menu cannot be observed from
/// the outside at all — and why forcing the window closed from another thread
/// takes the process down.
///
/// A `CFRunLoopTimer` added to the *common* modes is the way in. Common modes
/// include event tracking, so the timer fires while the menu is up, on the main
/// thread, between events — exactly where it is safe to look at the window list
/// and to post the key event that dismisses it.
///
/// The timer repeats every `interval` seconds until `body` returns `true`, so a
/// dismissal that does not take the first time is simply tried again.
///
/// # Safety
/// Must be called on the main thread, and `body` runs on it too.
#[cfg(target_os = "macos")]
pub unsafe fn during_tracking(delay: f64, interval: f64, body: fn() -> bool) {
    #[repr(C)]
    struct TimerContext {
        version: isize,
        info: *mut c_void,
        retain: *const c_void,
        release: *const c_void,
        copy_description: *const c_void,
    }
    unsafe extern "C" fn fire(timer: *mut c_void, info: *mut c_void) {
        unsafe {
            let body: fn() -> bool = core::mem::transmute(info);
            if body() {
                let invalidate: unsafe extern "C" fn(*mut c_void) =
                    core::mem::transmute(cf(c"CFRunLoopTimerInvalidate"));
                invalidate(timer);
            }
        }
    }
    unsafe {
        type Create = unsafe extern "C" fn(
            *const c_void, f64, f64, u64, isize,
            unsafe extern "C" fn(*mut c_void, *mut c_void),
            *mut TimerContext,
        ) -> *mut c_void;
        type Add = unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void);
        type Now = unsafe extern "C" fn() -> f64;
        type Main = unsafe extern "C" fn() -> *mut c_void;
        let create: Create = core::mem::transmute(cf(c"CFRunLoopTimerCreate"));
        let add: Add = core::mem::transmute(cf(c"CFRunLoopAddTimer"));
        let now: Now = core::mem::transmute(cf(c"CFAbsoluteTimeGetCurrent"));
        let main: Main = core::mem::transmute(cf(c"CFRunLoopGetMain"));
        let mut ctx = TimerContext {
            version: 0,
            info: body as *mut c_void,
            retain: core::ptr::null(),
            release: core::ptr::null(),
            copy_description: core::ptr::null(),
        };
        let timer = create(core::ptr::null(), now() + delay, interval, 0, 0, fire, &mut ctx);
        // The *constant*, not a string with the same characters: CF compares the
        // common-modes name by pointer, so an equal `NSString` silently adds the
        // timer to a mode called "kCFRunLoopCommonModes" that nothing runs.
        let modes = *(cf(c"kCFRunLoopCommonModes") as *const *mut c_void);
        add(main(), timer, modes);
    }
}

/// A CoreFoundation entry point, by name.
///
/// CoreFoundation is already in the process — AppKit cannot load without it —
/// so this never needs a `dlopen`, only a lookup.
#[cfg(target_os = "macos")]
fn cf(name: &core::ffi::CStr) -> *mut c_void {
    let p = unsafe { libc::dlsym((-2isize) as *mut c_void, name.as_ptr()) };
    assert!(!p.is_null(), "CoreFoundation: {}", name.to_string_lossy());
    p
}

/// Post a key press and release to whichever window is key.
///
/// Window number 0 means "the key window", which while a menu is tracking is the
/// menu itself — so an Escape posted here is what dismisses it. Menus read the
/// event queue directly, so this reaches them without a `sendEvent:`.
///
/// # Safety
/// Must be called on the main thread.
#[cfg(target_os = "macos")]
pub unsafe fn post_key(key_code: u16, characters: &str) {
    unsafe {
        type Make = unsafe extern "C" fn(
            *mut c_void, *const c_void, u64, objc::NSPoint, u64, f64, i64,
            *mut c_void, *mut c_void, *mut c_void, bool, u16,
        ) -> *mut c_void;
        let make: Make = core::mem::transmute(objc::msg_send_addr());
        let chars = objc::nsstring(characters);
        // 10 = NSEventTypeKeyDown, 11 = NSEventTypeKeyUp.
        for kind in [10u64, 11] {
            let event = make(
                objc::class(c"OBJC_CLASS_$_NSEvent"),
                objc::sel(c"keyEventWithType:location:modifierFlags:timestamp:windowNumber:context:characters:charactersIgnoringModifiers:isARepeat:keyCode:"),
                kind,
                objc::NSPoint { x: 0.0, y: 0.0 },
                0,
                uptime(),
                0,
                core::ptr::null_mut(),
                chars,
                chars,
                false,
                key_code,
            );
            if !event.is_null() {
                objc::send_id_bool(objc::shared_app(), objc::sel(c"postEvent:atStart:"), event, true);
            }
        }
    }
}

/// Run a real event loop for `seconds`, dequeuing and dispatching `NSEvent`s.
///
/// [`pump`] turns the run loop, which is enough for SwiftUI's clock and for
/// display, but it never touches the application's *event queue* — so an event
/// posted with `postEvent:atStart:` just sits there and a gesture never fires.
/// This is the loop that delivers them.
///
/// Use [`pump`] for anything that only needs time to pass; use this when
/// something has to receive input.
#[cfg(target_os = "macos")]
pub fn pump_events(seconds: f64) {
    unsafe {
        let app = objc::shared_app();
        let deadline = uptime() + seconds;
        while uptime() < deadline {
            type Next = unsafe extern "C" fn(
                *mut c_void, *const c_void, u64, *mut c_void, *mut c_void, bool,
            ) -> *mut c_void;
            let next: Next = core::mem::transmute(objc::msg_send_addr());
            type DateFn = unsafe extern "C" fn(*mut c_void, *const c_void, f64) -> *mut c_void;
            let date: DateFn = core::mem::transmute(objc::msg_send_addr());
            let until = date(
                objc::class(c"OBJC_CLASS_$_NSDate"),
                objc::sel(c"dateWithTimeIntervalSinceNow:"),
                0.01,
            );
            let event = next(
                app,
                objc::sel(c"nextEventMatchingMask:untilDate:inMode:dequeue:"),
                u64::MAX,
                until,
                objc::nsstring("kCFRunLoopDefaultMode"),
                true,
            );
            if !event.is_null() {
                objc::send_id(app, objc::sel(c"sendEvent:"), event);
            }
        }
    }
}

/// Seconds since boot — the timebase `NSEvent` timestamps use.
pub fn uptime() -> f64 {
    unsafe {
        let info = objc::send(
            objc::class(c"OBJC_CLASS_$_NSProcessInfo"),
            objc::sel(c"processInfo"),
        );
        objc::send_ret_f64(info, objc::sel(c"systemUptime"))
    }
}

/// Bring the application forward and wait until the window server agrees.
///
/// Mouse events are only routed to a view's gestures while the application is
/// active, so anything posting synthetic input has to establish that first —
/// and activation is asynchronous, so asking is not enough.
#[cfg(target_os = "macos")]
pub fn activate(timeout: f64) -> bool {
    unsafe {
        let app = objc::shared_app();
        objc::send_i64(app, objc::sel(c"setActivationPolicy:"), 0); // .regular

        // `activateIgnoringOtherApps:` is deprecated and, for a binary with no
        // bundle, increasingly ignored; `activate` is its macOS 14 replacement
        // and `NSRunningApplication` is a third route. Try all of them — which
        // one works depends on the OS version and on what is frontmost.
        objc::send_bool(app, objc::sel(c"activateIgnoringOtherApps:"), true);
        if objc::responds(app, objc::sel(c"activate")) {
            objc::send(app, objc::sel(c"activate"));
        }
        let running = objc::send(
            objc::class(c"OBJC_CLASS_$_NSRunningApplication"),
            objc::sel(c"currentApplication"),
        );
        if !running.is_null() {
            // NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps
            objc::send_u64(running, objc::sel(c"activateWithOptions:"), 1 | 2);
        }

        let deadline = uptime() + timeout;
        while uptime() < deadline {
            if objc::send(app, objc::sel(c"isActive")) as usize & 1 == 1 {
                return true;
            }
            pump_events(0.05);
        }
        false
    }
}

/// Give up frontmost status and wait until the window server agrees.
///
/// Being active is not cosmetic: an alert draws its default button accented
/// while its application is frontmost and plain when it is not. So anything
/// that compares renders has to pin the state rather than inherit whatever
/// [`activate`] last left behind.
#[cfg(target_os = "macos")]
pub fn deactivate(timeout: f64) -> bool {
    unsafe {
        let app = objc::shared_app();
        // `.prohibited` is what the Swift reference renders under, and unlike
        // `.accessory` it takes the application out of the foreground outright
        // rather than asking politely.
        objc::send_i64(app, objc::sel(c"setActivationPolicy:"), 2);
        objc::send_id(app, objc::sel(c"hide:"), core::ptr::null_mut());
        objc::send(app, objc::sel(c"deactivate"));
        let deadline = uptime() + timeout;
        while uptime() < deadline {
            if objc::send(app, objc::sel(c"isActive")) as usize & 1 == 0 {
                return true;
            }
            pump_events(0.05);
        }
        false
    }
}

/// [`pump_until`], but dequeuing application events as well.
///
/// Anything waiting on a synthetic click needs this rather than [`pump_until`]:
/// turning the run loop does not drain the application's event queue, so the
/// event that would satisfy `ready` never arrives and the wait always runs to
/// its limit.
#[cfg(target_os = "macos")]
pub fn pump_events_until(limit: f64, mut ready: impl FnMut() -> bool) {
    let step = 0.005;
    let mut waited = 0.0;
    while waited < limit {
        pump_events(step);
        waited += step;
        if ready() {
            pump_events(0.02);
            return;
        }
    }
}

/// Post a synthetic mouse event to `window`, to be delivered by [`pump_events`].
///
/// `kind` is an `NSEventType`: 1 left-down, 2 left-up, 6 left-dragged,
/// 3 right-down, 4 right-up. `x`/`y` are in the window's coordinate space, with
/// the origin at the bottom left.
///
/// # Safety
/// `window` must be a live `NSWindow`.
#[cfg(target_os = "macos")]
pub unsafe fn post_mouse(window: *mut c_void, kind: u64, x: f64, y: f64, clicks: i64) {
    unsafe {
        let event = mouse_event(window, kind, x, y, clicks);
        if !event.is_null() {
            objc::send_id_bool(objc::shared_app(), objc::sel(c"postEvent:atStart:"), event, false);
        }
    }
}

/// Build a synthetic `NSEvent` in `window`'s coordinate space.
///
/// `kind` is an `NSEventType`: 1 left-down, 2 left-up, 6 left-dragged,
/// 3 right-down, 4 right-up. `x`/`y` have the origin at the bottom left.
/// Build a synthetic `NSEvent` without delivering it, so a caller can choose the
/// route. Only `examples/activation_probe.rs` needs this — it compares the
/// routes against each other; everything else should use [`send_mouse`].
///
/// # Safety
/// `window` must be a live `NSWindow`.
#[cfg(target_os = "macos")]
pub unsafe fn mouse_event_for(
    window: *mut c_void,
    kind: u64,
    x: f64,
    y: f64,
    clicks: i64,
) -> *mut c_void {
    unsafe { mouse_event(window, kind, x, y, clicks) }
}

#[cfg(target_os = "macos")]
unsafe fn mouse_event(window: *mut c_void, kind: u64, x: f64, y: f64, clicks: i64) -> *mut c_void {
    unsafe {
        let number = objc::send_ret_u64(window, objc::sel(c"windowNumber")) as i64;
        type Make = unsafe extern "C" fn(
            *mut c_void, *const c_void, u64, objc::NSPoint, u64, f64, i64, *mut c_void, i64, i64, f32,
        ) -> *mut c_void;
        let make: Make = core::mem::transmute(objc::msg_send_addr());
        make(
            objc::class(c"OBJC_CLASS_$_NSEvent"),
            objc::sel(c"mouseEventWithType:location:modifierFlags:timestamp:windowNumber:context:eventNumber:clickCount:pressure:"),
            kind,
            objc::NSPoint { x, y },
            0,
            uptime(),
            number,
            core::ptr::null_mut(),
            0,
            clicks,
            if kind == 2 || kind == 4 { 0.0 } else { 1.0 },
        )
    }
}

/// Hand a synthetic mouse event straight to `window`, bypassing the
/// application's event queue.
///
/// [`post_mouse`] enqueues on `NSApp` and needs the run loop to dequeue it;
/// `sendEvent:` is the method `NSApp` would itself call once it had, so the
/// event arrives without waiting on the queue.
///
/// This is not a way around needing focus, and neither is anything else. With
/// the process inactive and its window on screen but not key — measured, the
/// window was `isVisible: true` and occlusion-visible on a real screen — a
/// click was delivered by none of: this, `NSApp sendEvent:`, `NSApp
/// postEvent:`, `mouseDown:` at the hit-tested view, or any of those with
/// `acceptsFirstMouse:` installed on the hosting view's class at run time.
/// Nor by changing what the window *is*: an `NSPanel`, and a
/// `nonactivatingPanel` — which becomes key without activating its
/// application, and is the obvious thing to reach for here — both stayed
/// non-key and delivered nothing, with and without a `makeKeyWindow` or an
/// [`activate`].
///
/// What decides it is `CGSSessionScreenIsLocked`. A locked login session has no
/// active application and cannot be given one, so every route above is closed
/// at the same place; unlock it and all of them work. That is the point of the
/// lock rather than a gap, so code here should ask whether the session is
/// locked and say so, not try to route around it.
///
/// Below AppKit is worse, not better: Quartz Event Services
/// (`CGEventPostToPid`, `CGEventPost`) is gated on the Accessibility
/// permission, and an unbundled binary reports `AXIsProcessTrusted() == false`,
/// so both of those deliver nothing even when the application *is* frontmost.
/// See `examples/activation_probe.rs`, which measures each route side by side.
///
/// # Safety
/// `window` must be a live `NSWindow`.
#[cfg(target_os = "macos")]
pub unsafe fn send_mouse(window: *mut c_void, kind: u64, x: f64, y: f64, clicks: i64) {
    unsafe {
        let event = mouse_event(window, kind, x, y, clicks);
        if !event.is_null() {
            objc::send_id(window, objc::sel(c"sendEvent:"), event);
        }
    }
}

/// Send a key down and up straight to `window`.
///
/// [`post_key`] puts the event on the *application's* queue, which is what a
/// tracking menu reads. This hands it to one window with `sendEvent:`, the same
/// route [`send_mouse`] takes — which is what a check driving a focused view
/// wants, since it does not depend on which window the application thinks is
/// key beyond that window being able to accept it at all.
///
/// `flags` are `NSEvent.ModifierFlags`, so `1 << 20` is Command and `1 << 17`
/// Shift. They are what SwiftUI turns into the `EventModifiers` a `KeyPress`
/// carries.
///
/// # Safety
/// `window` must be a live `NSWindow`, and this must run on the main thread.
#[cfg(target_os = "macos")]
pub unsafe fn send_key(window: *mut c_void, key_code: u16, characters: &str, flags: u64) {
    unsafe {
        type Make = unsafe extern "C" fn(
            *mut c_void, *const c_void, u64, objc::NSPoint, u64, f64, i64,
            *mut c_void, *mut c_void, *mut c_void, bool, u16,
        ) -> *mut c_void;
        let make: Make = core::mem::transmute(objc::msg_send_addr());
        let chars = objc::nsstring(characters);
        let number = objc::send_ret_u64(window, objc::sel(c"windowNumber")) as i64;
        // 10 = NSEventTypeKeyDown, 11 = NSEventTypeKeyUp.
        for kind in [10u64, 11] {
            let event = make(
                objc::class(c"OBJC_CLASS_$_NSEvent"),
                objc::sel(c"keyEventWithType:location:modifierFlags:timestamp:windowNumber:context:characters:charactersIgnoringModifiers:isARepeat:keyCode:"),
                kind,
                objc::NSPoint { x: 0.0, y: 0.0 },
                flags,
                uptime(),
                number,
                core::ptr::null_mut(),
                chars,
                chars,
                false,
                key_code,
            );
            if !event.is_null() {
                objc::send_id(window, objc::sel(c"sendEvent:"), event);
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// UIKit capture
// ═══════════════════════════════════════════════════════════════════════════
//
// AppKit's `cacheDisplayInRect:toBitmapImageRep:` has no UIKit counterpart, so
// these go through the layer instead. A hosting controller's view has to be
// inside a window before UIKit will lay it out at all — the same reason the
// macOS path builds an offscreen `NSWindow`.

/// Render a view offscreen at exactly `width` x `height` pixels.
#[cfg(not(target_os = "macos"))]
pub fn render(view: &ViewHandle, width: u32, height: u32) -> Rendered {
    let hv = HostingView::new(view);
    render_hosting(&hv, width, height)
}

/// Render an existing hosting view — used when the root is swapped between frames.
#[cfg(not(target_os = "macos"))]
pub fn render_hosting(hv: &HostingView, width: u32, height: u32) -> Rendered {
    unsafe {
        let _pool = objc::AutoreleasePool::new();
        let window = hv.offscreen(width as f64, height as f64);
        hv.set_frame(width as f64, height as f64);
        objc::send(window, objc::sel(c"layoutIfNeeded"));
        capture_view(hv.as_ptr(), width, height)
    }
}

/// Capture any `UIView` into a `width` x `height` bitmap.
///
/// # Safety
/// `view` must be a live `UIView`.
#[cfg(not(target_os = "macos"))]
pub unsafe fn capture_view(view: *mut c_void, width: u32, height: u32) -> Rendered {
    unsafe {
        let layer = objc::send(view, objc::sel(c"layer"));
        assert!(!layer.is_null(), "the view has no layer to render");
        let pixels = crate::cg::capture_layer(layer, width, height);
        Rendered { width, height, pixels }
    }
}

/// Run the main run loop for `seconds`, letting SwiftUI's clock advance.
///
/// Needed between frames when capturing something driven by [`crate::views::timeline`]:
/// without turning the run loop, SwiftUI never gets to redisplay.
pub fn pump(seconds: f64) {
    unsafe {
        let loop_ = objc::send(
            objc::class(c"OBJC_CLASS_$_NSRunLoop"),
            objc::sel(c"currentRunLoop"),
        );
        type DateFn = unsafe extern "C" fn(*mut c_void, *const c_void, f64) -> *mut c_void;
        let f: DateFn = core::mem::transmute(objc::msg_send_addr());
        let until = f(
            objc::class(c"OBJC_CLASS_$_NSDate"),
            objc::sel(c"dateWithTimeIntervalSinceNow:"),
            seconds,
        );
        objc::send_id(loop_, objc::sel(c"runUntilDate:"), until);
    }
}

/// Render straight to a PNG file.
pub fn render_png(view: &ViewHandle, width: u32, height: u32, path: &str) -> bool {
    let img = render(view, width, height);
    img.write_png(path)
}

#[cfg(target_os = "macos")]
unsafe fn new_bitmap(width: u32, height: u32) -> *mut c_void {
    let alloc = unsafe {
        objc::send(objc::class(c"OBJC_CLASS_$_NSBitmapImageRep"), objc::sel(c"alloc"))
    };
    #[allow(clippy::too_many_arguments)]
    type Init = unsafe extern "C" fn(
        *mut c_void,
        *const c_void,
        *mut u8, // planes
        i64,     // pixelsWide
        i64,     // pixelsHigh
        i64,     // bitsPerSample
        i64,     // samplesPerPixel
        bool,    // hasAlpha
        bool,    // isPlanar
        *mut c_void, // colorSpaceName
        i64,     // bytesPerRow
        i64,     // bitsPerPixel
    ) -> *mut c_void;
    let init: Init = unsafe { core::mem::transmute(objc::msg_send_addr()) };
    let space = unsafe { objc::nsstring("NSDeviceRGBColorSpace") };
    let rep = unsafe {
        init(
            alloc,
            objc::sel(c"initWithBitmapDataPlanes:pixelsWide:pixelsHigh:bitsPerSample:samplesPerPixel:hasAlpha:isPlanar:colorSpaceName:bytesPerRow:bitsPerPixel:"),
            core::ptr::null_mut(),
            width as i64,
            height as i64,
            8,
            4,
            true,
            false,
            space,
            0,
            0,
        )
    };
    assert!(!rep.is_null(), "NSBitmapImageRep creation failed");
    rep
}

#[cfg(target_os = "macos")]
unsafe fn write_rep_png(rep: *mut c_void, path: &str) -> bool {
    unsafe {
        let props =
            objc::send(objc::class(c"OBJC_CLASS_$_NSDictionary"), objc::sel(c"dictionary"));
        // 4 = NSBitmapImageFileTypePNG
        let data =
            objc::send_u64_id(rep, objc::sel(c"representationUsingType:properties:"), 4, props);
        if data.is_null() {
            return false;
        }
        objc::send_id_bool(
            data,
            objc::sel(c"writeToFile:atomically:"),
            objc::nsstring(path),
            true,
        )
    }
}


/// Render a view through SwiftUI's own `ImageRenderer`.
///
/// This is a different path from [`render`], and the difference matters:
/// `cacheDisplayInRect` captures the AppKit layer tree, which does *not* execute
/// Metal shader effects or Liquid Glass compositing — those are resolved by
/// SwiftUI's renderer, so they come out as no-ops. `ImageRenderer` goes through
/// SwiftUI itself and produces what the shader actually computes.
///
/// The view is framed to the requested size first, since `ImageRenderer` renders
/// at the content's natural size.
pub fn render_image(view: &ViewHandle, width: u32, height: u32) -> Rendered {
    unsafe {
        let _pool = objc::AutoreleasePool::new();
        let framed = crate::views::frame(view, width as f64, height as f64);

        let meta = crate::abi::generic_metadata2(
            crate::resolve::image_renderer_ma(),
            crate::resolve::anyview_meta(),
            crate::resolve::anyview_wt(),
        );
        assert!(!meta.is_null(), "ImageRenderer<AnyView> metadata");

        // init(content:) — x0 = @in AnyView, x20 = ImageRenderer<AnyView>.Type
        // `as_ptr` hands back a `+1` AnyView of its own; the initialiser
        // consumes it. No extra retain.
        let mut content: u64 = framed.as_ptr() as u64;
        let renderer: *mut c_void;
        core::arch::asm!("blr {f}", f = in(reg) crate::resolve::image_renderer_init(),
            in("x0") &mut content as *mut u64,
            in("x20") meta,
            lateout("x0") renderer,
            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("x21") _, clobber_abi("C"),
        );
        assert!(!renderer.is_null(), "ImageRenderer creation failed");

        // scale = 1, so the output is exactly width x height pixels
        core::arch::asm!("blr {f}", f = in(reg) crate::resolve::image_renderer_scale_set(),
            in("d0") 1.0f64,
            in("x20") renderer,
            lateout("x0") _, lateout("x1") _, lateout("x2") _, lateout("x3") _,
            lateout("x4") _, lateout("x5") _, lateout("x6") _, lateout("x7") _,
            lateout("x8") _, lateout("x9") _, lateout("x10") _, lateout("x11") _,
            lateout("x12") _, lateout("x13") _, lateout("x14") _, lateout("x15") _,
            lateout("x16") _, lateout("x17") _, lateout("lr") _, lateout("x21") _,
            clobber_abi("C"),
        );

        let cg: *mut c_void;
        core::arch::asm!("blr {f}", f = in(reg) crate::resolve::image_renderer_cgimage(),
            in("x20") renderer,
            lateout("x0") cg,
            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("x21") _, clobber_abi("C"),
        );
        assert!(!cg.is_null(), "ImageRenderer produced no image");

        let out = {
            #[cfg(target_os = "macos")]
            {
                let alloc =
                    objc::send(objc::class(c"OBJC_CLASS_$_NSBitmapImageRep"), objc::sel(c"alloc"));
                let rep = objc::send_id(alloc, objc::sel(c"initWithCGImage:"), cg);
                assert!(!rep.is_null(), "NSBitmapImageRep from CGImage failed");

                let data = objc::send_ret_ptr(rep, objc::sel(c"bitmapData"));
                let row = objc::send_ret_u64(rep, objc::sel(c"bytesPerRow")) as usize;
                let w = objc::send_ret_u64(rep, objc::sel(c"pixelsWide")) as u32;
                let h = objc::send_ret_u64(rep, objc::sel(c"pixelsHigh")) as u32;

                let mut pixels = vec![0u8; (w * h * 4) as usize];
                for y in 0..h as usize {
                    core::ptr::copy_nonoverlapping(
                        data.add(y * row),
                        pixels.as_mut_ptr().add(y * w as usize * 4),
                        w as usize * 4,
                    );
                }
                objc::send(rep, objc::sel(c"release"));
                Rendered { width: w, height: h, pixels }
            }
            #[cfg(not(target_os = "macos"))]
            {
                let (w, h, pixels) = crate::cg::cgimage_to_rgba(cg);
                Rendered { width: w, height: h, pixels }
            }
        };

        // A Swift property getter returns an owned value, and `ImageRenderer`
        // is a class: both are ours to let go of. Rendering a few hundred
        // frames otherwise costs a renderer and a full-size image each.
        unsafe extern "C" {
            fn CGImageRelease(image: *mut c_void);
        }
        CGImageRelease(cg);
        swift_runtime_sys::RuntimeRaw::swift_release(renderer);
        out
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Animated capture
// ═══════════════════════════════════════════════════════════════════════════

/// A sequence of rendered frames.
pub struct Animation {
    pub frames: Vec<Rendered>,
}

impl Animation {
    /// Render `count` frames, asking `build` for the view at each step.
    ///
    /// `t` runs from 0.0 to 1.0 inclusive, so the caller expresses the animation
    /// as a pure function of progress. That keeps capture deterministic: no
    /// wall-clock, no run loop, and the same frames every run and on both sides
    /// of a parity comparison.
    pub fn sweep(
        count: usize,
        width: u32,
        height: u32,
        build: impl Fn(f64) -> ViewHandle,
    ) -> Self {
        Self::sweep_with(count, width, height, false, build)
    }

    /// As [`Animation::sweep`], but choosing the capture path.
    ///
    /// Filter effects — blur, saturation, brightness, contrast, grayscale — and
    /// Metal shaders do not execute through `cacheDisplayInRect`; capturing an
    /// animation of one that way yields frames that are all identical.
    pub fn sweep_with(
        count: usize,
        width: u32,
        height: u32,
        via_image_renderer: bool,
        build: impl Fn(f64) -> ViewHandle,
    ) -> Self {
        let frames = (0..count)
            .map(|i| {
                let t = if count <= 1 { 0.0 } else { i as f64 / (count - 1) as f64 };
                let view = build(t);
                if via_image_renderer {
                    render_image(&view, width, height)
                } else {
                    render(&view, width, height)
                }
            })
            .collect();
        Self { frames }
    }

    /// Total pixels differing from `other`, summed over frames.
    /// `u32::MAX` if the frame counts differ.
    pub fn diff_count(&self, other: &Animation, tolerance: u8) -> u32 {
        if self.frames.len() != other.frames.len() {
            return u32::MAX;
        }
        self.frames
            .iter()
            .zip(&other.frames)
            .map(|(a, b)| a.diff_count(b, tolerance))
            .fold(0u32, |acc, n| acc.saturating_add(n))
    }

    /// Per-frame change: how many pixels differ between consecutive frames.
    ///
    /// An animation whose frames are all identical is not animating, however
    /// well-formed the file is.
    pub fn frame_deltas(&self) -> Vec<u32> {
        self.frames
            .windows(2)
            .map(|w| w[0].diff_count(&w[1], 0))
            .collect()
    }

    /// Write the frames tiled left-to-right as one still image.
    ///
    /// An APNG only animates in a viewer that supports it — most macOS previews
    /// show frame one and stop — so a filmstrip is the version that is legible
    /// anywhere.
    pub fn write_filmstrip(&self, path: &str) -> bool {
        let Some(first) = self.frames.first() else { return false };
        let (fw, fh) = (first.width as usize, first.height as usize);
        let n = self.frames.len();
        let gap = 4usize;
        let width = fw * n + gap * (n - 1);
        let mut pixels = vec![0u8; width * fh * 4];
        for (i, frame) in self.frames.iter().enumerate() {
            let x0 = i * (fw + gap);
            for y in 0..fh {
                let src = &frame.pixels[y * fw * 4..(y + 1) * fw * 4];
                let dst = (y * width + x0) * 4;
                pixels[dst..dst + fw * 4].copy_from_slice(src);
            }
        }
        Rendered { width: width as u32, height: fh as u32, pixels }.write_png(path)
    }

    /// Write the frames as an animated PNG.
    pub fn write_apng(&self, path: &str, delay_ms: u16) -> std::io::Result<()> {
        std::fs::write(path, encode_apng(&self.frames, delay_ms))
    }
}

// ── A minimal APNG encoder ────────────────────────────────────────────────
//
// Deflate is emitted as *stored* (uncompressed) blocks. That is a valid zlib
// stream, needs no compression code and no dependency, and produces bytes that
// are identical for identical pixels — which is what matters for a test
// artifact. The files are large; that is the trade.

fn crc32(data: &[u8]) -> u32 {
    let mut table = [0u32; 256];
    for (i, entry) in table.iter_mut().enumerate() {
        let mut c = i as u32;
        for _ in 0..8 {
            c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };
        }
        *entry = c;
    }
    let mut c = 0xFFFF_FFFFu32;
    for &b in data {
        c = table[((c ^ b as u32) & 0xFF) as usize] ^ (c >> 8);
    }
    c ^ 0xFFFF_FFFF
}

fn adler32(data: &[u8]) -> u32 {
    let (mut a, mut b) = (1u32, 0u32);
    for &byte in data {
        a = (a + byte as u32) % 65521;
        b = (b + a) % 65521;
    }
    (b << 16) | a
}

/// zlib stream made of stored deflate blocks.
fn zlib_stored(data: &[u8]) -> Vec<u8> {
    let mut out = vec![0x78, 0x01]; // CMF/FLG for a stored stream
    let mut chunks = data.chunks(65535).peekable();
    if data.is_empty() {
        out.extend_from_slice(&[0x01, 0x00, 0x00, 0xFF, 0xFF]);
    }
    while let Some(chunk) = chunks.next() {
        let last = chunks.peek().is_none();
        out.push(u8::from(last));
        let n = chunk.len() as u16;
        out.extend_from_slice(&n.to_le_bytes());
        out.extend_from_slice(&(!n).to_le_bytes());
        out.extend_from_slice(chunk);
    }
    out.extend_from_slice(&adler32(data).to_be_bytes());
    out
}

fn chunk(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(payload.len() + 12);
    out.extend_from_slice(&(payload.len() as u32).to_be_bytes());
    out.extend_from_slice(kind);
    out.extend_from_slice(payload);
    let mut crc_input = Vec::with_capacity(payload.len() + 4);
    crc_input.extend_from_slice(kind);
    crc_input.extend_from_slice(payload);
    out.extend_from_slice(&crc32(&crc_input).to_be_bytes());
    out
}

/// PNG scanlines with a leading filter byte of 0 on each row.
fn scanlines(frame: &Rendered) -> Vec<u8> {
    let stride = frame.width as usize * 4;
    let mut raw = Vec::with_capacity((stride + 1) * frame.height as usize);
    for y in 0..frame.height as usize {
        raw.push(0);
        raw.extend_from_slice(&frame.pixels[y * stride..(y + 1) * stride]);
    }
    raw
}

fn encode_apng(frames: &[Rendered], delay_ms: u16) -> Vec<u8> {
    assert!(!frames.is_empty(), "an APNG needs at least one frame");
    let (w, h) = (frames[0].width, frames[0].height);

    let mut png = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];

    let mut ihdr = Vec::new();
    ihdr.extend_from_slice(&w.to_be_bytes());
    ihdr.extend_from_slice(&h.to_be_bytes());
    ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); // 8-bit RGBA
    png.extend_from_slice(&chunk(b"IHDR", &ihdr));

    let mut actl = Vec::new();
    actl.extend_from_slice(&(frames.len() as u32).to_be_bytes());
    actl.extend_from_slice(&0u32.to_be_bytes()); // loop forever
    png.extend_from_slice(&chunk(b"acTL", &actl));

    let mut seq = 0u32;
    for (i, frame) in frames.iter().enumerate() {
        let mut fctl = Vec::new();
        fctl.extend_from_slice(&seq.to_be_bytes());
        seq += 1;
        fctl.extend_from_slice(&w.to_be_bytes());
        fctl.extend_from_slice(&h.to_be_bytes());
        fctl.extend_from_slice(&0u32.to_be_bytes()); // x offset
        fctl.extend_from_slice(&0u32.to_be_bytes()); // y offset
        fctl.extend_from_slice(&delay_ms.to_be_bytes());
        fctl.extend_from_slice(&1000u16.to_be_bytes()); // delay denominator
        fctl.extend_from_slice(&[0, 0]); // dispose = none, blend = source
        png.extend_from_slice(&chunk(b"fcTL", &fctl));

        let data = zlib_stored(&scanlines(frame));
        if i == 0 {
            png.extend_from_slice(&chunk(b"IDAT", &data));
        } else {
            let mut fdat = seq.to_be_bytes().to_vec();
            seq += 1;
            fdat.extend_from_slice(&data);
            png.extend_from_slice(&chunk(b"fdAT", &fdat));
        }
    }

    png.extend_from_slice(&chunk(b"IEND", &[]));
    png
}