grim-rs 0.1.9

Rust implementation of grim screenshot utility for Wayland
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
use super::transform::{apply_image_transform, flip_vertical};
use super::*;
use wayland_protocols::ext::image_copy_capture::v1::client::ext_image_copy_capture_manager_v1::Options as ExtCopyOptions;

impl WaylandCapture {
    fn refresh_outputs(&mut self) -> Result<()> {
        self.globals.outputs.clear();
        self.globals.output_info.clear();
        self.globals.output_xdg_map.clear();

        let mut event_queue = self._connection.new_event_queue();
        let qh = event_queue.handle();

        let _registry = self._connection.display().get_registry(&qh, ());

        event_queue.roundtrip(self).map_err(|e| {
            Error::WaylandConnection(format!("Failed to refresh Wayland globals: {}", e))
        })?;
        if self.globals.output_info.is_empty() {
            return Err(Error::NoOutputs);
        }

        for _ in 0..2 {
            event_queue.roundtrip(self).map_err(|e| {
                Error::WaylandConnection(format!("Failed to process output events: {}", e))
            })?;
        }

        if self.globals.xdg_output_manager.is_none() {
            for info in self.globals.output_info.values_mut() {
                if !info.logical_scale_known {
                    guess_output_logical_geometry(info);
                }
            }
        }

        Ok(())
    }

    fn collect_outputs_snapshot(&self) -> Vec<(WlOutput, OutputInfo)> {
        self.globals
            .outputs
            .iter()
            .filter_map(|output| {
                let id = output.id().protocol_id();
                self.globals
                    .output_info
                    .get(&id)
                    .cloned()
                    .map(|info| (output.clone(), info))
            })
            .collect()
    }

    fn capture_region_for_output(
        &mut self,
        output: &WlOutput,
        region: Region,
        overlay_cursor: bool,
    ) -> Result<CaptureResult> {
        // Validation is shared
        if region.width() <= 0 || region.height() <= 0 {
            return Err(Error::InvalidRegion(
                "Capture region must have positive width and height".to_string(),
            ));
        }
        if region.x() < 0 || region.y() < 0 {
            return Err(Error::InvalidRegion(
                "Capture region origin must be non-negative".to_string(),
            ));
        }

        let backend = self.backend_cloned()?;
        match backend {
            CaptureBackend::WlrScreencopy { manager } => {
                self.capture_region_wlr(&manager, output, region, overlay_cursor)
            }
            CaptureBackend::ExtImageCopyCapture {
                source_manager,
                copy_manager,
            } => self.capture_region_ext(
                &source_manager,
                &copy_manager,
                output,
                region,
                overlay_cursor,
            ),
        }
    }

