xgpui-gpu-interop 0.2.0

Experimental zero-copy GPU interop for xgpui: show frames from your own GPU engine (wgpu or Metal) in xgpui windows
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
//! Headless Metal tests: a raw-Metal "engine" on its own command queue draws
//! into slots; xgpui's real Metal renderer composites them.
use super::*;
use crate::{AcquireError, Transport};
use gpui::{Bounds, CustomContent, DevicePixels, Size};
use gpui::{
    ContentMask, CustomDraw, PlatformHeadlessRenderer, ScaledPixels, Scene, WindowColorMode, point,
    size,
};
use gpui_apple::metal_renderer::MetalHeadlessRenderer;
use objc2_metal::{MTLClearColor, MTLCommandQueue, MTLCreateSystemDefaultDevice};
use std::sync::Arc;
use std::time::{Duration, Instant};

/// An independent engine: its own command queue and shared event.
struct Engine {
    device: Retained<ProtocolObject<dyn MTLDevice>>,
    queue: Retained<ProtocolObject<dyn objc2_metal::MTLCommandQueue>>,
    event: Retained<ProtocolObject<dyn MTLSharedEvent>>,
    next: u64,
}
impl Engine {
    fn new() -> Self {
        let device = MTLCreateSystemDefaultDevice().expect("Metal device");
        let queue = device.newCommandQueue().expect("engine queue");
        let event = device.newSharedEvent().expect("engine event");
        Self {
            device,
            queue,
            event,
            next: 0,
        }
    }

    /// Clear `slot` to `color` (in the slot's own encoding), signal, present.
    fn draw_and_present(&mut self, surface: &EngineSurface, slot: SurfaceSlot, color: [f64; 4]) {
        let texture = surface_texture(
            &self.device,
            slot.iosurface(),
            &slot.desc(),
            MTLTextureUsage::RenderTarget | MTLTextureUsage::ShaderRead,
        )
        .unwrap();
        let command = self.queue.commandBuffer().expect("engine command buffer");
        let pass = MTLRenderPassDescriptor::new();
        let attachment = unsafe { pass.colorAttachments().objectAtIndexedSubscript(0) };
        attachment.setTexture(Some(&texture));
        attachment.setLoadAction(MTLLoadAction::Clear);
        attachment.setStoreAction(MTLStoreAction::Store);
        let [red, green, blue, alpha] = color;
        attachment.setClearColor(MTLClearColor {
            red,
            green,
            blue,
            alpha,
        });
        command
            .renderCommandEncoderWithDescriptor(&pass)
            .expect("engine encoder")
            .endEncoding();
        self.next += 1;
        command.encodeSignalEvent_value(ProtocolObject::from_ref(&*self.event), self.next);
        command.commit();
        surface
            // SAFETY: the signal was committed above.
            .present(slot, unsafe {
                SyncPoint::submitted(self.event.clone(), self.next)
            })
            .unwrap();
    }
}

fn desc(format: SurfaceFormat, slots: usize) -> SurfaceDesc {
    SurfaceDesc {
        width: 16,
        height: 8,
        format,
        slots,
    }
}

/// A scene placing `content` at twice the slot size.
fn scene(content: Arc<dyn CustomContent>) -> Scene {
    let bounds = Bounds::new(
        point(ScaledPixels(0.), ScaledPixels(0.)),
        size(ScaledPixels(32.), ScaledPixels(16.)),
    );
    let mut scene = Scene::default();
    scene.insert_primitive(CustomDraw {
        order: 0,
        bounds,
        content_mask: ContentMask { bounds },
        corner_radii: Default::default(),
        opacity: 1.,
        content,
        coverage: None,
    });
    scene.finish();
    scene
}

fn viewport() -> Size<DevicePixels> {
    size(DevicePixels(32), DevicePixels(16))
}

fn near(actual: [u8; 4], expected: [u8; 4]) -> bool {
    actual.iter().zip(expected).all(|(a, e)| a.abs_diff(e) <= 2)
}

#[test]
fn bgra_frame_composites_scaled_without_copy() {
    objc2::rc::autoreleasepool(|_| {
        let surface = EngineSurface::new(desc(SurfaceFormat::Bgra8Srgb, 3)).unwrap();
        let mut engine = Engine::new();
        let mut renderer = MetalHeadlessRenderer::new().unwrap();
        assert!(surface.content().is_none());
        let slot = surface.acquire().unwrap();
        engine.draw_and_present(&surface, slot, [0.2, 0.6, 0.9, 1.0]);
        let image = renderer
            .render_scene_to_image(&scene(surface.content().unwrap()), viewport())
            .unwrap();
        for (x, y) in [(1, 1), (16, 8), (30, 14)] {
            let pixel = image.get_pixel(x, y).0;
            assert!(near(pixel, [51, 153, 230, 255]), "({x},{y}) = {pixel:?}");
        }
        assert_eq!(surface.stats().presents, 1);
        assert_eq!(surface.transport(), Transport::ZeroCopy);
    });
}

