drmkit-cursor 0.1.3

Cursor themes and rasterized cursors
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
// SPDX-FileCopyrightText: (c) 2026 Joel Winarske
// SPDX-License-Identifier: MIT

//! The renderer against a real device.
//!
//! The pieces are tested on their own in the crate; what needs hardware is
//! that they fit together — a plane is chosen, a size the kernel accepts is
//! settled on, buffers are allocated with framebuffers registered, and a frame
//! reaches them.

use drm::control::Device as _;
use drmkit_core::{AtomicRequest, Device};
use drmkit_cursor::{Cursor, PlanePath, Renderer, RendererConfig, Rotation};
use drmkit_planes::{PlaneCapabilities, PlaneRegistry, PlaneType};

static CARD_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

fn card_guard() -> std::sync::MutexGuard<'static, ()> {
    CARD_LOCK
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

/// A device holding DRM master, plus a registry built from its real planes.
fn fixture() -> Option<(Device, PlaneRegistry, u32, u32)> {
    let path = std::env::var("DRMKIT_TEST_CARD").unwrap_or_else(|_| "/dev/dri/card0".to_owned());
    drmkit_testkit::announce_card(&path);
    let Ok(device) = Device::open(&path) else {
        drmkit_testkit::skipped(&format!("{path} did not open"));
        return None;
    };
    device.enable_universal_planes().expect("universal planes");
    device.enable_atomic().expect("atomic");
    if device.set_master().is_err() {
        assert!(
            std::env::var_os("DRMKIT_REQUIRE_MASTER").is_none(),
            "not DRM master, but DRMKIT_REQUIRE_MASTER is set"
        );
        drmkit_testkit::skipped("another client holds DRM master");
        return None;
    }

    let resources = device.resource_handles().expect("resources");
    let crtcs = resources.crtcs();
    // The output DRMKIT_TEST_CONNECTORS names, where it is set: a CRTC it can
    // be driven from. Otherwise prefer a CRTC something is connected to; the
    // first is often not it.
    let index = match drmkit_testkit::connector::wanted(&device) {
        Some(connector) => crtc_for(&device, &resources, connector)?,
        None => resources
            .connectors()
            .iter()
            .find_map(|handle| {
                let connector = device.get_connector(*handle, false).ok()?;
                if connector.state() != drm::control::connector::State::Connected {
                    return None;
                }
                let encoder = device.get_encoder(connector.current_encoder()?).ok()?;
                let crtc = encoder.crtc()?;
                crtcs.iter().position(|candidate| *candidate == crtc)
            })
            .unwrap_or(0),
    };
    let crtc_id: u32 = (*crtcs.get(index)?).into();

    // The registry a compositor would have: zpos ranges, formats by
    // layout and the CRTC's blend-stage limit, all of which the renderer
    // reads.
    let registry = PlaneRegistry::probe(&device).expect("plane registry");
    Some((
        device,
        registry,
        crtc_id,
        u32::try_from(index).expect("small"),
    ))
}

/// A 16x16 opaque square with its hotspot in the middle.
fn square() -> Cursor {
    Cursor::from_argb(&vec![0xffff_00ff; 16 * 16], 16, 16, 8, 8).expect("cursor")
}

fn config(crtc_id: u32, crtc_index: u32) -> RendererConfig {
    RendererConfig {
        crtc_id,
        crtc_index,
        ..RendererConfig::default()
    }
}

/// The index of a CRTC that can drive `connector`: the one it is on, else the
/// first its encoders allow.
fn crtc_for(
    device: &Device,
    resources: &drm::control::ResourceHandles,
    connector: u32,
) -> Option<usize> {
    let handle = *resources
        .connectors()
        .iter()
        .find(|handle| u32::from(**handle) == connector)?;
    let info = device.get_connector(handle, false).ok()?;
    let crtcs = resources.crtcs();
    if let Some(crtc) = info
        .current_encoder()
        .and_then(|encoder| device.get_encoder(encoder).ok())
        .and_then(|encoder| encoder.crtc())
    {
        return crtcs.iter().position(|candidate| *candidate == crtc);
    }
    info.encoders().iter().find_map(|encoder| {
        let encoder = device.get_encoder(*encoder).ok()?;
        let allowed = resources.filter_crtcs(encoder.possible_crtcs());
        crtcs
            .iter()
            .position(|candidate| allowed.contains(candidate))
    })
}