    fn capture_region_wlr(
        &mut self,
        manager: &ZwlrScreencopyManagerV1,
        output: &WlOutput,
        region: Region,
        overlay_cursor: bool,
    ) -> Result<CaptureResult> {
        let screencopy_manager = manager;
        let mut event_queue = self._connection.new_event_queue();
        let qh = event_queue.handle();
        let frame_state = Arc::new(Mutex::new(FrameState {
            buffer: None,
            width: 0,
            height: 0,
            format: None,
            ready: false,
            flags: 0,
            linux_dmabuf_received: false,
            constraints_done: false,
        }));
        let frame = screencopy_manager.capture_output_region(
            if overlay_cursor { 1 } else { 0 },
            output,
            region.x(),
            region.y(),
            region.width(),
            region.height(),
            &qh,
            frame_state.clone(),
        );

        let mut attempts = 0;
        loop {
            {
                let state = lock_frame_state(&frame_state)?;
                if state.buffer.is_some() || state.ready || state.linux_dmabuf_received {
                    if state.ready && state.buffer.is_none() && !state.linux_dmabuf_received {
                        return Err(Error::FrameCapture(
                            "Frame is ready but buffer was not received".to_string(),
                        ));
                    }
                    break;
                }
            }
            if attempts >= MAX_ATTEMPTS {
                return Err(Error::FrameCapture(
                    "Timeout waiting for frame buffer".to_string(),
                ));
            }
            event_queue.blocking_dispatch(self).map_err(|e| {
                Error::FrameCapture(format!("Failed to dispatch frame events: {}", e))
            })?;
            attempts += 1;
        }

        // If we received linux_dmabuf but no Buffer event, populate buffer from dmabuf info.
        {
            let mut state = lock_frame_state(&frame_state)?;
            if state.buffer.is_none() && state.linux_dmabuf_received {
                let stride = state.width * 4;
                let size = checked_buffer_size(state.width, state.height, 4, Some(stride))?;
                state.buffer = Some(vec![0u8; size]);
            }
        }

        let shm = self
            .globals
            .shm
            .as_ref()
            .ok_or_else(|| Error::UnsupportedProtocol("wl_shm not available".to_string()))?;

        let (width, height, stride, size, format) = {
            let state = lock_frame_state(&frame_state)?;
            if state.width == 0 || state.height == 0 {
                return Err(Error::CaptureFailed);
            }
            let width = state.width;
            let height = state.height;
            let stride = width * 4;
            let size = checked_buffer_size(width, height, 4, Some(stride))?;
            let format = state.format.unwrap_or(ShmFormat::Xrgb8888);
            (width, height, stride, size, format)
        };

        let mut tmp_file = tempfile::NamedTempFile::new().map_err(|e| {
            Error::BufferCreation(format!("failed to create temporary file: {}", e))
        })?;
        tmp_file.as_file_mut().set_len(size as u64).map_err(|e| {
            Error::BufferCreation(format!("failed to resize buffer to {} bytes: {}", size, e))
        })?;
        let mmap = unsafe {
            memmap2::MmapMut::map_mut(&tmp_file)
                .map_err(|e| Error::BufferCreation(format!("failed to memory-map buffer: {}", e)))?
        };

        let pool = shm.create_pool(
            unsafe { BorrowedFd::borrow_raw(tmp_file.as_file().as_raw_fd()) },
            size as i32,
            &qh,
            (),
        );
        let buffer = pool.create_buffer(
            0,
            width as i32,
            height as i32,
            stride as i32,
            format,
            &qh,
            (),
        );
        frame.copy(&buffer);

        let mut attempts = 0;
        loop {
            {
                let state = lock_frame_state(&frame_state)?;
                if state.ready {
                    if state.buffer.is_none() {
                        return Err(Error::FrameCapture(
                            "Frame is ready but buffer was not received".to_string(),
                        ));
                    }
                    break;
                }
            }
            if attempts >= MAX_ATTEMPTS {
                return Err(Error::FrameCapture(
                    "Timeout waiting for frame capture completion".to_string(),
                ));
            }
            event_queue.blocking_dispatch(self).map_err(|e| {
                Error::FrameCapture(format!("Failed to dispatch frame events: {}", e))
            })?;
            attempts += 1;
        }

        let mut buffer_data = mmap.to_vec();
        if let Some(pf) = shm_to_pixel(format) {
            crate::pixel_format::convert_to_rgba(&mut buffer_data, pf);
        }
        let output_id = output.id().protocol_id();
        let mut final_data = buffer_data;
        let mut final_width = width;
        let mut final_height = height;

        if let Some(info) = self.globals.output_info.get(&output_id) {
            if !matches!(
                info.transform,
                wayland_client::protocol::wl_output::Transform::Normal
            ) {
                let (transformed_data, new_width, new_height) =
                    apply_image_transform(&final_data, final_width, final_height, info.transform);
                final_data = transformed_data;
                final_width = new_width;
                final_height = new_height;
            }
        }

        let flags = {
            let state = lock_frame_state(&frame_state)?;
            state.flags
        };

        if (flags & ZWLR_SCREENCOPY_FRAME_V1_FLAGS_Y_INVERT) != 0 {
            let (inverted_data, inv_width, inv_height) =
                flip_vertical(&final_data, final_width, final_height);
            final_data = inverted_data;
            final_width = inv_width;
            final_height = inv_height;
        }

        Ok(CaptureResult {
            data: final_data,
            width: final_width,
            height: final_height,
        })
    }

