Record mouse movement (#51)

* Record mouse movement

* Use get for last_point and first_point

* Use first and las for first_point and last_point

* Remove unnecessary comment

* Derive Default for Trace

Co-authored-by: RustyNixieTube <RustyNixieTube@users.noreply.github.com>
This commit is contained in:
RustyNixieTube 2021-03-28 19:59:41 +02:00 committed by Keavon Chambers
parent 00fa95aa91
commit f8ac13c3f2
3 changed files with 44 additions and 9 deletions

View File

@ -16,22 +16,35 @@ pub fn select_tool(tool: String) -> Result<(), JsValue> {
})
}
static mut POS: (u32, u32) = (0, 0);
/// Mouse movement with the bounds of the canvas
#[wasm_bindgen]
pub fn on_mouse_move(x: u32, y: u32) {
// SAFETY: This is safe because the code can only ever run in a single thread
unsafe {
POS = (x, y);
}
EDITOR_STATE.with(|editor| {
let mut editor = editor.borrow_mut();
if editor.tools.mouse_is_clicked {
editor.tools.trace.append_point(x, y)
}
})
}
/// Mouse click within the bounds of the canvas
#[wasm_bindgen]
pub fn on_mouse_click(x: u32, y: u32) -> Result<(), JsValue> {
let ev = events::Event::Click(events::MouseState::from_pos(x, y));
EDITOR_STATE.with(|editor| editor.borrow_mut().handle_event(ev)).map_err(|err| Error::new(&err.to_string()).into())
EDITOR_STATE
.with(|editor| {
let mut editor = editor.borrow_mut();
editor.tools.mouse_is_clicked = true;
editor.tools.trace.clear();
editor.handle_event(ev)
})
.map_err(|err| Error::new(&err.to_string()).into())
}
/// Mouse released
#[wasm_bindgen]
pub fn on_mouse_release() {
EDITOR_STATE.with(|editor| editor.borrow_mut().tools.mouse_is_clicked = false)
}
/// Update working colors

View File

@ -16,8 +16,26 @@ pub enum Response {
UpdateCanvas,
}
#[derive(Debug, Clone)]
#[derive(Debug, Clone, Default)]
pub struct Trace(Vec<MouseState>);
impl Trace {
pub fn new() -> Self {
Self::default()
}
pub fn first_point(&self) -> Option<&MouseState> {
self.0.first()
}
pub fn last_point(&self) -> Option<&MouseState> {
self.0.last()
}
pub fn append_point(&mut self, x: u32, y: u32) {
self.0.push(MouseState::from_pos(x, y))
}
pub fn clear(&mut self) {
self.0.clear()
}
}
#[derive(Debug, Clone, Default)]
pub struct MouseState {
x: u32,

View File

@ -1,7 +1,9 @@
use crate::Color;
use crate::{events::Trace, Color};
use std::collections::HashMap;
pub struct ToolState {
pub mouse_is_clicked: bool,
pub trace: Trace,
pub primary_color: Color,
pub secondary_color: Color,
pub active_tool: ToolType,
@ -11,6 +13,8 @@ pub struct ToolState {
impl ToolState {
pub fn new() -> Self {
ToolState {
mouse_is_clicked: false,
trace: Trace::new(),
primary_color: Color::BLACK,
secondary_color: Color::WHITE,
active_tool: ToolType::Select,