#[test]
fn wide_frame_composites_in_wide_window() {
    objc2::rc::autoreleasepool(|_| {
        let surface = EngineSurface::new(desc(SurfaceFormat::Rgba16FloatLinearP3, 2)).unwrap();
        let mut engine = Engine::new();
        let mut renderer = MetalHeadlessRenderer::new().unwrap();
        renderer
            .set_color_mode(WindowColorMode::WideGamutSdr)
            .unwrap();
        let slot = surface.acquire().unwrap();
        // Linear neutral 0.5 is identical in P3 and sRGB: encoded ≈ 188.
        engine.draw_and_present(&surface, slot, [0.5, 0.5, 0.5, 1.0]);
        let image = renderer
            .render_scene_to_image(&scene(surface.content().unwrap()), viewport())
            .unwrap();
        let pixel = image.get_pixel(16, 8).0;
        assert!(near(pixel, [188, 188, 188, 255]), "{pixel:?}");
    });
}

#[test]
fn retained_snapshot_keeps_its_slot_immutable() {
    objc2::rc::autoreleasepool(|_| {
        let surface = EngineSurface::new(desc(SurfaceFormat::Bgra8Srgb, 2)).unwrap();
        let mut engine = Engine::new();
        let mut renderer = MetalHeadlessRenderer::new().unwrap();
        let first = surface.acquire().unwrap();
        let first_index = first.index();
        engine.draw_and_present(&surface, first, [1.0, 0.0, 0.0, 1.0]);
        let old_scene = scene(surface.content().unwrap());
        let second = surface.acquire().unwrap();
        engine.draw_and_present(&surface, second, [0.0, 1.0, 0.0, 1.0]);

        // Slot one is retained by the old scene, slot two is the latest frame.
        assert_eq!(surface.acquire().err(), Some(AcquireError::WouldBlock));
        assert_eq!(surface.stats().would_block, 1);
        // Replaying the old scene still shows the first frame.
        let replay = renderer
            .render_scene_to_image(&old_scene, viewport())
            .unwrap();
        assert!(near(replay.get_pixel(16, 8).0, [255, 0, 0, 255]));
        let latest = renderer
            .render_scene_to_image(&scene(surface.content().unwrap()), viewport())
            .unwrap();
        assert!(near(latest.get_pixel(16, 8).0, [0, 255, 0, 255]));

        drop(old_scene);
        // The renderer also released its in-flight reference after completion.
        let deadline = Instant::now() + Duration::from_secs(2);
        let reacquired = loop {
            if let Ok(slot) = surface.acquire() {
                break slot;
            }
            assert!(Instant::now() < deadline, "slot never returned");
            std::thread::sleep(Duration::from_millis(2));
        };
        assert_eq!(reacquired.index(), first_index);
    });
}

#[test]
fn slot_returns_only_after_gpu_composition_completes() {
    objc2::rc::autoreleasepool(|_| {
        let surface = EngineSurface::new(desc(SurfaceFormat::Bgra8Srgb, 2)).unwrap();
        let mut engine = Engine::new();
        let mut renderer = MetalHeadlessRenderer::new().unwrap();
        let first = surface.acquire().unwrap();
        engine.draw_and_present(&surface, first, [1.0, 0.0, 0.0, 1.0]);
        // Submit a composition without waiting, then drop every CPU reference.
        let frame = scene(surface.content().unwrap());
        renderer.render_scene(&frame, viewport()).unwrap();
        drop(frame);
        let second = surface.acquire().unwrap();
        engine.draw_and_present(&surface, second, [0.0, 1.0, 0.0, 1.0]);
        // The first slot comes back once the renderer's completion handler
        // releases its snapshot, without any further frames.
        let deadline = Instant::now() + Duration::from_secs(2);
        while surface.acquire().is_err() {
            assert!(
                Instant::now() < deadline,
                "slot never returned after completion"
            );
            std::thread::sleep(Duration::from_millis(2));
        }
    });
}

#[test]
fn present_wakes_and_rejects_foreign_slots() {
    let surface = EngineSurface::new(desc(SurfaceFormat::Bgra8Srgb, 2)).unwrap();
    let other = EngineSurface::new(desc(SurfaceFormat::Bgra8Srgb, 2)).unwrap();
    let wakes = Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let counter = wakes.clone();
    surface.on_present(move || {
        counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    });
    let engine = Engine::new();
    let foreign = other.acquire().unwrap();
    assert!(
        surface
            .present(foreign, SyncPoint::new(engine.event.clone(), 0))
            .is_err()
    );
    let slot = surface.acquire().unwrap();
    surface
        .present(slot, SyncPoint::new(engine.event.clone(), 0))
        .unwrap();
    assert_eq!(wakes.load(std::sync::atomic::Ordering::Relaxed), 1);
}

/// Fill a BGRA slot with four quadrant colors from the CPU (test only).
fn fill_quadrants(engine: &mut Engine, surface: &EngineSurface, slot: SurfaceSlot) {
    let desc = slot.desc();
    let texture = surface_texture(
        &engine.device,
        slot.iosurface(),
        &desc,
        MTLTextureUsage::ShaderRead,
    )
    .unwrap();
    let (w, h) = (desc.width as usize, desc.height as usize);
    let mut bytes = vec![0u8; w * h * 4];
    for y in 0..h {
        for x in 0..w {
            // BGRA: TL red, TR green, BL blue, BR white.
            let pixel = match (x < w / 2, y < h / 2) {
                (true, true) => [0, 0, 255, 255],
                (false, true) => [0, 255, 0, 255],
                (true, false) => [255, 0, 0, 255],
                (false, false) => [255, 255, 255, 255],
            };
            bytes[(y * w + x) * 4..][..4].copy_from_slice(&pixel);
        }
    }
    unsafe {
        texture.replaceRegion_mipmapLevel_withBytes_bytesPerRow(
            objc2_metal::MTLRegion {
                origin: objc2_metal::MTLOrigin { x: 0, y: 0, z: 0 },
                size: objc2_metal::MTLSize {
                    width: w,
                    height: h,
                    depth: 1,
                },
            },
            0,
            std::ptr::NonNull::new(bytes.as_mut_ptr().cast()).unwrap(),
            w * 4,
        );
    }
    engine.next += 1;
    engine.event.setSignaledValue(engine.next);
    surface
        .present(slot, SyncPoint::new(engine.event.clone(), engine.next))
        .unwrap();
}

