wip: EdnItem -> Atom, rewrite tokenizer

This commit is contained in:
🪞👃🪞 2025-01-17 21:47:34 +01:00
parent 143cd24e09
commit ff31957fed
39 changed files with 477 additions and 376 deletions

View file

@ -1,12 +1,9 @@
default:
bacon -sj test
edn-view:
tui:
reset
cargo run --example edn-view
edn-keys:
reset
cargo run --example edn-keys
cargo run --example tui
test:
cargo test --workspace --exclude jack

11
edn/src/describe.rs Normal file
View file

@ -0,0 +1,11 @@
use crate::*;
pub trait TryFromEdn<'a, T>: Sized {
fn try_from_edn (state: &'a T, head: &Atom<impl AsRef<str>>, tail: &'a [Atom<impl AsRef<str>>]) ->
Option<Self>;
}
pub trait TryIntoEdn<'a, T>: Sized {
fn try_from_edn (state: &'a T, head: &Atom<impl AsRef<str>>, tail: &'a [Atom<impl AsRef<str>>]) ->
Option<Self>;
}

View file

@ -1,18 +0,0 @@
use crate::*;
#[derive(Debug)] pub enum ParseError {
Empty,
Incomplete,
Unexpected(char),
Code(u8),
}
impl std::fmt::Display for ParseError {
fn fmt (&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Self::Empty => write!(f, "empty"),
Self::Incomplete => write!(f, "incomplete"),
Self::Unexpected(c) => write!(f, "unexpected '{c}'"),
Self::Code(i) => write!(f, "error #{i}"),
}
}
}
impl std::error::Error for ParseError {}

View file

