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
//! Framebuffer for memory displays
//!
//! Considerations:
//! - No flip or mirror support
//! - Rotation is needed
//! - TODO: double buffering

use embedded_graphics_core::{
    pixelcolor::BinaryColor,
    prelude::{DrawTarget, OriginDimensions, RawData, Size},
    primitives::Rectangle,
    Pixel,
};
use embedded_hal_1::spi::SpiBusWrite;

use crate::pixelcolor::Rgb111;

/// Display rotation.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Rotation {
    /// No rotation.
    Deg0,
    /// 90° clockwise rotation.
    Deg90,
    /// 180° clockwise rotation.
    Deg180,
    /// 270° clockwise rotation.
    Deg270,
}

impl Rotation {
    #[inline]
    fn is_column_row_swap(self) -> bool {
        matches!(self, Rotation::Deg90 | Rotation::Deg270)
    }
}

pub(crate) mod sealed {
    use embedded_hal_1::spi::SpiBusWrite;

    pub trait FramebufferSpiUpdate {
        fn update<SPI: SpiBusWrite>(&self, spi: &mut SPI) -> Result<(), SPI::Error>;
    }
}

pub trait FramebufferType: OriginDimensions + DrawTarget + Default + sealed::FramebufferSpiUpdate {}

pub struct Framebuffer4Bit<const WIDTH: u16, const HEIGHT: u16>
where
    [(); WIDTH as usize * HEIGHT as usize / 2]:,
{
    data: [u8; WIDTH as usize * HEIGHT as usize / 2],
    rotation: Rotation,
}

impl<const WIDTH: u16, const HEIGHT: u16> Default for Framebuffer4Bit<WIDTH, HEIGHT>
where
    [(); WIDTH as usize * HEIGHT as usize / 2]:,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<const WIDTH: u16, const HEIGHT: u16> sealed::FramebufferSpiUpdate for Framebuffer4Bit<WIDTH, HEIGHT>
where
    [(); WIDTH as usize * HEIGHT as usize / 2]:,
{
    // only burst update is supported
    fn update<SPI: SpiBusWrite>(&self, spi: &mut SPI) -> Result<(), SPI::Error> {
        for i in 0..HEIGHT {
            let start = (i as usize) * WIDTH as usize / 2;
            let end = start + WIDTH as usize / 2;
            let line_data = &self.data[start..end];
            // NOTE: refer to manual, gate address counter is 1-based
            spi.write(&[crate::CMD_UPDATE_4BIT, i as u8 + 1])?;
            spi.write(line_data)?;
        }
        spi.write(&[0x00, 0x00])?;
        Ok(())
    }
}

impl<const WIDTH: u16, const HEIGHT: u16> Framebuffer4Bit<WIDTH, HEIGHT>
where
    [(); WIDTH as usize * HEIGHT as usize / 2]:,
{
    pub fn new() -> Self {
        Self {
            data: [0; WIDTH as usize * HEIGHT as usize / 2],
            rotation: Rotation::Deg0,
        }
    }

    pub fn set_rotation(&mut self, rotation: Rotation) {
        self.rotation = rotation;
    }

    pub fn get_rotation(&self) -> Rotation {
        self.rotation
    }

    pub(crate) fn set_pixel(&mut self, x: u16, y: u16, color: Rgb111) {
        if self.rotation.is_column_row_swap() {
            if x >= HEIGHT || y >= WIDTH {
                return;
            }
        } else {
            if y >= HEIGHT || x >= WIDTH {
                return;
            }
        }
        let x = x as usize;
        let y = y as usize;

        let (x, y) = match self.rotation {
            Rotation::Deg0 => (x, y),
            Rotation::Deg90 => (y, HEIGHT as usize - x - 1),
            Rotation::Deg180 => (WIDTH as usize - x - 1, HEIGHT as usize - y - 1),
            Rotation::Deg270 => (WIDTH as usize - y - 1, x),
        };

        let index = (y * WIDTH as usize + x) / 2;

        let color = color.0.into_inner();

        if x % 2 == 0 {
            self.data[index] = (self.data[index] & 0b00001111) | (color << 4);
        } else {
            self.data[index] = (self.data[index] & 0b11110000) | color;
        }
    }
}

impl<const WIDTH: u16, const HEIGHT: u16> FramebufferType for Framebuffer4Bit<WIDTH, HEIGHT> where
    [(); WIDTH as usize * HEIGHT as usize / 2]:
{
}

impl<const WIDTH: u16, const HEIGHT: u16> OriginDimensions for Framebuffer4Bit<WIDTH, HEIGHT>
where
    [(); WIDTH as usize * HEIGHT as usize / 2]:,
{
    fn size(&self) -> Size {
        match self.rotation {
            Rotation::Deg0 | Rotation::Deg180 => Size::new(WIDTH as u32, HEIGHT as u32),
            Rotation::Deg90 | Rotation::Deg270 => Size::new(HEIGHT as u32, WIDTH as u32),
        }
    }
}