#[test]
fn placements_of_different_sizes_show_the_whole_slot() {
    objc2::rc::autoreleasepool(|_| {
        let surface = EngineSurface::new(desc(SurfaceFormat::Bgra8Srgb, 2)).unwrap();
        let mut engine = Engine::new();
        let mut renderer = MetalHeadlessRenderer::new().unwrap();
        let slot = surface.acquire().unwrap();
        fill_quadrants(&mut engine, &surface, slot);
        let content = surface.content().unwrap();
        let mut scene = Scene::default();
        // Large placement 64x32 at (0,0); small placement 16x8 at (64,0).
        for (x, w, h) in [(0., 64., 32.), (64., 16., 8.)] {
            let bounds = Bounds::new(
                point(ScaledPixels(x), ScaledPixels(0.)),
                size(ScaledPixels(w), ScaledPixels(h)),
            );
            scene.insert_primitive(CustomDraw {
                order: 0,
                bounds,
                content_mask: ContentMask { bounds },
                corner_radii: Default::default(),
                opacity: 1.,
                content: content.clone(),
                coverage: None,
            });
        }
        scene.finish();
        let image = renderer
            .render_scene_to_image(&scene, size(DevicePixels(80), DevicePixels(32)))
            .unwrap();
        let red = [255, 0, 0, 255];
        let green = [0, 255, 0, 255];
        let blue = [0, 0, 255, 255];
        let white = [255; 4];
        let mut report = Vec::new();
        for (name, (x0, w, h)) in [("large", (0u32, 64u32, 32u32)), ("small", (64, 16, 8))] {
            for (label, fx, fy, want) in [
                ("TL", 0.25, 0.25, red),
                ("TR", 0.75, 0.25, green),
                ("BL", 0.25, 0.75, blue),
                ("BR", 0.75, 0.75, white),
            ] {
                let x = x0 + (w as f32 * fx) as u32;
                let y = (h as f32 * fy) as u32;
                let got = image.get_pixel(x, y).0;
                if !near(got, want) {
                    report.push(format!(
                        "{name} {label} at ({x},{y}) = {got:?}, want {want:?}"
                    ));
                }
            }
        }
        assert!(report.is_empty(), "{}", report.join("\n"));
    });
}

// Engines present from their own threads; the UI composites on its own.
const _: () = {
    const fn send_sync<T: Send + Sync>() {}
    send_sync::<EngineSurface>();
    send_sync::<SyncPoint>();
};
#[cfg(feature = "wgpu")]
const _: () = {
    const fn send<T: Send>() {}
    send::<WgpuSurfaceTarget>();
};

#[test]
fn present_from_engine_thread_composites_on_ui_thread() {
    objc2::rc::autoreleasepool(|_| {
        let surface = EngineSurface::new(desc(SurfaceFormat::Bgra8Srgb, 3)).unwrap();
        let mut renderer = MetalHeadlessRenderer::new().unwrap();
        let engine_surface = surface.clone();
        std::thread::spawn(move || {
            let mut engine = Engine::new();
            let slot = engine_surface.acquire().unwrap();
            engine.draw_and_present(&engine_surface, slot, [0.0, 0.0, 1.0, 1.0]);
        })
        .join()
        .unwrap();
        let image = renderer
            .render_scene_to_image(&scene(surface.content().unwrap()), viewport())
            .unwrap();
        assert!(near(image.get_pixel(16, 8).0, [0, 0, 255, 255]));
    });
}

#[test]
fn rounded_placement_clips_corners() {
    objc2::rc::autoreleasepool(|_| {
        let surface = EngineSurface::new(desc(SurfaceFormat::Bgra8Srgb, 2)).unwrap();
        let mut engine = Engine::new();
        let mut renderer = MetalHeadlessRenderer::new().unwrap();
        let slot = surface.acquire().unwrap();
        engine.draw_and_present(&surface, slot, [1.0, 1.0, 1.0, 1.0]);
        let bounds = Bounds::new(
            point(ScaledPixels(0.), ScaledPixels(0.)),
            size(ScaledPixels(32.), ScaledPixels(16.)),
        );
        let mut rounded = Scene::default();
        rounded.insert_primitive(CustomDraw {
            order: 0,
            bounds,
            content_mask: ContentMask { bounds },
            corner_radii: gpui::Corners::all(ScaledPixels(6.)),
            opacity: 1.,
            content: surface.content().unwrap(),
            coverage: None,
        });
        rounded.finish();
        let image = renderer
            .render_scene_to_image(&rounded, viewport())
            .unwrap();
        let corner = image.get_pixel(0, 0).0;
        assert!(!near(corner, [255; 4]), "corner not clipped: {corner:?}");
        assert!(near(image.get_pixel(16, 8).0, [255; 4]));
    });
}

