Skip to main content

embedded_graphics_readback/
adapters.rs

1//! Adapters that carry [`ReadbackTarget`] down a pipeline.
2//!
3//! `embedded-graphics`' own [`DrawTargetExt`] adapters keep their parent in a
4//! private field and expose no accessor, so readback cannot be delegated
5//! through them. These are read-capable equivalents: each implements
6//! [`DrawTarget`] with the same write semantics as its `embedded-graphics`
7//! counterpart, and [`ReadbackTarget`] on top.
8//!
9//! [`ReadbackTargetExt`] is blanket-implemented, so the adapters are themselves
10//! readback targets and chain like the originals:
11//!
12//! ```
13//! use embedded_graphics_core::{geometry::Point, primitives::Rectangle};
14//! use embedded_graphics_readback::{ReadbackTarget, ReadbackTargetExt};
15//!
16//! # use embedded_graphics_core::{
17//! #     Pixel, draw_target::DrawTarget, geometry::{OriginDimensions, Size},
18//! #     pixelcolor::{Rgb565, RgbColor},
19//! # };
20//! # struct Fb([Rgb565; 64]);
21//! # impl Fb {
22//! #     fn index(p: Point) -> Option<usize> {
23//! #         ((0..8).contains(&p.x) && (0..8).contains(&p.y)).then(|| (p.y * 8 + p.x) as usize)
24//! #     }
25//! # }
26//! # impl OriginDimensions for Fb {
27//! #     fn size(&self) -> Size { Size::new(8, 8) }
28//! # }
29//! # impl DrawTarget for Fb {
30//! #     type Color = Rgb565;
31//! #     type Error = core::convert::Infallible;
32//! #     fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
33//! #     where I: IntoIterator<Item = Pixel<Self::Color>> {
34//! #         for Pixel(p, c) in pixels {
35//! #             if let Some(i) = Fb::index(p) { self.0[i] = c; }
36//! #         }
37//! #         Ok(())
38//! #     }
39//! # }
40//! # impl ReadbackTarget for Fb {
41//! #     fn read_pixel(&self, point: Point) -> Option<Rgb565> {
42//! #         Fb::index(point).map(|i| self.0[i])
43//! #     }
44//! # }
45//! let mut fb = Fb([Rgb565::BLACK; 64]);
46//! assert_eq!(fb.read_pixel(Point::new(4, 4)), Some(Rgb565::BLACK));
47//!
48//! // Shift the origin, then mask: the capability survives both layers.
49//! let mut layer = fb.shifted(Point::new(2, 2));
50//! let view = layer.masked(&Rectangle::new(Point::zero(), Size::new(3, 3)));
51//!
52//! // (0, 0) in the view is (2, 2) in the framebuffer.
53//! assert_eq!(view.read_pixel(Point::zero()), Some(Rgb565::BLACK));
54//! // Outside the mask, even though the framebuffer still has a pixel there.
55//! assert_eq!(view.read_pixel(Point::new(4, 4)), None);
56//! ```
57//!
58//! [`DrawTargetExt`]:
59//!     https://docs.rs/embedded-graphics/latest/embedded_graphics/draw_target/trait.DrawTargetExt.html
60
61use embedded_graphics_core::{
62    Pixel,
63    draw_target::DrawTarget,
64    geometry::{Dimensions, OriginDimensions, Point, Size},
65    primitives::{PointsIter, Rectangle},
66};
67
68use crate::{ReadbackTarget, read_area_by_pixel};
69
70/// Shift a rectangle; `Transform` lives in `embedded-graphics`, not core.
71#[inline]
72fn translate(area: &Rectangle, offset: Point) -> Rectangle {
73    Rectangle::new(area.top_left + offset, area.size)
74}
75
76/// Adapters for [`ReadbackTarget`], mirroring `embedded-graphics`'
77/// `DrawTargetExt`.
78///
79/// Blanket-implemented for every [`ReadbackTarget`], including the adapters
80/// themselves, so layers compose. The names differ from `DrawTargetExt`'s so
81/// both traits can sit in scope without ambiguous calls; each method is
82/// shorthand for the matching struct constructor.
83pub trait ReadbackTargetExt: ReadbackTarget + Sized {
84    /// Translate the target's origin by `offset`.
85    ///
86    /// Point `p` on the adapter addresses `p + offset` on the parent.
87    #[must_use]
88    fn shifted(&mut self, offset: Point) -> Shifted<'_, Self>;
89
90    /// Restrict the target to `area`, moving the origin to `area.top_left`.
91    ///
92    /// `area` is clamped to the parent's bounding box first.
93    #[must_use]
94    fn windowed(&mut self, area: &Rectangle) -> Windowed<'_, Self>;
95
96    /// Restrict the target to `area`, keeping the parent's coordinates.
97    ///
98    /// `area` is clamped to the parent's bounding box first.
99    #[must_use]
100    fn masked(&mut self, area: &Rectangle) -> Masked<'_, Self>;
101}
102
103impl<T> ReadbackTargetExt for T
104where
105    T: ReadbackTarget,
106{
107    fn shifted(&mut self, offset: Point) -> Shifted<'_, Self> {
108        Shifted::new(self, offset)
109    }
110
111    fn windowed(&mut self, area: &Rectangle) -> Windowed<'_, Self> {
112        Windowed::new(self, area)
113    }
114
115    fn masked(&mut self, area: &Rectangle) -> Masked<'_, Self> {
116        Masked::new(self, area)
117    }
118}
119
120/// A target with its origin moved, from [`ReadbackTargetExt::shifted`].
121#[derive(Debug)]
122pub struct Shifted<'a, T> {
123    parent: &'a mut T,
124    offset: Point,
125}
126
127impl<'a, T> Shifted<'a, T> {
128    /// Wrap `parent`, shifting every coordinate that crosses this layer by
129    /// `offset`.
130    #[must_use]
131    pub fn new(parent: &'a mut T, offset: Point) -> Self {
132        Self { parent, offset }
133    }
134
135    /// The target underneath this layer.
136    #[must_use]
137    pub fn parent(&self) -> &T {
138        self.parent
139    }
140
141    /// The offset applied to every coordinate crossing this layer.
142    #[must_use]
143    pub fn offset(&self) -> Point {
144        self.offset
145    }
146}
147
148impl<T> DrawTarget for Shifted<'_, T>
149where
150    T: DrawTarget,
151{
152    type Color = T::Color;
153    type Error = T::Error;
154
155    fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
156    where
157        I: IntoIterator<Item = Pixel<Self::Color>>,
158    {
159        let offset = self.offset;
160
161        self.parent
162            .draw_iter(pixels.into_iter().map(|Pixel(p, c)| Pixel(p + offset, c)))
163    }
164
165    fn fill_contiguous<I>(&mut self, area: &Rectangle, colors: I) -> Result<(), Self::Error>
166    where
167        I: IntoIterator<Item = Self::Color>,
168    {
169        let area = translate(area, self.offset);
170
171        self.parent.fill_contiguous(&area, colors)
172    }
173
174    fn fill_solid(&mut self, area: &Rectangle, color: Self::Color) -> Result<(), Self::Error> {
175        let area = translate(area, self.offset);
176
177        self.parent.fill_solid(&area, color)
178    }
179
180    fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> {
181        self.parent.clear(color)
182    }
183}
184
185impl<T> Dimensions for Shifted<'_, T>
186where
187    T: DrawTarget,
188{
189    fn bounding_box(&self) -> Rectangle {
190        translate(&self.parent.bounding_box(), -self.offset)
191    }
192}
193
194impl<T> ReadbackTarget for Shifted<'_, T>
195where
196    T: ReadbackTarget,
197{
198    fn read_pixel(&self, point: Point) -> Option<Self::Color> {
199        self.parent.read_pixel(point + self.offset)
200    }
201
202    fn read_area(&self, area: &Rectangle, out: &mut [Self::Color]) -> usize {
203        // A pure coordinate shift, so the parent's bulk path survives intact.
204        self.parent.read_area(&translate(area, self.offset), out)
205    }
206}
207
208/// A target restricted to a sub-region, from [`ReadbackTargetExt::windowed`].
209#[derive(Debug)]
210pub struct Windowed<'a, T> {
211    parent: Shifted<'a, T>,
212    size: Size,
213}
214
215impl<'a, T> Windowed<'a, T>
216where
217    T: DrawTarget,
218{
219    /// Wrap `parent`, restricting it to `area` and moving the origin to
220    /// `area.top_left`. `area` is clamped to the parent's bounding box.
221    #[must_use]
222    pub fn new(parent: &'a mut T, area: &Rectangle) -> Self {
223        let area = area.intersection(&parent.bounding_box());
224
225        Self {
226            size: area.size,
227            parent: Shifted::new(parent, area.top_left),
228        }
229    }
230}
231
232impl<T> Windowed<'_, T> {
233    /// The target underneath this layer.
234    #[must_use]
235    pub fn parent(&self) -> &T {
236        self.parent.parent()
237    }
238
239    /// The window's top-left corner, in the parent's coordinates.
240    #[must_use]
241    pub fn offset(&self) -> Point {
242        self.parent.offset()
243    }
244}
245
246impl<T> DrawTarget for Windowed<'_, T>
247where
248    T: DrawTarget,
249{
250    type Color = T::Color;
251    type Error = T::Error;
252
253    fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
254    where
255        I: IntoIterator<Item = Pixel<Self::Color>>,
256    {
257        self.parent.draw_iter(pixels)
258    }
259
260    fn fill_contiguous<I>(&mut self, area: &Rectangle, colors: I) -> Result<(), Self::Error>
261    where
262        I: IntoIterator<Item = Self::Color>,
263    {
264        self.parent.fill_contiguous(area, colors)
265    }
266
267    fn fill_solid(&mut self, area: &Rectangle, color: Self::Color) -> Result<(), Self::Error> {
268        self.parent.fill_solid(area, color)
269    }
270}
271
272impl<T> OriginDimensions for Windowed<'_, T>
273where
274    T: DrawTarget,
275{
276    fn size(&self) -> Size {
277        self.size
278    }
279}
280
281impl<T> ReadbackTarget for Windowed<'_, T>
282where
283    T: ReadbackTarget,
284{
285    fn read_pixel(&self, point: Point) -> Option<Self::Color> {
286        // Reads honour the window, unlike writes: `read_pixel` promises `None`
287        // outside the bounding box.
288        if self.bounding_box().contains(point) {
289            self.parent.read_pixel(point)
290        } else {
291            None
292        }
293    }
294
295    fn read_area(&self, area: &Rectangle, out: &mut [Self::Color]) -> usize {
296        if self.bounding_box().intersection(area) == *area {
297            self.parent.read_area(area, out)
298        } else {
299            read_area_by_pixel(self, area, out)
300        }
301    }
302}
303
304/// A target masked to a region, from [`ReadbackTargetExt::masked`].
305#[derive(Debug)]
306pub struct Masked<'a, T> {
307    parent: &'a mut T,
308    mask_area: Rectangle,
309}
310
311impl<'a, T> Masked<'a, T>
312where
313    T: DrawTarget,
314{
315    /// Wrap `parent`, admitting only the pixels inside `area`.
316    ///
317    /// `area` is clamped to the parent's bounding box.
318    #[must_use]
319    pub fn new(parent: &'a mut T, area: &Rectangle) -> Self {
320        let mask_area = area.intersection(&parent.bounding_box());
321
322        Self { parent, mask_area }
323    }
324}
325
326impl<T> Masked<'_, T> {
327    /// The target underneath this layer.
328    #[must_use]
329    pub fn parent(&self) -> &T {
330        self.parent
331    }
332
333    /// The region this layer admits, in the parent's coordinates.
334    #[must_use]
335    pub fn mask_area(&self) -> Rectangle {
336        self.mask_area
337    }
338}
339
340impl<T> DrawTarget for Masked<'_, T>
341where
342    T: DrawTarget,
343{
344    type Color = T::Color;
345    type Error = T::Error;
346
347    fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
348    where
349        I: IntoIterator<Item = Pixel<Self::Color>>,
350    {
351        let mask_area = self.mask_area;
352
353        self.parent.draw_iter(
354            pixels
355                .into_iter()
356                .filter(|Pixel(p, _)| mask_area.contains(*p)),
357        )
358    }
359
360    fn fill_contiguous<I>(&mut self, area: &Rectangle, colors: I) -> Result<(), Self::Error>
361    where
362        I: IntoIterator<Item = Self::Color>,
363    {
364        if self.mask_area.intersection(area) == *area {
365            self.parent.fill_contiguous(area, colors)
366        } else {
367            // Partial overlap: pair each colour with its point and let
368            // `draw_iter` drop the ones outside the mask.
369            self.draw_iter(area.points().zip(colors).map(|(p, c)| Pixel(p, c)))
370        }
371    }
372
373    fn fill_solid(&mut self, area: &Rectangle, color: Self::Color) -> Result<(), Self::Error> {
374        let area = area.intersection(&self.mask_area);
375
376        self.parent.fill_solid(&area, color)
377    }
378}
379
380impl<T> Dimensions for Masked<'_, T>
381where
382    T: DrawTarget,
383{
384    fn bounding_box(&self) -> Rectangle {
385        self.mask_area
386    }
387}
388
389impl<T> ReadbackTarget for Masked<'_, T>
390where
391    T: ReadbackTarget,
392{
393    fn read_pixel(&self, point: Point) -> Option<Self::Color> {
394        if self.mask_area.contains(point) {
395            self.parent.read_pixel(point)
396        } else {
397            None
398        }
399    }
400
401    fn read_area(&self, area: &Rectangle, out: &mut [Self::Color]) -> usize {
402        if self.mask_area.intersection(area) == *area {
403            self.parent.read_area(area, out)
404        } else {
405            read_area_by_pixel(self, area, out)
406        }
407    }
408}
409
410#[cfg(test)]
411mod tests {
412    use super::*;
413    use embedded_graphics::prelude::*;
414    use embedded_graphics_core::pixelcolor::Rgb565;
415
416    /// An 8×8 framebuffer that records how many bulk reads it served, so the
417    /// adapters' fast paths can be observed rather than assumed.
418    struct Fb {
419        pixels: [Rgb565; 64],
420        bulk_reads: core::cell::Cell<usize>,
421    }
422
423    impl Fb {
424        fn new() -> Self {
425            Self {
426                pixels: [Rgb565::BLACK; 64],
427                bulk_reads: core::cell::Cell::new(0),
428            }
429        }
430
431        fn index(p: Point) -> Option<usize> {
432            ((0..8).contains(&p.x) && (0..8).contains(&p.y)).then(|| (p.y * 8 + p.x) as usize)
433        }
434    }
435
436    impl OriginDimensions for Fb {
437        fn size(&self) -> Size {
438            Size::new(8, 8)
439        }
440    }
441
442    impl DrawTarget for Fb {
443        type Color = Rgb565;
444        type Error = core::convert::Infallible;
445
446        fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
447        where
448            I: IntoIterator<Item = Pixel<Self::Color>>,
449        {
450            for Pixel(p, c) in pixels {
451                if let Some(i) = Self::index(p) {
452                    self.pixels[i] = c;
453                }
454            }
455            Ok(())
456        }
457    }
458
459    impl ReadbackTarget for Fb {
460        fn read_pixel(&self, point: Point) -> Option<Self::Color> {
461            Self::index(point).map(|i| self.pixels[i])
462        }
463
464        fn read_area(&self, area: &Rectangle, out: &mut [Self::Color]) -> usize {
465            self.bulk_reads.set(self.bulk_reads.get() + 1);
466            read_area_by_pixel(self, area, out)
467        }
468    }
469
470    fn rect(x: i32, y: i32, w: u32, h: u32) -> Rectangle {
471        Rectangle::new(Point::new(x, y), Size::new(w, h))
472    }
473
474    // --- shifted ------------------------------------------------------
475
476    #[test]
477    fn shifted_reads_through_the_offset() {
478        let mut fb = Fb::new();
479        Pixel(Point::new(5, 6), Rgb565::RED).draw(&mut fb).unwrap();
480
481        let layer = fb.shifted(Point::new(3, 4));
482
483        assert_eq!(layer.read_pixel(Point::new(2, 2)), Some(Rgb565::RED));
484        assert_eq!(layer.read_pixel(Point::new(0, 0)), Some(Rgb565::BLACK));
485    }
486
487    #[test]
488    fn shifted_round_trips_a_write_through_the_adapter() {
489        let mut fb = Fb::new();
490        let mut layer = fb.shifted(Point::new(3, 4));
491
492        Pixel(Point::new(1, 1), Rgb565::GREEN)
493            .draw(&mut layer)
494            .unwrap();
495
496        assert_eq!(layer.read_pixel(Point::new(1, 1)), Some(Rgb565::GREEN));
497        // ...and it landed at the shifted position underneath.
498        assert_eq!(fb.read_pixel(Point::new(4, 5)), Some(Rgb565::GREEN));
499    }
500
501    #[test]
502    fn shifted_moves_the_bounding_box() {
503        let mut fb = Fb::new();
504        let layer = fb.shifted(Point::new(3, 4));
505
506        assert_eq!(layer.bounding_box(), rect(-3, -4, 8, 8));
507    }
508
509    #[test]
510    fn shifted_read_area_keeps_the_parent_bulk_path() {
511        let mut fb = Fb::new();
512        Pixel(Point::new(3, 4), Rgb565::RED).draw(&mut fb).unwrap();
513
514        let layer = fb.shifted(Point::new(3, 4));
515        let mut out = [Rgb565::WHITE; 4];
516        let n = layer.read_area(&rect(0, 0, 2, 2), &mut out);
517
518        assert_eq!(n, 4);
519        assert_eq!(out[0], Rgb565::RED);
520        // Exactly one bulk call reached the framebuffer: no per-pixel fallback.
521        assert_eq!(layer.parent().bulk_reads.get(), 1);
522    }
523
524    // --- windowed ---------------------------------------------------------
525
526    #[test]
527    fn windowed_moves_the_origin_and_reports_its_size() {
528        let mut fb = Fb::new();
529        Pixel(Point::new(2, 3), Rgb565::RED).draw(&mut fb).unwrap();
530
531        let view = fb.windowed(&rect(2, 3, 4, 4));
532
533        assert_eq!(view.bounding_box(), rect(0, 0, 4, 4));
534        assert_eq!(view.offset(), Point::new(2, 3));
535        assert_eq!(view.read_pixel(Point::zero()), Some(Rgb565::RED));
536    }
537
538    #[test]
539    fn windowed_reads_are_none_outside_the_window() {
540        let mut fb = Fb::new();
541        let view = fb.windowed(&rect(2, 2, 3, 3));
542
543        // (3, 3) in view space is (5, 5) in the framebuffer, which still holds a
544        // pixel — but it is outside this target's bounding box.
545        assert_eq!(view.read_pixel(Point::new(3, 3)), None);
546        assert_eq!(view.read_pixel(Point::new(-1, 0)), None);
547    }
548
549    #[test]
550    fn windowed_clamps_to_the_parent() {
551        let mut fb = Fb::new();
552        let view = fb.windowed(&rect(6, 6, 8, 8));
553
554        assert_eq!(view.bounding_box(), rect(0, 0, 2, 2));
555    }
556
557    #[test]
558    fn windowed_read_area_straddling_the_edge_counts_only_the_window() {
559        let mut fb = Fb::new();
560        let view = fb.windowed(&rect(0, 0, 2, 2));
561
562        let mut out = [Rgb565::WHITE; 4];
563        let n = view.read_area(&rect(1, 1, 2, 2), &mut out);
564
565        // Only (1, 1) is inside the 2×2 window.
566        assert_eq!(n, 1);
567        // The slow path ran, so the parent saw no bulk read.
568        assert_eq!(view.parent().bulk_reads.get(), 0);
569    }
570
571    // --- masked ---------------------------------------------------------
572
573    #[test]
574    fn masked_keeps_parent_coordinates() {
575        let mut fb = Fb::new();
576        Pixel(Point::new(4, 4), Rgb565::RED).draw(&mut fb).unwrap();
577
578        let view = fb.masked(&rect(2, 2, 4, 4));
579
580        assert_eq!(view.read_pixel(Point::new(4, 4)), Some(Rgb565::RED));
581        assert_eq!(view.bounding_box(), rect(2, 2, 4, 4));
582    }
583
584    #[test]
585    fn masked_reads_are_none_outside_the_mask() {
586        let mut fb = Fb::new();
587        let view = fb.masked(&rect(2, 2, 4, 4));
588
589        assert_eq!(view.read_pixel(Point::new(1, 1)), None);
590        assert_eq!(view.read_pixel(Point::new(6, 6)), None);
591    }
592
593    #[test]
594    fn masked_clamps_to_the_parent() {
595        let mut fb = Fb::new();
596        let view = fb.masked(&rect(4, 4, 100, 100));
597
598        // The mask cannot report more pixels than the parent holds.
599        assert_eq!(view.bounding_box(), rect(4, 4, 4, 4));
600        assert_eq!(view.mask_area(), rect(4, 4, 4, 4));
601    }
602
603    #[test]
604    fn masked_drops_writes_outside_the_mask() {
605        let mut fb = Fb::new();
606        let mut view = fb.masked(&rect(2, 2, 2, 2));
607
608        view.fill_solid(&rect(0, 0, 8, 8), Rgb565::RED).unwrap();
609
610        assert_eq!(fb.read_pixel(Point::new(2, 2)), Some(Rgb565::RED));
611        assert_eq!(fb.read_pixel(Point::new(0, 0)), Some(Rgb565::BLACK));
612    }
613
614    #[test]
615    fn masked_fill_contiguous_crops_a_straddling_run() {
616        let mut fb = Fb::new();
617        let mut view = fb.masked(&rect(0, 0, 2, 8));
618
619        // A 4-wide run: the right half falls outside the mask.
620        view.fill_contiguous(
621            &rect(0, 0, 4, 1),
622            [Rgb565::RED, Rgb565::GREEN, Rgb565::BLUE, Rgb565::WHITE],
623        )
624        .unwrap();
625
626        assert_eq!(fb.read_pixel(Point::new(0, 0)), Some(Rgb565::RED));
627        assert_eq!(fb.read_pixel(Point::new(1, 0)), Some(Rgb565::GREEN));
628        // Colours stay paired with their points; the masked ones are dropped.
629        assert_eq!(fb.read_pixel(Point::new(2, 0)), Some(Rgb565::BLACK));
630        assert_eq!(fb.read_pixel(Point::new(3, 0)), Some(Rgb565::BLACK));
631    }
632
633    #[test]
634    fn masked_read_area_wholly_inside_uses_the_parent_bulk_path() {
635        let mut fb = Fb::new();
636        let view = fb.masked(&rect(0, 0, 8, 8));
637
638        let mut out = [Rgb565::WHITE; 4];
639        assert_eq!(view.read_area(&rect(1, 1, 2, 2), &mut out), 4);
640        assert_eq!(view.parent().bulk_reads.get(), 1);
641    }
642
643    // --- composition -----------------------------------------------------
644
645    #[test]
646    fn adapters_chain_and_keep_readback() {
647        let mut fb = Fb::new();
648        Pixel(Point::new(2, 2), Rgb565::RED).draw(&mut fb).unwrap();
649
650        let mut layer = fb.shifted(Point::new(2, 2));
651        let view = layer.masked(&rect(0, 0, 3, 3));
652
653        // (0, 0) through both layers is (2, 2) on the framebuffer.
654        assert_eq!(view.read_pixel(Point::zero()), Some(Rgb565::RED));
655        assert_eq!(view.read_pixel(Point::new(4, 4)), None);
656    }
657
658    #[test]
659    fn chained_read_area_agrees_with_read_pixel() {
660        let mut fb = Fb::new();
661        Pixel(Point::new(3, 3), Rgb565::GREEN)
662            .draw(&mut fb)
663            .unwrap();
664
665        let mut layer = fb.shifted(Point::new(2, 2));
666        let view = layer.windowed(&rect(0, 0, 4, 4));
667
668        let mut out = [Rgb565::WHITE; 4];
669        let n = view.read_area(&rect(0, 0, 2, 2), &mut out);
670
671        assert_eq!(n, 4);
672        let by_pixel: [Rgb565; 4] = core::array::from_fn(|i| {
673            view.read_pixel(Point::new(i as i32 % 2, i as i32 / 2))
674                .unwrap()
675        });
676        assert_eq!(out, by_pixel);
677        assert_eq!(out[3], Rgb565::GREEN);
678    }
679}