xa11y-core 0.15.4

Core types, traits, and selector engine for xa11y cross-platform accessibility
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
//! Screenshot capture: pixel-level snapshots of the screen or a region.
//!
//! Screenshot is **separate from** both the accessibility action layer
//! ([`crate::Provider`]) and the input-synthesis layer ([`crate::InputProvider`]).
//! Backends that only capture pixels do not know how to read the a11y tree,
//! synthesise input, or activate windows — they are pure pixel readers.
//!
//! # What you get
//!
//! The caller-facing entry points in the `xa11y` umbrella crate
//! (`xa11y::screenshot()`, `xa11y::screenshot_region()`,
//! `xa11y::screenshot_element()`) all return a [`Screenshot`] carrying raw
//! RGBA8 pixels in **physical** (device) pixels — the same resolution the
//! compositor renders at. On macOS and scaled Linux displays, pixel dimensions
//! can exceed the logical bounds you passed in; [`Screenshot::scale`] records a
//! compatibility ratio for simple one-display consumers. It is not a desktop
//! transform: use the screenshot's explicit coordinate methods for mixed-DPI,
//! cropped, or resized images. Call [`Screenshot::to_png`] or
//! [`Screenshot::save_png`] to encode.
//!
//! # No auto-activation
//!
//! Capturing an element that is occluded or off-screen returns whatever pixels
//! are at those coordinates — the target window is **not** activated. If you
//! need the element in the foreground, do that explicitly
//! before calling `xa11y::screenshot_element`.
//!
//! # Annotation
//!
//! [`annotate`] draws boxes and tags onto a capture: [`Screenshot::annotate`]
//! takes [`Annotation`]s in desktop coordinates, plus the desktop
//! coordinate the capture's own pixel `(0, 0)` sits at, and returns a new
//! capture with them drawn in. That second argument is why
//! [`ScreenshotProvider::capture_full`] returns a pair: what a full capture
//! covers differs per platform, and so does where it starts. That module is
//! pure pixels — it knows nothing about selectors, providers, or platforms.
//!
//! [`legend`] carries the other half of the result: [`Annotated`],
//! [`LegendEntry`], [`Omission`] and [`OmissionReason`] describe *what* was
//! drawn and what could not be. They are built by
//! `xa11y::screenshot_annotated`, which is where selectors are resolved, and
//! live here so the language bindings that surface them are covered by
//! `cargo xtask check-bindings-parity`.

use std::path::Path;

use crate::element::Rect;
use crate::error::{Error, Result};
use crate::input::Point;

pub mod annotate;
pub mod legend;

pub use annotate::{tag_for, Annotation, ANNOTATION_PALETTE};
pub use legend::{Annotated, LegendEntry, Omission, OmissionReason};

/// One affine piece of a capture's desktop-to-image mapping.
///
/// This is a backend construction detail. Public consumers use
/// [`Screenshot::desktop_to_image`], [`Screenshot::image_to_desktop`], and
/// [`Screenshot::desktop_rect_to_image`] instead.
#[doc(hidden)]
#[allow(
    clippy::exhaustive_structs,
    reason = "Backend construction detail: one affine segment is completely described by its desktop and image rectangles."
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CaptureMappingSegment {
    pub desktop: Rect,
    pub image: Rect,
}

/// Mapping metadata frozen at capture time.
///
/// Backends provide affine segments for the portions present in the returned
/// image. Windows uses identity segments clipped to each display. A layout
/// token and validator are optional; Windows supplies both so
/// conversions fail after a relevant display-layout change instead of using a
/// stale transform.
#[doc(hidden)]
#[derive(Clone)]
pub struct CaptureMapping {
    segments: Vec<CaptureMappingSegment>,
    // Keep capture-time segments immutable. Requantizing their desktop
    // rectangles after an odd-pixel HiDPI crop loses the fractional origin.
    // Current image coordinates are (capture coordinates - origin) * scale.
    origin: (f64, f64),
    image_scale: (f64, f64),
    layout_token: Option<u64>,
    validator: Option<fn(u64) -> Result<bool>>,
}

impl std::fmt::Debug for CaptureMapping {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CaptureMapping")
            .field("segments", &self.segments)
            .field("layout_token", &self.layout_token)
            .finish_non_exhaustive()
    }
}

