fix(input): sorting out event map

This commit is contained in:
🪞👃🪞 2025-07-19 19:53:02 +03:00
parent 238ac2e888
commit d72a3b5b8f
5 changed files with 155 additions and 316 deletions

View file

@ -1,4 +1,8 @@
use crate::*;
/// Map of each event (e.g. key combination) to
/// all command expressions bound to it by
/// all loaded input layers.
type EventMapImpl<E, C> = BTreeMap<E, Vec<Binding<C>>>;
/// A collection of input bindings.
///
/// Each contained layer defines a mapping from input event to command invocation
@ -8,209 +12,100 @@ use crate::*;
/// When a key is pressed, the bindings for it are checked in sequence.
/// When the first non-conditional or true conditional binding is executed,
/// that .event()binding's value is returned.
#[derive(Debug)] pub struct EventMap<E, D: Dsl>(
/// Map of each event (e.g. key combination) to
/// all command expressions bound to it by
/// all loaded input layers.
pub EventBindings<E, D>
);
type EventBindings<E, D> = BTreeMap<E, Vec<Binding<D>>>;
/// An input binding.
#[derive(Debug, Default)] pub struct Binding<D: Dsl> {
condition: Option<D>,
command: D,
description: Option<Arc<str>>,
source: Option<Arc<PathBuf>>,
}
impl<E, D: Dsl> Default for EventMap<E, D> {
fn default () -> Self {
Self(Default::default())
#[derive(Debug)]
pub struct EventMap<E, C>(EventMapImpl<E, C>);
/// Default is always empty map regardless if `E` and `C` implement [Default].
impl<E, C> Default for EventMap<E, C> { fn default () -> Self { Self(Default::default()) } }
impl<E: Clone + Ord, C> EventMap<E, C> {
/// Create a new event map
pub fn new () -> Self {
Default::default()
}
}
impl<E: Ord + Debug + From<Arc<str>> + Clone> EventMap<E, Ast> {
/// Create input layer collection from DSL.
pub fn new (dsl: Ast) -> Usually<Self> {
use Val::*;
let mut input_map: EventBindings<E, Ast> = Default::default();
match dsl.exp_head() {
Str(path) => {
let path = PathBuf::from(path.as_ref() as &str);
for (key, val) in Self::from_path(&path)?.0.into_iter() {
todo!("import {path:?} {key:?} {val:?}");
let key: E = key.into();
if !input_map.contains_key(&key) {
input_map.insert(key, vec![]);
}
}
},
Sym(s) => {
let key: Arc<str> = s.as_ref().into();
let key: E = key.into();
if !input_map.contains_key(&key) {
input_map.insert(key.clone(), vec![]);
}
todo!("binding {s:?} {:?}", dsl.exp_tail());
},
Key(k) if k.as_ref() == "if" => {
todo!("conditional binding {:?}", dsl.exp_tail());
},
_ => return Err(format!("invalid form in keymap: {dsl:?}").into())
}
Ok(Self(input_map))
}
/// Create input layer collection from string.
pub fn from_source (source: &str) -> Usually<Self> {
Self::new(Ast::from(source))
}
/// Create input layer collection from path to text file.
pub fn from_path <P: Debug + AsRef<Path>> (path: P) -> Usually<Self> {
if !exists(path.as_ref())? {
return Err(format!("(e5) not found: {path:?}").into())
}
Self::from_source(read_and_leak(path)?)
}
/// Evaluate the active layers for a given state,
/// returning the command to be executed, if any.
pub fn handle <S, O> (&self, state: &mut S, event: &E) -> Perhaps<O> where
S: DslInto<bool> + DslInto<O>,
O: Command<S>
{
todo!();
//let layers = self.0.as_slice();
//for InputLayer { cond, bind } in layers.iter() {
//let mut matches = true;
//if let Some(cond) = cond {
//matches = state.dsl_into(cond, ||format!("input: no cond").into())?;
//}
//if matches
//&& let Some(exp) = bind.val().exp_head()
//&& input.dsl_into(exp, ||format!("EventMap: input.eval(binding) failed").into())?
//&& let Some(command) = state.try_dsl_into(exp)? {
//return Ok(Some(command))
//}
//}
Ok(None)
}
/*
/// Create an input map with a single non-condal layer.
/// (Use [Default::default] to get an empty map.)
pub fn new (layer: Val<T::Str, T::Exp>) -> Self {
Self::default().layer(layer)
}
/// Add layer, return `Self`.
pub fn layer (mut self, layer: Val<T::Str, T::Exp>) -> Self {
self.add_layer(layer); self
}
/// Add condal layer, return `Self`.
pub fn layer_if (mut self, cond: Val<T::Str, T::Exp>, layer: Val<T::Str, T::Exp>) -> Self {
self.add_layer_if(Some(cond), layer); self
}
/// Add layer, return `&mut Self`.
pub fn add_layer (&mut self, layer: Val<T::Str, T::Exp>) -> &mut Self {
self.add_layer_if(None, layer.into()); self
}
/// Add condal layer, return `&mut Self`.
pub fn add_layer_if (&mut self, cond: Option<Val<T::Str, T::Exp>>, bind: Val<T::Str, T::Exp>) -> &mut Self {
self.0.push(InputLayer { cond, bind });
/// Add a binding to an owned event map.
pub fn def (mut self, event: E, binding: Binding<C>) -> Self {
self.add(event, binding);
self
}
*/
/// Add a binding to an event map.
pub fn add (&mut self, event: E, binding: Binding<C>) -> &mut Self {
if (!self.0.contains_key(&event)) {
self.0.insert(event.clone(), Default::default());
}
self.0.get_mut(&event).unwrap().push(binding);
self
}
/// Return the binding(s) that correspond to an event.
pub fn query (&self, event: &E) -> Option<&[Binding<C>]> {
self.0.get(event).map(|x|x.as_slice())
}
/// Return the first binding that corresponds to an event, considering conditions.
pub fn dispatch (&self, event: &E) -> Option<&Binding<C>> {
self.query(event)
.map(|bb|bb.iter().filter(|b|b.condition.as_ref().map(|c|(c.0)()).unwrap_or(true)).next())
.flatten()
}
/// Create event map from path to text file.
pub fn from_path <P: AsRef<Path>> (path: P) -> Usually<Self> where E: From<Arc<str>> {
if exists(path.as_ref())? {
Self::from_source(read_and_leak(path)?)
} else {
return Err(format!("(e5) not found: {:?}", path.as_ref()).into())
}
}
/// Create event map from string.
pub fn from_source (source: impl AsRef<str>) -> Usually<Self> where E: From<Arc<str>> {
Self::from_dsl(Cst::from(source.as_ref()))
}
/// Create event map from DSL tokenizer.
pub fn from_dsl (mut dsl: impl Dsl) -> Usually<Self> where E: From<Arc<str>> {
use Val::*;
let mut map: Self = Default::default();
loop {
match dsl.exp_next().unwrap() {
Str(path) => {
map.0.extend(Self::from_path(PathBuf::from(path.as_ref() as &str))?.0)
},
Exp(_, e) => match e.head() {
Key(k) if k.as_ref() == "if" => {
todo!("conditional binding {:?}", dsl.tail());
},
Sym(s) => {
let key: Arc<str> = s.as_ref().into();
let key: E = key.into();
map.add(key, Binding::from_dsl(e)?);
todo!("binding {s:?} {:?}", dsl.tail());
},
_ => panic!(),
},
_ => panic!(),
}
}
Ok(map)
}
}
//let mut keys = iter.unwrap();
//let mut map = EventMap::default();
//while let Some(token) = keys.next() {
//if let Value::Exp(_, mut exp) = token.value {
//let next = exp.next();
//if let Some(Token { value: Value::Key(sym), .. }) = next {
//match sym {
//"layer" => {
//if let Some(Token { value: Value::Str(path), .. }) = exp.peek() {
//let path = base.as_ref().parent().unwrap().join(unquote(path));
//if !std::fs::exists(&path)? {
//return Err(format!("(e5) not found: {path:?}").into())
//}
//map.add_layer(read_and_leak(path)?.into());
//print!("layer:\n path: {:?}...", exp.0.0.trim());
//println!("ok");
//} else {
//return Err(format!("(e4) unexpected non-string {next:?}").into())
//}
//},
//"layer-if" => {
//let mut cond = None;
//if let Some(Token { value: Value::Sym(sym), .. }) = exp.next() {
//cond = Some(leak(sym));
//} else {
//return Err(format!("(e4) unexpected non-symbol {next:?}").into())
//};
//if let Some(Token { value: Value::Str(path), .. }) = exp.peek() {
//let path = base.as_ref().parent().unwrap().join(unquote(path));
//if !std::fs::exists(&path)? {
//return Err(format!("(e5) not found: {path:?}").into())
//}
//print!("layer-if:\n cond: {}\n path: {path:?}...",
//cond.unwrap_or_default());
//let keys = read_and_leak(path)?.into();
//let cond = cond.unwrap();
//println!("ok");
//map.add_layer_if(
//Box::new(move |state: &App|Take::take_or_fail(
//state, exp, ||"missing input layer conditional"
//)), keys
//);
//} else {
//return Err(format!("(e4) unexpected non-symbol {next:?}").into())
//}
//},
//_ => return Err(format!("(e3) unexpected symbol {sym:?}").into())
//}
//} else {
//return Err(format!("(e2) unexpected exp {:?}", next.map(|x|x.value)).into())
//}
//} else {
//return Err(format!("(e1) unexpected token {token:?}").into())
//}
//}
//Ok(map)
//}
//{
//}
//fn from (source: &'s str) -> Self {
//// this should be for single layer:
//use Val::*;
//let mut layers = vec![];
//let mut source = CstIter::from(source);
//while let Some(Exp(_, mut iter)) = source.next().map(|x|x.value) {
//let mut iter = iter.clone();
//layers.push(match iter.next().map(|x|x.value) {
//Some(Sym(sym)) if sym.starts_with("@") => InputLayer {
//cond: None,
//bind: vec![[
//dsl_val(source.nth(1).unwrap()),
//dsl_val(source.nth(2).unwrap()),
//]],
//},
//Some(Str(layer)) => InputLayer {
//cond: None,
//bind: dsl_val(source.nth(1).unwrap()),
//},
//Some(Key("if")) => InputLayer {
//cond: Some(dsl_val(source.nth(1).unwrap())),
//bind: dsl_val(source.nth(2).unwrap()),
//},
//_ => panic!("invalid token in keymap"),
//})
//}
//Self(layers)
//}
//}
/// An input binding.
#[derive(Debug)]
pub struct Binding<C> {
pub command: C,
pub condition: Option<Condition>,
pub description: Option<Arc<str>>,
pub source: Option<Arc<PathBuf>>,
}
impl<C> Binding<C> {
fn from_dsl (dsl: impl Dsl) -> Usually<Self> {
let mut command: Option<C> = None;
let mut condition: Option<Condition> = None;
let mut description: Option<Arc<str>> = None;
let mut source: Option<Arc<PathBuf>> = None;
if let Some(command) = command {
Ok(Self { command, condition, description, source })
} else {
Err(format!("no command in {dsl:?}").into())
}
}
}
pub struct Condition(Box<dyn Fn()->bool + Send + Sync>);
impl_debug!(Condition |self, w| { write!(w, "*") });
fn unquote (x: &str) -> &str {
let mut chars = x.chars();