wlr-capture 1.3.0

Reusable wlroots capture engine + shared UI toolkit for the wlr-utils tools.
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
//! xdg-toplevel windowing host for the live mirror.
//!
//! A normal floating window (so the compositor handles stacking; pair with sway
//! rules `floating enable, sticky enable` for always-on-top across workspaces).
//! Rendering uses the shared [`wlr_capture::render::Gpu`]. Capture frames arrive
//! over a calloop channel, so we only repaint when there is new content or an
//! interaction — no free-running render loop for an always-on tile.
//!
//! Interactions (all hit-tested here, in logical coordinates, so egui stays a
//! pure painter): drag the body to move (`xdg_toplevel.move`), the bottom-right
//! grip to resize (`xdg_toplevel.resize`), the toolbar buttons to collapse to an
//! icon badge or close, and `Esc` to close. The tile keeps the source aspect
//! ratio; collapsing shrinks it, and any new frame while collapsed restores it.

use crate::render::{DmabufImporter, Gpu};
use crate::stream;
use crate::theme::Theme;
use crate::tr;
use crate::wl;
use smithay_client_toolkit::{
    compositor::{CompositorHandler, CompositorState},
    delegate_compositor, delegate_keyboard, delegate_output, delegate_pointer, delegate_registry,
    delegate_seat, delegate_xdg_shell, delegate_xdg_window,
    output::{OutputHandler, OutputState},
    reexports::calloop::EventLoop,
    reexports::calloop::channel::{Channel, Event as ChannelEvent, channel},
    reexports::calloop_wayland_source::WaylandSource,
    reexports::protocols::xdg::shell::client::xdg_toplevel::ResizeEdge,
    registry::{ProvidesRegistryState, RegistryState},
    registry_handlers,
    seat::{
        Capability, SeatHandler, SeatState,
        keyboard::{KeyEvent, KeyboardHandler, Keysym, Modifiers, RawModifiers},
        pointer::{PointerEvent, PointerEventKind, PointerHandler},
    },
    shell::{
        WaylandSurface,
        xdg::{
            XdgShell,
            window::{Window, WindowConfigure, WindowDecorations, WindowHandler},
        },
    },
};
use std::time::{Duration, Instant};
use wayland_client::{
    Connection, QueueHandle,
    globals::registry_queue_init,
    protocol::{wl_keyboard, wl_output, wl_pointer, wl_seat, wl_surface},
};

/// Texture cache key for the single mirrored source.
const KEY: &str = "pip";
/// Default tile width (logical px) before the source aspect ratio is known.
const DEFAULT_W: u32 = 480;
/// Side of the collapsed icon badge (logical px).
const BADGE: u32 = 132;
/// Smallest tile width the user can resize to.
const MIN_W: u32 = 120;
/// Repaint frames to keep the "just restored" accent border visible.
const ACCENT_FRAMES: u32 = 60;
/// How long to show the "window closed" notice before exiting.
const GONE_LINGER: Duration = Duration::from_millis(1400);
/// Frame budget per capture round (~30 fps ceiling; capture is damage-driven).
const ROUND: Duration = Duration::from_millis(33);
/// How long to wait for the target window to appear before giving up.
const APPEAR_GRACE: Duration = Duration::from_secs(5);

/// Frames + textures for the mirrored source; a pure painter (the host owns input).
struct Content {
    /// shm texture (CPU upload path).
    tex: Option<egui::TextureHandle>,
    /// dma-buf texture (GPU zero-copy path): egui id + source pixel size.
    native: Option<(egui::TextureId, egui::Vec2)>,
    icon: Option<egui::TextureHandle>,
    /// Frames awaiting upload/import at the next render.
    pending: Vec<PipMsg>,
    gone: bool,
    label: String,
    theme: Theme,
    /// Region mode: the normalized sub-rectangle of the captured frame to show
    /// (the magnified region). `None` shows the whole frame (toplevel mirror).
    crop_uv: Option<egui::Rect>,
}

