bare shortcuts

This commit is contained in:
Robin Appelman 2023-06-17 20:40:03 +02:00
commit a8079c1b4d
4 changed files with 41 additions and 10 deletions

2
Cargo.lock generated
View file

@ -86,7 +86,7 @@ dependencies = [
[[package]]
name = "evdev-shortcut"
version = "0.1.2"
version = "0.1.3"
dependencies = [
"async-stream",
"evdev",

View file

@ -1,6 +1,6 @@
[package]
name = "evdev-shortcut"
version = "0.1.2"
version = "0.1.3"
authors = ["Robin Appelman <robin@icewind.nl>"]
edition = "2021"
description = "Global shortcuts using evdev"

View file

@ -1,7 +1,7 @@
pub use keycodes::Key;
use parse_display::{Display, FromStr, ParseError};
use std::collections::HashSet;
use std::fmt::{self, Display};
use std::fmt::{self, Debug, Display, Formatter};
use std::str::FromStr;
use thiserror::Error;
@ -89,7 +89,7 @@ impl Modifier {
}
}
#[derive(Clone, Debug, Hash, PartialEq, Eq, Copy)]
#[derive(Clone, Debug, Hash, PartialEq, Eq, Copy, Default)]
pub struct ModifierList(u8);
impl ModifierList {
@ -152,18 +152,47 @@ impl FromStr for ModifierList {
}
}
#[derive(Clone, Debug, Hash, PartialEq, Eq, Display, FromStr)]
#[display("{modifiers}-{key}")]
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct Shortcut {
pub modifiers: ModifierList,
pub key: Key,
}
impl FromStr for Shortcut {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if let Some((modifiers, key)) = s.split_once('-') {
Ok(Shortcut {
modifiers: modifiers.parse()?,
key: key.parse()?,
})
} else {
Ok(Shortcut {
modifiers: ModifierList::default(),
key: s.parse()?,
})
}
}
}
impl Display for Shortcut {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
if self.modifiers.is_empty() {
write!(f, "{}", self.key)
} else {
write!(f, "{}-{}", self.modifiers, self.key)
}
}
}
#[cfg(test)]
mod tests {
use test_case::test_case;
use crate::{Key, Modifier, ModifierList, Shortcut};
#[test_case("KeyP", Shortcut::new(& [], Key::KeyP))]
#[test_case("<Ctrl>-KeyP", Shortcut::new(& [Modifier::Ctrl], Key::KeyP))]
#[test_case("<LeftAlt><LeftCtrl>-KeyLeft", Shortcut::new(& [Modifier::LeftCtrl, Modifier::LeftAlt], Key::KeyLeft))]
fn shortcut_parse_display_test(s: &str, shortcut: Shortcut) {

View file

@ -75,11 +75,13 @@ impl ShortcutListener {
})
}
pub fn add(&self, shortcut: Shortcut) {
self.shortcuts.lock().unwrap().insert(shortcut);
/// Returns `true` if the shortcut was not previously listened to
pub fn add(&self, shortcut: Shortcut) -> bool {
self.shortcuts.lock().unwrap().insert(shortcut)
}
pub fn remove(&self, shortcut: Shortcut) {
self.shortcuts.lock().unwrap().remove(&shortcut);
/// Returns `true` if the shortcut was previously listened to
pub fn remove(&self, shortcut: Shortcut) -> bool {
self.shortcuts.lock().unwrap().remove(&shortcut)
}
}