impl CaptureMapping {
    #[doc(hidden)]
    pub fn new(segments: Vec<CaptureMappingSegment>) -> Self {
        Self {
            segments,
            origin: (0.0, 0.0),
            image_scale: (1.0, 1.0),
            layout_token: None,
            validator: None,
        }
    }

    /// Build the usual one-display mapping from a logical origin, returned
    /// image dimensions, and physical/logical scale.
    #[doc(hidden)]
    pub fn single(origin: Point, image_width: u32, image_height: u32, scale: f32) -> Self {
        let scale = crate::element::sane_scale(f64::from(scale));
        Self::new(vec![CaptureMappingSegment {
            desktop: Rect {
                x: origin.x,
                y: origin.y,
                width: (f64::from(image_width) / scale).round() as u32,
                height: (f64::from(image_height) / scale).round() as u32,
            },
            image: Rect {
                x: 0,
                y: 0,
                width: image_width,
                height: image_height,
            },
        }])
    }

    #[doc(hidden)]
    pub fn with_layout_validation(
        segments: Vec<CaptureMappingSegment>,
        layout_token: u64,
        validator: fn(u64) -> Result<bool>,
    ) -> Self {
        Self {
            segments,
            origin: (0.0, 0.0),
            image_scale: (1.0, 1.0),
            layout_token: Some(layout_token),
            validator: Some(validator),
        }
    }

    fn validate(&self) -> Result<()> {
        if let (Some(token), Some(validator)) = (self.layout_token, self.validator) {
            if !validator(token)? {
                return Err(Error::Platform {
                    code: -1,
                    message: "screenshot coordinate mapping is stale because the display layout changed; capture a new screenshot".into(),
                });
            }
        }
        Ok(())
    }
}

/// Platform backend trait for screen capture.
///
/// Implementors snapshot pixels from a display or a sub-region. They must
/// return **physical** (device) pixels — never downscaled to logical points —
/// and report the scale factor alongside the pixel buffer.
///
/// # Errors
///
/// - [`Error::PermissionDenied`] when the OS denies the capture permission
///   (e.g. macOS Screen Recording).
/// - [`Error::Unsupported`] when the current session has no capture path
///   (e.g. Linux with neither X11 DISPLAY nor a working Wayland portal).
/// - [`Error::Platform`] for raw OS / FFI failures.
pub trait ScreenshotProvider: Send + Sync {
    /// Capture everything this backend treats as "the screen", and report
    /// **where** those pixels are.
    ///
    /// The returned [`Point`] is the desktop coordinate that the
    /// capture's pixel `(0, 0)` sits at. It is not always the origin:
    ///
    /// - Windows captures the whole **virtual desktop**, whose top-left is
    ///   `(SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN)` — negative whenever a
    ///   monitor is arranged left of or above the primary one.
    /// - macOS captures one `SCDisplay`, whose `frame.origin` is only `(0, 0)`
    ///   when it is the display at the coordinate-space origin.
    /// - Linux X11 captures the root window, which is at `(0, 0)`.
    ///
    /// Reporting it is the whole reason this method returns a pair. Anything
    /// that maps a logical rectangle (an `Element::bounds`) onto these pixels
    /// — [`Screenshot::annotate`] above all — must subtract this origin
    /// first, and a backend that guessed `(0, 0)` drew every box one
    /// monitor's width out of place with nothing to report it.
    fn capture_full(&self) -> Result<(Screenshot, Point)>;

    /// Capture a sub-rectangle specified in desktop coordinates
    /// (the same coordinate space as [`Rect`] in `Element::bounds`).
    ///
    /// No origin is returned because `rect` **is** it: an implementation must
    /// capture the pixels at `rect`, so the capture's pixel `(0, 0)` is at
    /// `(rect.x, rect.y)` by contract.
    fn capture_region(&self, rect: Rect) -> Result<Screenshot>;
}