#[test]
#[ignore = "needs a DRM device and DRM master"]
fn a_renderer_settles_on_a_plane_and_a_size_vkms() {
    let _guard = card_guard();
    let Some((device, registry, crtc_id, crtc_index)) = fixture() else {
        return;
    };
    let renderer = match Renderer::create(&device, &registry, &config(crtc_id, crtc_index)) {
        Ok(renderer) => renderer,
        Err(error) => {
            drmkit_testkit::skipped(&format!("no usable cursor path here: {error}"));
            return;
        }
    };

    let plane = renderer.plane();
    let (w, h) = renderer.size();
    println!(
        "note: plane {} via {:?}, buffer {w}x{h}",
        plane.plane_id, plane.path
    );

    assert_ne!(plane.plane_id, 0, "an atomic path names a plane");
    assert!(
        matches!(
            plane.path,
            PlanePath::AtomicCursor | PlanePath::AtomicOverlay
        ),
        "legacy is refused rather than half-supported: {:?}",
        plane.path
    );
    assert_eq!(w, h, "a cursor buffer is square");
    assert!(w >= 64, "never below the floor: {w}");

    // The size has to come from the driver's own cap, not from a floor.
    //
    // It used to read `PlaneCapabilities::cursor_max_w`, which nothing fills:
    // `PlaneRegistry::probe` zeroes it on every plane, so the cap was always
    // absent and every atomic path quietly took 64. On this card, which
    // advertises 512, that was a cursor four times coarser than the hardware
    // offers -- and the only visible symptom was a blurry pointer.
    //
    // `DRM_CAP_CURSOR_WIDTH` is an upper bound rather than a list of accepted
    // sizes, so the settled size is the largest rung of the {256, 128, 64}
    // ladder that fits under it and that the kernel accepted. Asserting the
    // rung rather than the cap keeps this honest on a driver that refuses its
    // own advertised maximum.
    let cap = |which| {
        drm::Device::get_driver_capability(&device, which)
            .ok()
            .and_then(|v| u32::try_from(v).ok())
            .filter(|v| *v != 0)
    };
    if let (Some(cap_w), Some(cap_h)) = (
        cap(drm::DriverCapability::CursorWidth),
        cap(drm::DriverCapability::CursorHeight),
    ) {
        let advertised = cap_w.min(cap_h);
        let expected = [256, 128, 64]
            .into_iter()
            .find(|rung| *rung <= advertised)
            .unwrap_or(64);
        assert!(
            w >= expected.min(advertised),
            "this card advertises {advertised}x{advertised} and the buffer is \
             {w}x{h}; a cursor pinned at the 64px floor means the driver cap \
             is not being read"
        );
    }
}

#[test]
#[ignore = "needs a DRM device and DRM master"]
fn a_cursor_is_drawn_and_staged_vkms() {
    let _guard = card_guard();
    let Some((device, registry, crtc_id, crtc_index)) = fixture() else {
        return;
    };
    let Ok(mut renderer) = Renderer::create(&device, &registry, &config(crtc_id, crtc_index))
    else {
        drmkit_testkit::skipped("no usable cursor path here");
        return;
    };

    renderer.set_cursor(square()).expect("set cursor");
    renderer.move_to(100, 200);
    renderer.prepare().expect("prepare");

    let mut request = AtomicRequest::new();
    let written = renderer.stage_into(&mut request).expect("stage");
    assert!(written >= 10, "wrote only {written} properties");

    // The plane is armed at the position the hotspot implies -- and the
    // hotspot is in *buffer* coordinates, not the frame's. A 16x16 sprite
    // centered in a 64x64 cursor buffer starts 24 pixels in, so a hotspot 8
    // pixels into the sprite is 32 into the buffer, and a pointer at
    // (100, 200) puts the buffer's corner at (68, 168).
    //
    // Getting this wrong by using the frame's hotspot gives (92, 192): off by
    // exactly the centering offset, which is invisible until the cursor is
    // near a screen edge or someone clicks.
    let plane_id = renderer.plane().plane_id;
    let store = {
        let mut store = drmkit_core::PropertyStore::new();
        store
            .cache_properties(&device, plane_id, drmkit_core::ObjectType::Plane)
            .expect("props");
        store
    };
    let value = |name: &str| {
        let id = store.property_id(plane_id, name).expect(name);
        request
            .writes()
            .iter()
            .find(|w| w.object_id == plane_id && w.property_id == id)
            .map(|w| w.value)
    };
    let (buffer_w, _) = renderer.size();
    let centering = i64::from(buffer_w - 16) / 2;
    //
    // At the driver's real cursor size that corner can be off the left or
    // top edge. The sprite is then drawn moved up and left by the overhang
    // and the plane starts at the edge (drm-cxx#384), so the position never
    // goes below zero.
    let expected_x = (100 - (8 + centering)).max(0);
    let expected_y = (200 - (8 + centering)).max(0);
    let as_property = |v: i64| Some(v.cast_unsigned());
    assert_eq!(value("CRTC_X"), as_property(expected_x));
    assert_eq!(value("CRTC_Y"), as_property(expected_y));
    assert_ne!(value("FB_ID"), Some(0), "a visible cursor names a buffer");
    assert_eq!(value("CRTC_ID"), Some(u64::from(crtc_id)));
}

