emerald_kernel_user_link/
mouse.rs

1pub const MOUSE_PATH: &str = "/devices/mouse";
2
3pub mod buttons {
4    pub const LEFT: u8 = 1 << 0;
5    pub const RIGHT: u8 = 1 << 1;
6    pub const MIDDLE: u8 = 1 << 2;
7    pub const FOURTH: u8 = 1 << 3;
8    pub const FIFTH: u8 = 1 << 4;
9}
10
11#[derive(Debug, Clone, Copy)]
12#[repr(u8)]
13pub enum ScrollType {
14    None = 0,
15    VerticalUp,
16    VerticalDown,
17    HorizontalRight,
18    HorizontalNegative,
19}
20
21#[derive(Debug, Clone, Copy)]
22pub struct MouseEvent {
23    pub x: i16,
24    pub y: i16,
25    pub scroll_type: ScrollType,
26    pub buttons: u8,
27}
28
29impl MouseEvent {
30    pub const BYTES_SIZE: usize = 5;
31
32    /// # Safety
33    /// The `bytes` must be a valid representation of a `MouseEvent`
34    /// that has been created by `as_bytes`
35    pub unsafe fn from_bytes(bytes: [u8; Self::BYTES_SIZE]) -> Self {
36        let x = i16::from_le_bytes([bytes[0], bytes[1]]);
37        let y = i16::from_le_bytes([bytes[2], bytes[3]]);
38        let buttons = bytes[4] & 0b11111;
39        let scroll_type = match bytes[4] >> 5 {
40            0 => ScrollType::None,
41            1 => ScrollType::VerticalUp,
42            2 => ScrollType::VerticalDown,
43            3 => ScrollType::HorizontalRight,
44            4 => ScrollType::HorizontalNegative,
45            _ => panic!("invalid scroll type"),
46        };
47
48        Self {
49            x,
50            y,
51            buttons,
52            scroll_type,
53        }
54    }
55
56    pub fn as_bytes(&self) -> [u8; Self::BYTES_SIZE] {
57        let mut bytes = [0; Self::BYTES_SIZE];
58
59        // bytes[0..4] = x, y
60        let x_bytes = self.x.to_le_bytes();
61        let y_bytes = self.y.to_le_bytes();
62        bytes[0..2].copy_from_slice(&x_bytes);
63        bytes[2..4].copy_from_slice(&y_bytes);
64
65        // merge the buttons and scroll type
66        // low 5 bits are the buttons
67        // high 3 bits are the scroll type
68        let scroll_type = self.scroll_type as u8;
69        bytes[4] = self.buttons & 0b11111 | (scroll_type << 5);
70
71        bytes
72    }
73}