/// A captured image: raw RGBA8 pixels plus dimensions and scale.
///
/// `width` and `height` are in **image** pixels. `scale` is the compatibility ratio of
/// physical to logical (1.0 on standard displays, 2.0 on typical Retina /
/// 1.5/1.75/2.0 on common Linux HiDPI configurations). Windows uses physical
/// desktop coordinates and reports `1.0`. A single value
/// cannot describe mixed-DPI displays or non-uniform resizing; use
/// [`Screenshot::desktop_to_image`] and related methods for coordinates.
/// `pixels.len()` equals `width * height * 4`.
///
/// `#[non_exhaustive]`: capture metadata grows — which display the pixels came
/// from, and the colour space they are in, are both things a backend could
/// start reporting. Build one with [`Screenshot::new`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Screenshot {
    pub width: u32,
    pub height: u32,
    pub pixels: Vec<u8>,
    pub scale: f32,
    mapping: Option<CaptureMapping>,
}

impl Screenshot {
    /// A capture of `width` × `height` physical pixels in RGBA8.
    ///
    /// No validation here — [`Screenshot::to_png`] is where a `pixels` length
    /// that disagrees with the dimensions is reported, so a backend that
    /// builds one can still hand back a partial buffer for inspection.
    pub fn new(width: u32, height: u32, pixels: Vec<u8>, scale: f32) -> Self {
        Self {
            width,
            height,
            pixels,
            scale,
            mapping: None,
        }
    }

    /// Attach capture-owned coordinate metadata. Intended for platform
    /// backends; ordinary callers receive mapped screenshots from the public
    /// capture functions.
    #[doc(hidden)]
    #[must_use]
    pub fn with_mapping(mut self, mapping: CaptureMapping) -> Self {
        self.mapping = Some(mapping);
        self
    }

    /// Whether this image can convert between desktop coordinates and its
    /// actual returned pixels.
    #[must_use]
    pub fn mapping_available(&self) -> bool {
        self.mapping.is_some()
    }

    /// Convert a desktop point to a pixel in this returned image.
    ///
    /// Coordinates use pixel centres and half-open image bounds: `(0, 0)` is
    /// the centre of the top-left pixel, and `x == width` is outside.
    pub fn desktop_to_image(&self, point: Point) -> Result<Point> {
        let mapping = self.mapping()?;
        mapping.validate()?;
        mapping
            .segments
            .iter()
            .filter_map(|segment| {
                map_point_f64(
                    (f64::from(point.x), f64::from(point.y)),
                    segment.desktop,
                    segment.image,
                )
            })
            .map(|(x, y)| {
                (
                    (x - mapping.origin.0) * mapping.image_scale.0,
                    (y - mapping.origin.1) * mapping.image_scale.1,
                )
            })
            .find(|&(x, y)| {
                x >= 0.0 && y >= 0.0 && x < f64::from(self.width) && y < f64::from(self.height)
            })
            .map(|(x, y)| Point::new(x.floor() as i32, y.floor() as i32))
            .ok_or_else(|| mapping_error("desktop point is outside the captured display areas"))
    }

    /// Convert a pixel in this returned image to desktop coordinates.
    ///
    /// The result can be passed to simulated input. If the backend recorded a
    /// display-layout identity, the conversion first verifies that the layout
    /// still matches the one captured.
    pub fn image_to_desktop(&self, point: Point) -> Result<Point> {
        if point.x < 0
            || point.y < 0
            || point.x as u32 >= self.width
            || point.y as u32 >= self.height
        {
            return Err(mapping_error("image point is outside the screenshot"));
        }
        let mapping = self.mapping()?;
        mapping.validate()?;
        mapping
            .segments
            .iter()
            .find_map(|segment| {
                map_point_f64(
                    (
                        f64::from(point.x) / mapping.image_scale.0 + mapping.origin.0,
                        f64::from(point.y) / mapping.image_scale.1 + mapping.origin.1,
                    ),
                    segment.image,
                    segment.desktop,
                )
            })
            .map(|(x, y)| Point::new(x.floor() as i32, y.floor() as i32))
            .ok_or_else(|| mapping_error("image point does not belong to a captured display"))
    }