/// Losing the engine (#197 K6): new work is rejected, the last frame keeps
/// compositing from the surface's own memory, and a new surface recovers.
#[test]
fn invalidated_surface_keeps_last_frame_and_recovers() {
    objc2::rc::autoreleasepool(|_| {
        let surface = EngineSurface::new(desc(SurfaceFormat::Bgra8Srgb, 2)).unwrap();
        let mut renderer = MetalHeadlessRenderer::new().unwrap();
        let pending = {
            let mut engine = Engine::new();
            let slot = surface.acquire().unwrap();
            engine.draw_and_present(&surface, slot, [1.0, 0.0, 0.0, 1.0]);
            let image = renderer
                .render_scene_to_image(&scene(surface.content().unwrap()), viewport())
                .unwrap();
            assert!(near(image.get_pixel(16, 8).0, [255, 0, 0, 255]));
            let pending = surface.acquire().unwrap();
            (pending, engine.event.clone())
            // The engine's queue and resources are dropped here.
        };
        surface.invalidate();
        assert!(!surface.is_valid());
        assert_eq!(surface.acquire().err(), Some(AcquireError::Invalidated));
        let (slot, event) = pending;
        assert!(surface.present(slot, SyncPoint::new(event, 0)).is_err());
        let image = renderer
            .render_scene_to_image(&scene(surface.content().unwrap()), viewport())
            .unwrap();
        assert!(
            near(image.get_pixel(16, 8).0, [255, 0, 0, 255]),
            "last frame must survive the engine"
        );
        let replacement = EngineSurface::new(desc(SurfaceFormat::Bgra8Srgb, 2)).unwrap();
        let mut engine = Engine::new();
        let slot = replacement.acquire().unwrap();
        engine.draw_and_present(&replacement, slot, [0.0, 1.0, 0.0, 1.0]);
        let image = renderer
            .render_scene_to_image(&scene(replacement.content().unwrap()), viewport())
            .unwrap();
        assert!(near(image.get_pixel(16, 8).0, [0, 255, 0, 255]));
    });
}

/// Linear P3 (0.5, 0.25, 0.25) mapped to clipped sRGB and encoded. Unmapped
/// channels would encode as (188, 137, 137).
const P3_PREVIEW: [u8; 4] = [197, 134, 136, 255];

fn near3(actual: [u8; 4], expected: [u8; 4]) -> bool {
    actual.iter().zip(expected).all(|(a, e)| a.abs_diff(e) <= 3)
}

/// K2: an RGBA16F surface in a standard (non-wide) window composites as an
/// sRGB preview from the same slot, without a copy; the wide placement is
/// still rejected there.
#[test]
fn wide_frame_previews_in_standard_window() {
    objc2::rc::autoreleasepool(|_| {
        let surface = EngineSurface::new(desc(SurfaceFormat::Rgba16FloatLinearP3, 2)).unwrap();
        let mut engine = Engine::new();
        let mut renderer = MetalHeadlessRenderer::new().unwrap();
        let slot = surface.acquire().unwrap();
        engine.draw_and_present(&surface, slot, [0.5, 0.25, 0.25, 1.0]);
        assert!(
            renderer
                .render_scene_to_image(&scene(surface.content().unwrap()), viewport())
                .is_err(),
            "wide placement needs a wide window"
        );
        let image = renderer
            .render_scene_to_image(&scene(surface.preview_content().unwrap()), viewport())
            .unwrap();
        let pixel = image.get_pixel(16, 8).0;
        assert!(near3(pixel, P3_PREVIEW), "{pixel:?}");
    });
}

/// K2: the same frame placed in a wide and a standard window at once.
#[test]
fn one_frame_composites_wide_and_preview() {
    objc2::rc::autoreleasepool(|_| {
        let surface = EngineSurface::new(desc(SurfaceFormat::Rgba16FloatLinearP3, 2)).unwrap();
        let mut engine = Engine::new();
        let mut standard = MetalHeadlessRenderer::new().unwrap();
        let mut wide = MetalHeadlessRenderer::new().unwrap();
        wide.set_color_mode(WindowColorMode::WideGamutSdr).unwrap();
        let slot = surface.acquire().unwrap();
        engine.draw_and_present(&surface, slot, [0.5, 0.5, 0.5, 1.0]);
        let wide_scene = scene(surface.content().unwrap());
        let preview_scene = scene(surface.preview_content().unwrap());
        for image in [
            wide.render_scene_to_image(&wide_scene, viewport()).unwrap(),
            standard
                .render_scene_to_image(&preview_scene, viewport())
                .unwrap(),
        ] {
            let pixel = image.get_pixel(16, 8).0;
            assert!(near(pixel, [188, 188, 188, 255]), "{pixel:?}");
        }
        drop((wide_scene, preview_scene));
        let deadline = Instant::now() + Duration::from_secs(2);
        while surface.stats().free < 1 && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(5));
        }
        assert_eq!(surface.stats().free, 1, "both placements released the slot");
    });
}

