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
//! Code for interacting the experimental Wasmer Framebuffer.
//!
//! See the [example][fb-example] for details about how to use this crate to
//! interact with the framebuffer.
//!
//! [fb-example]: https://github.com/wasmerio/io-devices-lib/blob/master/rust/examples/fb_test_2/src/main.rs

use num_traits::FromPrimitive;

use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use std::{fs, io};

pub mod color;

use color::*;

/// Wrapper around framebuffer primitives, allows you to draw and get input easily
pub struct FrameBufferCtx {
    frame_buffer_handle: File,
    resolution_handle: File,
    index_handle: File,
    input_handle: File,

    resolution: (u32, u32),
}

impl FrameBufferCtx {
    /// Create a new framebuffer with the specified resolution.
    pub fn new(x: u32, y: u32) -> Result<Self, String> {
        Self::new_inner(x, y).map_err(|e| {
            format!(
                "Failed to open files at `/_wasmer/dev/fb0`: \"{}\". These are \
                 non-standard files. If you're using Wasmer, please ensure that \
                 you've updated to version 0.13.1 and are using the \
                 `--enable-experimental-io-devices` flag.",
                e.to_string()
            )
        })
    }

    /// Build a new framebuffer
    fn new_inner(x: u32, y: u32) -> io::Result<Self> {
        let frame_buffer_handle = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open("/_wasmer/dev/fb0/fb")?;

        let mut resolution_handle = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open("/_wasmer/dev/fb0/virtual_size")?;

        let index_handle = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open("/_wasmer/dev/fb0/draw")?;

        let input_handle = fs::OpenOptions::new()
            .read(true)
            .open("/_wasmer/dev/fb0/input")?;

        resolution_handle.write(format!("{}x{}", x, y).as_bytes())?;

        Ok(Self {
            frame_buffer_handle,
            resolution_handle,
            index_handle,
            input_handle,

            resolution: (x, y),
        })
    }

    /// Gets the input from the input file and returns an iterator that parses the results
    pub fn get_input(&mut self) -> Option<InputIter> {
        let mut input_vec = vec![];
        self.input_handle.read_to_end(&mut input_vec).ok()?;

        Some(InputIter {
            idx: 0,
            bytes: input_vec,
        })
    }

    /// resize the window
    pub fn set_resolution(&mut self, x: u32, y: u32) -> Option<()> {
        self.resolution_handle
            .write(format!("{}x{}", x, y).as_bytes())
            .ok()?;

        self.resolution.0 = x;
        self.resolution.1 = y;

        Some(())
    }

    /// Draws the values in the buffer to the screen
    pub fn draw(&mut self) -> Option<()> {
        self.index_handle.write(&[b'0']).ok()?;
        Some(())
    }

    /// Updates the buffer starting at position (x,y) with the specified colors
    /// If the length of `pixels` + x is greater than the max length of the row,
    /// drawing will continue at (0, y + 1) and so on.
    ///
    /// Returns `None` if something went wrong, otherwise returns the numbers of pixels
    /// written to the buffer.
    ///
    /// To be able to see these updates, you must call `draw`
    pub fn update_pixels<I>(&mut self, x: u32, y: u32, pixels: I) -> Option<u32>
    where
        I: Iterator<Item = RGBA>,
    {
        self.frame_buffer_handle
            .seek(SeekFrom::Start((self.resolution.0 * y + x) as u64 * 4))
            .ok()?;

        let mut bytes_written = 0;
        for pixel in pixels {
            // TODO: if this is too slow, try stepping the iterator by a larger
            // amount and feeding more bytes at a time to the write calls
            bytes_written += self.frame_buffer_handle.write(&pixel.as_bytes()).ok()?;
        }

        Some(bytes_written as u32)
    }
}

// copied from Wasmer -- maybe this data should be shared somewhere?
// though it is nice to have this crate be simple and self-contained
const KEY_PRESS: u8 = 1;
const MOUSE_MOVE: u8 = 2;
const KEY_RELEASE: u8 = 3;
const MOUSE_PRESS_LEFT: u8 = 4;
const MOUSE_PRESS_RIGHT: u8 = 5;
const MOUSE_PRESS_MIDDLE: u8 = 7;
const WINDOW_CLOSED: u8 = 8;

/// Iterator over [`InputEvent`]s.
pub struct InputIter {
    idx: usize,
    bytes: Vec<u8>,
}

