cosmic-files/src/key_bind.rs

79 lines
2.5 KiB
Rust
Raw Normal View History

2024-02-09 07:09:51 -07:00
use cosmic::{
iced::keyboard::{Key, Modifiers},
iced_core::keyboard::key::Named,
};
2024-01-29 12:21:54 -07:00
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, fmt};
2024-02-01 15:14:14 -07:00
use crate::app::Action;
2024-01-29 12:21:54 -07:00
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub enum Modifier {
Super,
Ctrl,
Alt,
Shift,
}
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct KeyBind {
pub modifiers: Vec<Modifier>,
2024-02-09 07:09:51 -07:00
pub key: Key,
2024-01-29 12:21:54 -07:00
}
impl KeyBind {
2024-02-09 07:09:51 -07:00
pub fn matches(&self, modifiers: Modifiers, key: &Key) -> bool {
key == &self.key
2024-01-29 12:21:54 -07:00
&& modifiers.logo() == self.modifiers.contains(&Modifier::Super)
&& modifiers.control() == self.modifiers.contains(&Modifier::Ctrl)
&& modifiers.alt() == self.modifiers.contains(&Modifier::Alt)
&& modifiers.shift() == self.modifiers.contains(&Modifier::Shift)
}
}
impl fmt::Display for KeyBind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for modifier in self.modifiers.iter() {
write!(f, "{:?} + ", modifier)?;
}
2024-02-09 07:09:51 -07:00
match &self.key {
Key::Character(c) => write!(f, "{}", c.to_uppercase()),
Key::Named(named) => write!(f, "{:?}", named),
other => write!(f, "{:?}", other),
}
2024-01-29 12:21:54 -07:00
}
}
//TODO: load from config
pub fn key_binds() -> HashMap<KeyBind, Action> {
let mut key_binds = HashMap::new();
macro_rules! bind {
2024-02-09 07:09:51 -07:00
([$($modifier:ident),+ $(,)?], $key:expr, $action:ident) => {{
2024-01-29 12:21:54 -07:00
key_binds.insert(
KeyBind {
modifiers: vec![$(Modifier::$modifier),+],
2024-02-09 07:09:51 -07:00
key: $key,
2024-01-29 12:21:54 -07:00
},
Action::$action,
);
}};
}
2024-02-09 07:09:51 -07:00
bind!([Ctrl], Key::Character("c".into()), Copy);
bind!([Ctrl], Key::Character("x".into()), Cut);
bind!([Alt], Key::Named(Named::ArrowRight), HistoryNext);
bind!([Alt], Key::Named(Named::ArrowLeft), HistoryPrevious);
bind!([Alt], Key::Named(Named::ArrowUp), LocationUp);
bind!([Ctrl], Key::Character("v".into()), Paste);
bind!([Ctrl], Key::Character("a".into()), SelectAll);
bind!([Ctrl], Key::Character("w".into()), TabClose);
bind!([Ctrl], Key::Character("t".into()), TabNew);
bind!([Ctrl], Key::Named(Named::Tab), TabNext);
bind!([Ctrl, Shift], Key::Named(Named::Tab), TabPrev);
bind!([Ctrl], Key::Character("q".into()), WindowClose);
bind!([Ctrl], Key::Character("n".into()), WindowNew);
2024-01-29 12:21:54 -07:00
key_binds
}