mod code;
pub use code::KeyCode;
use std::fmt::{self, Write as _};
use std::ops::{BitOr, BitOrAssign};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct KeyMod(i64);
impl KeyMod {
pub const NONE: Self = Self(0);
pub const SHIFT: Self = Self(1);
pub const ALT: Self = Self(1 << 1);
pub const CTRL: Self = Self(1 << 2);
pub const META: Self = Self(1 << 3);
pub const HYPER: Self = Self(1 << 4);
pub const SUPER: Self = Self(1 << 5);
pub const CAPS_LOCK: Self = Self(1 << 6);
pub const NUM_LOCK: Self = Self(1 << 7);
pub const SCROLL_LOCK: Self = Self(1 << 8);
#[must_use]
pub const fn contains(self, mods: Self) -> bool {
self.0 & mods.0 == mods.0
}
#[must_use]
pub const fn is_empty(self) -> bool {
self.0 == 0
}
pub(crate) const fn bits(self) -> i64 {
self.0
}
pub(crate) const fn from_bits(bits: i64) -> Self {
Self(bits)
}
pub(crate) const fn without(self, mods: Self) -> Self {
Self(self.0 & !mods.0)
}
}
impl BitOr for KeyMod {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl BitOrAssign for KeyMod {
fn bitor_assign(&mut self, rhs: Self) {
self.0 |= rhs.0;
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Key {
pub text: String,
pub mods: KeyMod,
pub code: KeyCode,
pub shifted_code: Option<KeyCode>,
pub base_code: Option<KeyCode>,
pub is_repeat: bool,
}
const MOD_NAMES: [(KeyMod, &str, KeyCode, KeyCode); 6] = [
(KeyMod::CTRL, "ctrl+", KeyCode::LeftCtrl, KeyCode::RightCtrl),
(KeyMod::ALT, "alt+", KeyCode::LeftAlt, KeyCode::RightAlt),
(
KeyMod::SHIFT,
"shift+",
KeyCode::LeftShift,
KeyCode::RightShift,
),
(KeyMod::META, "meta+", KeyCode::LeftMeta, KeyCode::RightMeta),
(
KeyMod::HYPER,
"hyper+",
KeyCode::LeftHyper,
KeyCode::RightHyper,
),
(
KeyMod::SUPER,
"super+",
KeyCode::LeftSuper,
KeyCode::RightSuper,
),
];
const MATCH_MODS: [(&str, KeyMod); 9] = [
("ctrl", KeyMod::CTRL),
("alt", KeyMod::ALT),
("shift", KeyMod::SHIFT),
("meta", KeyMod::META),
("hyper", KeyMod::HYPER),
("super", KeyMod::SUPER),
("capslock", KeyMod::CAPS_LOCK),
("scrolllock", KeyMod::SCROLL_LOCK),
("numlock", KeyMod::NUM_LOCK),
];
impl Key {
#[must_use]
pub const fn new(code: KeyCode) -> Self {
Self {
text: String::new(),
mods: KeyMod::NONE,
code,
shifted_code: None,
base_code: None,
is_repeat: false,
}
}
#[must_use]
pub fn char(c: char) -> Self {
let mut key = Self::new(KeyCode::from_rune(i64::from(u32::from(c))));
key.text = c.to_string();
if c.is_ascii_uppercase() {
key.code = KeyCode::Char(c.to_ascii_lowercase());
key.shifted_code = Some(KeyCode::Char(c));
key.mods = KeyMod::SHIFT;
}
key
}
#[must_use]
pub const fn ctrl(c: char) -> Self {
Self::new(KeyCode::Char(c)).with_mods(KeyMod::CTRL)
}
#[must_use]
pub const fn with_mods(mut self, mods: KeyMod) -> Self {
self.mods = mods;
self
}
#[must_use]
pub fn with_text(mut self, text: impl Into<String>) -> Self {
self.text = text.into();
self
}
#[must_use]
pub const fn with_shifted_code(mut self, code: KeyCode) -> Self {
self.shifted_code = Some(code);
self
}
#[must_use]
pub const fn with_base_code(mut self, code: KeyCode) -> Self {
self.base_code = Some(code);
self
}
#[must_use]
pub const fn with_repeat(mut self, on: bool) -> Self {
self.is_repeat = on;
self
}
#[must_use]
pub fn keystroke(&self) -> String {
let mut s = String::new();
let _ = self.write_keystroke(&mut s);
s
}
#[must_use]
pub fn matches(&self, name: &str) -> bool {
let (mods, code, text) = parse_match(name);
let by_code = self.mods == mods && code == Some(self.code);
by_code || (!self.text.is_empty() && self.text == text)
}
#[must_use]
pub fn matches_any(&self, names: &[&str]) -> bool {
names.iter().any(|name| self.matches(name))
}
fn write_keystroke(&self, w: &mut impl fmt::Write) -> fmt::Result {
for (m, name, left, right) in MOD_NAMES {
if self.mods.contains(m) && ![left, right].contains(&self.code) {
w.write_str(name)?;
}
}
self.write_code(w)
}
fn write_code(&self, w: &mut impl fmt::Write) -> fmt::Result {
if let KeyCode::F(n) = self.code {
return write!(w, "f{n}");
}
if let Some(name) = self.code.name() {
return w.write_str(name);
}
match self.base_code.unwrap_or(self.code) {
KeyCode::Space => w.write_str("space"),
KeyCode::Extended => w.write_str(&self.text),
code => {
w.write_char(char::from_u32(code.rune()).unwrap_or(crate::unicode::REPLACEMENT))
}
}
}
}
fn parse_match(name: &str) -> (KeyMod, Option<KeyCode>, String) {
let (mut mods, mut code, mut text) = (KeyMod::NONE, None, String::new());
for part in name.split('+') {
if let Some((_, m)) = MATCH_MODS.iter().find(|(n, _)| *n == part) {
mods |= *m;
continue;
}
let named = KeyCode::from_name(part);
code = Some(named.unwrap_or_else(|| code_of(part, &mut text)));
}
if text.is_empty() {
text = typed_text(mods, code);
}
(mods, code, text)
}
fn typed_text(mods: KeyMod, code: Option<KeyCode>) -> String {
let plain = mods.without(KeyMod::SHIFT | KeyMod::CAPS_LOCK).is_empty();
let Some(c) = code.filter(|c| plain && c.is_print()) else {
return String::new();
};
let c = char::from_u32(c.rune()).unwrap_or(crate::unicode::REPLACEMENT);
let shifted = mods.contains(KeyMod::SHIFT) || mods.contains(KeyMod::CAPS_LOCK);
let typed = if shifted {
crate::unicode::to_upper(c)
} else {
c
};
typed.to_string()
}
fn code_of(part: &str, text: &mut String) -> KeyCode {
let mut chars = part.chars();
if let (Some(c), None) = (chars.next(), chars.next()) {
return KeyCode::from_rune(i64::from(u32::from(c)));
}
*text = part.to_string();
KeyCode::Extended
}
impl fmt::Display for Key {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if !self.text.is_empty() && self.text != " " {
return f.write_str(&self.text);
}
self.write_keystroke(f)
}
}
impl PartialEq<&str> for Key {
fn eq(&self, name: &&str) -> bool {
let mut rest = Prefix(Some(name));
let _ = write!(rest, "{self}");
rest.0 == Some("")
}
}
struct Prefix<'a>(Option<&'a str>);
impl fmt::Write for Prefix<'_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.0 = self.0.and_then(|rest| rest.strip_prefix(s));
Ok(())
}
}
#[cfg(test)]
mod tests;