    fn capture_region_ext(
        &mut self,
        source_manager: &ExtOutputImageCaptureSourceManagerV1,
        copy_manager: &ExtImageCopyCaptureManagerV1,
        output: &WlOutput,
        region: Region,
        overlay_cursor: bool,
    ) -> Result<CaptureResult> {
        let mut event_queue = self._connection.new_event_queue();
        let qh = event_queue.handle();
        let frame_state = Arc::new(Mutex::new(FrameState {
            buffer: None,
            width: 0,
            height: 0,
            format: None,
            ready: false,
            flags: 0,
            linux_dmabuf_received: false,
            constraints_done: false,
        }));
        let source = source_manager.create_source(output, &qh, ());
        let mut options = ExtCopyOptions::empty();
        if overlay_cursor {
            options |= ExtCopyOptions::PaintCursors;
        }
        let _session = copy_manager.create_session(&source, options, &qh, frame_state.clone());

        let mut attempts = 0;
        loop {
            {
                let state = lock_frame_state(&frame_state)?;
                if state.constraints_done {
                    break;
                }
            }
            if attempts >= MAX_ATTEMPTS {
                return Err(Error::FrameCapture(
                    "Timeout waiting for session constraints".to_string(),
                ));
            }
            event_queue.blocking_dispatch(self).map_err(|e| {
                Error::FrameCapture(format!("Failed to dispatch session events: {}", e))
            })?;
            attempts += 1;
        }

        let (full_width, full_height, format) = {
            let state = lock_frame_state(&frame_state)?;
            if state.width == 0 || state.height == 0 {
                return Err(Error::CaptureFailed);
            }
            (
                state.width,
                state.height,
                state.format.unwrap_or(ShmFormat::Xrgb8888),
            )
        };

        let stride = full_width * 4;
        let size = checked_buffer_size(full_width, full_height, 4, Some(stride))?;
        let shm = self
            .globals
            .shm
            .as_ref()
            .ok_or_else(|| Error::UnsupportedProtocol("wl_shm not available".to_string()))?;
        let mut tmp_file = tempfile::NamedTempFile::new().map_err(|e| {
            Error::BufferCreation(format!("failed to create temporary file: {}", e))
        })?;
        tmp_file.as_file_mut().set_len(size as u64).map_err(|e| {
            Error::BufferCreation(format!("failed to resize buffer to {} bytes: {}", size, e))
        })?;
        let mmap = unsafe {
            memmap2::MmapMut::map_mut(&tmp_file)
                .map_err(|e| Error::BufferCreation(format!("failed to memory-map buffer: {}", e)))?
        };
        let pool = shm.create_pool(
            unsafe { BorrowedFd::borrow_raw(tmp_file.as_file().as_raw_fd()) },
            size as i32,
            &qh,
            (),
        );
        let buffer = pool.create_buffer(
            0,
            full_width as i32,
            full_height as i32,
            stride as i32,
            format,
            &qh,
            (),
        );

        // Set buffer placeholder — ext doesn't have a Buffer event like wlr
        {
            let mut state = lock_frame_state(&frame_state)?;
            state.buffer = Some(vec![0u8; size]);
        }

        // create frame, attach buffer, capture
        let frame = _session.create_frame(&qh, frame_state.clone());
        frame.attach_buffer(&buffer);
        frame.damage_buffer(0, 0, full_width as i32, full_height as i32);
        frame.capture();
        let mut attempts = 0;
        loop {
            {
                let state = lock_frame_state(&frame_state)?;
                if state.ready {
                    if state.buffer.is_none() {
                        return Err(Error::FrameCapture(
                            "Frame is ready but buffer was not received".to_string(),
                        ));
                    }
                    break;
                }
            }
            if attempts >= MAX_ATTEMPTS {
                return Err(Error::FrameCapture(
                    "Timeout waiting for frame capture completion".to_string(),
                ));
            }
            event_queue.blocking_dispatch(self).map_err(|e| {
                Error::FrameCapture(format!("Failed to dispatch frame events: {}", e))
            })?;
            attempts += 1;
        }
        let mut buffer_data = mmap.to_vec();
        if let Some(pf) = shm_to_pixel(format) {
            crate::pixel_format::convert_to_rgba(&mut buffer_data, pf);
        }
        let output_id = output.id().protocol_id();
        let (mut final_data, mut final_width, mut final_height) =
            self.apply_output_transform(buffer_data, full_width, full_height, output_id);
        let region_w = region.width() as u32;
        let region_h = region.height() as u32;
        let need_crop = {
            let info = self.globals.output_info.get(&output_id);
            info.is_none_or(|info| {
                region.x() != 0
                    || region.y() != 0
                    || region_w as i32 != info.logical_width
                    || region_h as i32 != info.logical_height
            })
        };

        if need_crop && region_w > 0 && region_h > 0 {
            let scale = self
                .globals
                .output_info
                .get(&output_id)
                .map_or(1.0, |info| {
                    if info.logical_scale_known && info.logical_scale.is_finite() {
                        info.logical_scale
                    } else {
                        info.scale as f64
                    }
                });
            let crop_x = ((region.x() as f64) * scale) as usize;
            let crop_y = ((region.y() as f64) * scale) as usize;
            let crop_w = ((region_w as f64) * scale) as u32;
            let crop_h = ((region_h as f64) * scale) as u32;
            let (cropped, cw, ch) = crop_rgba(
                &final_data,
                final_width,
                final_height,
                crop_x,
                crop_y,
                crop_w,
                crop_h,
            );
            final_data = cropped;
            final_width = cw;
            final_height = ch;
        }

        Ok(CaptureResult {
            data: final_data,
            width: final_width,
            height: final_height,
        })
    }

