wasm4fun_input/
mouse.rs

1// Copyright Claudio Mattera 2022.
2//
3// Distributed under the MIT License or the Apache 2.0 License at your option.
4// See the accompanying files License-MIT.txt and License-Apache-2.0.txt, or
5// online at
6// https://opensource.org/licenses/MIT
7// https://opensource.org/licenses/Apache-2.0
8
9use wasm4fun_core::{MOUSE_BUTTONS, MOUSE_X, MOUSE_Y};
10
11/// A mouse
12#[derive(Clone, Copy)]
13pub struct Mouse;
14
15static mut PREVIOUS_BUTTONS: u8 = 0;
16
17impl Mouse {
18    /// Update previous status of buttons
19    ///
20    /// The previous status of mouse buttons is used to detect clicks.
21    /// A click happens when the previous status was down and the current
22    /// status is up.
23    pub fn update(&self) {
24        unsafe { PREVIOUS_BUTTONS = *MOUSE_BUTTONS }
25    }
26
27    /// Get the coordinates
28    pub fn coordinates(&self) -> (i16, i16) {
29        unsafe { (*MOUSE_X, *MOUSE_Y) }
30    }
31
32    /// Get the X coordinate
33    pub fn x(&self) -> i16 {
34        unsafe { *MOUSE_X }
35    }
36
37    /// Get the Y coordinate
38    pub fn y(&self) -> i16 {
39        unsafe { *MOUSE_Y }
40    }
41
42    /// Check whether left button is pressed
43    pub fn left_pressed(&self) -> bool {
44        left_pressed(unsafe { *MOUSE_BUTTONS })
45    }
46
47    /// Check whether left button is pressed
48    pub fn right_pressed(&self) -> bool {
49        right_pressed(unsafe { *MOUSE_BUTTONS })
50    }
51
52    /// Check whether left button is pressed
53    pub fn middle_pressed(&self) -> bool {
54        middle_pressed(unsafe { *MOUSE_BUTTONS })
55    }
56
57    /// Check whether left button was clicked
58    pub fn left_clicked(&self) -> bool {
59        let current_unpressed = !left_pressed(unsafe { *MOUSE_BUTTONS });
60        let previously_pressed = left_pressed(unsafe { PREVIOUS_BUTTONS });
61        current_unpressed && previously_pressed
62    }
63
64    /// Check whether right button was clicked
65    pub fn right_clicked(&self) -> bool {
66        let current_unpressed = !right_pressed(unsafe { *MOUSE_BUTTONS });
67        let previously_pressed = right_pressed(unsafe { PREVIOUS_BUTTONS });
68        current_unpressed && previously_pressed
69    }
70
71    /// Check whether middle button was clicked
72    pub fn middle_clicked(&self) -> bool {
73        let current_unpressed = !middle_pressed(unsafe { *MOUSE_BUTTONS });
74        let previously_pressed = middle_pressed(unsafe { PREVIOUS_BUTTONS });
75        current_unpressed && previously_pressed
76    }
77}
78
79fn left_pressed(value: u8) -> bool {
80    (value & 0b001) != 0
81}
82
83fn right_pressed(value: u8) -> bool {
84    (value & 0b010) != 0
85}
86
87fn middle_pressed(value: u8) -> bool {
88    (value & 0b100) != 0
89}