generalize EdnItem.

maybe should rename it to Atom? ~90 instances of it
This commit is contained in:
🪞👃🪞 2025-01-17 19:47:35 +01:00
parent 1b9da07280
commit 143cd24e09
20 changed files with 314 additions and 286 deletions

View file

@ -1,14 +1,34 @@
use crate::*;
use std::sync::Arc;
#[derive(Default, Clone, PartialEq)] pub enum EdnItem {
#[derive(Default, Clone, PartialEq)] pub enum EdnItem<T> {
#[default] Nil,
Num(usize),
Sym(Arc<str>),
Key(Arc<str>),
Exp(Vec<EdnItem>),
Sym(T),
Key(T),
Exp(Vec<EdnItem<T>>),
}
impl EdnItem {
pub fn read_all (mut source: &str) -> Result<Vec<Self>, ParseError> {
impl<'a, T: 'a> EdnItem<T> {
pub fn transform <U: 'a, F: Fn(&'a T)->U + Clone> (&'a self, f: F) -> EdnItem<U> {
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<str>> EdnItem<T> {
pub fn to_ref (&'a self) -> EdnItem<&'a str> {
self.transform(|t|t.as_ref())
}
pub fn to_arc (&'a self) -> EdnItem<Arc<str>> {
self.transform(|t|t.as_ref().into())
}
}
impl<'a> EdnItem<Arc<str>> {
pub fn read_all (mut source: &'a str) -> Result<Vec<Self>, 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<Self, ParseError> {
use Token::*;
pub fn read (token: Token<'a>) -> Result<Self, ParseError> {
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<T: Debug> Debug for EdnItem<T> {
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<T: Display> Display for EdnItem<T> {
fn fmt (&self, f: &mut Formatter<'_>) -> Result<(), FormatError> {
use EdnItem::*;
use itertools::join;
@ -71,18 +87,3 @@ impl Display for EdnItem {
}
}
}
impl<'a> TryFrom<Token<'a>> for EdnItem {
type Error = ParseError;
fn try_from (token: Token<'a>) -> Result<Self, Self::Error> {
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")
})
}
}

View file

@ -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<impl AsRef<str>>) -> Option<U> {
None
}
fn get_or_fail (&'a self, edn: &'a EdnItem<impl AsRef<str>>) -> 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<impl AsRef<str>>) -> Option<U> {
(*self).get(edn)
}
fn get_or_fail (&'a self, edn: &'a EdnItem<impl AsRef<str>>) -> U {
(*self).get_or_fail(edn)
}
}
impl<'a, T: EdnProvide<'a, U>, U> EdnProvide<'a, U> for Option<T> {
fn get (&'a self, edn: &'a EdnItem<impl AsRef<str>>) -> Option<U> {
self.as_ref().map(|s|s.get(edn)).flatten()
}
fn get_or_fail (&'a self, edn: &'a EdnItem<impl AsRef<str>>) -> 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<impl AsRef<str>>) -> 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<impl AsRef<str>>) -> 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<impl AsRef<str>>) -> 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<impl AsRef<str>>) -> 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<dyn Render<E> + 'a>> for $State {
fn get (&'a $self, edn: &'a EdnItem<impl AsRef<str>>) -> Option<Box<dyn Render<E> + '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<U> {
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<U> {
(*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<T> {
fn get (&'a self, edn: &'a EdnItem) -> Option<U> {
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<dyn Render<$Output> + 'a>> for $State {
fn get (&'a $self, edn: &'a EdnItem<impl AsRef<str>>) -> Option<Box<dyn Render<$Output> + 'a>> {
Some(match edn.to_ref() {
$(EdnItem::Sym($pat) => $expr),*,
_ => return None
})
}
}
}
}

View file

@ -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") }

View file

@ -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<impl AsRef<str>>, tail: &'a [EdnItem<impl AsRef<str>>]) ->
Option<Self>;
}

View file