    fn composite_region(
        &mut self,
        region: Region,
        outputs: &[(WlOutput, OutputInfo)],
        overlay_cursor: bool,
    ) -> Result<CaptureResult> {
        if region.width() <= 0 || region.height() <= 0 {
            return Err(Error::InvalidRegion(
                "Capture region must have positive width and height".to_string(),
            ));
        }

        let dest_width_u32 = u32::try_from(region.width()).map_err(|_| {
            Error::InvalidRegion("Capture region width exceeds supported range".to_string())
        })?;
        let dest_height_u32 = u32::try_from(region.height()).map_err(|_| {
            Error::InvalidRegion("Capture region height exceeds supported range".to_string())
        })?;
        let dest_bytes = checked_buffer_size(dest_width_u32, dest_height_u32, 4, None)?;
        let dest_width = dest_width_u32 as usize;
        let dest_height = dest_height_u32 as usize;
        let mut dest = vec![0u8; dest_bytes];
        let mut any_capture = false;

        for (output, info) in outputs {
            let output_box = Region::new(
                info.logical_x,
                info.logical_y,
                info.logical_width,
                info.logical_height,
            );
            if let Some(intersection) = output_box.intersection(&region) {
                if intersection.width() <= 0 || intersection.height() <= 0 {
                    continue;
                }

                let scale = if info.logical_scale_known && info.logical_scale.is_finite() {
                    info.logical_scale
                } else {
                    info.scale as f64
                };
                let local_region = Region::new(
                    intersection.x() - info.logical_x,
                    intersection.y() - info.logical_y,
                    intersection.width(),
                    intersection.height(),
                );
                let mut capture =
                    self.capture_region_for_output(output, local_region, overlay_cursor)?;

                if scale != 1.0 {
                    capture = self.scale_image_data(capture, 1.0 / scale)?;
                }

                let offset_x = (intersection.x() - region.x()) as usize;
                let offset_y = (intersection.y() - region.y()) as usize;

                blit_capture(
                    &mut dest,
                    dest_width,
                    dest_height,
                    &capture,
                    offset_x,
                    offset_y,
                );
                any_capture = true;
            }
        }

        if !any_capture {
            return Err(Error::InvalidRegion(
                "Capture region does not intersect with any output".to_string(),
            ));
        }

        Ok(CaptureResult {
            data: dest,
            width: region.width() as u32,
            height: region.height() as u32,
        })
    }