#[test]
#[ignore = "needs a DRM device and DRM master"]
fn hiding_disarms_the_plane_vkms() {
    // There is no property for "invisible": a cursor hides by letting go of
    // the plane. A zero-alpha buffer would still cost scanout bandwidth.
    let _guard = card_guard();
    let Some((device, registry, crtc_id, crtc_index)) = fixture() else {
        return;
    };
    let Ok(mut renderer) = Renderer::create(&device, &registry, &config(crtc_id, crtc_index))
    else {
        drmkit_testkit::skipped("no usable cursor path here");
        return;
    };
    renderer.set_cursor(square()).expect("set cursor");
    renderer.set_visible(false);

    let mut request = AtomicRequest::new();
    renderer.stage_into(&mut request).expect("stage");

    let plane_id = renderer.plane().plane_id;
    let mut store = drmkit_core::PropertyStore::new();
    store
        .cache_properties(&device, plane_id, drmkit_core::ObjectType::Plane)
        .expect("props");
    for name in ["FB_ID", "CRTC_ID"] {
        let id = store.property_id(plane_id, name).expect(name);
        let value = request
            .writes()
            .iter()
            .find(|w| w.object_id == plane_id && w.property_id == id)
            .map(|w| w.value);
        assert_eq!(value, Some(0), "{name} should be cleared while hidden");
    }
}

#[test]
#[ignore = "needs a DRM device and DRM master"]
fn an_animation_redraws_only_when_the_frame_changes_vkms() {
    // A cursor ticking at 60Hz against a 100ms animation redraws on three
    // frames in eighteen. Redrawing every tick would burn a map, a compose and
    // a buffer flip each time for nothing.
    let _guard = card_guard();
    let Some((device, registry, crtc_id, crtc_index)) = fixture() else {
        return;
    };
    let Ok(mut renderer) = Renderer::create(&device, &registry, &config(crtc_id, crtc_index))
    else {
        drmkit_testkit::skipped("no usable cursor path here");
        return;
    };

    // Two frames, 100ms each.
    let frames = vec![
        drmkit_cursor::Frame {
            pixels: vec![0xffff_0000; 64],
            width: 8,
            height: 8,
            xhot: 0,
            yhot: 0,
            delay: std::time::Duration::from_millis(100),
        },
        drmkit_cursor::Frame {
            pixels: vec![0xff00_ff00; 64],
            width: 8,
            height: 8,
            xhot: 0,
            yhot: 0,
            delay: std::time::Duration::from_millis(100),
        },
    ];
    let animated = Cursor::from_frames(frames).expect("animated cursor");
    renderer.set_cursor(animated).expect("set cursor");

    let mut redraws = 0;
    for step in 0..12u64 {
        // ~60Hz through one 200ms cycle.
        if renderer
            .tick(std::time::Duration::from_millis(step * 16))
            .expect("tick")
        {
            redraws += 1;
        }
    }
    assert_eq!(
        redraws, 1,
        "one frame boundary is crossed in 192ms, so one redraw"
    );
}

#[test]
#[ignore = "needs a DRM device and DRM master"]
fn a_static_cursor_never_redraws_vkms() {
    let _guard = card_guard();
    let Some((device, registry, crtc_id, crtc_index)) = fixture() else {
        return;
    };
    let Ok(mut renderer) = Renderer::create(&device, &registry, &config(crtc_id, crtc_index))
    else {
        drmkit_testkit::skipped("no usable cursor path here");
        return;
    };
    renderer.set_cursor(square()).expect("set cursor");
    for step in 0..8u64 {
        assert!(
            !renderer
                .tick(std::time::Duration::from_millis(step * 500))
                .expect("tick"),
            "a static cursor has nothing to advance to"
        );
    }
}

#[test]
#[ignore = "needs a DRM device and DRM master"]
fn rotation_is_asked_of_the_hardware_only_when_it_can_do_it_vkms() {
    let _guard = card_guard();
    let Some((device, registry, crtc_id, crtc_index)) = fixture() else {
        return;
    };
    let Ok(mut renderer) = Renderer::create(&device, &registry, &config(crtc_id, crtc_index))
    else {
        drmkit_testkit::skipped("no usable cursor path here");
        return;
    };
    renderer.set_cursor(square()).expect("set cursor");
    renderer.set_rotation(Rotation::Quarter).expect("rotate");

    let plane_id = renderer.plane().plane_id;
    let mut store = drmkit_core::PropertyStore::new();
    store
        .cache_properties(&device, plane_id, drmkit_core::ObjectType::Plane)
        .expect("props");
    let Ok(id) = store.property_id(plane_id, "rotation") else {
        println!("note: this plane has no rotation property, so the turn is in software");
        return;
    };

    let mut request = AtomicRequest::new();
    renderer.stage_into(&mut request).expect("stage");
    let value = request
        .writes()
        .iter()
        .find(|w| w.object_id == plane_id && w.property_id == id)
        .map(|w| w.value)
        .expect("rotation written");

    // A plane that can turn a quarter is asked to. One that cannot had the
    // pixels turned in software, and must be asked for none.
    let can_turn = registry
        .by_id(plane_id)
        .is_some_and(|plane| plane.rotation_bits & Rotation::Quarter.drm_mask() != 0);
    let expected = if can_turn {
        Rotation::Quarter.drm_mask()
    } else {
        Rotation::None.drm_mask()
    };
    assert_eq!(
        value, expected,
        "asking the hardware to turn pixels that are already turned turns them twice"
    );
}