impl Content {
    /// Drain pending frames into textures (needs the egui ctx for shm uploads and
    /// the host importer for dma-buf). Called inside the render closure.
    fn pump(&mut self, ctx: &egui::Context, importer: &mut dyn DmabufImporter) {
        for msg in self.pending.drain(..) {
            match msg {
                PipMsg::Shm { w, h, rgba } if w > 0 && h > 0 => {
                    let img = egui::ColorImage::from_rgba_unmultiplied([w, h], &rgba);
                    match self.tex.as_mut() {
                        Some(t) => t.set(img, egui::TextureOptions::LINEAR),
                        None => {
                            self.tex =
                                Some(ctx.load_texture(KEY, img, egui::TextureOptions::LINEAR))
                        }
                    }
                    self.native = None; // shm now authoritative
                }
                PipMsg::Dmabuf { frame } => {
                    if let Some(t) = importer.import(KEY, frame) {
                        self.native = Some(t);
                    }
                }
                PipMsg::Shm { .. } => {}
                PipMsg::Gone => self.gone = true,
            }
        }
    }

    /// The drawable texture: dma-buf if present, else shm.
    fn tex(&self) -> Option<(egui::TextureId, egui::Vec2)> {
        if let Some(t) = self.native {
            return Some(t);
        }
        self.tex.as_ref().map(|t| (t.id(), t.size_vec2()))
    }

    /// Paint one frame into the surface-sized area.
    #[allow(clippy::too_many_arguments)]
    fn draw(
        &self,
        ui: &mut egui::Ui,
        size: (f32, f32),
        collapsed: bool,
        hovered: bool,
        accent: bool,
        frozen: bool,
        opacity: f32,
    ) {
        let (w, h) = size;
        let full = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(w, h));
        let t = &self.theme;
        // Image/icon tint carries the window opacity (the GL backdrop carries it too).
        let tint = egui::Color32::from_white_alpha((opacity.clamp(0.0, 1.0) * 255.0) as u8);
        egui::CentralPanel::default()
            .frame(egui::Frame::NONE)
            .show_inside(ui, |ui| {
                let p = ui.painter();
                // The captured image, contained (letterboxed) in the tile. In region
                // mode only `crop_uv` of the frame is shown, so the visible source
                // size is the texture scaled by the crop's normalized extent.
                if let Some((id, ts)) = self.tex() {
                    let uv = self.crop_uv.unwrap_or(egui::Rect::from_min_max(
                        egui::pos2(0.0, 0.0),
                        egui::pos2(1.0, 1.0),
                    ));
                    let src = egui::vec2(ts.x * uv.width(), ts.y * uv.height());
                    let scale = (full.width() / src.x).min(full.height() / src.y);
                    let draw = egui::Rect::from_center_size(full.center(), src * scale);
                    p.image(id, draw, uv, tint);
                } else if let Some(icon) = &self.icon {
                    let isz = icon.size_vec2();
                    let scale = (full.width() / isz.x).min(full.height() / isz.y).min(1.0);
                    let draw = egui::Rect::from_center_size(full.center(), isz * scale);
                    p.image(
                        icon.id(),
                        draw,
                        egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
                        tint,
                    );
                } else {
                    p.text(
                        full.center(),
                        egui::Align2::CENTER_CENTER,
                        tr!("loading"),
                        egui::FontId::proportional(16.0),
                        t.text_dim,
                    );
                }

                if self.gone {
                    p.rect_filled(full, 0.0, egui::Color32::from_black_alpha(180));
                    p.text(
                        full.center(),
                        egui::Align2::CENTER_CENTER,
                        tr!("pip-gone"),
                        egui::FontId::proportional(16.0),
                        t.text,
                    );
                    return;
                }

                // "Just restored" / live accent border.
                if accent {
                    p.rect_stroke(
                        full,
                        0.0,
                        egui::Stroke::new(2.0, t.window_accent),
                        egui::StrokeKind::Inside,
                    );
                }

                // Freeze indicator: a pause glyph in the top-left corner.
                if frozen {
                    let bar = egui::Stroke::new(3.0, egui::Color32::from_white_alpha(220));
                    let (x, y) = (8.0, 8.0);
                    p.line_segment([egui::pos2(x, y), egui::pos2(x, y + 12.0)], bar);
                    p.line_segment([egui::pos2(x + 6.0, y), egui::pos2(x + 6.0, y + 12.0)], bar);
                }

                if collapsed {
                    return; // badge: just the contained image/icon
                }

                if hovered {
                    let (close, collapse) = toolbar_rects(w);
                    let strip = egui::Rect::from_min_max(
                        egui::pos2(0.0, 0.0),
                        egui::pos2(w, close.bottom() + 6.0),
                    );
                    p.rect_filled(strip, 0.0, egui::Color32::from_black_alpha(150));
                    // Title at the left.
                    let mut job = egui::text::LayoutJob::simple_singleline(
                        self.label.clone(),
                        egui::FontId::proportional(12.0),
                        egui::Color32::WHITE,
                    );
                    job.wrap = egui::text::TextWrapping::truncate_at_width(
                        (collapse.left() - 12.0).max(0.0),
                    );
                    let galley = ui.painter().layout_job(job);
                    p.galley(
                        egui::pos2(8.0, strip.center().y - galley.size().y / 2.0),
                        galley,
                        egui::Color32::WHITE,
                    );
                    // Collapse glyph (a downward chevron) and close glyph (an X).
                    draw_collapse(p, collapse, egui::Color32::WHITE);
                    draw_close(p, close, egui::Color32::WHITE);
                    // Resize grip in the bottom-right corner.
                    draw_grip(p, grip_rect(w, h), egui::Color32::from_white_alpha(160));
                }
            });
    }
}