/// K2: a wgpu engine writes an RGBA16F slot from a compute shader.
#[cfg(feature = "wgpu")]
#[test]
fn compute_written_frame_composites() {
    use crate::{test_engine::compute_fill, wgpu};
    objc2::rc::autoreleasepool(|_| {
        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
            backends: wgpu::Backends::METAL,
            ..wgpu::InstanceDescriptor::new_without_display_handle()
        });
        let adapter =
            gpui::block_on(instance.request_adapter(&Default::default())).expect("Metal adapter");
        let (device, queue) = gpui::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
            required_features: WgpuSurfaceTarget::required_features(),
            ..Default::default()
        }))
        .unwrap();
        let mut target =
            WgpuSurfaceTarget::new(desc(SurfaceFormat::Rgba16FloatLinearP3, 2), &device, &queue)
                .unwrap();
        let slot = target.surface().acquire().unwrap();
        let texture = target.texture(&slot).unwrap();
        let commands = compute_fill(&device, &texture, [0.5, 0.25, 0.25, 1.0]);
        target.present(slot, [commands]).unwrap();
        let mut renderer = MetalHeadlessRenderer::new().unwrap();
        let image = renderer
            .render_scene_to_image(
                &scene(target.surface().preview_content().unwrap()),
                viewport(),
            )
            .unwrap();
        let pixel = image.get_pixel(16, 8).0;
        assert!(near3(pixel, P3_PREVIEW), "{pixel:?}");
    });
}

/// Clear `slot` to `color` and present it with an observed point on a
/// separate event that the test signals from the CPU (or never).
fn present_observed(
    engine: &mut Engine,
    surface: &EngineSurface,
    slot: SurfaceSlot,
    color: [f64; 4],
    gate: &Retained<ProtocolObject<dyn MTLSharedEvent>>,
    value: u64,
) {
    let texture = surface_texture(
        &engine.device,
        slot.iosurface(),
        &slot.desc(),
        MTLTextureUsage::RenderTarget | MTLTextureUsage::ShaderRead,
    )
    .unwrap();
    let command = engine.queue.commandBuffer().expect("engine command buffer");
    let pass = MTLRenderPassDescriptor::new();
    let attachment = unsafe { pass.colorAttachments().objectAtIndexedSubscript(0) };
    attachment.setTexture(Some(&texture));
    attachment.setLoadAction(MTLLoadAction::Clear);
    attachment.setStoreAction(MTLStoreAction::Store);
    let [red, green, blue, alpha] = color;
    attachment.setClearColor(MTLClearColor {
        red,
        green,
        blue,
        alpha,
    });
    command
        .renderCommandEncoderWithDescriptor(&pass)
        .expect("engine encoder")
        .endEncoding();
    command.commit();
    command.waitUntilCompleted();
    surface
        .present(slot, SyncPoint::new(gate.clone(), value))
        .unwrap();
}

/// Acceptance (#197): an engine that never signals cannot stall the
/// compositor. Its frames wait off-screen; the last ready frame keeps
/// compositing; the ring fills and backpressures the engine.
#[test]
fn never_signaled_frames_cannot_stall_composition() {
    objc2::rc::autoreleasepool(|_| {
        let surface = EngineSurface::new(desc(SurfaceFormat::Bgra8Srgb, 3)).unwrap();
        let mut engine = Engine::new();
        let mut renderer = MetalHeadlessRenderer::new().unwrap();
        let slot = surface.acquire().unwrap();
        engine.draw_and_present(&surface, slot, [1.0, 0.0, 0.0, 1.0]);
        let never = engine.device.newSharedEvent().expect("event");
        let mut presented = 0;
        while let Ok(slot) = surface.acquire() {
            present_observed(&mut engine, &surface, slot, [0.0, 0.0, 1.0, 1.0], &never, 1);
            presented += 1;
        }
        assert!(presented >= 1);
        assert_eq!(surface.stats().waiting, presented);
        assert_eq!(surface.acquire().err(), Some(AcquireError::WouldBlock));
        let started = Instant::now();
        for _ in 0..3 {
            let image = renderer
                .render_scene_to_image(&scene(surface.content().unwrap()), viewport())
                .unwrap();
            assert!(near(image.get_pixel(16, 8).0, [255, 0, 0, 255]));
        }
        assert!(
            started.elapsed() < Duration::from_secs(2),
            "composition stalled: {:?}",
            started.elapsed()
        );
    });
}

/// An observed frame appears once its point is reached, the waiter wakes the
/// UI without a new present, and older frames are then released.
#[test]
fn observed_frame_appears_when_reached_and_wakes_the_ui() {
    objc2::rc::autoreleasepool(|_| {
        let surface = EngineSurface::new(desc(SurfaceFormat::Bgra8Srgb, 3)).unwrap();
        let mut engine = Engine::new();
        let mut renderer = MetalHeadlessRenderer::new().unwrap();
        let wakes = Arc::new(std::sync::atomic::AtomicU32::new(0));
        let counter = wakes.clone();
        surface.on_present(move || {
            counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        });
        let slot = surface.acquire().unwrap();
        engine.draw_and_present(&surface, slot, [1.0, 0.0, 0.0, 1.0]);
        let gate = engine.device.newSharedEvent().expect("event");
        let slot = surface.acquire().unwrap();
        present_observed(&mut engine, &surface, slot, [0.0, 1.0, 0.0, 1.0], &gate, 5);
        let presents_woken = wakes.load(std::sync::atomic::Ordering::SeqCst);
        let image = renderer
            .render_scene_to_image(&scene(surface.content().unwrap()), viewport())
            .unwrap();
        assert!(
            near(image.get_pixel(16, 8).0, [255, 0, 0, 255]),
            "unreached frame must not show"
        );
        assert_eq!(surface.stats().waiting, 1);
        gate.setSignaledValue(5);
        let deadline = Instant::now() + Duration::from_secs(2);
        while wakes.load(std::sync::atomic::Ordering::SeqCst) == presents_woken {
            assert!(Instant::now() < deadline, "waiter never woke the UI");
            std::thread::sleep(Duration::from_millis(2));
        }
        let image = renderer
            .render_scene_to_image(&scene(surface.content().unwrap()), viewport())
            .unwrap();
        assert!(near(image.get_pixel(16, 8).0, [0, 255, 0, 255]));
        let deadline = Instant::now() + Duration::from_secs(2);
        while surface.stats().free < 2 {
            assert!(Instant::now() < deadline, "superseded frame kept its slot");
            std::thread::sleep(Duration::from_millis(2));
        }
        assert_eq!(surface.stats().waiting, 0);
    });
}