/// A registry offering only a primary plane, so selection falls to legacy.
fn primary_only(registry: &PlaneRegistry, crtc_index: u32) -> PlaneRegistry {
    let planes: Vec<PlaneCapabilities> = registry
        .all()
        .iter()
        .filter(|plane| plane.plane_type == PlaneType::Primary)
        .cloned()
        .collect();
    assert!(
        planes
            .iter()
            .any(|p| p.possible_crtcs & (1 << crtc_index) != 0),
        "the fixture needs a primary plane on this CRTC"
    );
    PlaneRegistry::from_capabilities(planes)
}

#[test]
#[ignore = "needs a DRM device and DRM master"]
fn the_legacy_path_probes_before_promising_anything_vkms() {
    // drmModeSetCursor has no TEST_ONLY, so create() probes with a cursor
    // *disable*: harmless where there is cursor hardware, refused where there
    // is none. i.MX LCDIF and tilcdc have no cursor at all, and those are
    // exactly the controllers that fall through to this path — finding out at
    // create() lets a caller composite a cursor instead of getting a renderer
    // that dies on its first show.
    let _guard = card_guard();
    let Some((device, registry, crtc_id, crtc_index)) = fixture() else {
        return;
    };
    let legacy_only = primary_only(&registry, crtc_index);

    match Renderer::create(&device, &legacy_only, &config(crtc_id, crtc_index)) {
        Ok(renderer) => {
            assert_eq!(renderer.plane().path, PlanePath::Legacy);
            assert_eq!(renderer.plane().plane_id, 0, "legacy addresses the CRTC");
            let (w, h) = renderer.size();
            assert_eq!((w, h), (64, 64), "legacy is 64 on every driver");
            println!("note: this driver has a legacy cursor");
        }
        Err(error) => {
            // Also a correct outcome, and the one the probe exists for.
            println!("note: this driver has no legacy cursor ({error})");
        }
    }
}

#[test]
#[ignore = "needs a DRM device and DRM master"]
fn legacy_refuses_rotation_rather_than_pretending_vkms() {
    // drmModeSetCursor has nowhere to put a rotation. Turning the pixels in
    // software would still leave the hotspot wrong for a caller who believes
    // the hardware did it, so the ask is refused.
    let _guard = card_guard();
    let Some((device, registry, crtc_id, crtc_index)) = fixture() else {
        return;
    };
    let legacy_only = primary_only(&registry, crtc_index);
    let mut rotated = config(crtc_id, crtc_index);
    rotated.rotation = Rotation::Quarter;

    assert!(
        Renderer::create(&device, &legacy_only, &rotated).is_err(),
        "a rotated cursor on the legacy path must be refused"
    );
}

#[test]
#[ignore = "needs a DRM device and DRM master"]
fn legacy_refuses_when_the_caller_forbids_it_vkms() {
    // A compositor that must commit the cursor with the rest of its frame
    // cannot use a path that has no atomic commit, and would rather be told.
    let _guard = card_guard();
    let Some((device, registry, crtc_id, crtc_index)) = fixture() else {
        return;
    };
    let legacy_only = primary_only(&registry, crtc_index);
    let mut strict = config(crtc_id, crtc_index);
    strict.allow_legacy = false;

    assert!(matches!(
        Renderer::create(&device, &legacy_only, &strict),
        Err(drmkit_cursor::CursorError::NoPlane)
    ));
}

#[test]
#[ignore = "needs a DRM device and DRM master"]
fn a_legacy_cursor_installs_once_and_then_moves_vkms() {
    // The install hands the CRTC a GEM handle; every move after that is a
    // cheap drmModeMoveCursor rather than a re-upload.
    let _guard = card_guard();
    let Some((device, registry, crtc_id, crtc_index)) = fixture() else {
        return;
    };
    let legacy_only = primary_only(&registry, crtc_index);
    let Ok(mut renderer) = Renderer::create(&device, &legacy_only, &config(crtc_id, crtc_index))
    else {
        drmkit_testkit::skipped("this driver has no legacy cursor");
        return;
    };

    renderer.set_cursor(square()).expect("set cursor");
    renderer.move_to(10, 10);
    renderer.commit().expect("install");

    for (x, y) in [(20, 20), (300, 400), (0, 0)] {
        renderer.move_to(x, y);
        renderer.commit().expect("move");
    }

    // Hiding lets go of the CRTC's cursor, so the test leaves nothing on
    // screen for whoever looks at the panel next.
    renderer.set_visible(false);
    renderer.commit().expect("hide");
}