/// Smallest tile size honouring the source aspect (width is the floor at `MIN_W`).
/// Falls back to 16:9 before the aspect is known (toplevel mirror's first frame).
fn min_size_for(aspect: Option<f32>) -> (u32, u32) {
    match aspect {
        Some(a) if a > 0.0 => (MIN_W, ((MIN_W as f32 / a).round() as u32).max(1)),
        _ => (MIN_W, (MIN_W * 9 / 16).max(1)),
    }
}

/// Close / collapse button rects (top-right), in logical coordinates.
fn toolbar_rects(w: f32) -> (egui::Rect, egui::Rect) {
    let s = 22.0;
    let pad = 6.0;
    let close = egui::Rect::from_min_size(egui::pos2(w - pad - s, pad), egui::vec2(s, s));
    let collapse =
        egui::Rect::from_min_size(egui::pos2(w - pad - 2.0 * s - 6.0, pad), egui::vec2(s, s));
    (close, collapse)
}

/// Resize-grip rect (bottom-right), in logical coordinates.
fn grip_rect(w: f32, h: f32) -> egui::Rect {
    let s = 18.0;
    egui::Rect::from_min_size(egui::pos2(w - s, h - s), egui::vec2(s, s))
}

fn draw_close(p: &egui::Painter, r: egui::Rect, c: egui::Color32) {
    let r = r.shrink(5.0);
    let s = egui::Stroke::new(2.0, c);
    p.line_segment([r.left_top(), r.right_bottom()], s);
    p.line_segment([r.right_top(), r.left_bottom()], s);
}

fn draw_collapse(p: &egui::Painter, r: egui::Rect, c: egui::Color32) {
    let r = r.shrink(5.0);
    let s = egui::Stroke::new(2.0, c);
    // A downward chevron ⌄.
    p.line_segment([r.left_top(), egui::pos2(r.center().x, r.bottom())], s);
    p.line_segment([egui::pos2(r.center().x, r.bottom()), r.right_top()], s);
}

fn draw_grip(p: &egui::Painter, r: egui::Rect, c: egui::Color32) {
    let s = egui::Stroke::new(1.5, c);
    for f in [0.35_f32, 0.7] {
        p.line_segment(
            [
                egui::pos2(r.right() - r.width() * f, r.bottom()),
                egui::pos2(r.right(), r.bottom() - r.height() * f),
            ],
            s,
        );
    }
}

struct State {
    registry_state: RegistryState,
    seat_state: SeatState,
    output_state: OutputState,

    window: Window,
    seat: Option<wl_seat::WlSeat>,
    keyboard: Option<wl_keyboard::WlKeyboard>,
    pointer: Option<wl_pointer::WlPointer>,

    egui_ctx: egui::Context,
    gpu: Option<Gpu>,
    content: Content,

    // logical size we render at, integer scale, and the source aspect (w/h).
    width: u32,
    height: u32,
    scale: u32,
    aspect: Option<f32>,
    /// Region mode: the aspect is pinned to the region, so frame sizes (the whole
    /// output) must not retune it.
    fixed_aspect: bool,
    /// Remembered expanded size, restored when un-collapsing.
    expanded: (u32, u32),
    collapsed: bool,

    hovered: bool,
    pointer_pos: egui::Pos2,
    accent: u32,
    gone_since: Option<Instant>,

    /// Window opacity (1.0 = opaque); adjusted with the wheel or `+`/`-`.
    opacity: f32,
    /// Freeze the live feed on the last frame (Space toggles).
    frozen: bool,

    start: Instant,
    closing: bool,
    configured: bool,
    /// Args to re-exec ourselves with on re-pick (`r`); empty disables it.
    relaunch: Vec<String>,
}