    pub fn get_outputs(&mut self) -> Result<Vec<Output>> {
        self.refresh_outputs()?;
        let snapshot = self.collect_outputs_snapshot();
        let outputs = snapshot
            .into_iter()
            .map(|(_, info)| {
                let (x, y, width, height) = if info.logical_scale_known {
                    (
                        info.logical_x,
                        info.logical_y,
                        info.logical_width,
                        info.logical_height,
                    )
                } else {
                    (info.x, info.y, info.width, info.height)
                };

                Output {
                    name: info.name.clone(),
                    geometry: Region::new(x, y, width, height),
                    scale: info.scale,
                    description: info.description.clone(),
                }
            })
            .collect::<Vec<_>>();
        if outputs.is_empty() {
            return Err(Error::NoOutputs);
        }
        Ok(outputs)
    }

    pub fn capture_all(&mut self) -> Result<CaptureResult> {
        self.refresh_outputs()?;
        let snapshot = self.collect_outputs_snapshot();
        if snapshot.is_empty() {
            return Err(Error::NoOutputs);
        }

        let (_, first_info) = &snapshot[0];
        let mut min_x = first_info.logical_x;
        let mut min_y = first_info.logical_y;
        let mut max_x = first_info.logical_x + first_info.logical_width;
        let mut max_y = first_info.logical_y + first_info.logical_height;

        for (_, info) in &snapshot {
            min_x = min_x.min(info.logical_x);
            min_y = min_y.min(info.logical_y);
            max_x = max_x.max(info.logical_x + info.logical_width);
            max_y = max_y.max(info.logical_y + info.logical_height);
        }

        let region = Region::new(min_x, min_y, max_x - min_x, max_y - min_y);
        self.composite_region(region, &snapshot, false)
    }

    pub fn capture_all_with_scale(&mut self, scale: f64) -> Result<CaptureResult> {
        let result = self.capture_all()?;
        self.scale_image_data(result, scale)
    }

    pub fn capture_output(&mut self, output_name: &str) -> Result<CaptureResult> {
        self.refresh_outputs()?;
        let snapshot = self.collect_outputs_snapshot();
        let (output_handle, info) = snapshot
            .into_iter()
            .find(|(_, info)| info.name == output_name)
            .ok_or_else(|| Error::OutputNotFound(output_name.to_string()))?;

        let local_region = Region::new(0, 0, info.logical_width, info.logical_height);
        self.capture_region_for_output(&output_handle, local_region, false)
    }

    pub fn capture_output_with_scale(
        &mut self,
        output_name: &str,
        scale: f64,
    ) -> Result<CaptureResult> {
        let result = self.capture_output(output_name)?;
        self.scale_image_data(result, scale)
    }

    pub fn capture_region(&mut self, region: Region) -> Result<CaptureResult> {
        self.refresh_outputs()?;
        let snapshot = self.collect_outputs_snapshot();
        self.composite_region(region, &snapshot, false)
    }

    pub fn capture_region_with_scale(
        &mut self,
        region: Region,
        scale: f64,
    ) -> Result<CaptureResult> {
        let result = self.capture_region(region)?;
        self.scale_image_data(result, scale)
    }

    pub fn capture_outputs(
        &mut self,
        parameters: Vec<CaptureParameters>,
    ) -> Result<MultiOutputCaptureResult> {
        self.refresh_outputs()?;

        let backend = self.backend_cloned()?;
        match backend {
            CaptureBackend::WlrScreencopy { manager } => {
                self.capture_outputs_wlr(manager, parameters)
            }
            CaptureBackend::ExtImageCopyCapture {
                source_manager,
                copy_manager,
            } => self.capture_outputs_ext(source_manager, copy_manager, parameters),
        }
    }