#[test]
#[ignore = "needs a DRM device and DRM master"]
fn a_paused_renderer_comes_back_with_its_cursor_vkms() {
    // A VT switch revokes the descriptor. What survives is the state that
    // describes the cursor, not the kernel objects behind it, and the first
    // commit after coming back has to carry the right pixels rather than an
    // empty buffer.
    let _guard = card_guard();
    let Some((device, registry, crtc_id, crtc_index)) = fixture() else {
        return;
    };
    let Ok(mut renderer) = Renderer::create(&device, &registry, &config(crtc_id, crtc_index))
    else {
        drmkit_testkit::skipped("no usable cursor path here");
        return;
    };

    renderer.set_cursor(square()).expect("set cursor");
    renderer.move_to(120, 240);
    let plane_before = renderer.plane().plane_id;
    let size_before = renderer.size();

    let paused = renderer.pause();
    assert!(paused.has_cursor(), "the cursor outlives the descriptor");

    // Stand in for the new descriptor libseat would hand back.
    let resumed_device = {
        let path =
            std::env::var("DRMKIT_TEST_CARD").unwrap_or_else(|_| "/dev/dri/card0".to_owned());
        let device = Device::open(&path).expect("reopen");
        device.enable_universal_planes().expect("universal planes");
        device.enable_atomic().expect("atomic");
        device
    };
    let mut renderer = paused.resume(&resumed_device).expect("resume");

    assert_eq!(renderer.plane().plane_id, plane_before, "same plane");
    assert_eq!(renderer.size(), size_before, "same size, not re-probed");

    // The position survived, and the cursor was redrawn: staging produces the
    // same placement it did before the pause.
    let mut request = AtomicRequest::new();
    let written = renderer.stage_into(&mut request).expect("stage");
    assert!(written >= 10);

    let plane_id = renderer.plane().plane_id;
    let mut store = drmkit_core::PropertyStore::new();
    store
        .cache_properties(&resumed_device, plane_id, drmkit_core::ObjectType::Plane)
        .expect("props");
    let fb = store.property_id(plane_id, "FB_ID").expect("FB_ID");
    let value = request
        .writes()
        .iter()
        .find(|w| w.object_id == plane_id && w.property_id == fb)
        .map(|w| w.value)
        .expect("FB_ID written");
    assert_ne!(
        value, 0,
        "the resumed renderer names a framebuffer on the new descriptor"
    );

    let _ = renderer.tick(std::time::Duration::ZERO);
}

#[test]
#[ignore = "needs a DRM device and DRM master"]
fn pausing_without_a_cursor_is_fine_vkms() {
    // A compositor can be paused before it ever set one.
    let _guard = card_guard();
    let Some((device, registry, crtc_id, crtc_index)) = fixture() else {
        return;
    };
    let Ok(renderer) = Renderer::create(&device, &registry, &config(crtc_id, crtc_index)) else {
        drmkit_testkit::skipped("no usable cursor path here");
        return;
    };

    let paused = renderer.pause();
    assert!(!paused.has_cursor());
    let resumed = paused.resume(&device).expect("resume");
    assert_ne!(resumed.plane().plane_id, 0);
}

/// How many mappings this process holds of the DRM node.
///
/// Closing a descriptor unmaps nothing — a VMA keeps its own reference to the
/// file — so this is what grows if a pause forgets to release its mappings.
fn drm_mappings() -> usize {
    let maps = std::fs::read_to_string("/proc/self/maps").unwrap_or_default();
    maps.lines()
        .filter(|line| line.contains("/dev/dri/"))
        .count()
}

#[test]
#[ignore = "needs a DRM device and DRM master"]
fn repeated_pauses_do_not_leak_mappings_vkms() {
    // The reason `pause` releases its mappings rather than only dropping the
    // handles. A compositor VT-switches for as long as it runs, and a mapping
    // leaked per switch is invisible until the address space runs out.
    let _guard = card_guard();
    let Some((device, registry, crtc_id, crtc_index)) = fixture() else {
        return;
    };
    let Ok(mut renderer) = Renderer::create(&device, &registry, &config(crtc_id, crtc_index))
    else {
        drmkit_testkit::skipped("no usable cursor path here");
        return;
    };
    renderer.set_cursor(square()).expect("set cursor");

    // One cycle first, so any one-off allocation is already accounted for.
    renderer = renderer.pause().resume(&device).expect("resume");
    let baseline = drm_mappings();

    for _ in 0..16 {
        renderer = renderer.pause().resume(&device).expect("resume");
    }
    let after = drm_mappings();

    println!("note: {baseline} DRM mappings before, {after} after 16 cycles");
    assert!(
        after <= baseline,
        "16 pause/resume cycles grew DRM mappings from {baseline} to {after}"
    );
}

