working f and t bindings

This commit is contained in:
Kay Simmons 2023-01-06 14:03:01 -08:00
parent 6a57bd2794
commit 73e7967a12
37 changed files with 1143 additions and 860 deletions

View file

@ -0,0 +1,104 @@
use anyhow::Result;
use smallvec::SmallVec;
use crate::Action;
use super::{KeymapContext, KeymapContextPredicate, Keystroke};
pub struct Binding {
action: Box<dyn Action>,
keystrokes: Option<SmallVec<[Keystroke; 2]>>,
context_predicate: Option<KeymapContextPredicate>,
}
impl Binding {
pub fn new<A: Action>(keystrokes: &str, action: A, context: Option<&str>) -> Self {
Self::load(keystrokes, Box::new(action), context).unwrap()
}
pub fn load(keystrokes: &str, action: Box<dyn Action>, context: Option<&str>) -> Result<Self> {
let context = if let Some(context) = context {
Some(KeymapContextPredicate::parse(context)?)
} else {
None
};
let keystrokes = if keystrokes == "*" {
None // Catch all context
} else {
Some(
keystrokes
.split_whitespace()
.map(Keystroke::parse)
.collect::<Result<_>>()?,
)
};
Ok(Self {
keystrokes,
action,
context_predicate: context,
})
}
fn match_context(&self, context: &KeymapContext) -> bool {
self.context_predicate
.as_ref()
.map(|predicate| predicate.eval(context))
.unwrap_or(true)
}
pub fn match_keys_and_context(
&self,
pending_keystrokes: &Vec<Keystroke>,
context: &KeymapContext,
) -> BindingMatchResult {
if self
.keystrokes
.as_ref()
.map(|keystrokes| keystrokes.starts_with(&pending_keystrokes))
.unwrap_or(true)
&& self.match_context(context)
{
// If the binding is completed, push it onto the matches list
if self
.keystrokes
.as_ref()
.map(|keystrokes| keystrokes.len() == pending_keystrokes.len())
.unwrap_or(true)
{
BindingMatchResult::Complete(self.action.boxed_clone())
} else {
BindingMatchResult::Partial
}
} else {
BindingMatchResult::Fail
}
}
pub fn keystrokes_for_action(
&self,
action: &dyn Action,
context: &KeymapContext,
) -> Option<SmallVec<[Keystroke; 2]>> {
if self.action.eq(action) && self.match_context(context) {
self.keystrokes.clone()
} else {
None
}
}
pub fn keystrokes(&self) -> Option<&[Keystroke]> {
self.keystrokes.as_deref()
}
pub fn action(&self) -> &dyn Action {
self.action.as_ref()
}
}
pub enum BindingMatchResult {
Complete(Box<dyn Action>),
Partial,
Fail,
}

View file

@ -0,0 +1,61 @@
use smallvec::SmallVec;
use std::{
any::{Any, TypeId},
collections::HashMap,
};
use super::Binding;
#[derive(Default)]
pub struct Keymap {
bindings: Vec<Binding>,
binding_indices_by_action_type: HashMap<TypeId, SmallVec<[usize; 3]>>,
}
impl Keymap {
pub fn new(bindings: Vec<Binding>) -> Self {
let mut binding_indices_by_action_type = HashMap::new();
for (ix, binding) in bindings.iter().enumerate() {
binding_indices_by_action_type
.entry(binding.action().type_id())
.or_insert_with(SmallVec::new)
.push(ix);
}
Self {
binding_indices_by_action_type,
bindings,
}
}
pub(crate) fn bindings_for_action_type(
&self,
action_type: TypeId,
) -> impl Iterator<Item = &'_ Binding> {
self.binding_indices_by_action_type
.get(&action_type)
.map(SmallVec::as_slice)
.unwrap_or(&[])
.iter()
.map(|ix| &self.bindings[*ix])
}
pub(crate) fn add_bindings<T: IntoIterator<Item = Binding>>(&mut self, bindings: T) {
for binding in bindings {
self.binding_indices_by_action_type
.entry(binding.action().type_id())
.or_default()
.push(self.bindings.len());
self.bindings.push(binding);
}
}
pub(crate) fn clear(&mut self) {
self.bindings.clear();
self.binding_indices_by_action_type.clear();
}
pub fn bindings(&self) -> &Vec<Binding> {
&self.bindings
}
}

View file