    fn capture_outputs_wlr(
        &mut self,
        manager: ZwlrScreencopyManagerV1,
        parameters: Vec<CaptureParameters>,
    ) -> Result<MultiOutputCaptureResult> {
        let screencopy_manager = &manager;
        let mut event_queue = self._connection.new_event_queue();
        let qh = event_queue.handle();
        let mut frame_states: HashMap<String, Arc<Mutex<FrameState>>> = HashMap::new();
        let mut frames: HashMap<String, ZwlrScreencopyFrameV1> = HashMap::new();

        for param in &parameters {
            let (output_id, output_info) = self
                .globals
                .output_info
                .iter()
                .find(|(_, info)| info.name == param.output_name())
                .ok_or_else(|| Error::OutputNotFound(param.output_name().to_string()))?;

            let output = self
                .globals
                .outputs
                .iter()
                .find(|o| o.id().protocol_id() == *output_id)
                .ok_or_else(|| Error::OutputNotFound(param.output_name().to_string()))?;
            let region = if let Some(region) = param.region_ref() {
                let output_right = output_info.logical_width;
                let output_bottom = output_info.logical_height;
                if region.x() < 0
                    || region.y() < 0
                    || region.x() + region.width() > output_right
                    || region.y() + region.height() > output_bottom
                {
                    return Err(Error::InvalidRegion(
                        "Capture region extends outside output boundaries".to_string(),
                    ));
                }
                *region
            } else {
                Region::new(0, 0, output_info.logical_width, output_info.logical_height)
            };
            let frame_state = Arc::new(Mutex::new(FrameState {
                buffer: None,
                width: 0,
                height: 0,
                format: None,
                ready: false,
                flags: 0,
                linux_dmabuf_received: false,
                constraints_done: false,
            }));
            let frame = screencopy_manager.capture_output_region(
                if param.overlay_cursor_enabled() { 1 } else { 0 },
                output,
                region.x(),
                region.y(),
                region.width(),
                region.height(),
                &qh,
                frame_state.clone(),
            );
            frame_states.insert(param.output_name().to_string(), frame_state);
            frames.insert(param.output_name().to_string(), frame);
        }
        let mut attempts = 0;
        let mut completed_frames = 0;
        let total_frames = parameters.len();
        while completed_frames < total_frames && attempts < MAX_ATTEMPTS {
            completed_frames = frame_states
                .iter()
                .filter(|(_, state)| {
                    state
                        .lock()
                        .ok()
                        .is_some_and(|s| s.buffer.is_some() || s.ready || s.linux_dmabuf_received)
                })
                .count();
            if completed_frames >= total_frames {
                break;
            }
            event_queue.blocking_dispatch(self).map_err(|e| {
                Error::FrameCapture(format!("Failed to dispatch frame events: {}", e))
            })?;
            attempts += 1;
        }
        if attempts >= MAX_ATTEMPTS {
            return Err(Error::FrameCapture(
                "Timeout waiting for frame buffers".to_string(),
            ));
        }
        for frame_state in frame_states.values() {
            let mut state = lock_frame_state(frame_state)?;
            if state.buffer.is_none() {
                if state.linux_dmabuf_received {
                    let stride = state.width * 4;
                    let size = checked_buffer_size(state.width, state.height, 4, Some(stride))?;
                    state.buffer = Some(vec![0u8; size]);
                } else {
                    return Err(Error::CaptureFailed);
                }
            }
        }
        let mut buffers: HashMap<String, (tempfile::NamedTempFile, memmap2::MmapMut)> =
            HashMap::new();
        for (output_name, frame_state) in &frame_states {
            let (width, height, stride, size) = {
                let state = lock_frame_state(frame_state)?;
                let width = state.width;
                let height = state.height;
                let stride = width * 4;
                let size = checked_buffer_size(width, height, 4, Some(stride))?;
                (width, height, stride, size)
            };
            let mut tmp_file = tempfile::NamedTempFile::new().map_err(|e| {
                Error::BufferCreation(format!(
                    "failed to create temporary file for output '{}': {}",
                    output_name, e
                ))
            })?;
            tmp_file.as_file_mut().set_len(size as u64).map_err(|e| {
                Error::BufferCreation(format!(
                    "failed to resize buffer for output '{}' to {} bytes: {}",
                    output_name, size, e
                ))
            })?;
            let mmap = unsafe {
                memmap2::MmapMut::map_mut(&tmp_file).map_err(|e| {
                    Error::BufferCreation(format!(
                        "failed to memory-map buffer for output '{}': {}",
                        output_name, e
                    ))
                })?
            };
            let shm = self.globals.shm.as_ref().ok_or(Error::UnsupportedProtocol(
                "wl_shm not available".to_string(),
            ))?;
            {
                let format = {
                    let state = lock_frame_state(frame_state)?;
                    state.format.unwrap_or(ShmFormat::Xrgb8888)
                };
                let pool = shm.create_pool(
                    unsafe { BorrowedFd::borrow_raw(tmp_file.as_file().as_raw_fd()) },
                    size as i32,
                    &qh,
                    (),
                );
                let buffer = pool.create_buffer(
                    0,
                    width as i32,
                    height as i32,
                    stride as i32,
                    format,
                    &qh,
                    (),
                );
                if let Some(frame) = frames.get(output_name) {
                    frame.copy(&buffer);
                }
            }
            buffers.insert(output_name.clone(), (tmp_file, mmap));
        }
        let mut attempts = 0;
        let mut completed_frames = 0;
        while completed_frames < total_frames && attempts < MAX_ATTEMPTS {
            completed_frames = frame_states
                .iter()
                .filter(|(_, state)| state.lock().ok().is_some_and(|s| s.ready))
                .count();
            if completed_frames >= total_frames {
                break;
            }
            event_queue.blocking_dispatch(self).map_err(|e| {
                Error::FrameCapture(format!("Failed to dispatch frame events: {}", e))
            })?;
            attempts += 1;
        }
        if attempts >= MAX_ATTEMPTS {
            return Err(Error::FrameCapture(
                "Timeout waiting for frame capture completion".to_string(),
            ));
        }
        for frame_state in frame_states.values() {
            let state = lock_frame_state(frame_state)?;
            if state.ready && state.buffer.is_none() {
                return Err(Error::FrameCapture(
                    "Frame is ready but buffer was not received".to_string(),
                ));
            }
        }
        let mut results: HashMap<String, CaptureResult> = HashMap::new();
        for (output_name, (_tmp_file, mmap)) in buffers {
            let frame_state = &frame_states[&output_name];
            let (width, height) = {
                let state = lock_frame_state(frame_state)?;
                (state.width, state.height)
            };
            let format = {
                let state = lock_frame_state(frame_state)?;
                state.format.unwrap_or(ShmFormat::Xrgb8888)
            };
            let mut buffer_data = mmap.to_vec();
            if let Some(pf) = shm_to_pixel(format) {
                crate::pixel_format::convert_to_rgba(&mut buffer_data, pf);
            }
            let mut final_data = buffer_data;
            let mut final_width = width;
            let mut final_height = height;

            if let Some(info) = self
                .globals
                .output_info
                .values()
                .find(|info| info.name == output_name)
            {
                if !matches!(
                    info.transform,
                    wayland_client::protocol::wl_output::Transform::Normal
                ) {
                    let (transformed_data, new_width, new_height) = apply_image_transform(
                        &final_data,
                        final_width,
                        final_height,
                        info.transform,
                    );
                    final_data = transformed_data;
                    final_width = new_width;
                    final_height = new_height;
                }
            }

            let flags = {
                let state = lock_frame_state(frame_state)?;
                state.flags
            };

            if (flags & ZWLR_SCREENCOPY_FRAME_V1_FLAGS_Y_INVERT) != 0 {
                let (inverted_data, inv_width, inv_height) =
                    flip_vertical(&final_data, final_width, final_height);
                final_data = inverted_data;
                final_width = inv_width;
                final_height = inv_height;
            }
            results.insert(
                output_name,
                CaptureResult {
                    data: final_data,
                    width: final_width,
                    height: final_height,
                },
            );
        }
        Ok(MultiOutputCaptureResult::new(results))
    }