    /// Convert a desktop rectangle into the image rectangles it covers.
    ///
    /// A rectangle crossing display segments can produce one image rectangle
    /// per display. Windows uses continuous physical desktop coordinates, but
    /// keeps segments separate to exclude pixels in display-layout holes.
    /// Empty intersections are omitted.
    pub fn desktop_rect_to_image(&self, rect: Rect) -> Result<Vec<Rect>> {
        let mapping = self.mapping()?;
        mapping.validate()?;
        Ok(mapping
            .segments
            .iter()
            .filter_map(|segment| {
                if segment.image.width == 0 || segment.image.height == 0 {
                    return None;
                }
                let clipped = intersect_rect(rect, segment.desktop)?;
                let from = segment.desktop;
                let to = segment.image;
                let x = |v: f64| {
                    ((f64::from(to.x)
                        + (v - f64::from(from.x)) * f64::from(to.width) / f64::from(from.width))
                        - mapping.origin.0)
                        * mapping.image_scale.0
                };
                let y = |v: f64| {
                    ((f64::from(to.y)
                        + (v - f64::from(from.y)) * f64::from(to.height) / f64::from(from.height))
                        - mapping.origin.1)
                        * mapping.image_scale.1
                };
                let x0 = x(f64::from(clipped.x)).max(0.0).floor();
                let y0 = y(f64::from(clipped.y)).max(0.0).floor();
                let x1 = x(f64::from(clipped.x) + f64::from(clipped.width))
                    .min(f64::from(self.width))
                    .ceil();
                let y1 = y(f64::from(clipped.y) + f64::from(clipped.height))
                    .min(f64::from(self.height))
                    .ceil();
                (x1 > x0 && y1 > y0).then_some(Rect {
                    x: x0 as i32,
                    y: y0 as i32,
                    width: (x1 - x0) as u32,
                    height: (y1 - y0) as u32,
                })
            })
            .collect())
    }

    /// Crop using image-pixel coordinates, preserving and translating the
    /// capture mapping for the returned pixels.
    pub fn crop(&self, rect: Rect) -> Result<Screenshot> {
        let crop = intersect_rect(
            rect,
            Rect {
                x: 0,
                y: 0,
                width: self.width,
                height: self.height,
            },
        )
        .ok_or_else(|| mapping_error("crop rectangle is outside the screenshot or empty"))?;
        let expected = expected_len(self.width, self.height)?;
        if self.pixels.len() != expected {
            return Err(buffer_mismatch(self));
        }
        let mut pixels = Vec::with_capacity(expected_len(crop.width, crop.height)?);
        for row in 0..crop.height {
            let start =
                ((crop.y as usize + row as usize) * self.width as usize + crop.x as usize) * 4;
            let end = start + crop.width as usize * 4;
            pixels.extend_from_slice(&self.pixels[start..end]);
        }
        let mapping = self.mapping.clone().map(|mut mapping| {
            mapping.origin.0 += f64::from(crop.x) / mapping.image_scale.0;
            mapping.origin.1 += f64::from(crop.y) / mapping.image_scale.1;
            mapping
        });
        Ok(Screenshot {
            width: crop.width,
            height: crop.height,
            pixels,
            scale: self.scale,
            mapping,
        })
    }

    /// Resize to image-pixel dimensions using nearest-neighbour sampling,
    /// scaling the capture mapping to the actual returned image.
    pub fn resize(&self, width: u32, height: u32) -> Result<Screenshot> {
        if width == 0 || height == 0 {
            return Err(mapping_error("resize dimensions must be non-zero"));
        }
        if self.width == 0 || self.height == 0 {
            return Err(mapping_error("cannot resize an empty screenshot"));
        }
        let expected = expected_len(self.width, self.height)?;
        if self.pixels.len() != expected {
            return Err(buffer_mismatch(self));
        }
        let mut pixels = vec![0; expected_len(width, height)?];
        for y in 0..height {
            let sy = (u64::from(y) * u64::from(self.height) / u64::from(height)) as u32;
            for x in 0..width {
                let sx = (u64::from(x) * u64::from(self.width) / u64::from(width)) as u32;
                let src = (sy as usize * self.width as usize + sx as usize) * 4;
                let dst = (y as usize * width as usize + x as usize) * 4;
                pixels[dst..dst + 4].copy_from_slice(&self.pixels[src..src + 4]);
            }
        }
        let mapping = self.mapping.clone().map(|mut mapping| {
            mapping.image_scale.0 *= f64::from(width) / f64::from(self.width);
            mapping.image_scale.1 *= f64::from(height) / f64::from(self.height);
            mapping
        });
        Ok(Screenshot {
            width,
            height,
            pixels,
            scale: self.scale * width as f32 / self.width.max(1) as f32,
            mapping,
        })
    }