@ -0,0 +1,123 @@
use anyhow::anyhow;
use collections::{HashMap, HashSet};
use tree_sitter::{Language, Node, Parser};
extern "C" {
fn tree_sitter_context_predicate() -> Language;
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct KeymapContext {
pub set: HashSet<String>,
pub map: HashMap<String, String>,
}
impl KeymapContext {
pub fn extend(&mut self, other: &Self) {
for v in &other.set {
self.set.insert(v.clone());
}
for (k, v) in &other.map {
self.map.insert(k.clone(), v.clone());
}
}
}
#[derive(Debug, Eq, PartialEq)]
pub enum KeymapContextPredicate {
Identifier(String),
Equal(String, String),
NotEqual(String, String),
Not(Box<KeymapContextPredicate>),
And(Box<KeymapContextPredicate>, Box<KeymapContextPredicate>),
Or(Box<KeymapContextPredicate>, Box<KeymapContextPredicate>),
}
impl KeymapContextPredicate {
pub fn parse(source: &str) -> anyhow::Result<Self> {
let mut parser = Parser::new();
let language = unsafe { tree_sitter_context_predicate() };
parser.set_language(language).unwrap();
let source = source.as_bytes();
let tree = parser.parse(source, None).unwrap();
Self::from_node(tree.root_node(), source)
}
fn from_node(node: Node, source: &[u8]) -> anyhow::Result<Self> {
let parse_error = "error parsing context predicate";
let kind = node.kind();
match kind {
"source" => Self::from_node(node.child(0).ok_or_else(|| anyhow!(parse_error))?, source),
"identifier" => Ok(Self::Identifier(node.utf8_text(source)?.into())),
"not" => {
let child = Self::from_node(
node.child_by_field_name("expression")
.ok_or_else(|| anyhow!(parse_error))?,
source,
)?;
Ok(Self::Not(Box::new(child)))
}
"and" | "or" => {
let left = Box::new(Self::from_node(
node.child_by_field_name("left")
.ok_or_else(|| anyhow!(parse_error))?,
source,
)?);
let right = Box::new(Self::from_node(
node.child_by_field_name("right")
.ok_or_else(|| anyhow!(parse_error))?,
source,
)?);
if kind == "and" {
Ok(Self::And(left, right))
} else {
Ok(Self::Or(left, right))
}
}
"equal" | "not_equal" => {
let left = node
.child_by_field_name("left")
.ok_or_else(|| anyhow!(parse_error))?
.utf8_text(source)?
.into();
let right = node
.child_by_field_name("right")
.ok_or_else(|| anyhow!(parse_error))?
.utf8_text(source)?
.into();
if kind == "equal" {
Ok(Self::Equal(left, right))
} else {
Ok(Self::NotEqual(left, right))
}
}
"parenthesized" => Self::from_node(
node.child_by_field_name("expression")
.ok_or_else(|| anyhow!(parse_error))?,
source,
),
_ => Err(anyhow!(parse_error)),
}
}
pub fn eval(&self, context: &KeymapContext) -> bool {
match self {
Self::Identifier(name) => context.set.contains(name.as_str()),
Self::Equal(left, right) => context
.map
.get(left)
.map(|value| value == right)
.unwrap_or(false),
Self::NotEqual(left, right) => context
.map
.get(left)
.map(|value| value != right)
.unwrap_or(true),
Self::Not(pred) => !pred.eval(context),
Self::And(left, right) => left.eval(context) && right.eval(context),
Self::Or(left, right) => left.eval(context) || right.eval(context),
}
}
}

View file

@ -0,0 +1,97 @@
use std::fmt::Write;
use anyhow::anyhow;
use serde::Deserialize;
#[derive(Clone, Debug, Eq, PartialEq, Default, Deserialize)]
pub struct Keystroke {
pub ctrl: bool,
pub alt: bool,
pub shift: bool,
pub cmd: bool,
pub function: bool,
pub key: String,
}
impl Keystroke {
pub fn parse(source: &str) -> anyhow::Result<Self> {
let mut ctrl = false;
let mut alt = false;
let mut shift = false;
let mut cmd = false;
let mut function = false;
let mut key = None;
let mut components = source.split('-').peekable();
while let Some(component) = components.next() {
match component {
"ctrl" => ctrl = true,
"alt" => alt = true,
"shift" => shift = true,
"cmd" => cmd = true,
"fn" => function = true,
_ => {
if let Some(component) = components.peek() {
if component.is_empty() && source.ends_with('-') {
key = Some(String::from("-"));
break;
} else {
return Err(anyhow!("Invalid keystroke `{}`", source));
}
} else {
key = Some(String::from(component));
}
}
}
}
let key = key.ok_or_else(|| anyhow!("Invalid keystroke `{}`", source))?;
Ok(Keystroke {
ctrl,
alt,
shift,
cmd,
function,
key,
})
}
pub fn modified(&self) -> bool {
self.ctrl || self.alt || self.shift || self.cmd
}
}
impl std::fmt::Display for Keystroke {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.ctrl {
f.write_char('^')?;
}
if self.alt {
f.write_char('⎇')?;
}
if self.cmd {
f.write_char('⌘')?;
}
if self.shift {
f.write_char('⇧')?;
}
let key = match self.key.as_str() {
"backspace" => '⌫',
"up" => '↑',
"down" => '↓',
"left" => '←',
"right" => '→',
"tab" => '⇥',
"escape" => '⎋',
key => {
if key.len() == 1 {
key.chars().next().unwrap().to_ascii_uppercase()
} else {
return f.write_str(key);
}
}
};
f.write_char(key)
}
}