    fn capture_outputs_ext(
        &mut self,
        source_manager: ExtOutputImageCaptureSourceManagerV1,
        copy_manager: ExtImageCopyCaptureManagerV1,
        parameters: Vec<CaptureParameters>,
    ) -> Result<MultiOutputCaptureResult> {
        let mut results = HashMap::new();
        for param in &parameters {
            let (output_id, output_info) = self
                .globals
                .output_info
                .iter()
                .find(|(_, info)| info.name == param.output_name())
                .ok_or_else(|| Error::OutputNotFound(param.output_name().to_string()))?;

            let region = if let Some(region) = param.region_ref() {
                let output_right = output_info.logical_width;
                let output_bottom = output_info.logical_height;
                if region.x() < 0
                    || region.y() < 0
                    || region.x() + region.width() > output_right
                    || region.y() + region.height() > output_bottom
                {
                    return Err(Error::InvalidRegion(
                        "Capture region extends outside output boundaries".to_string(),
                    ));
                }
                *region
            } else {
                Region::new(0, 0, output_info.logical_width, output_info.logical_height)
            };
            let output_clone = {
                let output = self
                    .globals
                    .outputs
                    .iter()
                    .find(|o| o.id().protocol_id() == *output_id)
                    .ok_or_else(|| Error::OutputNotFound(param.output_name().to_string()))?;
                output.clone()
            };
            let capture = self.capture_region_ext(
                &source_manager,
                &copy_manager,
                &output_clone,
                region,
                param.overlay_cursor_enabled(),
            )?;
            results.insert(param.output_name().to_string(), capture);
        }
        Ok(MultiOutputCaptureResult::new(results))
    }