    fn mapping(&self) -> Result<&CaptureMapping> {
        self.mapping.as_ref().ok_or_else(|| mapping_error(
            "screenshot has no coordinate mapping; it was constructed from raw pixels rather than captured from a desktop",
        ))
    }

    /// Encode as PNG and return the bytes.
    pub fn to_png(&self) -> Result<Vec<u8>> {
        let expected = (self.width as usize)
            .checked_mul(self.height as usize)
            .and_then(|n| n.checked_mul(4))
            .ok_or_else(|| Error::Platform {
                code: -1,
                message: "screenshot dimensions overflow".into(),
            })?;
        if self.pixels.len() != expected {
            return Err(Error::Platform {
                code: -1,
                message: format!(
                    "screenshot pixel buffer size {} does not match {}x{} RGBA ({} bytes)",
                    self.pixels.len(),
                    self.width,
                    self.height,
                    expected
                ),
            });
        }

        let mut out = Vec::new();
        {
            let mut encoder = png::Encoder::new(&mut out, self.width, self.height);
            encoder.set_color(png::ColorType::Rgba);
            encoder.set_depth(png::BitDepth::Eight);
            let mut writer = encoder.write_header().map_err(png_err)?;
            writer.write_image_data(&self.pixels).map_err(png_err)?;
        }
        Ok(out)
    }

    /// Encode as PNG and write to `path`.
    pub fn save_png(&self, path: impl AsRef<Path>) -> Result<()> {
        let bytes = self.to_png()?;
        std::fs::write(path, bytes).map_err(|e| Error::Platform {
            code: e.raw_os_error().unwrap_or(-1) as i64,
            message: format!("save_png: {e}"),
        })
    }
}

fn expected_len(width: u32, height: u32) -> Result<usize> {
    (width as usize)
        .checked_mul(height as usize)
        .and_then(|n| n.checked_mul(4))
        .ok_or_else(|| mapping_error("screenshot dimensions overflow"))
}

fn buffer_mismatch(shot: &Screenshot) -> Error {
    Error::Platform {
        code: -1,
        message: format!(
            "screenshot pixel buffer size {} does not match {}x{} RGBA",
            shot.pixels.len(),
            shot.width,
            shot.height
        ),
    }
}

fn mapping_error(message: &str) -> Error {
    Error::Platform {
        code: -1,
        message: message.into(),
    }
}

fn map_point_f64(point: (f64, f64), from: Rect, to: Rect) -> Option<(f64, f64)> {
    let (x, y) = point;
    if from.width == 0
        || from.height == 0
        || to.width == 0
        || to.height == 0
        || x < f64::from(from.x)
        || y < f64::from(from.y)
        || x >= f64::from(from.x) + f64::from(from.width)
        || y >= f64::from(from.y) + f64::from(from.height)
    {
        return None;
    }
    Some((
        f64::from(to.x) + (x - f64::from(from.x)) * f64::from(to.width) / f64::from(from.width),
        f64::from(to.y) + (y - f64::from(from.y)) * f64::from(to.height) / f64::from(from.height),
    ))
}

fn intersect_rect(a: Rect, b: Rect) -> Option<Rect> {
    let left = i64::from(a.x).max(i64::from(b.x));
    let top = i64::from(a.y).max(i64::from(b.y));
    let right = (i64::from(a.x) + i64::from(a.width)).min(i64::from(b.x) + i64::from(b.width));
    let bottom = (i64::from(a.y) + i64::from(a.height)).min(i64::from(b.y) + i64::from(b.height));
    if right <= left || bottom <= top {
        return None;
    }
    Some(Rect {
        x: left as i32,
        y: top as i32,
        width: (right - left) as u32,
        height: (bottom - top) as u32,
    })
}

fn png_err(e: png::EncodingError) -> Error {
    Error::Platform {
        code: -1,
        message: format!("png encode: {e}"),
    }
}

