use serde::{Deserialize, Serialize};
use crate::ScriptContext;
mod tortuise {
#[link(wasm_import_module = "tortuise")]
unsafe extern "C" {
pub safe fn is_key_pressed_this_frame(context: u64, keycode: u32) -> u32;
}
}
/// Represents a key.
#[derive(Debug, PartialOrd, PartialEq, Eq, Clone, Copy, Hash, Serialize, Deserialize)]
pub enum KeyCode {
/// Backspace key (Delete on macOS, Backspace on other platforms).
Backspace,
/// Enter key.
Enter,
/// Left arrow key.
Left,
/// Right arrow key.
Right,
/// Up arrow key.
Up,
/// Down arrow key.
Down,
/// Home key.
Home,
/// End key.
End,
/// Page up key.
PageUp,
/// Page down key.
PageDown,
/// Tab key.
Tab,
/// Shift + Tab key.
BackTab,
/// Delete key. (Fn+Delete on macOS, Delete on other platforms)
Delete,
/// Insert key.
Insert,
/// F key.
///
/// `KeyCode::F(1)` represents F1 key, etc.
F(u8),
/// A character.
///
/// `KeyCode::Char('c')` represents `c` character, etc.
Char(char),
/// Null.
Null,
/// Escape key.
Esc,
}
fn key_code_to_number(key_code: KeyCode) -> u32 {
match key_code {
KeyCode::Null => 0,
KeyCode::Backspace => 1 << 24,
KeyCode::Enter => 2 << 24,
KeyCode::Left => 3 << 24,
KeyCode::Right => 4 << 24,
KeyCode::Up => 5 << 24,
KeyCode::Down => 6 << 24,
KeyCode::Home => 7 << 24,
KeyCode::End => 8 << 24,
KeyCode::PageUp => 9 << 24,
KeyCode::PageDown => 10 << 24,
KeyCode::Tab => 11 << 24,
KeyCode::BackTab => 12 << 24,
KeyCode::Delete => 13 << 24,
KeyCode::Insert => 14 << 24,
KeyCode::F(f) => 15 << 24 | f as u32,
KeyCode::Char(c) => 16 << 24 | c as u32,
KeyCode::Esc => 17 << 24,
}
}
impl ScriptContext {
pub fn is_key_pressed_this_frame(&self, key_code: KeyCode) -> bool {
tortuise::is_key_pressed_this_frame(self.0, key_code_to_number(key_code)) > 0
}
}
|