    pub fn capture_outputs_with_scale(
        &mut self,
        parameters: Vec<CaptureParameters>,
        default_scale: f64,
    ) -> Result<MultiOutputCaptureResult> {
        let result = self.capture_outputs(parameters)?;
        let mut scaled_results = std::collections::HashMap::new();

        for (output_name, capture_result) in result.into_outputs() {
            let scale = default_scale;
            let scaled_result = self.scale_image_data(capture_result, scale)?;
            scaled_results.insert(output_name, scaled_result);
        }

        Ok(MultiOutputCaptureResult::new(scaled_results))
    }

    fn apply_output_transform(
        &self,
        data: Vec<u8>,
        width: u32,
        height: u32,
        output_id: u32,
    ) -> (Vec<u8>, u32, u32) {
        if let Some(info) = self.globals.output_info.get(&output_id) {
            if !matches!(
                info.transform,
                wayland_client::protocol::wl_output::Transform::Normal
            ) {
                return transform::apply_image_transform(&data, width, height, info.transform);
            }
        }
        (data, width, height)
    }
}

fn crop_rgba(
    data: &[u8],
    full_width: u32,
    full_height: u32,
    x: usize,
    y: usize,
    width: u32,
    height: u32,
) -> (Vec<u8>, u32, u32) {
    let w = (width as usize).min(full_width as usize - x.min(full_width as usize));
    let h = (height as usize).min(full_height as usize - y.min(full_height as usize));
    if w == 0 || h == 0 {
        return (Vec::new(), 0, 0);
    }
    let mut out = vec![0u8; w * h * 4];
    for row in 0..h {
        let src_start = ((y + row) * full_width as usize + x) * 4;
        let dst_start = row * w * 4;
        out[dst_start..dst_start + w * 4].copy_from_slice(&data[src_start..src_start + w * 4]);
    }
    (out, w as u32, h as u32)
}