/// What the mirror window streams.
pub enum Source {
    /// Mirror the toplevel with this `ext-foreign-toplevel` identifier.
    Toplevel(String),
    /// Mirror (and magnify) a fixed logical region. We capture the covering output
    /// live and show only the region's sub-rectangle of it; mono-output for now.
    Region {
        /// Name of the output to capture (the one covering the region's top-left).
        output: String,
        /// Normalized sub-rectangle `(min_x, min_y, max_x, max_y)` of the region
        /// within that output's frame (scale-independent, so it survives any
        /// physical resolution the frames arrive at).
        crop: [f32; 4],
        /// Logical region size; fixes the window aspect ratio.
        region_w: u32,
        region_h: u32,
        /// Magnification factor (initial window size = region × zoom).
        zoom: f32,
    },
    /// Mirror (and magnify) a sub-rectangle of a *window*. Captures the toplevel
    /// (so it follows the window across moves/workspaces) and shows only `crop` of it.
    ToplevelRegion {
        /// `ext-foreign-toplevel` identifier of the window to capture.
        id: String,
        /// Normalized sub-rectangle of the region within the window's content.
        crop: [f32; 4],
        /// Logical region size; fixes the window aspect ratio.
        region_w: u32,
        region_h: u32,
        /// Magnification factor (initial window size = region × zoom).
        zoom: f32,
    },
}

/// Window chrome + behaviour for [`run`].
pub struct Config {
    /// Wayland `app_id` (for compositor window rules).
    pub app_id: String,
    /// Title shown in the hover toolbar.
    pub label: String,
    /// App icon for the collapsed badge, as `(w, h, rgba)`.
    pub icon: Option<(u32, u32, Vec<u8>)>,
    /// Args to re-exec the current binary with when the user presses `r` (re-pick).
    /// Empty disables re-pick.
    pub relaunch: Vec<String>,
}

/// Run the mirror until the source closes or the user quits.
pub fn run(source: Source, config: Config) -> anyhow::Result<()> {
    let conn = Connection::connect_to_env()?;
    run_on(&conn, source, config)
}