/// A submitted point whose engine work is still running is waited for on
/// the GPU: the frame shows at once, with no CPU wait.
#[test]
fn submitted_frame_is_waited_for_on_the_gpu() {
    objc2::rc::autoreleasepool(|_| {
        let surface = EngineSurface::new(desc(SurfaceFormat::Bgra8Srgb, 2)).unwrap();
        let mut engine = Engine::new();
        let mut renderer = MetalHeadlessRenderer::new().unwrap();
        let slot = surface.acquire().unwrap();
        engine.draw_and_present(&surface, slot, [0.0, 0.0, 1.0, 1.0]);
        assert_eq!(
            surface.stats().waiting,
            0,
            "submitted frames never wait off-screen"
        );
        let image = renderer
            .render_scene_to_image(&scene(surface.content().unwrap()), viewport())
            .unwrap();
        assert!(near(image.get_pixel(16, 8).0, [0, 0, 255, 255]));
    });
}

/// #197 K6: the compositor is replaced (new renderer and queue). Retained
/// scenes and new frames composite on the replacement.
#[test]
fn compositor_replacement_keeps_compositing() {
    objc2::rc::autoreleasepool(|_| {
        let surface = EngineSurface::new(desc(SurfaceFormat::Rgba16FloatLinearP3, 3)).unwrap();
        let mut engine = Engine::new();
        let mut first = MetalHeadlessRenderer::new().unwrap();
        first.set_color_mode(WindowColorMode::WideGamutSdr).unwrap();
        let slot = surface.acquire().unwrap();
        engine.draw_and_present(&surface, slot, [0.5, 0.5, 0.5, 1.0]);
        let retained = scene(surface.content().unwrap());
        let image = first.render_scene_to_image(&retained, viewport()).unwrap();
        assert!(near(image.get_pixel(16, 8).0, [188, 188, 188, 255]));
        drop(first);
        let mut second = MetalHeadlessRenderer::new().unwrap();
        second
            .set_color_mode(WindowColorMode::WideGamutSdr)
            .unwrap();
        let image = second.render_scene_to_image(&retained, viewport()).unwrap();
        assert!(near(image.get_pixel(16, 8).0, [188, 188, 188, 255]));
        drop(retained);
        for i in 0..4 {
            let slot = surface.acquire().unwrap();
            let v = if i % 2 == 0 { 1.0 } else { 0.0 };
            engine.draw_and_present(&surface, slot, [v, v, v, 1.0]);
            let image = second
                .render_scene_to_image(&scene(surface.content().unwrap()), viewport())
                .unwrap();
            let e = if i % 2 == 0 { 255 } else { 0 };
            assert!(near(image.get_pixel(16, 8).0, [e, e, e, 255]), "frame {i}");
        }
    });
}

/// Write `bytes` into `slot` from the CPU, mark it complete, present it.
fn present_bytes(
    engine: &mut Engine,
    surface: &EngineSurface,
    slot: SurfaceSlot,
    bytes: &mut [u8],
) {
    let desc = slot.desc();
    let texture = surface_texture(
        &engine.device,
        slot.iosurface(),
        &desc,
        MTLTextureUsage::ShaderRead,
    )
    .unwrap();
    let (w, h) = (desc.width as usize, desc.height as usize);
    unsafe {
        texture.replaceRegion_mipmapLevel_withBytes_bytesPerRow(
            objc2_metal::MTLRegion {
                origin: objc2_metal::MTLOrigin { x: 0, y: 0, z: 0 },
                size: objc2_metal::MTLSize {
                    width: w,
                    height: h,
                    depth: 1,
                },
            },
            0,
            std::ptr::NonNull::new(bytes.as_mut_ptr().cast()).unwrap(),
            w * desc.format.bytes_per_pixel() as usize,
        );
    }
    engine.next += 1;
    engine.event.setSignaledValue(engine.next);
    surface
        .present(slot, SyncPoint::new(engine.event.clone(), engine.next))
        .unwrap();
}

/// A strip placed 1:1 at `opacity`.
fn strip_scene(content: Arc<dyn CustomContent>, width: u32, opacity: f32) -> Scene {
    use crate::colour_reference::HEIGHT;
    let bounds = Bounds::new(
        point(ScaledPixels(0.), ScaledPixels(0.)),
        size(ScaledPixels(width as f32), ScaledPixels(HEIGHT as f32)),
    );
    let mut scene = Scene::default();
    scene.insert_primitive(CustomDraw {
        order: 0,
        bounds,
        content_mask: ContentMask { bounds },
        corner_radii: Default::default(),
        opacity,
        content,
        coverage: None,
    });
    scene.finish();
    scene
}