/// `prefer_legacy` drives the CRTC's cursor plane through the legacy ioctls,
/// and `reserved_plane_id` still names that plane, so a caller keeps its own
/// commits off it (drm-cxx `0925491`). On the atomic path it names the plane
/// the cursor draws on. The kernel is asked which plane the legacy cursor
/// actually lit.
#[test]
#[ignore = "needs a DRM device and DRM master"]
fn a_preferred_legacy_cursor_reserves_the_cursor_plane_vkms() {
    use drm::control::Device as _;

    let _guard = card_guard();
    let Some((device, registry, crtc_id, crtc_index)) = fixture() else {
        return;
    };
    let Some(cursor_plane) = registry
        .for_crtc(crtc_index)
        .find(|plane| plane.plane_type == drmkit_planes::PlaneType::Cursor)
        .map(|plane| plane.id)
    else {
        drmkit_testkit::skipped("no cursor plane on this CRTC");
        return;
    };

    let atomic = Renderer::create(&device, &registry, &config(crtc_id, crtc_index))
        .expect("an atomic cursor");
    assert_eq!(atomic.plane().path, PlanePath::AtomicCursor);
    assert_eq!(atomic.reserved_plane_id(), atomic.plane().plane_id);
    drop(atomic);

    let preferred = RendererConfig {
        prefer_legacy: true,
        ..config(crtc_id, crtc_index)
    };
    let Ok(mut renderer) = Renderer::create(&device, &registry, &preferred) else {
        drmkit_testkit::skipped("this driver has no legacy cursor");
        return;
    };
    assert_eq!(renderer.plane().path, PlanePath::Legacy);
    assert_eq!(renderer.reserved_plane_id(), cursor_plane);

    // drmModeSetCursor has no rotation, so the reference refuses one here as
    // it does at create, rather than pre-rotating the pixels and leaving the
    // hotspot wrong.
    assert_eq!(
        renderer.set_rotation(drmkit_cursor::Rotation::Quarter),
        Err(drmkit_cursor::CursorError::Unsupported)
    );
    renderer
        .set_rotation(drmkit_cursor::Rotation::None)
        .expect("upright is always fine");

    renderer.set_cursor(square()).expect("set cursor");
    renderer.move_to(10, 10);
    renderer.commit().expect("install");
    let handle = drm::control::plane::Handle::from(
        std::num::NonZeroU32::new(cursor_plane).expect("non-zero"),
    );
    let lit = device
        .get_plane(handle)
        .expect("the cursor plane")
        .framebuffer()
        .is_some();
    renderer.set_visible(false);
    renderer.commit().expect("hide");
    assert!(lit, "the legacy cursor did not land on the cursor plane");
}

/// A cursor whose buffer hangs off the top-left corner still commits.
///
/// With a buffer the driver's size, the plane's origin would be negative
/// anywhere within half a buffer of the edge. Some drivers -- the SA8155P's --
/// refuse that outright (drm-cxx#384), so the sprite is drawn moved up and
/// left inside the buffer and the plane starts at the edge. The kernel is read
/// back to show it got no negative position. The encoding of one, still
/// written for a hardware-rotated cursor, is pinned by
/// `a_negative_position_is_written_as_twos_complement_vkms`.
#[test]
#[ignore = "needs a DRM device and DRM master"]
fn a_cursor_off_the_top_left_corner_commits_vkms() {
    use drm::control::Device as _;

    let _guard = card_guard();
    let Some((device, registry, crtc_id, crtc_index)) = fixture() else {
        return;
    };

    // Light the CRTC first, so the cursor has an output to sit on.
    let resources = device.resource_handles().expect("resources");
    let crtc = resources.crtcs()[crtc_index as usize];
    let wanted = drmkit_testkit::connector::wanted(&device);
    let Some((connector, mode)) = resources.connectors().iter().find_map(|handle| {
        if wanted.is_some_and(|id| id != u32::from(*handle)) {
            return None;
        }
        let info = device.get_connector(*handle, false).ok()?;
        if info.state() != drm::control::connector::State::Connected {
            return None;
        }
        Some((*handle, *info.modes().first()?))
    }) else {
        drmkit_testkit::skipped("no connected connector");
        return;
    };
    let (width, height) = (u32::from(mode.size().0), u32::from(mode.size().1));
    let primary = drmkit_dumb::Buffer::create(
        &device,
        &drmkit_dumb::Config {
            width,
            height,
            fourcc: drmkit_fmt::fourcc::XRGB8888,
            bpp: 32,
            add_fb: true,
        },
    )
    .expect("primary buffer");
    let fb = drm::control::framebuffer::Handle::from(
        core::num::NonZeroU32::new(primary.fb_id().expect("framebuffer")).expect("non-zero"),
    );
    device
        .set_crtc(crtc, Some(fb), (0, 0), &[connector], Some(mode))
        .expect("light the output");

    let result = (|| {
        let mut renderer =
            Renderer::create(&device, &registry, &config(crtc_id, crtc_index)).ok()?;
        renderer.set_cursor(square()).expect("set cursor");
        renderer.move_to(1, 1);
        let committed = renderer.commit();
        let plane_id = renderer.plane().plane_id;
        let mut store = drmkit_core::PropertyStore::new();
        let origin = store
            .cache_properties(&device, plane_id, drmkit_core::ObjectType::Plane)
            .ok()
            .and_then(|()| {
                Some((
                    store.property_value(plane_id, "CRTC_X").ok()?,
                    store.property_value(plane_id, "CRTC_Y").ok()?,
                ))
            });
        Some((committed, renderer.plane().path, origin))
    })();

    let _ = device.set_crtc(crtc, None, (0, 0), &[], None);
    drop(primary);

    match result {
        None => drmkit_testkit::skipped("no usable cursor path here"),
        Some((committed, path, origin)) => {
            committed.expect("a cursor at the corner commits");
            if path != drmkit_cursor::PlanePath::Legacy {
                assert_eq!(origin, Some((0, 0)), "the plane was left off the corner");
            }
        }
    }
}