/// [`run`] on a caller-provided connection, so a process that first ran another GPU/EGL
/// overlay (e.g. the region selector) reuses the same `wl_display` and `EGLDisplay`
/// instead of opening a second one — a second EGL connection in one process can alias a
/// freed display and fail (`eglCreateWindowSurface: BadAlloc`).
pub fn run_on(conn: &Connection, source: Source, config: Config) -> anyhow::Result<()> {
    let Config {
        app_id,
        label,
        icon,
        relaunch,
    } = config;
    let (globals, event_queue) = registry_queue_init::<State>(conn)?;
    let qh = event_queue.handle();
    let mut event_loop: EventLoop<State> = EventLoop::try_new()?;
    let lh = event_loop.handle();
    WaylandSource::new(conn.clone(), event_queue)
        .insert(lh.clone())
        .map_err(|e| anyhow::anyhow!("calloop wayland source: {e}"))?;

    let compositor =
        CompositorState::bind(&globals, &qh).map_err(|e| anyhow::anyhow!("wl_compositor: {e}"))?;
    let xdg_shell =
        XdgShell::bind(&globals, &qh).map_err(|e| anyhow::anyhow!("xdg-shell missing: {e}"))?;

    // Region mode fixes the window aspect to the region and starts at region × zoom,
    // showing only the region's sub-rectangle of the captured output. Toplevel mode
    // learns its aspect from the first frame and starts at a default 16:9 tile.
    let (init_w, init_h, fixed_aspect, aspect0, crop_uv) = match &source {
        Source::Toplevel(_) => (DEFAULT_W, DEFAULT_W * 9 / 16, false, None, None),
        Source::Region {
            crop,
            region_w,
            region_h,
            zoom,
            ..
        }
        | Source::ToplevelRegion {
            crop,
            region_w,
            region_h,
            zoom,
            ..
        } => {
            let w = ((*region_w as f32 * zoom).round() as u32).max(MIN_W);
            let h = ((*region_h as f32 * zoom).round() as u32).max(1);
            let aspect = *region_w as f32 / (*region_h).max(1) as f32;
            let uv = egui::Rect::from_min_max(
                egui::pos2(crop[0], crop[1]),
                egui::pos2(crop[2], crop[3]),
            );
            (w, h, true, Some(aspect), Some(uv))
        }
    };
    let min0 = min_size_for(aspect0);

    let surface = compositor.create_surface(&qh);
    let window = xdg_shell.create_window(surface, WindowDecorations::RequestServer, &qh);
    window.set_app_id(&app_id);
    window.set_title(label.clone());
    window.set_min_size(Some(min0));
    window.commit();

    // Capture thread streams frames over a calloop channel; we repaint on each.
    // A region mirrors its covering output (the host crops to the region's sub-rect).
    let stream_source = match &source {
        Source::Toplevel(id) | Source::ToplevelRegion { id, .. } => {
            stream::Source::Toplevel(id.clone())
        }
        Source::Region { output, .. } => stream::Source::Output(output.clone()),
    };
    let (tx, ch): (_, Channel<PipMsg>) = channel();
    std::thread::spawn(move || capture_thread(stream_source, move |m| tx.send(m).is_ok()));
    lh.insert_source(ch, |event, _, state: &mut State| {
        if let ChannelEvent::Msg(m) = event {
            state.on_msg(m);
        }
    })
    .map_err(|e| anyhow::anyhow!("calloop channel source: {e}"))?;

    let theme = Theme::load();
    let egui_ctx = egui::Context::default();
    theme.apply(&egui_ctx);
    let icon_tex = icon.map(|(w, h, rgba)| {
        let img = egui::ColorImage::from_rgba_unmultiplied([w as usize, h as usize], &rgba);
        egui_ctx.load_texture("pip-icon", img, egui::TextureOptions::LINEAR)
    });

    let mut state = State {
        registry_state: RegistryState::new(&globals),
        seat_state: SeatState::new(&globals, &qh),
        output_state: OutputState::new(&globals, &qh),
        window,
        seat: None,
        keyboard: None,
        pointer: None,
        egui_ctx,
        gpu: None,
        content: Content {
            tex: None,
            native: None,
            icon: icon_tex,
            pending: Vec::new(),
            gone: false,
            label,
            theme,
            crop_uv,
        },
        width: init_w,
        height: init_h,
        scale: 1,
        aspect: aspect0,
        fixed_aspect,
        expanded: (init_w, init_h),
        collapsed: false,
        hovered: false,
        pointer_pos: egui::Pos2::ZERO,
        accent: 0,
        gone_since: None,
        opacity: 1.0,
        frozen: false,
        start: Instant::now(),
        closing: false,
        configured: false,
        relaunch,
    };

    while !state.closing {
        event_loop.dispatch(Duration::from_millis(400), &mut state)?;
        if let Some(t) = state.gone_since
            && t.elapsed() >= GONE_LINGER
        {
            break;
        }
    }
    Ok(())
}

impl State {
    /// A capture message arrived (host context): note source size / demise, queue
    /// the frame, restore from the badge on activity, and repaint.
    fn on_msg(&mut self, m: PipMsg) {
        match &m {
            PipMsg::Gone => {
                self.gone_since.get_or_insert(Instant::now());
                self.content.pending.push(m);
                self.redraw();
                return;
            }
            PipMsg::Shm { w, h, .. } => self.on_source_size(*w as u32, *h as u32),
            PipMsg::Dmabuf { frame } => self.on_source_size(frame.width, frame.height),
        }
        // Frozen: keep showing the last frame, drop incoming ones (the dropped
        // dma-buf fd closes here). Source-size tracking above still runs so a later
        // unfreeze keeps the right aspect.
        if self.frozen {
            return;
        }
        // Activity while collapsed pops the tile back open ("notify me on change").
        if self.collapsed {
            self.set_collapsed(false);
            self.accent = ACCENT_FRAMES;
        }
        self.content.pending.push(m);
        self.redraw();
    }

    /// Learn (or update) the source aspect ratio and, when expanded, keep the
    /// tile's height matching it.
    fn on_source_size(&mut self, sw: u32, sh: u32) {
        // Region mode pins the aspect to the region; the frame is the whole output,
        // so its size must not retune the tile.
        if self.fixed_aspect || sw == 0 || sh == 0 {
            return;
        }
        let a = sw as f32 / sh as f32;
        let first = self.aspect.is_none();
        self.aspect = Some(a);
        if !self.collapsed && (first || (self.height as f32 - self.width as f32 / a).abs() > 1.0) {
            let h = ((self.width as f32 / a).round() as u32).max(1);
            self.apply_size(self.width, h);
            self.expanded = (self.width, h);
        }
    }

