embedded-graphics-transform 0.1.0

Simple coordinate transforms for embedded display drivers
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
//! Add simple coordinate transforms for embedded graphics displays
//!
//! This crate adds [`DrawTarget`] implementations which apply various simple
//! transformations to coordinates as they're being written. This allows
//! graphics output to be rotated or mirrored to display correctly on a specific
//! display device.
//!
//! Specifically, it implements:
//! - rotation by 90/180/270 degrees (and 0, for consistency)
//! - mirroring
//! - transposition
//!
//! Note that these transformations can be composed if needed.
//!
//! Because this is a completely generic implementation, it cannot take
//! advantage of any hardware or driver specific specializations. In particular,
//! [`DrawTarget::fill_contiguous`] must fall back to a generic implementation
//! using [`draw_iter`](DrawTarget::draw_iter).
//! ([`fill_solid`](DrawTarget::fill_solid) and [`clear`](DrawTarget::clear) can
//! use specialized implementations, however.)
//!
//! All the transforms implement [`AsRef<D>`]/[`AsMut<D>`] to get access to the
//! underlying display object so that its inherent functions can be called.
#![no_std]

use core::ops::{Deref, DerefMut};
use embedded_graphics_core::{prelude::*, primitives::Rectangle};

#[cfg(test)]
mod tests;

macro_rules! xform_type {
    ($inner:ident , ) => { $inner };
    ($inner:ident , $xform: ident $($rest:ident)*) => {
        r#impl::$xform < xform_type!($inner, $($rest)*) >
    };
}

macro_rules! xform_new {
    ($inner:ident , ) => {
        $inner
    };
    ($inner:ident , $xform:ident $($rest:ident)*) => {
        r#impl::$xform::new(xform_new!($inner, $($rest)*))
    };
}