#[cfg(test)]
mod mapping_tests {
    use super::*;

    fn segment(desktop: Rect, image: Rect) -> CaptureMappingSegment {
        CaptureMappingSegment { desktop, image }
    }

    fn blank(width: u32, height: u32, mapping: CaptureMapping) -> Screenshot {
        Screenshot::new(
            width,
            height,
            vec![0; width as usize * height as usize * 4],
            1.0,
        )
        .with_mapping(mapping)
    }

    #[test]
    fn odd_pixel_crop_preserves_the_original_transform() {
        let shot = blank(
            20,
            20,
            CaptureMapping::single(Point::new(0, 0), 20, 20, 2.0),
        );
        let crop = shot
            .crop(Rect {
                x: 1,
                y: 1,
                width: 10,
                height: 10,
            })
            .unwrap();
        assert_eq!(
            crop.desktop_to_image(Point::new(1, 1)).unwrap(),
            Point::new(1, 1)
        );
        assert_eq!(
            crop.image_to_desktop(Point::new(1, 1)).unwrap(),
            Point::new(1, 1)
        );
        assert!(crop.desktop_to_image(Point::new(0, 0)).is_err());
    }

    #[test]
    fn single_pixel_hidpi_crop_keeps_a_mapping() {
        let shot = blank(
            20,
            20,
            CaptureMapping::single(Point::new(0, 0), 20, 20, 2.0),
        );
        let crop = shot
            .crop(Rect {
                x: 0,
                y: 0,
                width: 1,
                height: 1,
            })
            .unwrap();
        assert_eq!(
            crop.desktop_to_image(Point::new(0, 0)).unwrap(),
            Point::new(0, 0)
        );
        assert_eq!(
            crop.image_to_desktop(Point::new(0, 0)).unwrap(),
            Point::new(0, 0)
        );
    }

    #[test]
    fn cropped_rectangles_are_clipped_and_nonuniform_resize_preserves_origin() {
        let shot = blank(
            20,
            20,
            CaptureMapping::single(Point::new(-10, -10), 20, 20, 2.0),
        );
        let transformed = shot
            .crop(Rect {
                x: 1,
                y: 1,
                width: 10,
                height: 10,
            })
            .unwrap()
            .resize(20, 30)
            .unwrap();
        assert_eq!(
            transformed.desktop_to_image(Point::new(-9, -9)).unwrap(),
            Point::new(2, 3)
        );
        assert_eq!(
            transformed.image_to_desktop(Point::new(2, 3)).unwrap(),
            Point::new(-9, -9)
        );
        assert_eq!(
            transformed
                .desktop_rect_to_image(Rect {
                    x: -10,
                    y: -10,
                    width: 10,
                    height: 10
                })
                .unwrap(),
            vec![Rect {
                x: 0,
                y: 0,
                width: 20,
                height: 30
            }]
        );
        assert!(transformed
            .desktop_rect_to_image(Rect {
                x: -4,
                y: -4,
                width: 2,
                height: 2
            })
            .unwrap()
            .is_empty());
        let cropped_again = transformed
            .crop(Rect {
                x: 2,
                y: 3,
                width: 5,
                height: 5,
            })
            .unwrap();
        assert_eq!(
            cropped_again.desktop_to_image(Point::new(-9, -9)).unwrap(),
            Point::new(0, 0)
        );
    }

    #[test]
    fn issue_425_equal_dpi_secondary_maps_inside_full_capture() {
        let shot = blank(
            7680,
            2160,
            CaptureMapping::new(vec![
                segment(
                    Rect {
                        x: 0,
                        y: 0,
                        width: 1920,
                        height: 1080,
                    },
                    Rect {
                        x: 0,
                        y: 0,
                        width: 3840,
                        height: 2160,
                    },
                ),
                segment(
                    Rect {
                        x: 3840,
                        y: 0,
                        width: 1920,
                        height: 1080,
                    },
                    Rect {
                        x: 3840,
                        y: 0,
                        width: 3840,
                        height: 2160,
                    },
                ),
            ]),
        );
        let mapped = shot
            .desktop_rect_to_image(Rect {
                x: 3890,
                y: 50,
                width: 20,
                height: 20,
            })
            .expect("mapping must be available");
        assert_eq!(
            mapped,
            vec![Rect {
                x: 3940,
                y: 100,
                width: 40,
                height: 40
            }]
        );

        let (_, skipped) = shot
            .annotate(
                &[Annotation::new(
                    Rect {
                        x: 3890,
                        y: 50,
                        width: 20,
                        height: 20,
                    },
                    "A1",
                )],
                Point::new(0, 0),
            )
            .expect("mapped annotation must draw");
        assert!(skipped.is_empty());
    }

