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
use crate::output_settings::OutputSettings;
use core::marker::PhantomData;
use embedded_graphics::{
    geometry::Size,
    pixelcolor::{PixelColor, Rgb888},
    prelude::*,
    primitives::{self, Rectangle},
};
use std::{convert::TryInto, error::Error};
use wasm_bindgen::{JsCast, JsValue};
use web_sys::{Element, HtmlCanvasElement};

/// WebSimulator display.
pub struct WebSimulatorDisplay<C> {
    size: Size,
    canvas: HtmlCanvasElement,
    output_settings: OutputSettings,
    _color_type: PhantomData<C>,
}

impl<C> WebSimulatorDisplay<C>
where
    C: PixelColor + Into<Rgb888>,
{
    /// Creates a new display.
    ///
    /// This appends a `<canvas>` element with size corresponding to scale and pixel spacing used
    /// The display is filled with black.
    pub fn new(
        size: (u32, u32),
        output_settings: &OutputSettings,
        parent: Option<&Element>,
    ) -> Self {
        // source: https://github.com/embedded-graphics/simulator/blob/master/src/output_settings.rs
        let width = size.0 * output_settings.scale + (size.0 - 1) * output_settings.pixel_spacing;
        // source: https://github.com/embedded-graphics/simulator/blob/master/src/output_settings.rs
        let height = size.1 * output_settings.scale + (size.1 - 1) * output_settings.pixel_spacing;
        let document = web_sys::window().unwrap().document().unwrap();
        let canvas = document.create_element("canvas").unwrap();
        let canvas: web_sys::HtmlCanvasElement = canvas
            .dyn_into::<web_sys::HtmlCanvasElement>()
            .map_err(|_| ())
            .unwrap();
        canvas.set_width(width);
        canvas.set_height(height);
        let context = canvas
            .get_context("2d")
            .unwrap()
            .unwrap()
            .dyn_into::<web_sys::CanvasRenderingContext2d>()
            .unwrap();

        context.set_fill_style(&JsValue::from_str("black"));
        context.fill_rect(0.0, 0.0, width as f64, height as f64);
        parent
            .unwrap_or(
                &document
                    .body()
                    .expect("document doesn't have a body and no alternative parent was supplied")
                    .dyn_into::<web_sys::Element>()
                    .map_err(|_| ())
                    .unwrap(),
            )
            .append_child(&canvas)
            .expect("couldn't append canvas to parent");

        WebSimulatorDisplay {
            size: Size::new(width, height),
            canvas,
            output_settings: output_settings.clone(),
            _color_type: PhantomData,
        }
    }

    fn fill_rect(
        canvas: &HtmlCanvasElement,
        color: C,
        area: &Rectangle,
        scale: u32,
        pitch: u32,
    ) -> Result<(), Box<dyn Error>> {
        let context = canvas
            .get_context("2d")
            .unwrap()
            .unwrap()
            .dyn_into::<web_sys::CanvasRenderingContext2d>()
            .unwrap();
        let color_rgb888 = color.into();

        let css_color = format!(
            "rgb({},{},{})",
            color_rgb888.r(),
            color_rgb888.g(),
            color_rgb888.b()
        );
        context.set_fill_style(&JsValue::from_str(&css_color));

        let width = area.size.width * scale;
        let height = area.size.height * scale;

        let scale: i32 = scale.try_into()?;
        let pitch: i32 = pitch.try_into()?;

        let origin = area.top_left;

        context.fill_rect(
            (origin.x * scale * pitch).try_into()?,
            (origin.y * scale * pitch).try_into()?,
            width.try_into()?,
            height.try_into()?,
        );
        Ok(())
    }

    fn draw_pixel(&mut self, pixel: Pixel<C>) -> Result<(), core::convert::Infallible> {
        let Pixel(coord, color) = pixel;
        let scale = self.output_settings.scale;

        // source: https://github.com/embedded-graphics/simulator/blob/master/src/output_settings.rs#L39
        let pitch = scale + self.output_settings.pixel_spacing;

        Self::fill_rect(
            &self.canvas,
            color,
            &Rectangle::new(coord, Size::new(scale, scale)),
            scale,
            pitch,
        )
        .expect("numeric conversion failed");

        Ok(())
    }
}

impl<C> OriginDimensions for WebSimulatorDisplay<C>
where
    C: PixelColor + Into<Rgb888>,
{
    fn size(&self) -> Size {
        self.size
    }
}

impl<C> DrawTarget for WebSimulatorDisplay<C>
where
    C: PixelColor + Into<Rgb888>,
{
    type Color = C;
    type Error = Box<dyn Error>;

    fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
    where
        I: IntoIterator<Item = Pixel<Self::Color>>,
    {
        let bounding_box = primitives::Rectangle::new(Point::new(0, 0), self.size);
        for pixel in pixels.into_iter() {
            if bounding_box.contains(pixel.0) {
                self.draw_pixel(pixel)?;
            }
        }
        Ok(())
    }

    fn fill_solid(&mut self, area: &Rectangle, color: Self::Color) -> Result<(), Self::Error> {
        Self::fill_rect(&self.canvas, color, area, self.output_settings.scale, 1)?;

        Ok(())
    }
}