hal_sim/
display.rs

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
use core::convert::Infallible;

extern crate alloc;
use alloc::sync::Arc;

use log::trace;

use std::sync::Mutex;

use embedded_graphics_core::{
    prelude::{Dimensions, DrawTarget, PixelColor, Point, Size},
    primitives::Rectangle,
    Pixel,
};

pub use crate::dto::display::*;

pub(crate) static DISPLAYS: Mutex<Vec<DisplayState>> = Mutex::new(Vec::new());

pub struct Displays {
    id_gen: u8,
    changed: DisplaysChangedCallback,
}

impl Displays {
    pub(crate) fn new(changed: impl Fn() + 'static) -> Self {
        Self {
            id_gen: 0,
            changed: Arc::new(changed),
        }
    }

    pub fn display<C>(
        &mut self,
        name: impl TryInto<DisplayName>,
        width: usize,
        height: usize,
        converter: impl Fn(C) -> u32 + 'static,
    ) -> Display<C>
    where
        C: Clone + Default,
    {
        let id = self.id_gen;
        self.id_gen += 1;

        let state = DisplayState::new(name.try_into().map_err(|_| ()).unwrap(), width, height);

        {
            let mut states = DISPLAYS.lock().unwrap();
            states.push(state);
        }

        Display::new(id, self.changed.clone(), converter)
    }
}

pub type DisplaysChangedCallback = Arc<dyn Fn()>;

pub struct Display<C> {
    id: u8,
    changed: Arc<dyn Fn()>,
    converter: Box<dyn Fn(C) -> u32>,
}

impl<C> Display<C>
where
    C: Clone + Default,
{
    fn new(id: u8, changed: Arc<dyn Fn()>, converter: impl Fn(C) -> u32 + 'static) -> Self {
        Self {
            id,
            changed,
            converter: Box::new(converter),
        }
    }
}

impl<C> Drop for Display<C> {
    fn drop(&mut self) {
        {
            let mut guard = DISPLAYS.lock().unwrap();
            let state = &mut guard[self.id as usize];

            state.display.dropped = true;
            state.change.dropped = true;
        }

        (self.changed)();
    }
}

impl<C> DrawTarget for Display<C>
where
    C: PixelColor,
{
    type Color = C;

    type Error = Infallible;

    fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
    where
        I: IntoIterator<Item = Pixel<Self::Color>>,
    {
        let changed = {
            let mut guard = DISPLAYS.lock().unwrap();

            guard[self.id as usize].draw_iter(
                pixels
                    .into_iter()
                    .map(|Pixel(point, pixel)| (point, (self.converter)(pixel))),
            )
        };

        if changed {
            (self.changed)();
        }

        Ok(())
    }
}

impl<C> Dimensions for Display<C> {
    fn bounding_box(&self) -> Rectangle {
        let guard = DISPLAYS.lock().unwrap();

        let state = &guard[self.id as usize];

        Rectangle::new(
            Point::new(0, 0),
            Size::new(
                state.display.meta.width as _,
                state.display.meta.height as _,
            ),
        )
    }
}

pub struct DisplayState {
    display: SharedDisplay,
    change: Change,
}

impl DisplayState {
    fn new(name: DisplayName, width: usize, height: usize) -> Self {
        Self {
            display: SharedDisplay::new(name, width, height),
            change: Change {
                created: true,
                dropped: false,
                screen_updates: Vec::new(),
            },
        }
    }

    pub fn change(&self) -> &Change {
        &self.change
    }

    pub fn display(&self) -> &SharedDisplay {
        &self.display
    }

    pub fn split(&mut self) -> (&SharedDisplay, &mut Change) {
        (&self.display, &mut self.change)
    }

    fn draw_iter<I>(&mut self, pixels: I) -> bool
    where
        I: IntoIterator<Item = (Point, u32)>,
    {
        self.display.draw_iter(&mut self.change, pixels)
    }
}

pub struct SharedDisplay {
    meta: DisplayMeta,
    dropped: bool,
    buffer: Vec<u32>,
}

impl SharedDisplay {
    fn new(name: DisplayName, width: usize, height: usize) -> Self {
        Self {
            meta: DisplayMeta {
                name,
                width,
                height,
            },
            dropped: false,
            buffer: vec![0; width * height],
        }
    }

    pub fn meta(&self) -> &DisplayMeta {
        &self.meta
    }

    pub fn dropped(&self) -> bool {
        self.dropped
    }

    pub fn buffer(&self) -> &[u32] {
        &self.buffer
    }

    fn draw_iter<I>(&mut self, changed_state: &mut Change, pixels: I) -> bool
    where
        I: IntoIterator<Item = (Point, u32)>,
    {
        let mut changed = false;

        for pixel in pixels {
            if pixel.0.x >= 0
                && pixel.0.x < self.meta.width as _
                && pixel.0.y >= 0
                && pixel.0.y < self.meta.height as _
            {
                let x = pixel.0.x as usize;
                let y = pixel.0.y as usize;

                let cell = &mut self.buffer[y * self.meta.width + x];

                if *cell != pixel.1 {
                    *cell = pixel.1;

                    changed_state.update_row(y, x, x + 1);
                    changed = true;

                    trace!("Updated pixel x={} y={}", x, y);
                }
            }
        }

        changed
    }
}