macro_rules! impl_as_ref {
    ($_asref:ident, $expr:expr, ) => { $expr };

    ($asref:ident, $expr:expr, $xform:ident $($rest:ident)*) => {
        impl_as_ref!($asref, r#impl::$xform::$asref($expr), $($rest)*)
    };
}

macro_rules! impl_xform {
    ($($(#[$attr:meta])* $name:ident : $($xforms:ident)* ; )*) => {
        $(
            $(#[$attr])*
            pub struct $name<D> {
                target: xform_type!(D, $($xforms)*)
            }

            impl<D> $name<D> {
                /// Apply a transformation to display implementing [`DrawTarget`].
                #[allow(clippy::redundant_field_names)]
                pub fn new(target: D) -> Self {
                    $name {
                        target: xform_new!(target, $($xforms)*)
                    }
                }

                /// Recover the inner display instance.
                pub fn into_inner(self) -> D {
                    impl_as_ref!(into_inner, self.target, $($xforms)*)
                }
            }

            impl<D> Deref for $name<D> {
                type Target = D;

                fn deref(&self) -> &D {
                    self.as_ref()
                }
            }

            impl<D> DerefMut for $name<D> {
                fn deref_mut(&mut self) -> &mut D {
                    self.as_mut()
                }
            }

            impl<D> AsRef<D> for $name<D> {
                #[inline]
                fn as_ref(&self) -> &D {
                    impl_as_ref!(as_ref, &self.target, $($xforms)*)
                }
            }

            impl<D> AsMut<D> for $name<D> {
                #[inline]
                fn as_mut(&mut self) -> &mut D {
                    impl_as_ref!(as_mut, &mut self.target, $($xforms)*)
                }
            }

            impl<D: Dimensions> Dimensions for $name<D> {
                #[inline]
                fn bounding_box(&self) -> Rectangle {
                    self.target.bounding_box()
                }
            }

            impl<D: DrawTarget> DrawTarget for $name<D> {
                type Color = D::Color;
                type Error = D::Error;

                #[inline]
                fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
                where
                    I: IntoIterator<Item = Pixel<Self::Color>>,
                {
                    self.target.draw_iter(pixels)
                }

                #[inline]
                fn fill_contiguous<I>(&mut self, area: &Rectangle, colors: I) -> Result<(), Self::Error>
                where
                    I: IntoIterator<Item = Self::Color>,
                {
                    self.target.fill_contiguous(area, colors)
                }

                #[inline]
                fn fill_solid(&mut self, area: &Rectangle, color: Self::Color) -> Result<(), Self::Error> {
                    self.target.fill_solid(area, color)
                }

                #[inline]
                fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> {
                    self.target.clear(color)
                }
            }
        )*
    }
}

// Define rotations in terms of transpose and flip. Note that transforms are
// applied in order from last to first.
impl_xform! {
    /// No-op (identity) rotation for completeness.
    Rotate0: ;
    /// Rotate image 90 degrees to the right.
    Rotate90: MirrorY TransposeXY;
    /// Rotate image 90 degrees to the left.
    Rotate270: TransposeXY MirrorY;
    /// Rotate image 180 degrees.
    Rotate180: MirrorX MirrorY;

    /// Transpose X and Y coordinates.
    Transpose: TransposeXY;
    /// Mirror image around X axis.
    FlipX: MirrorX;
    /// Mirror image around Y axis.
    FlipY: MirrorY;
}

/// Image rotation direction and amount.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Rotation {
    /// No-op (identity) rotation.
    Rotate0,
    /// Rotate 90 degrees to the right.
    Rotate90,
    /// Rotate 180 degrees.
    Rotate180,
    /// Rotate 90 degrees to the left.
    Rotate270,
}

enum RotateInner<D> {
    Rotate0(Rotate0<D>),
    Rotate90(Rotate90<D>),
    Rotate180(Rotate180<D>),
    Rotate270(Rotate270<D>),
}

/// Rotate an image with runtime configuration.
///
/// Unlike the [`Rotate90`]/[`Rotate180`]/[`Rotate270`] types, this allows
/// rotation to be defined as a runtime paramter. It is simply a wrapper over
/// the other implementations, so it should be functionally identical. The only
/// overhead is the cost of dispatching to the appropriate implementation on
/// each call.
pub struct Rotate<D> {
    target: RotateInner<D>,
}

macro_rules! rotate_impl {
    (& $rot:expr, $func:ident ( $($args:expr),* $(,)?)) => {
        match &$rot.target {
            RotateInner::Rotate0(inner) => inner.$func($($args),*),
            RotateInner::Rotate90(inner) => inner.$func($($args),*),
            RotateInner::Rotate180(inner) => inner.$func($($args),*),
            RotateInner::Rotate270(inner) => inner.$func($($args),*),
        }
    };
    (&mut $rot:expr, $func:ident ( $($args:expr),* $(,)?)) => {
        match &mut $rot.target {
            RotateInner::Rotate0(inner) => inner.$func($($args),*),
            RotateInner::Rotate90(inner) => inner.$func($($args),*),
            RotateInner::Rotate180(inner) => inner.$func($($args),*),
            RotateInner::Rotate270(inner) => inner.$func($($args),*),
        }
    };
    ($rot:expr, $func:ident ( $($args:expr),* $(,)?)) => {
        match $rot.target {
            RotateInner::Rotate0(inner) => inner.$func($($args),*),
            RotateInner::Rotate90(inner) => inner.$func($($args),*),
            RotateInner::Rotate180(inner) => inner.$func($($args),*),
            RotateInner::Rotate270(inner) => inner.$func($($args),*),
        }
    };
}

impl<D> Rotate<D> {
    /// Create a new rotation transformation using the given [`Rotation`].
    pub fn new(rot: Rotation, target: D) -> Self {
        let target = match rot {
            Rotation::Rotate0 => RotateInner::Rotate0(Rotate0::new(target)),
            Rotation::Rotate90 => RotateInner::Rotate90(Rotate90::new(target)),
            Rotation::Rotate180 => RotateInner::Rotate180(Rotate180::new(target)),
            Rotation::Rotate270 => RotateInner::Rotate270(Rotate270::new(target)),
        };
        Rotate { target }
    }

    /// Recover the inner display instance.
    pub fn into_inner(self) -> D {
        rotate_impl!(self, into_inner())
    }
}

impl<D> Deref for Rotate<D> {
    type Target = D;

    fn deref(&self) -> &D {
        self.as_ref()
    }
}

impl<D> DerefMut for Rotate<D> {
    fn deref_mut(&mut self) -> &mut D {
        self.as_mut()
    }
}

impl<D> AsRef<D> for Rotate<D> {
    fn as_ref(&self) -> &D {
        rotate_impl!(&self, as_ref())
    }
}

impl<D> AsMut<D> for Rotate<D> {
    fn as_mut(&mut self) -> &mut D {
        rotate_impl!(&mut self, as_mut())
    }
}

impl<D: Dimensions> Dimensions for Rotate<D> {
    fn bounding_box(&self) -> Rectangle {
        rotate_impl!(&self, bounding_box())
    }
}

impl<D: DrawTarget> DrawTarget for Rotate<D> {
    type Color = D::Color;
    type Error = D::Error;

    fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
    where
        I: IntoIterator<Item = Pixel<Self::Color>>,
    {
        rotate_impl!(&mut self, draw_iter(pixels))
    }

    fn fill_contiguous<I>(&mut self, area: &Rectangle, colors: I) -> Result<(), Self::Error>
    where
        I: IntoIterator<Item = Self::Color>,
    {
        rotate_impl!(&mut self, fill_contiguous(area, colors))
    }

    fn fill_solid(&mut self, area: &Rectangle, color: Self::Color) -> Result<(), Self::Error> {
        rotate_impl!(&mut self, fill_solid(area, color))
    }

    fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> {
        rotate_impl!(&mut self, clear(color))
    }
}

mod r#impl {
    use embedded_graphics_core::{prelude::*, primitives::Rectangle};

    pub(crate) trait Transpose {
        fn transpose(self) -> Self;
    }

    impl Transpose for Point {
        #[inline]
        fn transpose(self) -> Point {
            Point {
                x: self.y,
                y: self.x,
            }
        }
    }

    impl Transpose for Size {
        #[inline]
        fn transpose(self) -> Size {
            Size {
                width: self.height,
                height: self.width,
            }
        }
    }

    impl Transpose for Rectangle {
        #[inline]
        fn transpose(self) -> Rectangle {
            Rectangle {
                top_left: self.top_left.transpose(),
                size: self.size.transpose(),
            }
        }
    }

    pub(crate) struct TransposeXY<D> {
        target: D,
    }

    impl<D> TransposeXY<D> {
        pub(crate) fn new(target: D) -> Self {
            TransposeXY { target }
        }

        pub(crate) fn into_inner(self) -> D {
            self.target
        }
    }

    impl<D> AsRef<D> for TransposeXY<D> {
        fn as_ref(&self) -> &D {
            &self.target
        }
    }

    impl<D> AsMut<D> for TransposeXY<D> {
        fn as_mut(&mut self) -> &mut D {
            &mut self.target
        }
    }

    impl<D: Dimensions> Dimensions for TransposeXY<D> {
        fn bounding_box(&self) -> Rectangle {
            self.target.bounding_box().transpose()
        }
    }

    impl<D: DrawTarget> DrawTarget for TransposeXY<D> {
        type Color = D::Color;
        type Error = D::Error;

        fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
        where
            I: IntoIterator<Item = Pixel<Self::Color>>,
        {
            self.target.draw_iter(
                pixels
                    .into_iter()
                    .map(|Pixel(loc, col)| Pixel(loc.transpose(), col)),
            )
        }

        fn fill_solid(&mut self, area: &Rectangle, color: Self::Color) -> Result<(), Self::Error> {
            let area = area.transpose();
            self.target.fill_solid(&area, color)
        }

        #[inline]
        fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> {
            self.target.clear(color)
        }
    }

    pub(crate) struct MirrorX<D> {
        target: D,
    }

    impl<D> MirrorX<D> {
        pub(crate) fn new(target: D) -> Self {
            MirrorX { target }
        }

        pub(crate) fn into_inner(self) -> D {
            self.target
        }
    }

    impl<D> AsRef<D> for MirrorX<D> {
        fn as_ref(&self) -> &D {
            &self.target
        }
    }

    impl<D> AsMut<D> for MirrorX<D> {
        fn as_mut(&mut self) -> &mut D {
            &mut self.target
        }
    }

    impl<D: Dimensions> Dimensions for MirrorX<D> {
        #[inline]
        fn bounding_box(&self) -> Rectangle {
            self.target.bounding_box()
        }
    }

    impl<D: DrawTarget> DrawTarget for MirrorX<D> {
        type Color = D::Color;
        type Error = D::Error;

        fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
        where
            I: IntoIterator<Item = Pixel<Self::Color>>,
        {
            let width = self.bounding_box().size.width as i32 - 1;

            self.target.draw_iter(
                pixels
                    .into_iter()
                    .map(|Pixel(Point { x, y }, col)| Pixel(Point { x: width - x, y }, col)),
            )
        }

        fn fill_solid(&mut self, area: &Rectangle, color: Self::Color) -> Result<(), Self::Error> {
            let width = self.bounding_box().size.width as i32 - 1;
            let area = Rectangle {
                top_left: Point {
                    x: width - area.top_left.x - area.size.width as i32,
                    y: area.top_left.y,
                },
                size: area.size,
            };
            self.target.fill_solid(&area, color)
        }

        #[inline]
        fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> {
            self.target.clear(color)
        }
    }

    pub(crate) struct MirrorY<D> {
        target: D,
    }

    impl<D> MirrorY<D> {
        pub(crate) fn new(target: D) -> Self {
            MirrorY { target }
        }

        pub(crate) fn into_inner(self) -> D {
            self.target
        }
    }

    impl<D> AsRef<D> for MirrorY<D> {
        fn as_ref(&self) -> &D {
            &self.target
        }
    }

    impl<D> AsMut<D> for MirrorY<D> {
        fn as_mut(&mut self) -> &mut D {
            &mut self.target
        }
    }

    impl<D: Dimensions> Dimensions for MirrorY<D> {
        #[inline]
        fn bounding_box(&self) -> Rectangle {
            self.target.bounding_box()
        }
    }

    impl<D: DrawTarget> DrawTarget for MirrorY<D> {
        type Color = D::Color;
        type Error = D::Error;

        fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
        where
            I: IntoIterator<Item = Pixel<Self::Color>>,
        {
            let height = self.bounding_box().size.height as i32 - 1;

            self.target.draw_iter(
                pixels
                    .into_iter()
                    .map(|Pixel(Point { x, y }, col)| Pixel(Point { x, y: height - y }, col)),
            )
        }

        fn fill_solid(&mut self, area: &Rectangle, color: Self::Color) -> Result<(), Self::Error> {
            let height = self.bounding_box().size.height as i32 - 1;
            let area = Rectangle {
                top_left: Point {
                    x: area.top_left.x,
                    y: height - area.top_left.y - area.size.height as i32,
                },
                size: area.size,
            };
            self.target.fill_solid(&area, color)
        }

        #[inline]
        fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> {
            self.target.clear(color)
        }
    }
}