/// Dropping a legacy renderer takes its cursor off the CRTC, as the
/// reference's destructor does.
///
/// Freeing the cursor buffers does not: `drmModeSetCursor` gives the kernel
/// its own framebuffer for the sprite, which stays on the CRTC's cursor plane
/// until something clears it. So a client that exits leaves its pointer on
/// screen for whoever comes next.
#[test]
#[ignore = "needs a DRM device and DRM master"]
fn dropping_a_legacy_renderer_takes_its_cursor_off_vkms() {
    use drm::control::Device as _;

    let _guard = card_guard();
    let Some((device, registry, crtc_id, crtc_index)) = fixture() else {
        return;
    };
    let Some(cursor_plane) = registry
        .all()
        .iter()
        .find(|p| p.plane_type == PlaneType::Cursor && p.possible_crtcs & (1 << crtc_index) != 0)
        .map(|p| p.id)
    else {
        drmkit_testkit::skipped("no cursor plane to watch");
        return;
    };
    let legacy_only = primary_only(&registry, crtc_index);
    let Ok(mut renderer) = Renderer::create(&device, &legacy_only, &config(crtc_id, crtc_index))
    else {
        drmkit_testkit::skipped("this driver has no legacy cursor");
        return;
    };
    renderer.set_cursor(square()).expect("set cursor");
    renderer.move_to(10, 10);
    renderer.commit().expect("install");

    let shown = |device: &Device| {
        let handle = drm::control::plane::Handle::from(
            core::num::NonZeroU32::new(cursor_plane).expect("non-zero"),
        );
        device
            .get_plane(handle)
            .expect("plane")
            .framebuffer()
            .is_some()
    };
    assert!(
        shown(&device),
        "the install put a sprite on the cursor plane"
    );

    drop(renderer);
    assert!(!shown(&device), "the sprite outlived its renderer");
}

/// A new cursor shape on the legacy path is handed to the CRTC again, as the
/// reference re-installs it, rather than only moved.
///
/// Whether a driver picks up new pixels in a buffer it already has is the
/// driver's business: some upload the sprite only when `drmModeSetCursor`
/// gives them a buffer, and keep showing the old shape after a move. Each
/// install makes the kernel a new framebuffer for the cursor plane, so a
/// framebuffer that does not change says the new shape was never handed over.
#[test]
#[ignore = "needs a DRM device and DRM master"]
fn a_new_legacy_cursor_is_installed_again_vkms() {
    use drm::control::Device as _;

    let _guard = card_guard();
    let Some((device, registry, crtc_id, crtc_index)) = fixture() else {
        return;
    };
    let Some(cursor_plane) = registry
        .all()
        .iter()
        .find(|p| p.plane_type == PlaneType::Cursor && p.possible_crtcs & (1 << crtc_index) != 0)
        .map(|p| p.id)
    else {
        drmkit_testkit::skipped("no cursor plane to watch");
        return;
    };
    let legacy_only = primary_only(&registry, crtc_index);
    let Ok(mut renderer) = Renderer::create(&device, &legacy_only, &config(crtc_id, crtc_index))
    else {
        drmkit_testkit::skipped("this driver has no legacy cursor");
        return;
    };
    let framebuffer = |device: &Device| {
        let handle = drm::control::plane::Handle::from(
            core::num::NonZeroU32::new(cursor_plane).expect("non-zero"),
        );
        device.get_plane(handle).expect("plane").framebuffer()
    };

    renderer.set_cursor(square()).expect("set cursor");
    renderer.move_to(10, 10);
    renderer.commit().expect("install");
    let first = framebuffer(&device);
    assert!(
        first.is_some(),
        "the install put a sprite on the cursor plane"
    );

    let other = Cursor::from_argb(&vec![0xff00_ff00; 16 * 16], 16, 16, 2, 2).expect("cursor");
    renderer.set_cursor(other).expect("set another cursor");
    renderer.move_to(20, 20);
    renderer.commit().expect("move with the new shape");
    assert_ne!(
        framebuffer(&device),
        first,
        "the new shape was only moved, never handed to the CRTC"
    );

    renderer.set_visible(false);
    renderer.commit().expect("hide");
}