    /// Snap a width/height to the source aspect ratio (width is authoritative).
    fn snap(&self, w: u32, h: u32) -> (u32, u32) {
        match self.aspect {
            Some(a) if a > 0.0 => (w.max(MIN_W), ((w as f32 / a).round() as u32).max(1)),
            _ => (w.max(MIN_W), h.max(1)),
        }
    }

    /// Set the render size and resize the EGL window to match (the floating
    /// compositor follows our buffer size).
    fn apply_size(&mut self, w: u32, h: u32) {
        self.width = w;
        self.height = h;
        if let Some(gpu) = &self.gpu {
            gpu.resize((w * self.scale) as i32, (h * self.scale) as i32);
        }
    }

    fn set_collapsed(&mut self, collapsed: bool) {
        if collapsed == self.collapsed {
            return;
        }
        self.collapsed = collapsed;
        if collapsed {
            self.expanded = (self.width, self.height);
            self.window.set_min_size(Some((BADGE, BADGE)));
            self.window.set_max_size(Some((BADGE, BADGE)));
            self.apply_size(BADGE, BADGE);
        } else {
            self.window.set_min_size(Some(min_size_for(self.aspect)));
            self.window.set_max_size(None);
            let (w, h) = self.expanded;
            self.apply_size(w, h);
        }
        self.window.commit();
        self.redraw();
    }

    fn ensure_gpu(&mut self, conn: &Connection) {
        if self.gpu.is_some() || self.width == 0 {
            return;
        }
        let (pw, ph) = (
            (self.width * self.scale) as i32,
            (self.height * self.scale) as i32,
        );
        self.gpu = Some(Gpu::new(conn, self.window.wl_surface(), pw, ph));
    }

    /// Render one frame (no frame-callback chain: driven by capture/interaction).
    fn redraw(&mut self) {
        if !self.configured {
            return;
        }
        let (pw, ph) = (self.width * self.scale, self.height * self.scale);
        let raw_input = egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::Pos2::ZERO,
                egui::vec2(self.width as f32, self.height as f32),
            )),
            time: Some(self.start.elapsed().as_secs_f64()),
            focused: true,
            ..Default::default()
        };
        let opacity = self.opacity;
        let backdrop = {
            let c = self.content.theme.thumb.to_normalized_gamma_f32();
            [c[0], c[1], c[2], opacity]
        };
        let size = (self.width as f32, self.height as f32);
        let (collapsed, hovered, accent) = (self.collapsed, self.hovered, self.accent > 0);
        let frozen = self.frozen;
        let content = &mut self.content;
        let Some(gpu) = self.gpu.as_mut() else {
            return;
        };
        gpu.render(
            &self.egui_ctx,
            raw_input,
            self.scale as f32,
            (pw, ph),
            backdrop,
            |ui, imp| {
                let ctx = ui.ctx().clone();
                content.pump(&ctx, imp);
                content.draw(ui, size, collapsed, hovered, accent, frozen, opacity);
            },
        );
        if self.accent > 0 {
            self.accent -= 1;
        }
    }
}

impl CompositorHandler for State {
    fn scale_factor_changed(
        &mut self,
        _: &Connection,
        _: &QueueHandle<Self>,
        _: &wl_surface::WlSurface,
        new_factor: i32,
    ) {
        self.scale = new_factor.max(1) as u32;
        self.window.wl_surface().set_buffer_scale(new_factor.max(1));
        if let Some(gpu) = &self.gpu {
            gpu.resize(
                (self.width * self.scale) as i32,
                (self.height * self.scale) as i32,
            );
        }
        self.redraw();
    }

    fn transform_changed(
        &mut self,
        _: &Connection,
        _: &QueueHandle<Self>,
        _: &wl_surface::WlSurface,
        _: wayland_client::protocol::wl_output::Transform,
    ) {
    }

    fn frame(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &wl_surface::WlSurface, _: u32) {
        // Driven by capture frames instead; nothing to do.
    }

    fn surface_enter(
        &mut self,
        _: &Connection,
        _: &QueueHandle<Self>,
        _: &wl_surface::WlSurface,
        _: &wl_output::WlOutput,
    ) {
    }
    fn surface_leave(
        &mut self,
        _: &Connection,
        _: &QueueHandle<Self>,
        _: &wl_surface::WlSurface,
        _: &wl_output::WlOutput,
    ) {
    }
}

impl WindowHandler for State {
    fn request_close(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &Window) {
        self.closing = true;
    }