/// Acceptance (#197): colour through the compositor against an independent
/// CPU reference. Preview: near-black, out-of-sRGB P3, fractional alpha and
/// opacity are mapped to clipped sRGB; sRGB controls are unchanged. Wide:
/// the FP16 linear-P3 composition keeps the values, including out-of-sRGB.
#[test]
fn colour_matches_reference_in_preview_and_wide() {
    use crate::colour_reference::*;
    objc2::rc::autoreleasepool(|_| {
        let mut engine = Engine::new();
        let strip_desc = SurfaceDesc {
            width: width(),
            height: HEIGHT,
            format: SurfaceFormat::Rgba16FloatLinearP3,
            slots: 2,
        };
        let strip = EngineSurface::new(strip_desc).unwrap();
        let slot = strip.acquire().unwrap();
        present_bytes(&mut engine, &strip, slot, &mut strip_rgba16f());
        let controls = EngineSurface::new(SurfaceDesc {
            width: SRGB_CONTROLS.len() as u32 * STRIPE,
            format: SurfaceFormat::Bgra8Srgb,
            ..strip_desc
        })
        .unwrap();
        let slot = controls.acquire().unwrap();
        present_bytes(&mut engine, &controls, slot, &mut controls_bgra8());
        let extent = size(DevicePixels(width() as i32), DevicePixels(HEIGHT as i32));
        let mut failures = Vec::new();
        let mut worst = 0f64;

        // Preview, standard window.
        let mut standard = MetalHeadlessRenderer::new().unwrap();
        for opacity in [1., 0.5] {
            let image = standard
                .render_scene_to_image(
                    &strip_scene(strip.preview_content().unwrap(), width(), opacity),
                    extent,
                )
                .unwrap();
            for (i, (name, patch)) in PATCHES.iter().enumerate() {
                let actual = image.get_pixel(centre(i), HEIGHT / 2).0;
                let expected = preview(*patch, opacity);
                let d = distance(actual, expected);
                worst = worst.max(d);
                eprintln!("preview {name} @ {opacity}: {actual:?} expected {expected:.1?}");
                if d > 2.5 {
                    failures.push(format!(
                        "preview {name} @ {opacity}: {actual:?} vs {expected:.1?}"
                    ));
                }
            }
            let image = standard
                .render_scene_to_image(
                    &strip_scene(
                        controls.content().unwrap(),
                        SRGB_CONTROLS.len() as u32 * STRIPE,
                        opacity,
                    ),
                    extent,
                )
                .unwrap();
            for (i, (name, rgba)) in SRGB_CONTROLS.iter().enumerate() {
                let actual = image.get_pixel(centre(i), HEIGHT / 2).0;
                let expected = control(*rgba, opacity);
                let d = distance(actual, expected);
                worst = worst.max(d);
                eprintln!("control {name} @ {opacity}: {actual:?} expected {expected:.1?}");
                if d > 2.5 {
                    failures.push(format!(
                        "control {name} @ {opacity}: {actual:?} vs {expected:.1?}"
                    ));
                }
            }
        }

        // Wide: the FP16 composition keeps linear P3, scaled by opacity.
        let mut wide = MetalHeadlessRenderer::new().unwrap();
        wide.set_color_mode(WindowColorMode::WideGamutSdr).unwrap();
        for opacity in [1., 0.5] {
            let image = wide
                .render_scene_to_linear_p3(
                    &strip_scene(strip.content().unwrap(), width(), opacity),
                    extent,
                )
                .unwrap();
            for (i, (name, patch)) in PATCHES.iter().enumerate() {
                let texel = image.pixels[(HEIGHT / 2 * width() + centre(i)) as usize];
                let actual: Vec<f32> = texel
                    .iter()
                    .map(|&bits| crate::colour_reference_f16(bits))
                    .collect();
                // Associated linear P3 over the opaque black background.
                let expected: Vec<f32> = patch[..3].iter().map(|v| v * opacity).collect();
                let d = actual[..3]
                    .iter()
                    .zip(&expected)
                    .map(|(a, e)| (a - e).abs())
                    .fold(0f32, f32::max);
                eprintln!("wide {name} @ {opacity}: {actual:.4?} expected {expected:.4?}");
                if d > 2e-3 {
                    failures.push(format!(
                        "wide {name} @ {opacity}: {actual:.4?} vs {expected:.4?}"
                    ));
                }
            }
        }
        assert!(
            failures.is_empty(),
            "colour mismatches:\n{}",
            failures.join("\n")
        );
        eprintln!("colour: all patches within tolerance (worst 8-bit distance {worst:.2})");
    });
}

/// Engine feedback: composited frames record their present-to-composite
/// delay; frames replaced before any composition count as unshown.
#[test]
fn feedback_counts_composited_and_unshown_frames() {
    objc2::rc::autoreleasepool(|_| {
        let surface = EngineSurface::new(desc(SurfaceFormat::Bgra8Srgb, 3)).unwrap();
        let mut engine = Engine::new();
        let mut renderer = MetalHeadlessRenderer::new().unwrap();
        let slot = surface.acquire().unwrap();
        engine.draw_and_present(&surface, slot, [1.0, 0.0, 0.0, 1.0]);
        renderer
            .render_scene_to_image(&scene(surface.content().unwrap()), viewport())
            .unwrap();
        // Two more frames; only the last is composited.
        for color in [[0.0, 1.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]] {
            let slot = surface.acquire().unwrap();
            engine.draw_and_present(&surface, slot, color);
        }
        renderer
            .render_scene_to_image(&scene(surface.content().unwrap()), viewport())
            .unwrap();
        let stats = surface.stats();
        assert_eq!(stats.composited, 2, "{stats:?}");
        assert_eq!(stats.unshown, 1, "{stats:?}");
        assert!(stats.composite_latency_ms >= 0. && stats.composite_latency_ms < 1000.);
    });
}