/// The cursor does not take an overlay this CRTC is already showing.
///
/// Without a cursor plane the cursor falls back to an overlay, preferring one
/// nothing is using, as the reference does. An overlay already lit on this
/// CRTC is the compositor's own layer: taking it would cost that layer just as
/// taking one from another output would.
#[test]
#[ignore = "needs a DRM device and DRM master"]
fn the_cursor_leaves_an_overlay_this_crtc_shows_vkms() {
    use drm::control::Device as _;

    let _guard = card_guard();
    let Some((device, registry, crtc_id, crtc_index)) = fixture() else {
        return;
    };
    let on_crtc = |p: &&PlaneCapabilities| p.possible_crtcs & (1 << crtc_index) != 0;
    let overlays: Vec<u32> = registry
        .all()
        .iter()
        .filter(on_crtc)
        .filter(|p| p.plane_type == PlaneType::Overlay)
        .map(|p| p.id)
        .collect();
    if overlays.len() < 2 {
        drmkit_testkit::skipped("needs two overlays on this CRTC");
        return;
    }
    // No cursor plane, so the cursor has to choose an overlay.
    let without_cursor = PlaneRegistry::from_capabilities(
        registry
            .all()
            .iter()
            .filter(|p| p.plane_type != PlaneType::Cursor)
            .cloned()
            .collect(),
    );

    // Light the output, then show something on the first overlay -- the one
    // the cursor would take first.
    let resources = device.resource_handles().expect("resources");
    let crtc = resources.crtcs()[crtc_index as usize];
    let Some((connector, mode)) = resources.connectors().iter().find_map(|handle| {
        let info = device.get_connector(*handle, false).ok()?;
        (info.state() == drm::control::connector::State::Connected)
            .then(|| Some((*handle, *info.modes().first()?)))
            .flatten()
    }) else {
        drmkit_testkit::skipped("no connected connector");
        return;
    };
    let (width, height) = (u32::from(mode.size().0), u32::from(mode.size().1));
    let buffer = |w: u32, h: u32, fourcc: u32| {
        drmkit_dumb::Buffer::create(
            &device,
            &drmkit_dumb::Config {
                width: w,
                height: h,
                fourcc,
                bpp: 32,
                add_fb: true,
            },
        )
        .expect("buffer")
    };
    let fb_of = |b: &drmkit_dumb::Buffer| {
        drm::control::framebuffer::Handle::from(
            core::num::NonZeroU32::new(b.fb_id().expect("framebuffer")).expect("non-zero"),
        )
    };
    let primary = buffer(width, height, drmkit_fmt::fourcc::XRGB8888);
    let layer = buffer(64, 64, drmkit_fmt::fourcc::ARGB8888);
    device
        .set_crtc(
            crtc,
            Some(fb_of(&primary)),
            (0, 0),
            &[connector],
            Some(mode),
        )
        .expect("light the output");
    let shown = drm::control::plane::Handle::from(
        core::num::NonZeroU32::new(overlays[0]).expect("non-zero"),
    );
    device
        .set_plane(
            shown,
            crtc,
            Some(fb_of(&layer)),
            0,
            (0, 0, 64, 64),
            (0, 0, 64 << 16, 64 << 16),
        )
        .expect("show a layer on the first overlay");

    let chosen = Renderer::create(&device, &without_cursor, &config(crtc_id, crtc_index))
        .map(|renderer| renderer.plane().plane_id);

    let _ = device.set_plane(shown, crtc, None, 0, (0, 0, 0, 0), (0, 0, 0, 0));
    let _ = device.set_crtc(crtc, None, (0, 0), &[], None);
    drop((primary, layer));

    let chosen = chosen.expect("a free overlay is there to take");
    assert_ne!(
        chosen, overlays[0],
        "the cursor took the overlay this CRTC was showing"
    );
}