use crate::event::{Key, KeyEvent, Modifiers};
pub fn parse_shortcut(text: &str) -> Option<(Modifiers, Key)> {
let mut modifiers = Modifiers::default();
let mut key = None;
let text = text.trim();
let (text, plus) = match text.strip_suffix("++") {
Some(rest) => (rest, true),
None => (text, text == "+"),
};
for part in text.split('+').map(str::trim).filter(|p| !p.is_empty()) {
match part.to_lowercase().as_str() {
"ctrl" | "control" => modifiers.ctrl = true,
"shift" => modifiers.shift = true,
"alt" => modifiers.alt = true,
"cmd" | "meta" | "win" => modifiers.meta = true,
p => {
key = Some(match p {
"del" | "delete" => Key::Delete,
"ins" | "insert" => Key::Insert,
"enter" | "return" => Key::Enter,
"esc" | "escape" => Key::Escape,
"tab" => Key::Tab,
"space" => Key::Space,
"backspace" => Key::Backspace,
"home" => Key::Home,
"end" => Key::End,
"pgup" | "pageup" => Key::PageUp,
"pgdn" | "pagedown" => Key::PageDown,
"up" => Key::Up,
"down" => Key::Down,
"left" => Key::Left,
"right" => Key::Right,
f if f.len() > 1 && f.starts_with('f') && f[1..].parse::<u8>().is_ok() => Key::F(f[1..].parse().ok()?),
c if c.chars().count() == 1 => Key::Char(c.chars().next()?),
_ => return None,
})
}
}
}
if plus {
key = Some(Key::Char('+'));
}
key.map(|k| (modifiers, k))
}
pub fn shortcut_matches((modifiers, key): (Modifiers, Key), event: &KeyEvent) -> bool {
let m = event.modifiers;
let same_key = match (key, event.key) {
(Key::Char(a), Key::Char(b)) => a.to_lowercase().eq(b.to_lowercase()),
(a, b) => a == b,
};
same_key && modifiers.ctrl == (m.ctrl || m.meta) && modifiers.shift == m.shift && modifiers.alt == m.alt
}
pub fn parse_shortcut_list(text: &str) -> Vec<(Modifiers, Key)> {
text.split(';').filter_map(parse_shortcut).collect()
}
pub fn char_set_contains(set: &str, ch: char) -> bool {
let chars: Vec<char> = set.chars().collect();
let mut i = 0;
while i < chars.len() {
let (first, next) = read_set_char(&chars, i);
if next + 1 < chars.len() && chars[next] == '-' {
let (last, after) = read_set_char(&chars, next + 1);
if (first..=last).contains(&ch) {
return true;
}
i = after;
continue;
}
if first == ch {
return true;
}
i = next;
}
false
}
fn read_set_char(chars: &[char], i: usize) -> (char, usize) {
if chars[i] == '\\' && i + 1 < chars.len() {
let c = match chars[i + 1] {
's' => ' ',
't' => '\t',
other => other,
};
(c, i + 2)
} else {
(chars[i], i + 1)
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CharFilter {
pub allowed: String,
pub blocked: String,
pub only_allowed: bool,
pub overrides: bool,
pub map: String,
pub case: CharCase,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CharCase {
#[default]
Normal,
Upper,
Lower,
}
impl CharCase {
pub fn apply(self, text: &str) -> String {
match self {
CharCase::Normal => text.to_string(),
CharCase::Upper => text.to_uppercase(),
CharCase::Lower => text.to_lowercase(),
}
}
}
impl crate::prop::PropEnum for CharCase {
const NAMES: &'static [&'static str] = &["normal", "upper", "lower"];
fn from_index(index: usize) -> Option<Self> {
[CharCase::Normal, CharCase::Upper, CharCase::Lower].get(index).copied()
}
fn index(self) -> usize {
self as usize
}
}
fn map_lookup(map: &str, ch: char) -> Option<char> {
let chars: Vec<char> = map.chars().collect();
chars.chunks_exact(2).find(|pair| pair[0] == ch).map(|pair| pair[1])
}
pub fn map_char(chain: &[CharFilter], ch: char) -> char {
if let Some(to) = chain.iter().rev().filter(|f| f.overrides).find_map(|f| map_lookup(&f.map, ch)) {
return to;
}
chain.iter().find_map(|f| map_lookup(&f.map, ch)).unwrap_or(ch)
}
impl CharFilter {
pub fn opinion(&self, ch: char) -> Option<bool> {
if char_set_contains(&self.blocked, ch) {
Some(false)
} else if char_set_contains(&self.allowed, ch) {
Some(true)
} else if self.only_allowed {
Some(false)
} else {
None
}
}
pub fn is_empty(&self) -> bool {
self.allowed.is_empty() && self.blocked.is_empty() && !self.only_allowed && self.map.is_empty() && self.case == CharCase::Normal
}
}
pub fn char_allowed(chain: &[CharFilter], ch: char) -> bool {
if ch.is_control() {
return true;
}
if let Some(verdict) = chain.iter().rev().filter(|f| f.overrides).find_map(|f| f.opinion(ch)) {
return verdict;
}
chain.iter().find_map(|f| f.opinion(ch)).unwrap_or(true)
}
pub fn mnemonic(text: &str) -> Option<char> {
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if c == '&' {
match chars.next() {
Some('&') => {}
Some(m) if !m.is_whitespace() => return m.to_lowercase().next(),
_ => return None,
}
}
}
None
}
pub fn strip_mnemonic(text: &str) -> (String, Option<usize>) {
if !text.contains('&') {
return (text.to_string(), None);
}
let mut out = String::new();
let mut at = None;
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if c == '&' {
match chars.peek() {
Some('&') => {
chars.next();
out.push('&');
}
Some(m) if !m.is_whitespace() && at.is_none() => at = Some(out.chars().count()),
_ => {}
}
continue;
}
out.push(c);
}
(out, at)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shortcuts_parse_and_match() {
let (m, k) = parse_shortcut("Shift+Enter").unwrap();
assert!(m.shift && !m.ctrl && k == Key::Enter);
assert_eq!(parse_shortcut("Ctrl++").map(|(_, k)| k), Some(Key::Char('+')));
assert_eq!(parse_shortcut_list("Enter; Down").len(), 2);
let event = KeyEvent { key: Key::Char('S'), modifiers: Modifiers { ctrl: true, ..Default::default() }, repeat: false };
assert!(shortcut_matches(parse_shortcut("Ctrl+S").unwrap(), &event));
}
#[test]
fn char_sets_take_ranges_and_escapes() {
assert!(char_set_contains("0-9", '5'));
assert!(!char_set_contains("0-9", 'a'));
assert!(char_set_contains("a-zA-Z_", 'Q'));
assert!(char_set_contains("@.\\-", '-'));
assert!(char_set_contains("0-9-", '-'), "o hífen no fim é ele mesmo");
assert!(char_set_contains("\\s", ' '));
}
#[test]
fn the_child_decides_first_unless_the_parent_overrides() {
let form = CharFilter { blocked: "@".into(), ..Default::default() };
let edit = CharFilter { allowed: "@".into(), ..Default::default() };
assert!(char_allowed(&[edit.clone(), form.clone()], '@'), "o filho libera");
assert!(!char_allowed(&[CharFilter::default(), form.clone()], '@'), "sem opinião, vale o pai");
let strict = CharFilter { overrides: true, ..form };
assert!(!char_allowed(&[edit, strict], '@'), "o pai com prioridade manda");
let digits = CharFilter { allowed: "0-9".into(), only_allowed: true, ..Default::default() };
assert!(char_allowed(&[digits.clone()], '7') && !char_allowed(&[digits], 'x'));
}
#[test]
fn mnemonics_read_and_strip() {
assert_eq!(mnemonic("&Salvar"), Some('s'));
assert_eq!(mnemonic("Sal&var"), Some('v'));
assert_eq!(mnemonic("A && B"), None);
assert_eq!(strip_mnemonic("Sal&var"), ("Salvar".to_string(), Some(3)));
assert_eq!(strip_mnemonic("A && &B"), ("A & B".to_string(), Some(4)));
}
}