@ -1,16 +1,20 @@
use crate::*;
use std::sync::Arc;
pub trait EdnInput: Input {
fn matches_edn (&self, token: &str) -> bool;
fn get_event <S: AsRef<str>> (_: &EdnItem) -> Option<Self::Event> {
fn get_event (_: &EdnItem<impl AsRef<str>>) -> Option<Self::Event> {
None
}
}
/// Turns an EDN item sequence into a command enum variant.
pub trait EdnCommand<C>: Command<C> {
fn from_edn <'a> (state: &C, head: &EdnItem, tail: &'a [EdnItem])
-> Option<Self>;
fn from_edn <'a> (
state: &C,
head: &EdnItem<impl AsRef<str>>,
tail: &'a [EdnItem<impl AsRef<str>>]
) -> Option<Self>;
}
/** Implement `EdnCommand` for given `State` and `Command` */
@ -39,15 +43,15 @@ pub trait EdnCommand<C>: Command<C> {
impl<$T: $Trait> EdnCommand<$T> for $Command {
fn from_edn <'a> (
$state: &$T,
head: &EdnItem,
tail: &'a [EdnItem]
head: &EdnItem<impl AsRef<str>>,
tail: &'a [EdnItem<impl AsRef<str>>]
) -> Option<Self> {
$(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<C>: Command<C> {
))* }) => {
impl EdnCommand<$State> for $Command {
fn from_edn <'a> (
$state: &$State, head: &EdnItem, tail: &'a [EdnItem]
$state: &$State,
head: &EdnItem<impl AsRef<str>>,
tail: &'a [EdnItem<impl AsRef<str>>],
) -> Option<Self> {
$(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<C>: Command<C> {
};
}
pub struct EdnKeyMapToCommand(Vec<EdnItem>);
pub struct EdnKeyMapToCommand(Vec<EdnItem<Arc<str>>>);
impl EdnKeyMapToCommand {
/// Construct keymap from source text or fail
pub fn new (keymap: &str) -> Usually<Self> {

View file

@ -210,7 +210,7 @@ edn_command!(MidiEditCommand: |state: MidiEditor| {
impl MidiEditCommand {
fn from_tui_event (state: &MidiEditor, input: &impl EdnInput) -> Usually<Option<Self>> {
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() {

View file

@ -192,7 +192,7 @@ content!(TuiOut: |self: ClipLength| {
impl PoolCommand {
pub fn from_tui_event (state: &MidiPool, input: &impl EdnInput) -> Usually<Option<Self>> {
use EdnItem::*;
let edns: Vec<EdnItem> = EdnItem::read_all(match state.mode() {
let edns: Vec<EdnItem<_>> = EdnItem::read_all(match state.mode() {
Some(PoolMode::Rename(..)) => KEYS_RENAME,
Some(PoolMode::Length(..)) => KEYS_LENGTH,
Some(PoolMode::Import(..)) | Some(PoolMode::Export(..)) => KEYS_FILE,

View file

@ -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 <S: AsRef<str>> (&'a $self, edn: &'a EdnItem) -> Option<$type> {
fn get (&'a $self, edn: &'a EdnItem<impl AsRef<str>>) -> 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<dyn Render<E> + 'a>> for $State {
fn get <S: AsRef<str>> (&'a $self, edn: &'a EdnItem) -> Option<Box<dyn Render<E> + 'a>> {
fn get (&'a $self, edn: &'a EdnItem<impl AsRef<str>>) -> Option<Box<dyn Render<E> + '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<dyn Render<$Output> + 'a>> for $State {
fn get <S: AsRef<str>> (&'a $self, edn: &'a EdnItem) -> Option<Box<dyn Render<$Output> + 'a>> {
fn get (&'a $self, edn: &'a EdnItem<impl AsRef<str>>) -> Option<Box<dyn Render<$Output> + '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<Arc<str>>),
//render: Box<dyn Fn(&'a T)->Box<dyn Render<E> + 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<EdnItem>) -> Self {
Self::Ok(state, EdnItem::Exp(items))
pub fn from_items (state: T, items: Vec<EdnItem<impl AsRef<str>>>) -> Self {
Self::Ok(state, EdnItem::Exp(items).to_arc())
}
}
impl<E: Output, T: for<'a>EdnViewData<'a, E> + Send + Sync + std::fmt::Debug> Content<E> for EdnView<'_, E, T> {
@ -110,7 +113,7 @@ pub trait EdnViewData<'a, E: Output>:
EdnProvide<'a, E::Unit> +
EdnProvide<'a, Box<dyn Render<E> + 'a>>
{
fn get_bool (&'a self, item: &'a EdnItem) -> Option<bool> {
fn get_bool (&'a self, item: &'a EdnItem<impl AsRef<str>>) -> Option<bool> {
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<usize> {
fn get_usize (&'a self, item: &'a EdnItem<impl AsRef<str>>) -> Option<usize> {
Some(match &item { Num(n) => *n, _ => return EdnProvide::get(self, item) })
}
fn get_unit (&'a self, item: &'a EdnItem) -> Option<E::Unit> {
fn get_unit (&'a self, item: &'a EdnItem<impl AsRef<str>>) -> Option<E::Unit> {
Some(match &item { Num(n) => (*n as u16).into(), _ => return EdnProvide::get(self, item) })
}
fn get_content (&'a self, item: &'a EdnItem) -> Option<Box<dyn Render<E> + 'a>> where E: 'a {
fn get_content (&'a self, item: &'a EdnItem<impl AsRef<str>>) -> Option<Box<dyn Render<E> + 'a>> where E: 'a {
Some(match item {
Nil => Box::new(()),
Exp(ref e) => {

View file

@ -1,33 +0,0 @@
use crate::*;
/// Show one item if a condition is true and another if the condition is false
pub struct Either<E, A, B>(pub PhantomData<E>, pub bool, pub A, pub B);
impl<E, A, B> Either<E, A, B> {
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<E, RenderBox<'a, E>, RenderBox<'a, E>> {
fn try_from_edn (state: &'a T, head: &EdnItem, tail: &'a [EdnItem]) -> Option<Self> {
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<E: Output, A: Render<E>, B: Render<E>> Content<E> for Either<E, A, B> {
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) }
}
}

View file

@ -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<T> = Result<T, Box<dyn Error>>;
/// Standard optional result type.
pub type Perhaps<T> = Result<Option<T>, Box<dyn Error>>;
#[cfg(test)] #[test] fn test_stub_output () -> Usually<()> {
use crate::*;
struct TestOutput([u16;4]);
@ -57,12 +44,10 @@ pub type Perhaps<T> = Result<Option<T>, Box<dyn Error>>;
}
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];

View file

@ -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<E, A>(PhantomData<E>, Alignment, A);
impl<E, A> Align<E, A> {
pub fn c (a: A) -> Self { Self(Default::default(), Alignment::Center, a) }
@ -46,9 +45,13 @@ impl<E: Output, A: Content<E>> Content<E> for Align<E, A> {
}
}
impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for Align<E, RenderBox<'a, E>> {
fn try_from_edn (state: &'a T, head: &EdnItem, tail: &'a [EdnItem]) -> Option<Self> {
fn try_from_edn (
state: &'a T,
head: &EdnItem<impl AsRef<str>>,
tail: &'a [EdnItem<impl AsRef<str>>]
) -> Option<Self> {
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")),

View file

@ -15,6 +15,7 @@ impl Direction {
}
}
}
/// A split or layer.
pub struct Bsp<E, X, Y>(PhantomData<E>, Direction, X, Y);
impl<E: Output, A: Content<E>, B: Content<E>> Content<E> for Bsp<E, A, B> {
fn layout (&self, outer: E::Area) -> E::Area {
@ -92,27 +93,27 @@ impl<E: Output, A: Content<E>, B: Content<E>> BspAreas<E, A, B> for Bsp<E, A, B>
fn contents (&self) -> (&A, &B) { (&self.2, &self.3) }
}
impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for Bsp<E, RenderBox<'a, E>, RenderBox<'a, E>> {
fn try_from_edn (s: &'a T, head: &EdnItem, tail: &'a [EdnItem]) -> Option<Self> {
fn try_from_edn (s: &'a T, head: &EdnItem<impl AsRef<str>>, tail: &'a [EdnItem<impl AsRef<str>>]) -> Option<Self> {
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
})
}

74
output/src/op_cond.rs Normal file
View file

@ -0,0 +1,74 @@
use crate::*;
/// Show an item only when a condition is true.
pub struct When<E, A>(pub PhantomData<E>, pub bool, pub A);
impl<E, A> When<E, A> {
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<E, RenderBox<'a, E>> {
fn try_from_edn (
state: &'a T, head: &EdnItem<impl AsRef<str>>, tail: &'a [EdnItem<impl AsRef<str>>]
) -> Option<Self> {
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<E: Output, A: Render<E>> Content<E> for When<E, A> {
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<E, A, B>(pub PhantomData<E>, pub bool, pub A, pub B);
impl<E, A, B> Either<E, A, B> {
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<E, RenderBox<'a, E>, RenderBox<'a, E>> {
fn try_from_edn (state: &'a T, head: &EdnItem<impl AsRef<str>>, tail: &'a [EdnItem<impl AsRef<str>>]) -> Option<Self> {
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<E: Output, A: Render<E>, B: Render<E>> Content<E> for Either<E, A, B> {
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) }
}
}

View file

@ -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<E, T> { _Unused(PhantomData<E>), X(T), Y(T), XY(T) }
impl<E, T> $Enum<E, T> {
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<E: Output, T: Content<E>> Content<E> for $Enum<E, T> {
fn content (&self) -> impl Render<E> {
match self {
Self::X(item) => item,
Self::Y(item) => item,
Self::XY(item) => item,
_ => unreachable!(),
}
}
fn layout (&$self, $to: <E as Output>::Area) -> <E as Output>::Area {
use $Enum::*;
$area
}
}
impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for $Enum<E, RenderBox<'a, E>> {
fn try_from_edn (
state: &'a T, head: &EdnItem<impl AsRef<str>>, tail: &'a [EdnItem<impl AsRef<str>>]
) -> Option<Self> {
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<E, E::Unit, RenderBox<'a, E>> {
fn try_from_edn (
state: &'a T, head: &EdnItem, tail: &'a [EdnItem]
state: &'a T, head: &EdnItem<impl AsRef<str>>, tail: &'a [EdnItem<impl AsRef<str>>]
) -> Option<Self> {
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 {

View file

@ -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<E, T> { _Unused(PhantomData<E>), X(T), Y(T), XY(T) }
impl<E, T> $Enum<E, T> {
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<E: Output, T: Content<E>> Content<E> for $Enum<E, T> {
fn content (&self) -> impl Render<E> {
match self {
Self::X(item) => item,
Self::Y(item) => item,
Self::XY(item) => item,
_ => unreachable!(),
}
}
fn layout (&$self, $to: <E as Output>::Area) -> <E as Output>::Area {
use $Enum::*;
$area
}
}
impl<'a, E: Output + 'a, T: EdnViewData<'a, E>> TryFromEdn<'a, T> for $Enum<E, RenderBox<'a, E>> {
fn try_from_edn (
state: &'a T, head: &EdnItem, tail: &'a [EdnItem]
) -> Option<Self> {
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()
});

View file

@ -1,42 +0,0 @@
use crate::*;
/// Show an item only when a condition is true.
pub struct When<E, A>(pub PhantomData<E>, pub bool, pub A);
impl<E, A> When<E, A> {
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<E, RenderBox<'a, E>> {
fn try_from_edn (
state: &'a T, head: &EdnItem, tail: &'a [EdnItem]
) -> Option<Self> {
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<E: Output, A: Render<E>> Content<E> for When<E, A> {
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) }
}
}

View file

@ -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),

View file

@ -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))

View file

@ -54,7 +54,7 @@ impl EdnInput for TuiIn {
false
}
}
fn get_event (item: &EdnItem) -> Option<Event> {
fn get_event (item: &EdnItem<impl AsRef<str>>) -> Option<Event> {
match item { EdnItem::Sym(s) => KeyMatcher::new(s).build(), _ => None }
}
}