    fn configure(
        &mut self,
        conn: &Connection,
        _: &QueueHandle<Self>,
        _: &Window,
        configure: WindowConfigure,
        _: u32,
    ) {
        if let (Some(w), Some(h)) = configure.new_size {
            let (w, h) = if self.collapsed {
                (BADGE, BADGE)
            } else {
                self.snap(w.get(), h.get())
            };
            self.apply_size(w, h);
            if !self.collapsed {
                self.expanded = (w, h);
            }
        }
        self.ensure_gpu(conn);
        self.configured = true;
        self.redraw();
    }
}

impl SeatHandler for State {
    fn seat_state(&mut self) -> &mut SeatState {
        &mut self.seat_state
    }
    fn new_seat(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_seat::WlSeat) {}
    fn new_capability(
        &mut self,
        _: &Connection,
        qh: &QueueHandle<Self>,
        seat: wl_seat::WlSeat,
        cap: Capability,
    ) {
        if cap == Capability::Keyboard && self.keyboard.is_none() {
            self.keyboard = self.seat_state.get_keyboard(qh, &seat, None).ok();
        }
        if cap == Capability::Pointer && self.pointer.is_none() {
            self.pointer = self.seat_state.get_pointer(qh, &seat).ok();
        }
        self.seat = Some(seat);
    }
    fn remove_capability(
        &mut self,
        _: &Connection,
        _: &QueueHandle<Self>,
        _: wl_seat::WlSeat,
        _: Capability,
    ) {
    }
    fn remove_seat(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_seat::WlSeat) {}
}

impl KeyboardHandler for State {
    fn enter(
        &mut self,
        _: &Connection,
        _: &QueueHandle<Self>,
        _: &wl_keyboard::WlKeyboard,
        _: &wl_surface::WlSurface,
        _: u32,
        _: &[u32],
        _: &[Keysym],
    ) {
    }
    fn leave(
        &mut self,
        _: &Connection,
        _: &QueueHandle<Self>,
        _: &wl_keyboard::WlKeyboard,
        _: &wl_surface::WlSurface,
        _: u32,
    ) {
    }
    fn press_key(
        &mut self,
        _: &Connection,
        _: &QueueHandle<Self>,
        _: &wl_keyboard::WlKeyboard,
        _: u32,
        event: KeyEvent,
    ) {
        self.on_key(event.keysym);
    }
    fn release_key(
        &mut self,
        _: &Connection,
        _: &QueueHandle<Self>,
        _: &wl_keyboard::WlKeyboard,
        _: u32,
        _: KeyEvent,
    ) {
    }
    fn repeat_key(
        &mut self,
        _: &Connection,
        _: &QueueHandle<Self>,
        _: &wl_keyboard::WlKeyboard,
        _: u32,
        _: KeyEvent,
    ) {
    }
    fn update_modifiers(
        &mut self,
        _: &Connection,
        _: &QueueHandle<Self>,
        _: &wl_keyboard::WlKeyboard,
        _: u32,
        _: Modifiers,
        _: RawModifiers,
        _: u32,
    ) {
    }
}

impl PointerHandler for State {
    fn pointer_frame(
        &mut self,
        _: &Connection,
        _: &QueueHandle<Self>,
        _: &wl_pointer::WlPointer,
        events: &[PointerEvent],
    ) {
        let Some(seat) = self.seat.clone() else {
            return;
        };
        for e in events {
            let pos = egui::pos2(e.position.0 as f32, e.position.1 as f32);
            match e.kind {
                PointerEventKind::Enter { .. } => {
                    self.pointer_pos = pos;
                    self.hovered = true;
                    self.redraw();
                }
                PointerEventKind::Motion { .. } => {
                    self.pointer_pos = pos;
                }
                PointerEventKind::Leave { .. } => {
                    self.hovered = false;
                    self.redraw();
                }
                // 0x110 == BTN_LEFT.
                PointerEventKind::Press {
                    button: 0x110,
                    serial,
                    ..
                } => {
                    self.pointer_pos = pos;
                    self.on_press(&seat, serial);
                }
                // Wheel adjusts opacity (up = more opaque).
                PointerEventKind::Axis { vertical, .. } if vertical.absolute != 0.0 => {
                    let step = if vertical.absolute < 0.0 { 0.1 } else { -0.1 };
                    self.set_opacity(self.opacity + step);
                }
                _ => {}
            }
        }
    }
}

