From 143cd24e0983d39fa66a9235355d6ce21eb88845 Mon Sep 17 00:00:00 2001 From: unspeaker Date: Fri, 17 Jan 2025 19:47:35 +0100 Subject: [PATCH] generalize EdnItem. maybe should rename it to Atom? ~90 instances of it --- edn/src/edn_item.rs | 71 ++++++------ edn/src/edn_provide.rs | 108 +++++++++++------- edn/src/edn_token.rs | 13 ++- edn/src/try_from_edn.rs | 2 +- input/src/edn_input.rs | 24 ++-- midi/src/midi_edit.rs | 2 +- midi/src/midi_pool.rs | 2 +- output/src/edn_view.rs | 29 ++--- output/src/either.rs | 33 ------ output/src/lib.rs | 41 +++---- output/src/{align.rs => op_align.rs} | 11 +- output/src/{direction.rs => op_bsp.rs} | 29 ++--- output/src/op_cond.rs | 74 ++++++++++++ output/src/{map.rs => op_iter.rs} | 0 .../{transform_xy_unit.rs => op_transform.rs} | 58 +++++++++- output/src/transform_xy.rs | 55 --------- output/src/when.rs | 42 ------- tek/src/lib.rs | 2 +- time/src/clock.rs | 2 +- tui/src/tui_input.rs | 2 +- 20 files changed, 314 insertions(+), 286 deletions(-) delete mode 100644 output/src/either.rs rename output/src/{align.rs => op_align.rs} (91%) rename output/src/{direction.rs => op_bsp.rs} (86%) create mode 100644 output/src/op_cond.rs rename output/src/{map.rs => op_iter.rs} (100%) rename output/src/{transform_xy_unit.rs => op_transform.rs} (69%) delete mode 100644 output/src/transform_xy.rs delete mode 100644 output/src/when.rs diff --git a/edn/src/edn_item.rs b/edn/src/edn_item.rs index cdab9b25..b7920208 100644 --- a/edn/src/edn_item.rs +++ b/edn/src/edn_item.rs @@ -1,14 +1,34 @@ use crate::*; use std::sync::Arc; -#[derive(Default, Clone, PartialEq)] pub enum EdnItem { +#[derive(Default, Clone, PartialEq)] pub enum EdnItem { #[default] Nil, Num(usize), - Sym(Arc), - Key(Arc), - Exp(Vec), + Sym(T), + Key(T), + Exp(Vec>), } -impl EdnItem { - pub fn read_all (mut source: &str) -> Result, ParseError> { +impl<'a, T: 'a> EdnItem { + pub fn transform U + Clone> (&'a self, f: F) -> EdnItem { + use EdnItem::*; + match self { + Nil => Nil, + Num(n) => Num(*n), + Sym(t) => Sym(f(t)), + Key(t) => Key(f(t)), + Exp(e) => Exp(e.iter().map(|i|i.transform(f.clone())).collect()) + } + } +} +impl<'a, T: AsRef> EdnItem { + pub fn to_ref (&'a self) -> EdnItem<&'a str> { + self.transform(|t|t.as_ref()) + } + pub fn to_arc (&'a self) -> EdnItem> { + self.transform(|t|t.as_ref().into()) + } +} +impl<'a> EdnItem> { + pub fn read_all (mut source: &'a str) -> Result, ParseError> { let mut items = vec![]; loop { if source.len() == 0 { @@ -20,7 +40,7 @@ impl EdnItem { } Ok(items) } - pub fn read_one (source: &str) -> Result<(Self, &str), ParseError> { + pub fn read_one (source: &'a str) -> Result<(Self, &'a str), ParseError> { Ok({ if source.len() == 0 { return Err(ParseError::Code(5)) @@ -29,23 +49,19 @@ impl EdnItem { (Self::read(token)?, remaining) }) } - pub fn read <'a> (token: Token<'a>) -> Result { - use Token::*; + pub fn read (token: Token<'a>) -> Result { + use EdnItem::*; Ok(match token { - Nil => EdnItem::Nil, - Num(chars, index, length) => - Self::Num(Token::number(&chars[index..index+length])), - Sym(chars, index, length) => - Self::Sym((&chars[index..index+length]).into()), - Key(chars, index, length) => - Self::Key((&chars[index..index+length]).into()), - Exp(chars, index, length, 0) => - Self::Exp(Self::read_all(&chars[index+1..(index+length).saturating_sub(1)])?), + Token::Nil => Nil, + Token::Num(_, _, _) => Num(Token::number(token.string())), + Token::Sym(_, _, _) => Sym(token.string().into()), + Token::Key(_, _, _) => Key(token.string().into()), + Token::Exp(_, _, _, 0) => Exp(EdnItem::read_all(token.string())?), _ => panic!("unclosed delimiter") }) } } -impl Debug for EdnItem { +impl Debug for EdnItem { fn fmt (&self, f: &mut Formatter<'_>) -> Result<(), FormatError> { use EdnItem::*; match self { @@ -58,7 +74,7 @@ impl Debug for EdnItem { } } } -impl Display for EdnItem { +impl Display for EdnItem { fn fmt (&self, f: &mut Formatter<'_>) -> Result<(), FormatError> { use EdnItem::*; use itertools::join; @@ -71,18 +87,3 @@ impl Display for EdnItem { } } } -impl<'a> TryFrom> for EdnItem { - type Error = ParseError; - fn try_from (token: Token<'a>) -> Result { - use Token::*; - Ok(match token { - Nil => Self::Nil, - Num(chars, index, length) => Self::Num(Token::number(&chars[index..index+length])), - Sym(chars, index, length) => Self::Sym((&chars[index..index+length]).into()), - Key(chars, index, length) => Self::Key((&chars[index..index+length]).into()), - Exp(chars, index, length, 0) => Self::Exp(Self::read_all( - &chars[index+1..(index+length).saturating_sub(1)])?), - _ => panic!("unclosed delimiter") - }) - } -} diff --git a/edn/src/edn_provide.rs b/edn/src/edn_provide.rs index 03703732..47b1f18f 100644 --- a/edn/src/edn_provide.rs +++ b/edn/src/edn_provide.rs @@ -1,69 +1,95 @@ use crate::*; -/// Implement `EdnProvide` for a type and context +/// Map EDN tokens to parameters of a given type for a given context +pub trait EdnProvide<'a, U>: Sized { + fn get (&'a self, _edn: &'a EdnItem>) -> Option { + None + } + fn get_or_fail (&'a self, edn: &'a EdnItem>) -> U { + self.get(edn).expect("no value") + } +} +impl<'a, T: EdnProvide<'a, U>, U> EdnProvide<'a, U> for &T { + fn get (&'a self, edn: &'a EdnItem>) -> Option { + (*self).get(edn) + } + fn get_or_fail (&'a self, edn: &'a EdnItem>) -> U { + (*self).get_or_fail(edn) + } +} +impl<'a, T: EdnProvide<'a, U>, U> EdnProvide<'a, U> for Option { + fn get (&'a self, edn: &'a EdnItem>) -> Option { + self.as_ref().map(|s|s.get(edn)).flatten() + } + fn get_or_fail (&'a self, edn: &'a EdnItem>) -> U { + self.as_ref().map(|s|s.get_or_fail(edn)).expect("no provider") + } +} +/// Implement `EdnProvide` for a context and type. #[macro_export] macro_rules! edn_provide { // Provide a value to the EDN template ($type:ty:|$self:ident:$State:ty|{ $($pat:pat => $expr:expr),* $(,)? }) => { impl<'a> EdnProvide<'a, $type> for $State { - fn get (&'a $self, edn: &'a EdnItem) -> Option<$type> { - Some(match EdnItem::<&str>::from(edn) { $(EdnItem::Sym($pat) => $expr,)* _ => return None }) + fn get (&'a $self, edn: &'a EdnItem>) -> Option<$type> { + use EdnItem::*; + Some(match edn.to_ref() { $(Sym($pat) => $expr,)* _ => return None }) } } }; // Provide a value more generically ($lt:lifetime: $type:ty:|$self:ident:$State:ty|{ $($pat:pat => $expr:expr),* $(,)? }) => { impl<$lt> EdnProvide<$lt, $type> for $State { - fn get (&$lt $self, edn: &$lt EdnItem) -> Option<$type> { - Some(match EdnItem::<&str>::from(edn) { $(EdnItem::Sym($pat) => $expr,)* _ => return None }) + fn get (&$lt $self, edn: &$lt EdnItem>) -> Option<$type> { + use EdnItem::*; + Some(match edn.to_ref() { $(Sym($pat) => $expr,)* _ => return None }) } } }; +} +/// Implement `EdnProvide` for a context and numeric type. +/// +/// This enables support for numeric literals. +#[macro_export] macro_rules! edn_provide_num { // Provide a value that may also be a numeric literal in the EDN, to a generic implementation. - (# $type:ty:|$self:ident:<$T:ident:$Trait:path>|{ $($pat:pat => $expr:expr),* $(,)? }) => { + ($type:ty:|$self:ident:<$T:ident:$Trait:path>|{ $($pat:pat => $expr:expr),* $(,)? }) => { impl<'a, $T: $Trait> EdnProvide<'a, $type> for $T { - fn get (&'a $self, edn: &'a EdnItem) -> Option<$type> { - Some(match edn { - $(EdnItem::Sym($pat) => $expr,)* - EdnItem::Num(n) => *n as $type, - _ => return None - }) + fn get (&'a $self, edn: &'a EdnItem>) -> Option<$type> { + use EdnItem::*; + Some(match edn.to_ref() { $(Sym($pat) => $expr,)* Num(n) => n as $type, _ => return None }) } } }; // Provide a value that may also be a numeric literal in the EDN, to a concrete implementation. - (# $type:ty:|$self:ident:$State:ty|{ $($pat:pat => $expr:expr),* $(,)? }) => { + ($type:ty:|$self:ident:$State:ty|{ $($pat:pat => $expr:expr),* $(,)? }) => { impl<'a> EdnProvide<'a, $type> for $State { - fn get (&'a $self, edn: &'a EdnItem) -> Option<$type> { - Some(match edn { - $(EdnItem::Sym($pat) => $expr,)* - EdnItem::Num(n) => *n as $type, + fn get (&'a $self, edn: &'a EdnItem>) -> Option<$type> { + use EdnItem::*; + Some(match edn.to_ref() { $(Sym($pat) => $expr,)* Num(n) => n as $type, _ => return None }) + } + } + }; +} +/// Implement `EdnProvide` for a context and content type. +/// +/// This enables support for layout expressions. +#[macro_export] macro_rules! edn_provide_content { + (|$self:ident:$State:ty|{ $($pat:pat => $expr:expr),* $(,)? }) => { + impl<'a, E: Output> EdnProvide<'a, Box + 'a>> for $State { + fn get (&'a $self, edn: &'a EdnItem>) -> Option + 'a>> { + Some(match edn.to_ref() { + $(EdnItem::Sym($pat) => $expr),*, _ => return None }) } } }; -} -/// Map EDN tokens to parameters of a given type for a given context -pub trait EdnProvide<'a, U>: Sized { - fn get (&'a self, _edn: &'a EdnItem) -> Option { - None - } - fn get_or_fail (&'a self, edn: &'a EdnItem) -> U { - self.get(edn).expect("no value") - } -} -impl<'a, T: EdnProvide<'a, U>, U> EdnProvide<'a, U> for &T { - fn get (&'a self, edn: &'a EdnItem) -> Option { - (*self).get(edn) - } - fn get_or_fail (&'a self, edn: &'a EdnItem) -> U { - (*self).get_or_fail(edn) - } -} -impl<'a, T: EdnProvide<'a, U>, U> EdnProvide<'a, U> for Option { - fn get (&'a self, edn: &'a EdnItem) -> Option { - self.as_ref().map(|s|s.get(edn)).flatten() - } - fn get_or_fail (&'a self, edn: &'a EdnItem) -> U { - self.as_ref().map(|s|s.get_or_fail(edn)).expect("no provider") + ($Output:ty: |$self:ident:$State:ty|{ $($pat:pat => $expr:expr),* $(,)? }) => { + impl<'a> EdnProvide<'a, Box + 'a>> for $State { + fn get (&'a $self, edn: &'a EdnItem>) -> Option + 'a>> { + Some(match edn.to_ref() { + $(EdnItem::Sym($pat) => $expr),*, + _ => return None + }) + } + } } } diff --git a/edn/src/edn_token.rs b/edn/src/edn_token.rs index 55205676..9fadfc31 100644 --- a/edn/src/edn_token.rs +++ b/edn/src/edn_token.rs @@ -72,7 +72,17 @@ impl<'a> Token<'a> { } Ok(("", state)) } - + pub fn string (&self) -> &str { + use Token::*; + match self { + Nil => "", + Num(src, start, len) => &src[*start..start+len], + Sym(src, start, len) => &src[*start..start+len], + Key(src, start, len) => &src[*start..start+len], + Exp(src, start, len, 0) => &src[*start..(start+len).saturating_sub(1)], + _ => panic!("unclosed delimiter") + } + } pub const fn number (digits: &str) -> usize { let mut value = 0; let mut chars = konst::string::char_indices(digits); @@ -82,7 +92,6 @@ impl<'a> Token<'a> { } value } - pub const fn digit (c: char) -> usize { match c { '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9, _ => panic!("not a digit") } diff --git a/edn/src/try_from_edn.rs b/edn/src/try_from_edn.rs index 23c64965..d71ba9cb 100644 --- a/edn/src/try_from_edn.rs +++ b/edn/src/try_from_edn.rs @@ -1,6 +1,6 @@ use crate::*; pub trait TryFromEdn<'a, T>: Sized { - fn try_from_edn (state: &'a T, head: &EdnItem, tail: &'a [EdnItem]) -> + fn try_from_edn (state: &'a T, head: &EdnItem>, tail: &'a [EdnItem>]) -> Option; } diff --git a/input/src/edn_input.rs b/input/src/edn_input.rs index d5b58930..d43809d6 100644 --- a/input/src/edn_input.rs +++ b/input/src/edn_input.rs @@ -1,16 +1,20 @@ use crate::*; +use std::sync::Arc; pub trait EdnInput: Input { fn matches_edn (&self, token: &str) -> bool; - fn get_event > (_: &EdnItem) -> Option { + fn get_event (_: &EdnItem>) -> Option { None } } /// Turns an EDN item sequence into a command enum variant. pub trait EdnCommand: Command { - fn from_edn <'a> (state: &C, head: &EdnItem, tail: &'a [EdnItem]) - -> Option; + fn from_edn <'a> ( + state: &C, + head: &EdnItem>, + tail: &'a [EdnItem>] + ) -> Option; } /** Implement `EdnCommand` for given `State` and `Command` */ @@ -39,15 +43,15 @@ pub trait EdnCommand: Command { impl<$T: $Trait> EdnCommand<$T> for $Command { fn from_edn <'a> ( $state: &$T, - head: &EdnItem, - tail: &'a [EdnItem] + head: &EdnItem>, + tail: &'a [EdnItem>] ) -> Option { $(if let (EdnItem::Key($key), [ // if the identifier matches // bind argument ids $($arg),* // bind rest parameters $(, $rest @ ..)? - ]) = (head, tail) { + ]) = (head.to_ref(), tail) { $( $(let $arg: Option<$type> = EdnProvide::<$type>::get($state, $arg);)? )* @@ -81,14 +85,16 @@ pub trait EdnCommand: Command { ))* }) => { impl EdnCommand<$State> for $Command { fn from_edn <'a> ( - $state: &$State, head: &EdnItem, tail: &'a [EdnItem] + $state: &$State, + head: &EdnItem>, + tail: &'a [EdnItem>], ) -> Option { $(if let (EdnItem::Key($key), [ // if the identifier matches // bind argument ids $($arg),* // bind rest parameters $(, $rest @ ..)? - ]) = (head, tail) { + ]) = (head.to_ref(), tail) { $( $(let $arg: Option<$type> = EdnProvide::<$type>::get($state, $arg);)? )* @@ -107,7 +113,7 @@ pub trait EdnCommand: Command { }; } -pub struct EdnKeyMapToCommand(Vec); +pub struct EdnKeyMapToCommand(Vec>>); impl EdnKeyMapToCommand { /// Construct keymap from source text or fail pub fn new (keymap: &str) -> Usually { diff --git a/midi/src/midi_edit.rs b/midi/src/midi_edit.rs index 0cb77c83..24a8da3b 100644 --- a/midi/src/midi_edit.rs +++ b/midi/src/midi_edit.rs @@ -210,7 +210,7 @@ edn_command!(MidiEditCommand: |state: MidiEditor| { impl MidiEditCommand { fn from_tui_event (state: &MidiEditor, input: &impl EdnInput) -> Usually> { use EdnItem::*; - let edns = EdnItem::<&str>::read_all(KEYS_EDIT)?; + let edns = EdnItem::read_all(KEYS_EDIT)?; for item in edns.iter() { if let Exp(e) = item { match e.as_slice() { diff --git a/midi/src/midi_pool.rs b/midi/src/midi_pool.rs index 0372575e..e1901714 100644 --- a/midi/src/midi_pool.rs +++ b/midi/src/midi_pool.rs @@ -192,7 +192,7 @@ content!(TuiOut: |self: ClipLength| { impl PoolCommand { pub fn from_tui_event (state: &MidiPool, input: &impl EdnInput) -> Usually> { use EdnItem::*; - let edns: Vec = EdnItem::read_all(match state.mode() { + let edns: Vec> = EdnItem::read_all(match state.mode() { Some(PoolMode::Rename(..)) => KEYS_RENAME, Some(PoolMode::Length(..)) => KEYS_LENGTH, Some(PoolMode::Import(..)) | Some(PoolMode::Export(..)) => KEYS_FILE, diff --git a/output/src/edn_view.rs b/output/src/edn_view.rs index 97c38e12..1ab4768c 100644 --- a/output/src/edn_view.rs +++ b/output/src/edn_view.rs @@ -1,7 +1,11 @@ use crate::*; -use std::marker::PhantomData; +use std::{sync::Arc, marker::PhantomData}; use EdnItem::*; - +/// Define an EDN-backed view. +/// +/// This consists of: +/// * render callback (implementation of [Content]) +/// * value providers (implementations of [EdnProvide]) #[macro_export] macro_rules! edn_view { ($Output:ty: |$self:ident: $App:ty| $content:expr; { $( $type:ty { $($sym:literal => $value:expr),* } );* @@ -11,19 +15,18 @@ use EdnItem::*; } $( impl<'a> EdnProvide<'a, $type> for $App { - fn get > (&'a $self, edn: &'a EdnItem) -> Option<$type> { + fn get (&'a $self, edn: &'a EdnItem>) -> Option<$type> { Some(match edn.to_ref() { $(EdnItem::Sym($sym) => $value,)* _ => return None }) } } )* } } - /// Implements `EdnProvide` for content components and expressions #[macro_export] macro_rules! edn_provide_content { (|$self:ident:$State:ty|{ $($pat:pat => $expr:expr),* $(,)? }) => { impl<'a, E: Output> EdnProvide<'a, Box + 'a>> for $State { - fn get > (&'a $self, edn: &'a EdnItem) -> Option + 'a>> { + fn get (&'a $self, edn: &'a EdnItem>) -> Option + 'a>> { Some(match edn.to_ref() { $(EdnItem::Sym($pat) => $expr),*, _ => return None @@ -33,7 +36,7 @@ use EdnItem::*; }; ($Output:ty: |$self:ident:$State:ty|{ $($pat:pat => $expr:expr),* $(,)? }) => { impl<'a> EdnProvide<'a, Box + 'a>> for $State { - fn get > (&'a $self, edn: &'a EdnItem) -> Option + 'a>> { + fn get (&'a $self, edn: &'a EdnItem>) -> Option + 'a>> { Some(match edn.to_ref() { $(EdnItem::Sym($pat) => $expr),*, _ => return None @@ -45,7 +48,7 @@ use EdnItem::*; /// Renders from EDN source and context. #[derive(Default)] pub enum EdnView<'a, E: Output, T: EdnViewData<'a, E> + std::fmt::Debug> { #[default] Inert, - Ok(T, EdnItem), + Ok(T, EdnItem>), //render: BoxBox + Send + Sync + 'a> + Send + Sync + 'a> Err(String), _Unused(PhantomData<&'a E>), @@ -76,8 +79,8 @@ impl<'a, E: Output, T: EdnViewData<'a, E> + std::fmt::Debug> EdnView<'a, E, T> { Err(error) => Self::Err(format!("{error} in {source}")) } } - pub fn from_items (state: T, items: Vec) -> Self { - Self::Ok(state, EdnItem::Exp(items)) + pub fn from_items (state: T, items: Vec>>) -> Self { + Self::Ok(state, EdnItem::Exp(items).to_arc()) } } implEdnViewData<'a, E> + Send + Sync + std::fmt::Debug> Content for EdnView<'_, E, T> { @@ -110,7 +113,7 @@ pub trait EdnViewData<'a, E: Output>: EdnProvide<'a, E::Unit> + EdnProvide<'a, Box + 'a>> { - fn get_bool (&'a self, item: &'a EdnItem) -> Option { + fn get_bool (&'a self, item: &'a EdnItem>) -> Option { Some(match &item { Sym(s) => match s.as_ref() { ":false" | ":f" => false, @@ -122,13 +125,13 @@ pub trait EdnViewData<'a, E: Output>: _ => return EdnProvide::get(self, item) }) } - fn get_usize (&'a self, item: &'a EdnItem) -> Option { + fn get_usize (&'a self, item: &'a EdnItem>) -> Option { Some(match &item { Num(n) => *n, _ => return EdnProvide::get(self, item) }) } - fn get_unit (&'a self, item: &'a EdnItem) -> Option { + fn get_unit (&'a self, item: &'a EdnItem>) -> Option { Some(match &item { Num(n) => (*n as u16).into(), _ => return EdnProvide::get(self, item) }) } - fn get_content (&'a self, item: &'a EdnItem) -> Option + 'a>> where E: 'a { + fn get_content (&'a self, item: &'a EdnItem>) -> Option + 'a>> where E: 'a { Some(match item { Nil => Box::new(()), Exp(ref e) => { diff --git a/output/src/either.rs b/output/src/either.rs deleted file mode 100644 index a104669c..00000000 --- a/output/src/either.rs +++ /dev/null @@ -1,33 +0,0 @@ -use crate::*; -/// Show one item if a condition is true and another if the condition is false -pub struct Either(pub PhantomData, pub bool, pub A, pub B); -impl Either { - pub fn new (c: bool, a: A, b: B) -> Self { - Self(Default::default(), c, a, b) - } -} -impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for Either, RenderBox<'a, E>> { - fn try_from_edn (state: &'a T, head: &EdnItem, tail: &'a [EdnItem]) -> Option { - use EdnItem::*; - if let (Key("either"), [condition, content, alternative]) = (head, tail) { - Some(Self::new( - state.get_bool(condition).expect("either: no condition"), - state.get_content(content).expect("either: no content"), - state.get_content(alternative).expect("either: no alternative") - )) - } else { - None - } - } -} -impl, B: Render> Content for Either { - fn layout (&self, to: E::Area) -> E::Area { - let Self(_, cond, a, b) = self; - if *cond { a.layout(to) } else { b.layout(to) } - } - fn render (&self, to: &mut E) { - let Self(_, cond, a, b) = self; - if *cond { a.render(to) } else { b.render(to) } - } -} - diff --git a/output/src/lib.rs b/output/src/lib.rs index 7fc745c7..54e0bd90 100644 --- a/output/src/lib.rs +++ b/output/src/lib.rs @@ -1,38 +1,25 @@ //#![feature(lazy_type_alias)] #![feature(type_alias_impl_trait)] #![feature(impl_trait_in_assoc_type)] - -mod coordinate; pub use self::coordinate::*; -mod size; pub use self::size::*; -mod area; pub use self::area::*; - -mod output; pub use self::output::*; -mod thunk; pub use self::thunk::*; - -mod when; pub use self::when::*; -mod either; pub use self::either::*; -mod map; pub use self::map::*; -mod reduce; pub use self::reduce::*; - -mod align; pub use self::align::*; -mod direction; pub use self::direction::*; -mod measure; pub use self::measure::*; -mod transform_xy; pub use self::transform_xy::*; -mod transform_xy_unit; pub use self::transform_xy_unit::*; - -mod edn_view; -pub use self::edn_view::*; -pub(crate) use ::tek_edn::*; - +mod coordinate; pub use self::coordinate::*; +mod size; pub use self::size::*; +mod area; pub use self::area::*; +mod output; pub use self::output::*; +mod measure; pub use self::measure::*; +mod thunk; pub use self::thunk::*; +mod op_cond; pub use self::op_cond::*; +mod op_iter; pub use self::op_iter::*; +mod op_align; pub use self::op_align::*; +mod op_bsp; pub use self::op_bsp::*; +mod op_transform; pub use self::op_transform::*; +mod edn_view; pub use self::edn_view::*; pub(crate) use std::marker::PhantomData; pub(crate) use std::error::Error; - +pub(crate) use ::tek_edn::*; /// Standard result type. pub type Usually = Result>; - /// Standard optional result type. pub type Perhaps = Result, Box>; - #[cfg(test)] #[test] fn test_stub_output () -> Usually<()> { use crate::*; struct TestOutput([u16;4]); @@ -57,12 +44,10 @@ pub type Perhaps = Result, Box>; } Ok(()) } - #[cfg(test)] #[test] fn test_dimensions () { use crate::*; assert_eq!(Area::center(&[10u16, 10, 20, 20]), [20, 20]); } - #[cfg(test)] #[test] fn test_layout () -> Usually<()> { use ::tek_tui::{*, tek_output::*}; let area: [u16;4] = [10, 10, 20, 20]; diff --git a/output/src/align.rs b/output/src/op_align.rs similarity index 91% rename from output/src/align.rs rename to output/src/op_align.rs index c56757e6..c4efc29e 100644 --- a/output/src/align.rs +++ b/output/src/op_align.rs @@ -1,6 +1,5 @@ use crate::*; -#[derive(Debug, Copy, Clone, Default)] -pub enum Alignment { #[default] Center, X, Y, NW, N, NE, E, SE, S, SW, W } +#[derive(Debug, Copy, Clone, Default)] pub enum Alignment { #[default] Center, X, Y, NW, N, NE, E, SE, S, SW, W } pub struct Align(PhantomData, Alignment, A); impl Align { pub fn c (a: A) -> Self { Self(Default::default(), Alignment::Center, a) } @@ -46,9 +45,13 @@ impl> Content for Align { } } impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for Align> { - fn try_from_edn (state: &'a T, head: &EdnItem, tail: &'a [EdnItem]) -> Option { + fn try_from_edn ( + state: &'a T, + head: &EdnItem>, + tail: &'a [EdnItem>] + ) -> Option { use EdnItem::*; - Some(match (head, tail) { + Some(match (head.to_ref(), tail) { (Key("align/c"), [a]) => Self::c(state.get_content(a).expect("no content")), (Key("align/x"), [a]) => Self::x(state.get_content(a).expect("no content")), (Key("align/y"), [a]) => Self::y(state.get_content(a).expect("no content")), diff --git a/output/src/direction.rs b/output/src/op_bsp.rs similarity index 86% rename from output/src/direction.rs rename to output/src/op_bsp.rs index 0cbff8a6..371b9fbd 100644 --- a/output/src/direction.rs +++ b/output/src/op_bsp.rs @@ -15,6 +15,7 @@ impl Direction { } } } +/// A split or layer. pub struct Bsp(PhantomData, Direction, X, Y); impl, B: Content> Content for Bsp { fn layout (&self, outer: E::Area) -> E::Area { @@ -92,27 +93,27 @@ impl, B: Content> BspAreas for Bsp fn contents (&self) -> (&A, &B) { (&self.2, &self.3) } } impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for Bsp, RenderBox<'a, E>> { - fn try_from_edn (s: &'a T, head: &EdnItem, tail: &'a [EdnItem]) -> Option { + fn try_from_edn (s: &'a T, head: &EdnItem>, tail: &'a [EdnItem>]) -> Option { use EdnItem::*; - Some(match (head, tail) { + Some(match (head.to_ref(), tail) { (Key("bsp/n"), [a, b]) => Self::n( - s.get_content(a).expect("no a"), - s.get_content(b).expect("no b")), + s.get_content(a).expect("no south"), + s.get_content(b).expect("no north")), (Key("bsp/s"), [a, b]) => Self::s( - s.get_content(a).expect("no a"), - s.get_content(b).expect("no b")), + s.get_content(a).expect("no north"), + s.get_content(b).expect("no south")), (Key("bsp/e"), [a, b]) => Self::e( - s.get_content(a).expect("no a"), - s.get_content(b).expect("no b")), + s.get_content(a).expect("no west"), + s.get_content(b).expect("no east")), (Key("bsp/w"), [a, b]) => Self::w( - s.get_content(a).expect("no a"), - s.get_content(b).expect("no b")), + s.get_content(a).expect("no east"), + s.get_content(b).expect("no west")), (Key("bsp/a"), [a, b]) => Self::a( - s.get_content(a).expect("no a"), - s.get_content(b).expect("no b")), + s.get_content(a).expect("no above"), + s.get_content(b).expect("no below")), (Key("bsp/b"), [a, b]) => Self::b( - s.get_content(a).expect("no a"), - s.get_content(b).expect("no b")), + s.get_content(a).expect("no above"), + s.get_content(b).expect("no below")), _ => return None }) } diff --git a/output/src/op_cond.rs b/output/src/op_cond.rs new file mode 100644 index 00000000..c3c2a4b0 --- /dev/null +++ b/output/src/op_cond.rs @@ -0,0 +1,74 @@ +use crate::*; +/// Show an item only when a condition is true. +pub struct When(pub PhantomData, pub bool, pub A); +impl When { + pub fn new (c: bool, a: A) -> Self { + Self(Default::default(), c, a) + } +} +impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for When> { + fn try_from_edn ( + state: &'a T, head: &EdnItem>, tail: &'a [EdnItem>] + ) -> Option { + use EdnItem::*; + if let (Key("when"), [condition, content]) = (head.to_ref(), tail) { + Some(Self( + Default::default(), + state.get_bool(condition).expect("when: no condition"), + state.get_content(content).expect("when: no content") + )) + } else { + None + } + } +} +impl> Content for When { + fn layout (&self, to: E::Area) -> E::Area { + let Self(_, cond, item) = self; + let mut area = E::Area::zero(); + if *cond { + let item_area = item.layout(to); + area[0] = item_area.x(); + area[1] = item_area.y(); + area[2] = item_area.w(); + area[3] = item_area.h(); + } + area.into() + } + fn render (&self, to: &mut E) { + let Self(_, cond, item) = self; + if *cond { item.render(to) } + } +} +/// Show one item if a condition is true and another if the condition is false +pub struct Either(pub PhantomData, pub bool, pub A, pub B); +impl Either { + pub fn new (c: bool, a: A, b: B) -> Self { + Self(Default::default(), c, a, b) + } +} +impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for Either, RenderBox<'a, E>> { + fn try_from_edn (state: &'a T, head: &EdnItem>, tail: &'a [EdnItem>]) -> Option { + use EdnItem::*; + if let (Key("either"), [condition, content, alternative]) = (head.to_ref(), tail) { + Some(Self::new( + state.get_bool(condition).expect("either: no condition"), + state.get_content(content).expect("either: no content"), + state.get_content(alternative).expect("either: no alternative") + )) + } else { + None + } + } +} +impl, B: Render> Content for Either { + fn layout (&self, to: E::Area) -> E::Area { + let Self(_, cond, a, b) = self; + if *cond { a.layout(to) } else { b.layout(to) } + } + fn render (&self, to: &mut E) { + let Self(_, cond, a, b) = self; + if *cond { a.render(to) } else { b.render(to) } + } +} + diff --git a/output/src/map.rs b/output/src/op_iter.rs similarity index 100% rename from output/src/map.rs rename to output/src/op_iter.rs diff --git a/output/src/transform_xy_unit.rs b/output/src/op_transform.rs similarity index 69% rename from output/src/transform_xy_unit.rs rename to output/src/op_transform.rs index 30209da6..06ff1db6 100644 --- a/output/src/transform_xy_unit.rs +++ b/output/src/op_transform.rs @@ -1,5 +1,46 @@ use crate::*; - +/// Defines an enum that transforms its content +/// along either the X axis, the Y axis, or both. +/// +/// The `_Unused` variant wraps the `Output` type +/// using `PhantomData` to permit the double generic. +macro_rules! transform_xy { + ($x:literal $y:literal $xy:literal |$self:ident : $Enum:ident, $to:ident|$area:expr) => { + pub enum $Enum { _Unused(PhantomData), X(T), Y(T), XY(T) } + impl $Enum { + pub fn x (item: T) -> Self { Self::X(item) } + pub fn y (item: T) -> Self { Self::Y(item) } + pub fn xy (item: T) -> Self { Self::XY(item) } + } + impl> Content for $Enum { + fn content (&self) -> impl Render { + match self { + Self::X(item) => item, + Self::Y(item) => item, + Self::XY(item) => item, + _ => unreachable!(), + } + } + fn layout (&$self, $to: ::Area) -> ::Area { + use $Enum::*; + $area + } + } + impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for $Enum> { + fn try_from_edn ( + state: &'a T, head: &EdnItem>, tail: &'a [EdnItem>] + ) -> Option { + use EdnItem::*; + Some(match (head.to_ref(), tail) { + (Key($x), [a]) => Self::x(state.get_content(a).expect("no content")), + (Key($y), [a]) => Self::y(state.get_content(a).expect("no content")), + (Key($xy), [a]) => Self::xy(state.get_content(a).expect("no content")), + _ => return None + }) + } + } + } +} /// Defines an enum that parametrically transforms its content /// along either the X axis, the Y axis, or both. macro_rules! transform_xy_unit { @@ -43,10 +84,10 @@ macro_rules! transform_xy_unit { } impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for $Enum> { fn try_from_edn ( - state: &'a T, head: &EdnItem, tail: &'a [EdnItem] + state: &'a T, head: &EdnItem>, tail: &'a [EdnItem>] ) -> Option { use EdnItem::*; - Some(match (head, tail) { + Some(match (head.to_ref(), tail) { (Key($x), [x, a]) => Self::x( state.get_unit(x).expect("no x"), state.get_content(a).expect("no content"), @@ -66,7 +107,16 @@ macro_rules! transform_xy_unit { } } } - +transform_xy!("fill/x" "fill/y" "fill/xy" |self: Fill, to|{ + let [x0, y0, wmax, hmax] = to.xywh(); + let [x, y, w, h] = self.content().layout(to).xywh(); + match self { + X(_) => [x0, y, wmax, h], + Y(_) => [x, y0, w, hmax], + XY(_) => [x0, y0, wmax, hmax], + _ => unreachable!() + }.into() +}); transform_xy_unit!("fixed/x" "fixed/y" "fixed/xy"|self: Fixed, area|{ let [x, y, w, h] = area.xywh(); let fixed_area = match self { diff --git a/output/src/transform_xy.rs b/output/src/transform_xy.rs deleted file mode 100644 index 697fbfb6..00000000 --- a/output/src/transform_xy.rs +++ /dev/null @@ -1,55 +0,0 @@ -use crate::*; - -/// Defines an enum that transforms its content -/// along either the X axis, the Y axis, or both. -/// -/// The `_Unused` variant wraps the `Output` type -/// using `PhantomData` to permit the double generic. -macro_rules! transform_xy { - ($x:literal $y:literal $xy:literal |$self:ident : $Enum:ident, $to:ident|$area:expr) => { - pub enum $Enum { _Unused(PhantomData), X(T), Y(T), XY(T) } - impl $Enum { - pub fn x (item: T) -> Self { Self::X(item) } - pub fn y (item: T) -> Self { Self::Y(item) } - pub fn xy (item: T) -> Self { Self::XY(item) } - } - impl> Content for $Enum { - fn content (&self) -> impl Render { - match self { - Self::X(item) => item, - Self::Y(item) => item, - Self::XY(item) => item, - _ => unreachable!(), - } - } - fn layout (&$self, $to: ::Area) -> ::Area { - use $Enum::*; - $area - } - } - impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for $Enum> { - fn try_from_edn ( - state: &'a T, head: &EdnItem, tail: &'a [EdnItem] - ) -> Option { - use EdnItem::*; - Some(match (head, tail) { - (Key($x), [a]) => Self::x(state.get_content(a).expect("no content")), - (Key($y), [a]) => Self::y(state.get_content(a).expect("no content")), - (Key($xy), [a]) => Self::xy(state.get_content(a).expect("no content")), - _ => return None - }) - } - } - } -} - -transform_xy!("fill/x" "fill/y" "fill/xy" |self: Fill, to|{ - let [x0, y0, wmax, hmax] = to.xywh(); - let [x, y, w, h] = self.content().layout(to).xywh(); - match self { - X(_) => [x0, y, wmax, h], - Y(_) => [x, y0, w, hmax], - XY(_) => [x0, y0, wmax, hmax], - _ => unreachable!() - }.into() -}); diff --git a/output/src/when.rs b/output/src/when.rs deleted file mode 100644 index 14649421..00000000 --- a/output/src/when.rs +++ /dev/null @@ -1,42 +0,0 @@ -use crate::*; -/// Show an item only when a condition is true. -pub struct When(pub PhantomData, pub bool, pub A); -impl When { - pub fn new (c: bool, a: A) -> Self { - Self(Default::default(), c, a) - } -} -impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for When> { - fn try_from_edn ( - state: &'a T, head: &EdnItem, tail: &'a [EdnItem] - ) -> Option { - use EdnItem::*; - if let (Key("when"), [condition, content]) = (head, tail) { - Some(Self( - Default::default(), - state.get_bool(condition).expect("when: no condition"), - state.get_content(content).expect("when: no content") - )) - } else { - None - } - } -} -impl> Content for When { - fn layout (&self, to: E::Area) -> E::Area { - let Self(_, cond, item) = self; - let mut area = E::Area::zero(); - if *cond { - let item_area = item.layout(to); - area[0] = item_area.x(); - area[1] = item_area.y(); - area[2] = item_area.w(); - area[3] = item_area.h(); - } - area.into() - } - fn render (&self, to: &mut E) { - let Self(_, cond, item) = self; - if *cond { item.render(to) } - } -} diff --git a/tek/src/lib.rs b/tek/src/lib.rs index 000b53bb..dbe7a624 100644 --- a/tek/src/lib.rs +++ b/tek/src/lib.rs @@ -161,7 +161,7 @@ has_editor!(|self: Tek|{ }; editor_h = 15; is_editing = self.editing.load(Relaxed); }); -edn_provide!(# usize: |self: Tek| { +edn_provide_num!(usize: |self: Tek| { ":scene" => self.selected.scene().unwrap_or(0), ":scene-next" => (self.selected.scene().unwrap_or(0) + 1).min(self.scenes.len()), ":scene-prev" => self.selected.scene().unwrap_or(0).saturating_sub(1), diff --git a/time/src/clock.rs b/time/src/clock.rs index 4c37274c..772053d6 100644 --- a/time/src/clock.rs +++ b/time/src/clock.rs @@ -22,7 +22,7 @@ pub enum ClockCommand { SetQuant(f64), SetSync(f64), } -edn_provide!(# u32: |self: Clock| {}); +edn_provide_num!(u32: |self: Clock| {}); edn_provide!(f64: |self: Clock| {}); edn_command!(ClockCommand: |state: Clock| { ("play" [] Self::Play(None)) diff --git a/tui/src/tui_input.rs b/tui/src/tui_input.rs index 10ae3705..1d23dea5 100644 --- a/tui/src/tui_input.rs +++ b/tui/src/tui_input.rs @@ -54,7 +54,7 @@ impl EdnInput for TuiIn { false } } - fn get_event (item: &EdnItem) -> Option { + fn get_event (item: &EdnItem>) -> Option { match item { EdnItem::Sym(s) => KeyMatcher::new(s).build(), _ => None } } }