impl<const WIDTH: u16, const HEIGHT: u16> DrawTarget for Framebuffer4Bit<WIDTH, HEIGHT>
where
    [(); WIDTH as usize * HEIGHT as usize / 2]:,
{
    type Color = Rgb111;

    type Error = core::convert::Infallible;

    fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
    where
        I: IntoIterator<Item = Pixel<Self::Color>>,
    {
        for Pixel(coord, color) in pixels.into_iter() {
            self.set_pixel(coord.x as u16, coord.y as u16, color);
        }
        Ok(())
    }

    fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> {
        let raw = color.0.into_inner() << 4 | color.0.into_inner();
        self.data.fill(raw);
        Ok(())
    }

    fn fill_solid(&mut self, area: &Rectangle, color: Self::Color) -> Result<(), Self::Error> {
        if self.rotation == Rotation::Deg0 && area.top_left.x % 2 == 0 && area.size.width % 2 == 0 {
            let w = area.size.width as usize / 2;
            let x_off = area.top_left.x as usize / 2;
            let raw_pix = color.0.into_inner() << 4 | color.0.into_inner();

            for y in area.top_left.y..area.top_left.y + area.size.height as i32 {
                let start = (y as usize) * WIDTH as usize / 2 + x_off;
                let end = start + w;
                self.data[start..end].fill(raw_pix);
            }
            Ok(())
        } else {
            self.fill_contiguous(area, core::iter::repeat(color))
        }
    }
}

pub struct FramebufferBW<const WIDTH: u16, const HEIGHT: u16>
where
    [(); WIDTH as usize * HEIGHT as usize / 8]:,
{
    data: [u8; WIDTH as usize * HEIGHT as usize / 8],
    rotation: Rotation,
}

impl<const WIDTH: u16, const HEIGHT: u16> Default for FramebufferBW<WIDTH, HEIGHT>
where
    [(); WIDTH as usize * HEIGHT as usize / 8]:,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<const WIDTH: u16, const HEIGHT: u16> FramebufferBW<WIDTH, HEIGHT>
where
    [(); WIDTH as usize * HEIGHT as usize / 8]:,
{
    pub fn new() -> Self {
        Self {
            data: [0; WIDTH as usize * HEIGHT as usize / 8],
            rotation: Rotation::Deg0,
        }
    }

    pub fn set_rotation(&mut self, rotation: Rotation) {
        self.rotation = rotation;
    }

    pub fn get_rotation(&self) -> Rotation {
        self.rotation
    }

    pub(crate) fn set_pixel(&mut self, x: u16, y: u16, color: BinaryColor) {
        if self.rotation.is_column_row_swap() {
            if x >= HEIGHT || y >= WIDTH {
                return;
            }
        } else {
            if y >= HEIGHT || x >= WIDTH {
                return;
            }
        }

        let x = x as usize;
        let y = y as usize;

        let (x, y) = match self.rotation {
            Rotation::Deg0 => (x, y),
            Rotation::Deg90 => (y, HEIGHT as usize - x - 1),
            Rotation::Deg180 => (WIDTH as usize - x - 1, HEIGHT as usize - y - 1),
            Rotation::Deg270 => (WIDTH as usize - y - 1, x),
        };

        if y >= HEIGHT as usize || x >= WIDTH as usize {
            return;
        }

        let index = y * WIDTH as usize + x;

        if color.is_on() {
            self.data[index / 8] |= 1 << (8 - (index % 8) - 1);
        } else {
            self.data[index / 8] &= !(1 << (8 - (index % 8) - 1));
        }
    }
}

impl<const WIDTH: u16, const HEIGHT: u16> sealed::FramebufferSpiUpdate for FramebufferBW<WIDTH, HEIGHT>
where
    [(); WIDTH as usize * HEIGHT as usize / 8]:,
{
    fn update<SPI: SpiBusWrite>(&self, spi: &mut SPI) -> Result<(), SPI::Error> {
        for i in 0..HEIGHT {
            let start = (i as usize) * WIDTH as usize / 8;
            let end = start + WIDTH as usize / 8;
            let gate_line = &self.data[start..end];
            // gate address is counted from 1
            spi.write(&[crate::CMD_UPDATE_1BIT, i as u8 + 1])?;
            spi.write(gate_line)?;
        }
        spi.write(&[0x00, 0x00])?;
        Ok(())
    }
}

impl<const WIDTH: u16, const HEIGHT: u16> FramebufferType for FramebufferBW<WIDTH, HEIGHT> where
    [(); WIDTH as usize * HEIGHT as usize / 8]:
{
}

impl<const WIDTH: u16, const HEIGHT: u16> OriginDimensions for FramebufferBW<WIDTH, HEIGHT>
where
    [(); WIDTH as usize * HEIGHT as usize / 8]:,
{
    fn size(&self) -> Size {
        match self.rotation {
            Rotation::Deg0 | Rotation::Deg180 => Size::new(WIDTH as u32, HEIGHT as u32),
            Rotation::Deg90 | Rotation::Deg270 => Size::new(HEIGHT as u32, WIDTH as u32),
        }
    }
}

impl<const WIDTH: u16, const HEIGHT: u16> DrawTarget for FramebufferBW<WIDTH, HEIGHT>
where
    [(); WIDTH as usize * HEIGHT as usize / 8]:,
{
    type Color = BinaryColor;

    type Error = core::convert::Infallible;

    fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
    where
        I: IntoIterator<Item = Pixel<Self::Color>>,
    {
        for Pixel(coord, color) in pixels.into_iter() {
            self.set_pixel(coord.x as u16, coord.y as u16, color);
        }
        Ok(())
    }

    fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> {
        if color.is_on() {
            self.data.fill(0xFF);
        } else {
            self.data.fill(0x00);
        }
        Ok(())
    }
}