    #[test]
    fn a_desktop_rect_crossing_mixed_dpi_displays_returns_two_image_rects() {
        let shot = blank(
            4480,
            1080,
            CaptureMapping::new(vec![
                segment(
                    Rect {
                        x: 0,
                        y: 0,
                        width: 1920,
                        height: 1080,
                    },
                    Rect {
                        x: 0,
                        y: 0,
                        width: 1920,
                        height: 1080,
                    },
                ),
                segment(
                    Rect {
                        x: 1920,
                        y: 0,
                        width: 1280,
                        height: 540,
                    },
                    Rect {
                        x: 1920,
                        y: 0,
                        width: 2560,
                        height: 1080,
                    },
                ),
            ]),
        );
        assert_eq!(
            shot.desktop_rect_to_image(Rect {
                x: 1800,
                y: 100,
                width: 260,
                height: 100
            })
            .unwrap(),
            vec![
                Rect {
                    x: 1800,
                    y: 100,
                    width: 120,
                    height: 100
                },
                Rect {
                    x: 1920,
                    y: 200,
                    width: 280,
                    height: 200
                },
            ]
        );
    }

    #[test]
    fn negative_origin_and_fractional_scale_round_trip() {
        let shot = blank(
            1920,
            1080,
            CaptureMapping::new(vec![segment(
                Rect {
                    x: -1920,
                    y: -100,
                    width: 1280,
                    height: 720,
                },
                Rect {
                    x: 0,
                    y: 0,
                    width: 1920,
                    height: 1080,
                },
            )]),
        );
        assert_eq!(
            shot.desktop_to_image(Point::new(-1280, 260)).unwrap(),
            Point::new(960, 540)
        );
        assert_eq!(
            shot.image_to_desktop(Point::new(960, 540)).unwrap(),
            Point::new(-1280, 260)
        );
    }

    #[test]
    fn crop_and_resize_update_the_mapping_for_actual_returned_pixels() {
        let shot = blank(
            200,
            100,
            CaptureMapping::single(Point::new(-50, 10), 200, 100, 2.0),
        );
        let transformed = shot
            .crop(Rect {
                x: 40,
                y: 20,
                width: 100,
                height: 60,
            })
            .unwrap()
            .resize(50, 30)
            .unwrap();
        assert_eq!(
            transformed.desktop_to_image(Point::new(-20, 30)).unwrap(),
            Point::new(10, 10)
        );
        assert_eq!(
            transformed.image_to_desktop(Point::new(10, 10)).unwrap(),
            Point::new(-20, 30)
        );
    }

    fn stale(_: u64) -> Result<bool> {
        Ok(false)
    }

    #[test]
    fn stale_layout_is_rejected_before_a_point_is_returned_for_input() {
        let mapping = CaptureMapping::with_layout_validation(
            vec![segment(
                Rect {
                    x: 0,
                    y: 0,
                    width: 10,
                    height: 10,
                },
                Rect {
                    x: 0,
                    y: 0,
                    width: 10,
                    height: 10,
                },
            )],
            7,
            stale,
        );
        let err = blank(10, 10, mapping)
            .image_to_desktop(Point::new(1, 1))
            .expect_err("a changed layout must invalidate capture coordinates");
        assert!(err.to_string().contains("display layout changed"));
    }
}

// The public entry points — `xa11y::screenshot()`, `screenshot_region()`,
// `screenshot_element()` — live in the umbrella crate (`xa11y/src/lib.rs`)
// so they can construct the platform-specific `ScreenshotProvider` backend
// and memoize it across calls. Keep this file focused on the data (Screenshot)
// and the backend trait (ScreenshotProvider); the umbrella crate composes
// them into the caller-facing API.