impl State {
    /// Left-button press: hit-test the toolbar / grip / body and act.
    fn on_press(&mut self, seat: &wl_seat::WlSeat, serial: u32) {
        if self.collapsed {
            self.set_collapsed(false);
            return;
        }
        let (w, h) = (self.width as f32, self.height as f32);
        let (close, collapse) = toolbar_rects(w);
        let p = self.pointer_pos;
        if self.hovered && close.contains(p) {
            self.closing = true;
        } else if self.hovered && collapse.contains(p) {
            self.set_collapsed(true);
        } else if self.hovered && grip_rect(w, h).contains(p) {
            self.window
                .xdg_toplevel()
                .resize(seat, serial, ResizeEdge::BottomRight);
        } else {
            self.window.xdg_toplevel()._move(seat, serial);
        }
    }

    /// Keyboard shortcuts (the window must hold keyboard focus — click it first).
    fn on_key(&mut self, key: Keysym) {
        match key {
            Keysym::Escape | Keysym::q => self.closing = true,
            Keysym::space => {
                self.frozen = !self.frozen;
                self.redraw();
            }
            Keysym::c => self.set_collapsed(!self.collapsed),
            // Opacity: `+`/`=` more opaque, `-` more transparent.
            Keysym::plus | Keysym::equal | Keysym::KP_Add => self.set_opacity(self.opacity + 0.1),
            Keysym::minus | Keysym::KP_Subtract => self.set_opacity(self.opacity - 0.1),
            Keysym::r => self.repick(),
            _ => {}
        }
    }

    fn set_opacity(&mut self, o: f32) {
        let o = o.clamp(0.2, 1.0);
        if (o - self.opacity).abs() > f32::EPSILON {
            self.opacity = o;
            self.redraw();
        }
    }

    /// Re-pick the mirrored source: re-exec ourselves (which runs the chooser) and
    /// close this tile. Simpler and more robust than swapping the capture thread in
    /// place, and the compositor controls position anyway. No-op if disabled.
    fn repick(&mut self) {
        if self.relaunch.is_empty() {
            return;
        }
        if let Ok(exe) = std::env::current_exe() {
            let _ = std::process::Command::new(exe).args(&self.relaunch).spawn();
        }
        self.closing = true;
    }
}

impl OutputHandler for State {
    fn output_state(&mut self) -> &mut OutputState {
        &mut self.output_state
    }
    fn new_output(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_output::WlOutput) {}
    fn update_output(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_output::WlOutput) {}
    fn output_destroyed(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_output::WlOutput) {}
}

impl ProvidesRegistryState for State {
    fn registry(&mut self) -> &mut RegistryState {
        &mut self.registry_state
    }
    registry_handlers![OutputState, SeatState];
}

delegate_compositor!(State);
delegate_output!(State);
delegate_seat!(State);
delegate_keyboard!(State);
delegate_pointer!(State);
delegate_xdg_shell!(State);
delegate_xdg_window!(State);
delegate_registry!(State);
/// A captured frame (or the source's demise) for the single mirrored window.
pub enum PipMsg {
    /// CPU shm frame at full resolution (RGBA8).
    Shm { w: usize, h: usize, rgba: Vec<u8> },
    /// GPU dma-buf frame to import zero-copy as a GL texture (host-side).
    Dmabuf { frame: wl::DmabufFrame },
    /// The source window is gone (closed, or never appeared): the mirror ends.
    Gone,
}

/// Capture thread body: open its own Wayland connection and stream `source` via the
/// shared [`stream::Stream`] driver, forwarding each frame (or the source's demise)
/// as a [`PipMsg`] until the source closes or the host drops the channel.
///
/// `sink` consumes each message and returns `false` once the receiver is gone (so
/// the thread can stop). It is generic so the host (calloop channel) and the
/// headless bench (std mpsc) can both drive it.
pub fn capture_thread(source: stream::Source, mut sink: impl FnMut(PipMsg) -> bool) {
    let mut client = match wl::Client::connect() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("wlr-capture: mirror: {e:#}");
            sink(PipMsg::Gone);
            return;
        }
    };

    let mut s = stream::Stream::new(source, APPEAR_GRACE);
    loop {
        let step = s.step(&mut client, ROUND);
        // Single source, so every delivered frame is ours.
        for frame in step.frames {
            let msg = match frame {
                wl::Frame::Shm(img) => PipMsg::Shm {
                    w: img.width as usize,
                    h: img.height as usize,
                    rgba: img.rgba,
                },
                wl::Frame::Dmabuf(frame) => PipMsg::Dmabuf { frame },
            };
            if !sink(msg) {
                return; // host gone
            }
        }
        if step.end.is_some() {
            sink(PipMsg::Gone);
            return;
        }
    }
}