/// Observe-only target: frames appear once complete, without a GPU wait,
/// and the waiter wakes the UI.
#[cfg(feature = "wgpu")]
#[test]
fn observe_only_target_shows_completed_frames() {
    use crate::{test_engine::compute_fill, wgpu};
    objc2::rc::autoreleasepool(|_| {
        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
            backends: wgpu::Backends::METAL,
            ..wgpu::InstanceDescriptor::new_without_display_handle()
        });
        let adapter =
            gpui::block_on(instance.request_adapter(&Default::default())).expect("Metal adapter");
        let (device, queue) = gpui::block_on(adapter.request_device(&Default::default())).unwrap();
        let mut target =
            WgpuSurfaceTarget::new(desc(SurfaceFormat::Rgba16FloatLinearP3, 2), &device, &queue)
                .unwrap();
        target.set_gpu_wait(false);
        assert!(!target.gpu_wait());
        let slot = target.surface().acquire().unwrap();
        let texture = target.texture(&slot).unwrap();
        let commands = compute_fill(&device, &texture, [0.5, 0.25, 0.25, 1.0]);
        target.present(slot, [commands]).unwrap();
        let deadline = Instant::now() + Duration::from_secs(2);
        while target.surface().stats().waiting > 0 {
            assert!(
                Instant::now() < deadline,
                "observed frame never became ready"
            );
            std::thread::sleep(Duration::from_millis(1));
        }
        let mut renderer = MetalHeadlessRenderer::new().unwrap();
        let image = renderer
            .render_scene_to_image(
                &scene(target.surface().preview_content().unwrap()),
                viewport(),
            )
            .unwrap();
        let pixel = image.get_pixel(16, 8).0;
        assert!(near3(pixel, P3_PREVIEW), "{pixel:?}");
    });
}

/// Heavy-engine mode on a target: observe-only, pacing and a measured frame
/// time that drives the chunk advice.
#[cfg(feature = "wgpu")]
#[test]
fn heavy_mode_paces_and_measures_frames() {
    use crate::{HeavyEngine, test_engine::compute_fill, wgpu};
    objc2::rc::autoreleasepool(|_| {
        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
            backends: wgpu::Backends::METAL,
            ..wgpu::InstanceDescriptor::new_without_display_handle()
        });
        let adapter =
            gpui::block_on(instance.request_adapter(&Default::default())).expect("Metal adapter");
        let (device, queue) = gpui::block_on(adapter.request_device(&Default::default())).unwrap();
        let mut target =
            WgpuSurfaceTarget::new(desc(SurfaceFormat::Rgba16FloatLinearP3, 3), &device, &queue)
                .unwrap();
        assert_eq!(target.pace(), Duration::ZERO, "no pacing unless heavy");
        assert_eq!(target.suggested_chunks(), 1);
        target.set_heavy(Some(HeavyEngine::default()));
        assert!(!target.gpu_wait(), "heavy mode is observe-only");
        for _ in 0..3 {
            let slot = target.surface().acquire().unwrap();
            let texture = target.texture(&slot).unwrap();
            let commands = compute_fill(&device, &texture, [0.5, 0.25, 0.25, 1.0]);
            target.present(slot, [commands]).unwrap();
            let _ = device.poll(wgpu::PollType::wait_indefinitely());
            let delay = target.pace();
            assert!(
                delay > Duration::ZERO && delay <= Duration::from_secs(4),
                "{delay:?}"
            );
        }
        let status = target.heavy().unwrap();
        assert!(status.frame_ms.is_some(), "frame time measured: {status:?}");
        assert!(status.suggested_chunks >= 1);
        target.set_heavy(None);
        assert!(target.gpu_wait() && target.heavy().is_none());
    });
}

/// Acceptance item 1: a compositor that cannot use the surface fails with a
/// typed reason once; the surface then offers no frames.
#[test]
fn unsupported_compositor_is_reported_once_and_detaches() {
    objc2::rc::autoreleasepool(|_| {
        let surface = EngineSurface::new(desc(SurfaceFormat::Bgra8Srgb, 2)).unwrap();
        let mut engine = Engine::new();
        let slot = surface.acquire().unwrap();
        engine.draw_and_present(&surface, slot, [1.0, 0.0, 0.0, 1.0]);
        let content = surface.content().unwrap();
        assert!(surface.unsupported().is_none());
        // Not a Metal compositor context.
        let error = content
            .prepare(&(), size(DevicePixels(16), DevicePixels(8)))
            .unwrap_err();
        assert!(error.downcast_ref::<Unsupported>().is_some(), "{error:#}");
        let reason = surface.unsupported().expect("reason latched");
        assert!(reason.contains("Metal compositor"), "{reason}");
        assert!(
            surface.content().is_none(),
            "no frames after an unsupported compositor"
        );
        assert!(surface.preview_content().is_none());
    });
}