impl Iterator for InputIter {
    type Item = InputEvent;
    fn next(&mut self) -> Option<Self::Item> {
        if self.idx >= self.bytes.len() {
            return None;
        }
        match self.bytes[self.idx] {
            KEY_PRESS => {
                if self.bytes.len() >= self.idx + 2 {
                    if let Some(key) = FromPrimitive::from_u8(self.bytes[self.idx + 1]) {
                        self.idx += 2;
                        return Some(InputEvent::KeyPress(key));
                    }
                }
            }
            KEY_RELEASE => {
                if self.bytes.len() >= self.idx + 2 {
                    if let Some(key) = FromPrimitive::from_u8(self.bytes[self.idx + 1]) {
                        self.idx += 2;
                        return Some(InputEvent::KeyRelease(key));
                    }
                }
            }
            MOUSE_MOVE | MOUSE_PRESS_LEFT | MOUSE_PRESS_RIGHT | MOUSE_PRESS_MIDDLE => {
                if self.bytes.len() >= self.idx + 9 {
                    // TODO: fix bug here, reading wrong values
                    let mut byte_array_x = [0u8; 4];
                    let mut byte_array_y = [0u8; 4];
                    for i in 0..4 {
                        byte_array_x[i] = self.bytes[self.idx + 1 + i];
                        byte_array_y[i] = self.bytes[self.idx + 1 + 4 + i];
                    }
                    let x = u32::from_le_bytes(byte_array_x);
                    let y = u32::from_le_bytes(byte_array_y);

                    let event_type = match self.bytes[self.idx] {
                        MOUSE_MOVE => MouseEventType::Move,
                        MOUSE_PRESS_LEFT => MouseEventType::LeftClick,
                        MOUSE_PRESS_RIGHT => MouseEventType::RightClick,
                        MOUSE_PRESS_MIDDLE => MouseEventType::MiddleClick,
                        _ => unreachable!("Fatal internal logic error in input event parsing"),
                    };

                    self.idx += 9;
                    return Some(InputEvent::MouseEvent(x, y, event_type));
                }
            }
            WINDOW_CLOSED => {
                return Some(InputEvent::WindowClosed);
            }
            _ => {
                // data corrupted
                return None;
            }
        }

        None
    }
}

// copied from Wasmer code which uses a match expression over minifb's `Key` type
// Numbers from https://css-tricks.com/snippets/javascript/javascript-keycodes/
/// A key on a keyboard.
#[derive(Debug, FromPrimitive, ToPrimitive)]
#[repr(u8)]
pub enum Key {
    Backspace = 8,
    Tab = 9,
    Enter = 13,
    Shift = 16,
    Ctrl = 17,
    Alt = 18,
    Pause = 19,
    CapsLock = 20,
    Escape = 27,
    Space = 32,
    PageUp = 33,
    PageDown = 34,
    End = 35,
    Home = 36,

    Left = 37,
    Up = 38,
    Right = 39,
    Down = 40,

    Insert = 45,
    Delete = 46,

    Key0 = 48,
    Key1 = 49,
    Key2 = 50,
    Key3 = 51,
    Key4 = 52,
    Key5 = 53,
    Key6 = 54,
    Key7 = 55,
    Key8 = 56,
    Key9 = 57,

    A = b'A',
    B = b'B',
    C = b'C',
    D = b'D',
    E = b'E',
    F = b'F',
    G = b'G',
    H = b'H',
    I = b'I',
    J = b'J',
    K = b'K',
    L = b'L',
    M = b'M',
    N = b'N',
    O = b'O',
    P = b'P',
    Q = b'Q',
    R = b'R',
    S = b'S',
    T = b'T',
    U = b'U',
    V = b'V',
    W = b'W',
    X = b'X',
    Y = b'Y',
    Z = b'Z',

    LeftSuper = 91,
    RightSuper = 92,

    NumPad0 = 96,
    NumPad1 = 97,
    NumPad2 = 98,
    NumPad3 = 99,
    NumPad4 = 100,
    NumPad5 = 101,
    NumPad6 = 102,
    NumPad7 = 103,
    NumPad8 = 104,
    NumPad9 = 105,
    NumPadAsterisk = 106,
    NumPadPlus = 107,
    NumPadMinus = 109,
    NumPadDot = 110,
    NumPadSlash = 111,

    F1 = 112,
    F2 = 113,
    F3 = 114,
    F4 = 115,
    F5 = 116,
    F6 = 117,
    F7 = 118,
    F8 = 119,
    F9 = 120,
    F10 = 121,
    F11 = 122,
    F12 = 123,

    NumLock = 144,
    ScrollLock = 145,

    Semicolon = 186,
    Equal = 187,
    Comma = 188,
    Minus = 189,
    Period = 190,
    Slash = 191,
    Backquote = 192,
    Backslash = 220,
    Apostrophe = 222,

    LeftBracket = 219,
    RightBracket = 221,

    Unknown = 255,
}

/// The type of mouse event.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum MouseEventType {
    LeftClick,
    RightClick,
    MiddleClick,
    Move,
}

/// An event of an input from the user.
#[derive(Debug)]
pub enum InputEvent {
    KeyPress(Key),
    KeyRelease(Key),
    MouseEvent(u32, u32, MouseEventType),
    WindowClosed,
}