use std::collections::HashMap;
use dces::prelude::Entity;
use crate::{shell::Key, theming::Theme};
#[derive(Default, Clone, Debug, PartialEq)]
pub struct Global {
pub focused_widget: Option<Entity>,
pub id_map: HashMap<String, Entity>,
pub keyboard_state: KeyboardState,
pub theme: Theme,
}
#[derive(Default, Clone, Debug, PartialEq)]
pub struct KeyboardState {
key_list: HashMap<Key, bool>,
}
impl KeyboardState {
pub fn set_key_state(&mut self, key: Key, pressed: bool) {
self.key_list.insert(key, pressed);
}
pub fn is_key_down(&self, key: Key) -> bool {
match self.key_list.get(&key) {
Some(item) => *item,
None => false,
}
}
pub fn is_shift_down(&self) -> bool {
self.is_key_down(Key::ShiftL) || self.is_key_down(Key::ShiftR)
}
pub fn is_alt_down(&self) -> bool {
self.is_key_down(Key::Alt)
}
pub fn is_ctrl_down(&self) -> bool {
self.is_key_down(Key::Control)
}
pub fn is_home_down(&self) -> bool {
self.is_key_down(Key::Home)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic_test() {
let mut state = KeyboardState::default();
assert_eq!(state.is_key_down(Key::ShiftL), false);
state.set_key_state(Key::ShiftL, true);
assert_eq!(state.is_key_down(Key::ShiftL), true);
state.set_key_state(Key::ShiftL, false);
assert_eq!(state.is_key_down(Key::ShiftL), false);
state.set_key_state(Key::ShiftL, true);
state.set_key_state(Key::ShiftR, true);
state.set_key_state(Key::Space, true);
state.set_key_state(Key::Control, true);
state.set_key_state(Key::Alt, true);
assert_eq!(state.is_key_down(Key::ShiftL), true);
assert_eq!(state.is_key_down(Key::ShiftR), true);
assert_eq!(state.is_key_down(Key::Space), true);
assert_eq!(state.is_key_down(Key::Control), true);
assert_eq!(state.is_key_down(Key::Alt), true);
}
#[test]
fn test_convenience() {
let mut state = KeyboardState::default();
assert_eq!(state.is_alt_down(), false);
assert_eq!(state.is_ctrl_down(), false);
assert_eq!(state.is_shift_down(), false);
state.set_key_state(Key::Control, true);
assert_eq!(state.is_ctrl_down(), true);
state.set_key_state(Key::Alt, true);
assert_eq!(state.is_alt_down(), true);
assert_eq!(state.is_shift_down(), false);
state.set_key_state(Key::ShiftL, true);
assert_eq!(state.is_shift_down(), true);
state.set_key_state(Key::ShiftR, true);
assert_eq!(state.is_shift_down(), true);
state.set_key_state(Key::ShiftL, false);
assert_eq!(state.is_shift_down(), true);
state.set_key_state(Key::ShiftR, false);
assert_eq!(state.is_shift_down(), false);
state.set_key_state(Key::Control, false);
assert_eq!(state.is_ctrl_down(), false);
state.set_key_state(Key::Alt, false);
assert_eq!(state.is_alt_down(), false);
}
}