@ -1,89 +0,0 @@
use crate::*;
use std::sync::Arc;
#[derive(Default, Clone, PartialEq)] pub enum EdnItem<T> {
#[default] Nil,
Num(usize),
Sym(T),
Key(T),
Exp(Vec<EdnItem<T>>),
}
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 {
break
}
let (remaining, token) = Token::chomp(source)?;
match Self::read(token)? { Self::Nil => {}, item => items.push(item) };
source = remaining
}
Ok(items)
}
pub fn read_one (source: &'a str) -> Result<(Self, &'a str), ParseError> {
Ok({
if source.len() == 0 {
return Err(ParseError::Code(5))
}
let (remaining, token) = Token::chomp(source)?;
(Self::read(token)?, remaining)
})
}
pub fn read (token: Token<'a>) -> Result<Self, ParseError> {
use EdnItem::*;
Ok(match token {
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<T: Debug> Debug for EdnItem<T> {
fn fmt (&self, f: &mut Formatter<'_>) -> Result<(), FormatError> {
use EdnItem::*;
match self {
Nil => write!(f, "(nil)"),
Num(u) => write!(f, "(num {u})"),
Sym(u) => write!(f, "(sym {u:?})"),
Key(u) => write!(f, "(key {u:?})"),
Exp(e) => write!(f, "(exp {})",
itertools::join(e.iter().map(|i|format!("{:?}", i)), ","))
}
}
}
impl<T: Display> Display for EdnItem<T> {
fn fmt (&self, f: &mut Formatter<'_>) -> Result<(), FormatError> {
use EdnItem::*;
use itertools::join;
match self {
Nil => write!(f, ""),
Num(u) => write!(f, "{u}"),
Sym(u) => write!(f, "{u}"),
Key(u) => write!(f, "{u}"),
Exp(e) => write!(f, "({})", join(e.iter().map(|i|format!("{}", i)), " "))
}
}
}

View file

@ -1,99 +0,0 @@
use crate::*;
#[derive(Debug, Copy, Clone, Default, PartialEq)]
pub enum Token<'a> {
#[default] Nil,
Num(&'a str, usize, usize),
Sym(&'a str, usize, usize),
Key(&'a str, usize, usize),
Exp(&'a str, usize, usize, usize),
}
pub type ChompResult<'a> = Result<(&'a str, Token<'a>), ParseError>;
impl<'a> Token<'a> {
pub const fn chomp (source: &'a str) -> ChompResult<'a> {
use Token::*;
use konst::string::{split_at, char_indices};
let mut state = Self::Nil;
let mut chars = char_indices(source);
while let Some(((index, c), next)) = chars.next() {
state = match state {
// must begin expression
Nil => match c {
' '|'\n'|'\r'|'\t' => Nil,
'(' => Exp(source, index, 1, 1),
':'|'@' => Sym(source, index, 1),
'0'..='9' => Num(source, index, 1),
'a'..='z' => Key(source, index, 1),
_ => return Err(ParseError::Unexpected(c))
},
Num(_, _, 0) => unreachable!(),
Sym(_, _, 0) => unreachable!(),
Key(_, _, 0) => unreachable!(),
Num(source, index, length) => match c {
'0'..='9' => Num(source, index, length + 1),
' '|'\n'|'\r'|'\t' => return Ok((
split_at(source, index+length).1,
Num(source, index, length)
)),
_ => return Err(ParseError::Unexpected(c))
},
Sym(source, index, length) => match c {
'a'..='z'|'0'..='9'|'-' => Sym(source, index, length + 1),
' '|'\n'|'\r'|'\t' => return Ok((
split_at(source, index+length).1,
Sym(source, index, length)
)),
_ => return Err(ParseError::Unexpected(c))
},
Key(source, index, length) => match c {
'a'..='z'|'0'..='9'|'-'|'/' => Key(source, index, length + 1),
' '|'\n'|'\r'|'\t' => return Ok((
split_at(source, index+length).1,
Key(source, index, length)
)),
_ => return Err(ParseError::Unexpected(c))
},
Exp(source, index, length, 0) => match c {
' '|'\n'|'\r'|'\t' => return Ok((
split_at(source, index+length).1,
Exp(source, index, length, 0)
)),
_ => return Err(ParseError::Unexpected(c))
},
Exp(source, index, length, balance) => match c {
')' => Exp(source, index, length + 1, balance - 1),
'(' => Exp(source, index, length + 1, balance + 1),
_ => Exp(source, index, length + 1, balance)
},
};
chars = next
}
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);
while let Some(((_, c), next)) = chars.next() {
value = 10 * value + Self::digit(c);
chars = next
}
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,37 +1,39 @@
#![feature(type_alias_impl_trait)]
#![feature(impl_trait_in_fn_trait_return)]
mod edn_error; pub use self::edn_error::*;
mod edn_item; pub use self::edn_item::*;
//mod edn_iter; pub use self::edn_iter::*;
mod edn_token; pub use self::edn_token::*;
mod edn_provide; pub use self::edn_provide::*;
mod try_from_edn; pub use self::try_from_edn::*;
pub(crate) use std::{fmt::{Debug, Display, Formatter, Error as FormatError}};
#[cfg(test)] #[test] fn test_edn () -> Result<(), ParseError> {
use EdnItem::*;
assert_eq!(EdnItem::<String>::read_all("")?,
mod token; pub use self::token::*;
mod provide; pub use self::provide::*;
mod describe; pub use self::describe::*;
pub(crate) use std::fmt::{Debug, Display, Formatter, Error as FormatError};
pub(crate) use std::sync::Arc;
#[cfg(test)] #[test] fn test_lang () -> Result<(), ParseError> {
use Atom::*;
assert_eq!(Atom::read_all("")?,
vec![]);
assert_eq!(EdnItem::<String>::read_all(" ")?,
assert_eq!(Atom::read_all(" ")?,
vec![]);
assert_eq!(EdnItem::<String>::read_all("1234")?,
assert_eq!(Atom::read_all("1234")?,
vec![Num(1234)]);
assert_eq!(EdnItem::<String>::read_all("1234 5 67")?,
assert_eq!(Atom::read_all("1234 5 67")?,
vec![Num(1234), Num(5), Num(67)]);
assert_eq!(EdnItem::<String>::read_all("foo/bar")?,
assert_eq!(Atom::read_all("foo/bar")?,
vec![Key("foo/bar".into())]);
assert_eq!(EdnItem::<String>::read_all(":symbol")?,
assert_eq!(Atom::read_all(":symbol")?,
vec![Sym(":symbol".into())]);
assert_eq!(EdnItem::<String>::read_all(" foo/bar :baz 456")?,
assert_eq!(Atom::read_all(" foo/bar :baz 456")?,
vec![Key("foo/bar".into()), Sym(":baz".into()), Num(456)]);
assert_eq!(EdnItem::<String>::read_all(" (foo/bar :baz 456) ")?,
assert_eq!(Atom::read_all(" (foo/bar :baz 456) ")?,
vec![Exp(vec![Key("foo/bar".into()), Sym(":baz".into()), Num(456)])]);
Ok(())
}
#[cfg(test)] #[test] fn test_edn_layout () -> Result<(), ParseError> {
EdnItem::<String>::read_all(include_str!("../../output/examples/edn01.edn"))?;
EdnItem::<String>::read_all(include_str!("../../output/examples/edn02.edn"))?;
#[cfg(test)] #[test] fn test_lang_examples () -> Result<(), ParseError> {
for example in [
include_str!("../../tui/examples/edn01.edn"),
include_str!("../../tui/examples/edn02.edn"),
] {
let items = Atom::read_all(example)?;
//panic!("{layout:?}");
//let content = <dyn EdnViewData<::tek_engine::tui::Tui>>::from(&layout);
}
Ok(())
}
#[macro_export] macro_rules! from_edn {

View file

@ -1,26 +1,26 @@
use crate::*;
/// 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> {
fn get (&'a self, _edn: &'a Atom<impl AsRef<str>>) -> Option<U> {
None
}
fn get_or_fail (&'a self, edn: &'a EdnItem<impl AsRef<str>>) -> U {
fn get_or_fail (&'a self, edn: &'a Atom<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> {
fn get (&'a self, edn: &'a Atom<impl AsRef<str>>) -> Option<U> {
(*self).get(edn)
}
fn get_or_fail (&'a self, edn: &'a EdnItem<impl AsRef<str>>) -> U {
fn get_or_fail (&'a self, edn: &'a Atom<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> {
fn get (&'a self, edn: &'a Atom<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 {
fn get_or_fail (&'a self, edn: &'a Atom<impl AsRef<str>>) -> U {
self.as_ref().map(|s|s.get_or_fail(edn)).expect("no provider")
}
}
@ -29,8 +29,8 @@ impl<'a, T: EdnProvide<'a, U>, U> EdnProvide<'a, U> for Option<T> {
// 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<impl AsRef<str>>) -> Option<$type> {
use EdnItem::*;
fn get (&'a $self, edn: &'a Atom<impl AsRef<str>>) -> Option<$type> {
use Atom::*;
Some(match edn.to_ref() { $(Sym($pat) => $expr,)* _ => return None })
}
}
@ -38,8 +38,8 @@ impl<'a, T: EdnProvide<'a, U>, U> EdnProvide<'a, U> for Option<T> {
// 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<impl AsRef<str>>) -> Option<$type> {
use EdnItem::*;
fn get (&$lt $self, edn: &$lt Atom<impl AsRef<str>>) -> Option<$type> {
use Atom::*;
Some(match edn.to_ref() { $(Sym($pat) => $expr,)* _ => return None })
}
}
@ -52,8 +52,8 @@ impl<'a, T: EdnProvide<'a, U>, U> EdnProvide<'a, U> for Option<T> {
// 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),* $(,)? }) => {
impl<'a, $T: $Trait> EdnProvide<'a, $type> for $T {
fn get (&'a $self, edn: &'a EdnItem<impl AsRef<str>>) -> Option<$type> {
use EdnItem::*;
fn get (&'a $self, edn: &'a Atom<impl AsRef<str>>) -> Option<$type> {
use Atom::*;
Some(match edn.to_ref() { $(Sym($pat) => $expr,)* Num(n) => n as $type, _ => return None })
}
}
@ -61,8 +61,8 @@ impl<'a, T: EdnProvide<'a, U>, U> EdnProvide<'a, U> for Option<T> {
// 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),* $(,)? }) => {
impl<'a> EdnProvide<'a, $type> for $State {
fn get (&'a $self, edn: &'a EdnItem<impl AsRef<str>>) -> Option<$type> {
use EdnItem::*;
fn get (&'a $self, edn: &'a Atom<impl AsRef<str>>) -> Option<$type> {
use Atom::*;
Some(match edn.to_ref() { $(Sym($pat) => $expr,)* Num(n) => n as $type, _ => return None })
}
}
@ -74,9 +74,9 @@ impl<'a, T: EdnProvide<'a, U>, U> EdnProvide<'a, U> for Option<T> {
#[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>> {
fn get (&'a $self, edn: &'a Atom<impl AsRef<str>>) -> Option<Box<dyn Render<E> + 'a>> {
Some(match edn.to_ref() {
$(EdnItem::Sym($pat) => $expr),*,
$(Atom::Sym($pat) => $expr),*,
_ => return None
})
}
@ -84,9 +84,9 @@ impl<'a, T: EdnProvide<'a, U>, U> EdnProvide<'a, U> for Option<T> {
};
($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>> {
fn get (&'a $self, edn: &'a Atom<impl AsRef<str>>) -> Option<Box<dyn Render<$Output> + 'a>> {
Some(match edn.to_ref() {
$(EdnItem::Sym($pat) => $expr),*,
$(Atom::Sym($pat) => $expr),*,
_ => return None
})
}

299
edn/src/token.rs Normal file
View file

@ -0,0 +1,299 @@
use crate::*;
use konst::string::{split_at, str_range, char_indices};
use self::ParseError::*;
use self::TokenKind::*;
macro_rules! iterate {
($expr:expr => $arg: pat => $body:expr) => {
let mut iter = $expr;
while let Some(($arg, next)) = iter.next() {
$body;
iter = next;
}
}
}
#[derive(Debug)] pub enum ParseError { Unimplemented, Empty, Incomplete, Unexpected(char), Code(u8), }
impl std::fmt::Display for ParseError {
fn fmt (&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Unimplemented => write!(f, "unimplemented"),
Empty => write!(f, "empty"),
Incomplete => write!(f, "incomplete"),
Unexpected(c) => write!(f, "unexpected '{c}'"),
Code(i) => write!(f, "error #{i}"),
}
}
}
impl std::error::Error for ParseError {}
#[derive(Debug, Copy, Clone, Default, PartialEq)]
pub enum TokenKind { #[default] Nil, Num, Sym, Key, Exp }
#[derive(Debug, Copy, Clone, Default, PartialEq)]
pub struct Token<'a> {
source: &'a str,
kind: TokenKind,
start: usize,
length: usize,
depth: usize,
}
impl<'a> Token<'a> {
pub const fn new (
source: &'a str, kind: TokenKind, start: usize, length: usize, depth: usize
) -> Self {
Self { source, kind, start, length, depth }
}
pub const fn end (&self) -> usize { self.start + self.length }
pub const fn slice (&self) -> &str { str_range(self.source, self.start, self.end()) }
pub const fn kind (&self) -> TokenKind { Nil }
pub const fn grow (self) -> Self {
Self { length: self.length + 1, ..self }
}
pub const fn grow_in (self) -> Self {
Self { length: self.length + 1, depth: self.depth + 1, ..self }
}
pub const fn grow_out (self) -> Result<Self, ParseError> {
match self.depth {
0 => Err(Unexpected(')')),
d => Ok(Self { length: self.length + 1, depth: d - 1, ..self })
}
}
pub const fn chomp_first (source: &'a str) -> Result<Self, ParseError> {
match Self::chomp(source) {
Ok((token, _)) => match token.kind() { Nil => Err(Empty), _ => Ok(token) },
Err(e) => Err(e),
}
}
pub const fn chomp (src: &'a str) -> Result<(Self, &'a str), ParseError> {
let mut token: Token<'a> = Token::new(src, Nil, 0, 0, 0);
iterate!(char_indices(src) => (index, c) => token = match token.kind() {
Nil => match c {
'(' => Self::new(src, Exp, index, 1, 1),
':'|'@' => Self::new(src, Sym, index, 1, 0),
'0'..='9' => Self::new(src, Num, index, 1, 0),
'/'|'a'..='z' => Self::new(src, Key, index, 1, 0),
' '|'\n'|'\r'|'\t' => token.grow(),
_ => return Err(Unexpected(c))
},
Num => match c {
'0'..='9' => token.grow(),
' '|'\n'|'\r'|'\t' => return Ok((token, split_at(src, token.end()).1)),
_ => return Err(Unexpected(c))
},
Sym => match c {
'a'..='z'|'0'..='9'|'-' => token.grow(),
' '|'\n'|'\r'|'\t' => return Ok((token, split_at(src, token.end()).1)),
_ => return Err(Unexpected(c)),
},
Key => match c {
'a'..='z'|'0'..='9'|'-'|'/' => token.grow(),
' '|'\n'|'\r'|'\t' => return Ok((token, split_at(src, token.end()).1)),
_ => return Err(Unexpected(c))
},
Exp => match token.depth {
0 => match c {
' '|'\n'|'\r'|'\t' => return Ok((token, split_at(src, token.end()).1)),
_ => return Err(Unexpected(c))
},
_ => match c {
')' => match token.grow_out() {
Ok(token) => token,
Err(e) => return Err(e)
},
'(' => token.grow_in(),
_ => token.grow(),
}
},
});
Err(Empty)
}
pub const fn number (digits: &str) -> Result<usize, ParseError> {
let mut value = 0;
iterate!(char_indices(digits) => (_, c) => match Self::digit(c) {
Ok(digit) => value = 10 * value + digit,
Err(e) => return Err(e)
});
Ok(value)
}
pub const fn digit (c: char) -> Result<usize, ParseError> {
Ok(match c {
'0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4,
'5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9,
_ => return Err(Unexpected(c))
})
}
pub const fn to_ref_atom (&'a self) -> Result<Atom<&'a str>, ParseError> {
Ok(match self.kind {
Nil => return Err(ParseError::Empty),
Num => match Self::number(self.slice()) {
Ok(n) => Atom::Num(n),
Err(e) => return Err(e)
},
Sym => Atom::Sym(self.slice()),
Key => Atom::Key(self.slice()),
Exp => todo!()
})
}
pub fn to_arc_atom (&self) -> Result<Atom<Arc<str>>, ParseError> {
Ok(match self.kind {
Nil => return Err(ParseError::Empty),
Num => match Self::number(self.slice()) {
Ok(n) => Atom::Num(n),
Err(e) => return Err(e)
},
Sym => Atom::Sym(self.slice().into()),
Key => Atom::Key(self.slice().into()),
Exp => todo!()
})
}
}
#[derive(Clone, PartialEq)] pub enum Atom<T> { Num(usize), Sym(T), Key(T), Exp(Vec<Atom<T>>) }
impl<'a, T: 'a> Atom<T> {
pub fn transform <U: 'a, F: Fn(&'a T)->U + Clone> (&'a self, f: F) -> Atom<U> {
use Atom::*;
match self {
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>> Atom<T> {
pub fn to_ref (&'a self) -> Atom<&'a str> {
self.transform(|t|t.as_ref())
}
pub fn to_arc (&'a self) -> Atom<Arc<str>> {
self.transform(|t|t.as_ref().into())
}
}
impl<'a> Atom<&'a str> {
pub const fn read_all_ref (_: &'a str) -> Result<Vec<Self>, ParseError> {
Err(Unimplemented)
}
}
impl<T: Debug> Debug for Atom<T> {
fn fmt (&self, f: &mut Formatter<'_>) -> Result<(), FormatError> {
use Atom::*;
match self {
Num(u) => write!(f, "(num {u})"),
Sym(u) => write!(f, "(sym {u:?})"),
Key(u) => write!(f, "(key {u:?})"),
Exp(e) => write!(f, "(exp {})",
itertools::join(e.iter().map(|i|format!("{:?}", i)), ","))
}
}
}
impl<T: Display> Display for Atom<T> {
fn fmt (&self, f: &mut Formatter<'_>) -> Result<(), FormatError> {
use Atom::*;
use itertools::join;
match self {
Num(u) => write!(f, "{u}"),
Sym(u) => write!(f, "{u}"),
Key(u) => write!(f, "{u}"),
Exp(e) => write!(f, "({})", join(e.iter().map(|i|format!("{}", i)), " "))
}
}
}
//impl<'a> Token<'a> {
//pub const fn chomp_one (source: &'a str) -> Result<Token<'a>, ParseError> {
//match Self::chomp(source) {
//Ok((_, token)) => Ok(token),
//Err(e) => Err(e)
//}
//}
//pub const fn from_nil (c: char) -> Result<(&'a str, Token<'a>), ParseError> {
//match c {
//' '|'\n'|'\r'|'\t' => Nil,
//'(' => Exp(source, index, 1, 1),
//':'|'@' => Sym(source, index, 1),
//'0'..='9' => Num(source, index, 1),
//'a'..='z' => Key(source, index, 1),
//_ => return Err(Unexpected(c))
//}
//}
//pub const fn chomp (source: &'a str) -> Result<(&'a str, Token<'a>), ParseError> {
//let mut state = Self::Nil;
//let mut chars = char_indices(source);
//while let Some(((index, c), next)) = chars.next() {
//state = match state {
//// must begin expression
//Nil => Self::from_nil(c),
//Num(_, _, 0) => unreachable!(),
//Sym(_, _, 0) => unreachable!(),
//Key(_, _, 0) => unreachable!(),
//Num(src, idx, len) => match c {
//'0'..='9' => Num(src, idx, len + 1),
//' '|'\n'|'\r'|'\t' => return Ok((split(src, idx+len).1, Num(src, idx, len))),
//_ => return Err(Unexpected(c))
//},
//Sym(src, idx, len) => match c {
//'a'..='z'|'0'..='9'|'-' => Sym(src, idx, len + 1),
//' '|'\n'|'\r'|'\t' => return Ok((split(src, idx+len).1, Sym(src, idx, len))),
//_ => return Err(Unexpected(c))
//},
//Key(src, idx, len) => match c {
//'a'..='z'|'0'..='9'|'-'|'/' => Key(src, idx, len + 1),
//' '|'\n'|'\r'|'\t' => return Ok((split(src, idx+len).1, Key(src, idx, len))),
//_ => return Err(Unexpected(c))
//},
//Exp(src, idx, len, 0) => match c {
//' '|'\n'|'\r'|'\t' => return Ok((split(src, idx+len).1, Exp(src, idx, len, 0))),
//_ => return Err(Unexpected(c))
//},
//Exp(src, idx, len, balance) => match c {
//')' => Exp(src, idx, len + 1, balance - 1),
//'(' => Exp(src, idx, len + 1, balance + 1),
//_ => Exp(src, idx, len + 1, balance)
//},
//};
//chars = next
//}
//Ok(("", state))
//}
//pub fn src (&self) -> &str {
//match self {
//Self::Nil => "",
//Self::Num(src, _, _) => src,
//Self::Sym(src, _, _) => src,
//Self::Key(src, _, _) => src,
//Self::Exp(src, _, _, _) => src,
//}
//}
//pub fn str (&self) -> &str {
//match self {
//Self::Nil => "",
//Self::Num(src, start, len) => &src[*start..start+len],
//Self::Sym(src, start, len) => &src[*start..start+len],
//Self::Key(src, start, len) => &src[*start..start+len],
//Self::Exp(src, start, len, 0) => &src[*start..(start+len)],
//Self::Exp(src, start, len, d) => panic!(
//"unclosed delimiter with depth {d} in:\n{}",
//&src[*start..(start+len)]
//)
//}
//}
//pub fn to_atom_ref (&'a self) -> Result<Atom<&'a str>, ParseError> {
//use Atom::*;
//Ok(match self {
//Token::Nil => Nil,
//Token::Num(_, _, _) => Num(Token::number(self.str())),
//Token::Sym(_, _, _) => Sym(self.str().into()),
//Token::Key(_, _, _) => Key(self.str().into()),
//Token::Exp(_, _, _, _) => Exp(match Atom::read_all_ref(self.str()) {
//Ok(exp) => exp,
//Err(e) => return Err(e)
//}),
//})
//}
//}
#[cfg(test)] #[test] fn test_edn_token () -> Result<(), Box<dyn std::error::Error>> {
use Token::*;
assert_eq!(Nil, Token::chomp_one("")?);
assert_eq!(Nil, Token::chomp_one(" \n \r \t ")?);
assert_eq!(Num("8", 0, 1), Token::chomp_one("8")?);
assert_eq!(Num(" 8 ", 3, 1), Token::chomp_one(" 8 ")?);
assert_eq!(Sym(":foo", 0, 4), Token::chomp_one(":foo")?);
assert_eq!(Sym("@bar", 0, 4), Token::chomp_one("@bar")?);
assert_eq!(Key("foo/bar", 0, 7), Token::chomp_one("foo/bar")?);
Ok(())
}

View file

@ -1,6 +0,0 @@
use crate::*;
pub trait TryFromEdn<'a, T>: Sized {
fn try_from_edn (state: &'a T, head: &EdnItem<impl AsRef<str>>, tail: &'a [EdnItem<impl AsRef<str>>]) ->
Option<Self>;
}

View file

@ -1 +0,0 @@
fn main () {}

View file

@ -3,7 +3,7 @@ use std::sync::Arc;
pub trait EdnInput: Input {
fn matches_edn (&self, token: &str) -> bool;
fn get_event (_: &EdnItem<impl AsRef<str>>) -> Option<Self::Event> {
fn get_event (_: &Atom<impl AsRef<str>>) -> Option<Self::Event> {
None
}
}
@ -12,8 +12,8 @@ pub trait EdnInput: Input {
pub trait EdnCommand<C>: Command<C> {
fn from_edn <'a> (
state: &C,
head: &EdnItem<impl AsRef<str>>,
tail: &'a [EdnItem<impl AsRef<str>>]
head: &Atom<impl AsRef<str>>,
tail: &'a [Atom<impl AsRef<str>>]
) -> Option<Self>;
}
@ -26,7 +26,7 @@ pub trait EdnCommand<C>: Command<C> {
$(
// argument name
$arg:ident
// if type is not provided defaults to EdnItem
// if type is not provided defaults to Atom
$(
// type:name separator
:
@ -43,10 +43,10 @@ pub trait EdnCommand<C>: Command<C> {
impl<$T: $Trait> EdnCommand<$T> for $Command {
fn from_edn <'a> (
$state: &$T,
head: &EdnItem<impl AsRef<str>>,
tail: &'a [EdnItem<impl AsRef<str>>]
head: &Atom<impl AsRef<str>>,
tail: &'a [Atom<impl AsRef<str>>]
) -> Option<Self> {
$(if let (EdnItem::Key($key), [ // if the identifier matches
$(if let (Atom::Key($key), [ // if the identifier matches
// bind argument ids
$($arg),*
// bind rest parameters
@ -69,7 +69,7 @@ pub trait EdnCommand<C>: Command<C> {
$(
// argument name
$arg:ident
// if type is not provided defaults to EdnItem
// if type is not provided defaults to Atom
$(
// type:name separator
:
@ -86,10 +86,10 @@ pub trait EdnCommand<C>: Command<C> {
impl EdnCommand<$State> for $Command {
fn from_edn <'a> (
$state: &$State,
head: &EdnItem<impl AsRef<str>>,
tail: &'a [EdnItem<impl AsRef<str>>],
head: &Atom<impl AsRef<str>>,
tail: &'a [Atom<impl AsRef<str>>],
) -> Option<Self> {
$(if let (EdnItem::Key($key), [ // if the identifier matches
$(if let (Atom::Key($key), [ // if the identifier matches
// bind argument ids
$($arg),*
// bind rest parameters
@ -113,18 +113,18 @@ pub trait EdnCommand<C>: Command<C> {
};
}
pub struct EdnKeyMapToCommand(Vec<EdnItem<Arc<str>>>);
impl EdnKeyMapToCommand {
pub struct KeyMap(Vec<Atom<Arc<str>>>);
impl KeyMap {
/// Construct keymap from source text or fail
pub fn new (keymap: &str) -> Usually<Self> {
Ok(Self(EdnItem::read_all(keymap)?))
Ok(Self(Atom::read_all(keymap)?))
}
/// Try to find a binding matching the currently pressed key
pub fn from <T, C> (&self, state: &T, input: &impl EdnInput) -> Option<C>
pub fn command <T, C> (&self, state: &T, input: &impl EdnInput) -> Option<C>
where
C: Command<T> + EdnCommand<T>
{
use EdnItem::*;
use Atom::*;
let mut command: Option<C> = None;
for item in self.0.iter() {
if let Exp(e) = item {
@ -145,6 +145,7 @@ impl EdnKeyMapToCommand {
}
}
#[cfg(test)] #[test] fn test_edn_keymap () {
let keymap = EdnKeymapToCommand::new("")?;
#[cfg(test)] #[test] fn test_edn_keymap () -> Usually<()> {
let keymap = KeyMap::new("")?;
Ok(())
}

View file

@ -1,19 +1,15 @@
#![feature(associated_type_defaults)]
//mod component; pub use self::component::*;
mod input; pub use self::input::*;
mod command; pub use self::command::*;
mod event_map; pub use self::event_map::*;
mod edn_input; pub use self::edn_input::*;
pub(crate) use ::tek_edn::EdnItem;
mod keymap; pub use self::keymap::*;
//mod event_map; pub use self::event_map::*;
pub(crate) use ::tek_edn::Atom;
/// Standard error trait.
pub(crate) use std::error::Error;
/// Standard result type.
pub(crate) type Usually<T> = Result<T, Box<dyn Error>>;
/// Standard optional result type.
pub(crate) type Perhaps<T> = Result<Option<T>, Box<dyn Error>>;
#[cfg(test)] #[test] fn test_stub_input () -> Usually<()> {
use crate::*;
struct TestInput(bool);

View file

@ -1,57 +0,0 @@
use tek_tui::{*, tek_input::*, tek_output::*};
use tek_edn::*;
use std::sync::{Arc, RwLock};
use crossterm::event::{*, KeyCode::*};
use crate::ratatui::style::Color;
const EDN: &'static [&'static str] = &[
include_str!("edn01.edn"),
include_str!("edn02.edn"),
include_str!("edn03.edn"),
include_str!("edn04.edn"),
include_str!("edn05.edn"),
include_str!("edn06.edn"),
include_str!("edn07.edn"),
include_str!("edn08.edn"),
include_str!("edn09.edn"),
include_str!("edn10.edn"),
include_str!("edn11.edn"),
include_str!("edn12.edn"),
include_str!("edn13.edn"),
];
fn main () -> Usually<()> {
let state = Arc::new(RwLock::new(Example(10, Measure::new())));
Tui::new().unwrap().run(&state)?;
Ok(())
}
#[derive(Debug)] pub struct Example(usize, Measure<TuiOut>);
edn_view!(TuiOut: |self: Example|{
let title = Tui::bg(Color::Rgb(60,10,10),
Push::y(1, Align::n(format!("Example {}/{} in {:?}", self.0 + 1, EDN.len(), &self.1.wh()))));
let code = Tui::bg(Color::Rgb(10,60,10),
Push::y(2, Align::n(format!("{}", EDN[self.0]))));
let content = Tui::bg(Color::Rgb(10,10,60),
EdnView::from_source(self, EDN[self.0]));
self.1.of(Bsp::s(title, Bsp::n(""/*code*/, content)))
};{
bool {};
u16 {};
usize {};
Box<dyn Render<TuiOut> + 'a> {
":title" => Tui::bg(Color::Rgb(60,10,10), Push::y(1, Align::n(format!("Example {}/{}:", self.0 + 1, EDN.len())))).boxed(),
":code" => Tui::bg(Color::Rgb(10,60,10), Push::y(2, Align::n(format!("{}", EDN[self.0])))).boxed(),
":hello-world" => "Hello world!".boxed(),
":hello" => Tui::bg(Color::Rgb(10, 100, 10), "Hello").boxed(),
":world" => Tui::bg(Color::Rgb(100, 10, 10), "world").boxed()
}
});
impl Handle<TuiIn> for Example {
fn handle (&mut self, input: &TuiIn) -> Perhaps<bool> {
match input.event() {
kpat!(Right) => self.0 = (self.0 + 1) % EDN.len(),
kpat!(Left) => self.0 = if self.0 > 0 { self.0 - 1 } else { EDN.len() - 1 },
_ => return Ok(None)
}
Ok(Some(true))
}
}

View file

@ -12,7 +12,7 @@ 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::*;
mod view; pub use self::view::*;
pub(crate) use std::marker::PhantomData;
pub(crate) use std::error::Error;
pub(crate) use ::tek_edn::*;

View file

@ -47,10 +47,10 @@ 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<impl AsRef<str>>,
tail: &'a [EdnItem<impl AsRef<str>>]
head: &Atom<impl AsRef<str>>,
tail: &'a [Atom<impl AsRef<str>>]
) -> Option<Self> {
use EdnItem::*;
use Atom::*;
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")),

View file

@ -93,8 +93,8 @@ 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<impl AsRef<str>>, tail: &'a [EdnItem<impl AsRef<str>>]) -> Option<Self> {
use EdnItem::*;
fn try_from_edn (s: &'a T, head: &Atom<impl AsRef<str>>, tail: &'a [Atom<impl AsRef<str>>]) -> Option<Self> {
use Atom::*;
Some(match (head.to_ref(), tail) {
(Key("bsp/n"), [a, b]) => Self::n(
s.get_content(a).expect("no south"),

View file

@ -8,9 +8,9 @@ impl<E, A> When<E, 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>>]
state: &'a T, head: &Atom<impl AsRef<str>>, tail: &'a [Atom<impl AsRef<str>>]
) -> Option<Self> {
use EdnItem::*;
use Atom::*;
if let (Key("when"), [condition, content]) = (head.to_ref(), tail) {
Some(Self(
Default::default(),
@ -48,8 +48,8 @@ impl<E, A, B> Either<E, 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::*;
fn try_from_edn (state: &'a T, head: &Atom<impl AsRef<str>>, tail: &'a [Atom<impl AsRef<str>>]) -> Option<Self> {
use Atom::*;
if let (Key("either"), [condition, content, alternative]) = (head.to_ref(), tail) {
Some(Self::new(
state.get_bool(condition).expect("either: no condition"),

View file

@ -28,9 +28,9 @@ macro_rules! transform_xy {
}
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>>]
state: &'a T, head: &Atom<impl AsRef<str>>, tail: &'a [Atom<impl AsRef<str>>]
) -> Option<Self> {
use EdnItem::*;
use Atom::*;
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")),
@ -84,9 +84,9 @@ 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<impl AsRef<str>>, tail: &'a [EdnItem<impl AsRef<str>>]
state: &'a T, head: &Atom<impl AsRef<str>>, tail: &'a [Atom<impl AsRef<str>>]
) -> Option<Self> {
use EdnItem::*;
use Atom::*;
Some(match (head.to_ref(), tail) {
(Key($x), [x, a]) => Self::x(
state.get_unit(x).expect("no x"),

View file

@ -1,6 +1,6 @@
use crate::*;
use std::{sync::Arc, marker::PhantomData};
use EdnItem::*;
use Atom::*;
/// Define an EDN-backed view.
///
/// This consists of:
@ -15,8 +15,8 @@ use EdnItem::*;
}
$(
impl<'a> EdnProvide<'a, $type> for $App {
fn get (&'a $self, edn: &'a EdnItem<impl AsRef<str>>) -> Option<$type> {
Some(match edn.to_ref() { $(EdnItem::Sym($sym) => $value,)* _ => return None })
fn get (&'a $self, edn: &'a Atom<impl AsRef<str>>) -> Option<$type> {
Some(match edn.to_ref() { $(Atom::Sym($sym) => $value,)* _ => return None })
}
}
)*
@ -26,9 +26,9 @@ use EdnItem::*;
#[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>> {
fn get (&'a $self, edn: &'a Atom<impl AsRef<str>>) -> Option<Box<dyn Render<E> + 'a>> {
Some(match edn.to_ref() {
$(EdnItem::Sym($pat) => $expr),*,
$(Atom::Sym($pat) => $expr),*,
_ => return None
})
}
@ -36,9 +36,9 @@ 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 (&'a $self, edn: &'a EdnItem<impl AsRef<str>>) -> Option<Box<dyn Render<$Output> + 'a>> {
fn get (&'a $self, edn: &'a Atom<impl AsRef<str>>) -> Option<Box<dyn Render<$Output> + 'a>> {
Some(match edn.to_ref() {
$(EdnItem::Sym($pat) => $expr),*,
$(Atom::Sym($pat) => $expr),*,
_ => return None
})
}
@ -48,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<Arc<str>>),
Ok(T, Atom<Arc<str>>),
//render: Box<dyn Fn(&'a T)->Box<dyn Render<E> + Send + Sync + 'a> + Send + Sync + 'a>
Err(String),
_Unused(PhantomData<&'a E>),
@ -74,13 +74,13 @@ impl<'a, E: Output, T> EdnViewData<'a, E> for T where T:
{}
impl<'a, E: Output, T: EdnViewData<'a, E> + std::fmt::Debug> EdnView<'a, E, T> {
pub fn from_source (state: T, source: &'a str) -> Self {
match EdnItem::read_one(&source) {
match Atom::read_one(&source) {
Ok((layout, _)) => Self::Ok(state, layout),
Err(error) => Self::Err(format!("{error} in {source}"))
}
}
pub fn from_items (state: T, items: Vec<EdnItem<impl AsRef<str>>>) -> Self {
Self::Ok(state, EdnItem::Exp(items).to_arc())
pub fn from_items (state: T, items: Vec<Atom<impl AsRef<str>>>) -> Self {
Self::Ok(state, Atom::Exp(items).to_arc())
}
}
impl<E: Output, T: for<'a>EdnViewData<'a, E> + Send + Sync + std::fmt::Debug> Content<E> for EdnView<'_, E, T> {
@ -113,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<impl AsRef<str>>) -> Option<bool> {
fn get_bool (&'a self, item: &'a Atom<impl AsRef<str>>) -> Option<bool> {
Some(match &item {
Sym(s) => match s.as_ref() {
":false" | ":f" => false,
@ -125,13 +125,13 @@ pub trait EdnViewData<'a, E: Output>:
_ => return EdnProvide::get(self, item)
})
}
fn get_usize (&'a self, item: &'a EdnItem<impl AsRef<str>>) -> Option<usize> {
fn get_usize (&'a self, item: &'a Atom<impl AsRef<str>>) -> Option<usize> {
Some(match &item { Num(n) => *n, _ => return EdnProvide::get(self, item) })
}
fn get_unit (&'a self, item: &'a EdnItem<impl AsRef<str>>) -> Option<E::Unit> {
fn get_unit (&'a self, item: &'a Atom<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<impl AsRef<str>>) -> Option<Box<dyn Render<E> + 'a>> where E: 'a {
fn get_content (&'a self, item: &'a Atom<impl AsRef<str>>) -> Option<Box<dyn Render<E> + 'a>> where E: 'a {
Some(match item {
Nil => Box::new(()),
Exp(ref e) => {

View file

@ -587,8 +587,6 @@ const KEYS_TRACK: &str = include_str!("keys_track.edn");
const KEYS_SCENE: &str = include_str!("keys_scene.edn");
const KEYS_MIX: &str = include_str!("keys_mix.edn");
handle!(TuiIn: |self: Tek, input|Ok({
use EdnItem::*;
let mut command: Option<TekCommand> = None;
// If editing, editor keys take priority
if self.is_editing() {
if self.editor.handle(input)? == Some(true) {
@ -596,17 +594,17 @@ handle!(TuiIn: |self: Tek, input|Ok({
}
}
// Handle from root keymap
if let Some(command) = EdnKeyMapToCommand::new(KEYS_APP)?.from::<_, TekCommand>(self, input) {
if let Some(command) = KeyMap::new(KEYS_APP)?.command::<_, TekCommand>(self, input) {
if let Some(undo) = command.execute(self)? { self.history.push(undo); }
return Ok(Some(true))
}
// Handle from selection-dependent keymaps
if let Some(command) = EdnKeyMapToCommand::new(match self.selected() {
if let Some(command) = KeyMap::new(match self.selected() {
Selection::Clip(t, s) => KEYS_CLIP,
Selection::Track(t) => KEYS_TRACK,
Selection::Scene(s) => KEYS_SCENE,
Selection::Mix => KEYS_MIX,
})?.from::<_, TekCommand>(
})?.command::<_, TekCommand>(
self, input
) {
if let Some(undo) = command.execute(self)? { self.history.push(undo); }

67
tui/examples/tui.rs Normal file
View file

@ -0,0 +1,67 @@
use tek_tui::{*, tek_input::*, tek_output::*};
use tek_edn::*;
use std::sync::{Arc, RwLock};
use crossterm::event::{*, KeyCode::*};
use crate::ratatui::style::Color;
fn main () -> Usually<()> {
let state = Arc::new(RwLock::new(Example(10, Measure::new())));
Tui::new().unwrap().run(&state)?;
Ok(())
}
#[derive(Debug)] pub struct Example(usize, Measure<TuiOut>);
const KEYMAP: &str = "(:left prev) (:right next)";
handle!(TuiIn: |self: Example, input|{
let keymap = KeyMap::new(KEYMAP)?;
let command = keymap.command::<_, ExampleCommand>(self, input);
if let Some(command) = command {
command.execute(self)?;
return Ok(Some(true))
}
return Ok(None)
});
enum ExampleCommand { Next, Previous }
edn_command!(ExampleCommand: |app: Example| {
(":prev" [] Self::Previous)
(":next" [] Self::Next)
});
command!(|self: ExampleCommand, state: Example|match self {
Self::Next =>
{ state.0 = (state.0 + 1) % EXAMPLES.len(); None },
Self::Previous =>
{ state.0 = if state.0 > 0 { state.0 - 1 } else { EXAMPLES.len() - 1 }; None },
});
const EXAMPLES: &'static [&'static str] = &[
include_str!("edn01.edn"),
include_str!("edn02.edn"),
include_str!("edn03.edn"),
include_str!("edn04.edn"),
include_str!("edn05.edn"),
include_str!("edn06.edn"),
include_str!("edn07.edn"),
include_str!("edn08.edn"),
include_str!("edn09.edn"),
include_str!("edn10.edn"),
include_str!("edn11.edn"),
include_str!("edn12.edn"),
include_str!("edn13.edn"),
];
edn_view!(TuiOut: |self: Example|{
let title = Tui::bg(Color::Rgb(60,10,10),
Push::y(1, Align::n(format!("Example {}/{} in {:?}", self.0 + 1, EXAMPLES.len(), &self.1.wh()))));
let code = Tui::bg(Color::Rgb(10,60,10),
Push::y(2, Align::n(format!("{}", EXAMPLES[self.0]))));
let content = Tui::bg(Color::Rgb(10,10,60),
EdnView::from_source(self, EXAMPLES[self.0]));
self.1.of(Bsp::s(title, Bsp::n(""/*code*/, content)))
}; {
bool {};
u16 {};
usize {};
Box<dyn Render<TuiOut> + 'a> {
":title" => Tui::bg(Color::Rgb(60,10,10), Push::y(1, Align::n(format!("Example {}/{}:", self.0 + 1, EXAMPLES.len())))).boxed(),
":code" => Tui::bg(Color::Rgb(10,60,10), Push::y(2, Align::n(format!("{}", EXAMPLES[self.0])))).boxed(),
":hello" => Tui::bg(Color::Rgb(10, 100, 10), "Hello").boxed(),
":world" => Tui::bg(Color::Rgb(100, 10, 10), "world").boxed(),
":hello-world" => "Hello world!".boxed()
}
});