well, it compiles. fails on run, though

This commit is contained in:
🪞👃🪞 2025-01-18 16:32:04 +01:00
parent a362028ae7
commit d14d67172c
6 changed files with 96 additions and 185 deletions

View file

@ -1,10 +1,10 @@
use crate::*; use crate::*;
pub trait TryFromAtom<T>: Sized { pub trait TryFromAtom<'a, T>: Sized {
fn try_from_atom (state: &T, value: Value) -> Option<Self> { fn try_from_atom (state: &'a T, value: Value<'a>) -> Option<Self> {
if let Value::Exp(0, iter) = value { return Self::try_from_expr(state, iter) } if let Value::Exp(0, iter) = value { return Self::try_from_expr(state, iter) }
None None
} }
fn try_from_expr (_state: &T, _iter: TokenIter) -> Option<Self> { fn try_from_expr (_state: &'a T, _iter: TokenIter<'a>) -> Option<Self> {
None None
} }
} }

View file

@ -3,33 +3,40 @@ use crate::*;
pub trait AtomInput: Input { pub trait AtomInput: Input {
fn matches_atom (&self, token: &str) -> bool; fn matches_atom (&self, token: &str) -> bool;
} }
pub trait KeyMap { pub trait KeyMap<'a> {
/// Try to find a command that matches the current input event. /// Try to find a command that matches the current input event.
fn command <S, C: AtomCommand<S>, I: AtomInput> (&self, state: &S, input: &I) -> Option<C>; fn command <S, C: AtomCommand<'a, S>, I: AtomInput> (&'a self, state: &'a S, input: &'a I)
-> Option<C>;
} }
impl KeyMap for TokenIter<'_> { impl<'a> KeyMap<'a> for TokenIter<'a> {
fn command <S, C: AtomCommand<S>, I: AtomInput> (&self, state: &S, input: &I) -> Option<C> { fn command <S, C: AtomCommand<'a, S>, I: AtomInput> (&'a self, state: &'a S, input: &'a I)
for token in *self { -> Option<C>
if let Value::Exp(0, iter) = token.value() { {
if let Some((Token { value: Value::Sym(binding), .. }, _)) = iter.next() { let iter = self.clone();
if input.matches_atom(binding) { while let Some(next) = iter.next() {
if let Some(command) = C::try_from_expr(state, iter.clone()) { match next {
return Some(command) (Token { value: Value::Exp(0, iter), .. }, _) => {
} let next = iter.next();
match next {
Some((Token { value: Value::Sym(binding), .. }, _)) => {
if input.matches_atom(binding) {
if let Some(command) = C::try_from_expr(state, iter.clone()) {
return Some(command)
}
}
},
_ => panic!("invalid config (expected symbol)")
} }
} else { },
panic!("invalid config: {token:?}") _ => panic!("invalid config (expected expression)")
}
} else {
panic!("invalid config: {token:?}")
} }
} }
None None
} }
} }
/// A [Command] that can be constructed from a [Token]. /// A [Command] that can be constructed from a [Token].
pub trait AtomCommand<C>: TryFromAtom<C> + Command<C> {} pub trait AtomCommand<'a, C>: TryFromAtom<'a, C> + Command<C> {}
impl<C, T: TryFromAtom<C> + Command<C>> AtomCommand<C> for T {} impl<'a, C, T: TryFromAtom<'a, C> + Command<C>> AtomCommand<'a, C> for T {}
/** Implement `AtomCommand` for given `State` and `Command` */ /** Implement `AtomCommand` for given `State` and `Command` */
#[macro_export] macro_rules! atom_command { #[macro_export] macro_rules! atom_command {
($Command:ty : |$state:ident:<$State:ident: $Trait:path>| { $(( ($Command:ty : |$state:ident:<$State:ident: $Trait:path>| { $((
@ -53,7 +60,7 @@ impl<C, T: TryFromAtom<C> + Command<C>> AtomCommand<C> for T {}
// bound command: // bound command:
$command:expr $command:expr
))* }) => { ))* }) => {
impl<$State: $Trait> TryFromAtom<$State> for $Command { impl<'a, $State: $Trait> TryFromAtom<'a, $State> for $Command {
fn try_from_expr ($state: &$State, iter: TokenIter) -> Option<Self> { fn try_from_expr ($state: &$State, iter: TokenIter) -> Option<Self> {
match $iter.next() { match $iter.next() {
$(Some((Token { value: Value::Key($key), .. }, _)) => { $(Some((Token { value: Value::Key($key), .. }, _)) => {
@ -94,7 +101,7 @@ impl<C, T: TryFromAtom<C> + Command<C>> AtomCommand<C> for T {}
// bound command: // bound command:
$command:expr $command:expr
))* }) => { ))* }) => {
impl TryFromAtom<$State> for $Command { impl<'a> TryFromAtom<'a, $State> for $Command {
fn try_from_expr ($state: &$State, iter: TokenIter) -> Option<Self> { fn try_from_expr ($state: &$State, iter: TokenIter) -> Option<Self> {
match iter.next() { match iter.next() {
$(Some((Token { value: Value::Key($key), .. }, _)) => { $(Some((Token { value: Value::Key($key), .. }, _)) => {

View file

@ -10,7 +10,7 @@ try_from_expr!(<'a, E>: When<RenderBox<'a, E>>: |state, iter| {
let iter = iter.clone(); let iter = iter.clone();
let condition = iter.next(); let condition = iter.next();
if let Some((ref condition, _)) = condition { if let Some((ref condition, _)) = condition {
let condition = state.get_bool(&condition.value).expect("no condition"); let condition = state.get(&condition.value).expect("no condition");
if let Some((ref content, _)) = iter.next() { if let Some((ref content, _)) = iter.next() {
let content = state.get_content(&content.value).expect("no atom"); let content = state.get_content(&content.value).expect("no atom");
return Some(Self(condition, content)) return Some(Self(condition, content))
@ -23,7 +23,7 @@ try_from_expr!(<'a, E>: Either<RenderBox<'a, E>, RenderBox<'a, E>>: |state, iter
let iter = iter.clone(); let iter = iter.clone();
let condition = iter.next(); let condition = iter.next();
if let Some((ref condition, _)) = condition { if let Some((ref condition, _)) = condition {
let condition = state.get_bool(&condition.value).expect("no condition"); let condition = state.get(&condition.value).expect("no condition");
if let Some((ref content1, _)) = iter.next() { if let Some((ref content1, _)) = iter.next() {
let content1 = state.get_content(&content1.value).expect("no content1"); let content1 = state.get_content(&content1.value).expect("no content1");
if let Some((ref content2, _)) = iter.next() { if let Some((ref content2, _)) = iter.next() {

View file

@ -12,9 +12,9 @@ macro_rules! transform_xy {
pub fn y (item: T) -> Self { Self::Y(item) } pub fn y (item: T) -> Self { Self::Y(item) }
pub fn xy (item: T) -> Self { Self::XY(item) } pub fn xy (item: T) -> Self { Self::XY(item) }
} }
impl<'a, E: Output + 'a, T: ViewContext<'a, E>> TryFromAtom<T> impl<'a, E: Output + 'a, T: ViewContext<'a, E>> TryFromAtom<'a, T>
for $Enum<RenderBox<'a, E>> { for $Enum<RenderBox<'a, E>> {
fn try_from_expr (state: &T, iter: TokenIter) -> Option<Self> { fn try_from_expr (state: &'a T, iter: TokenIter<'a>) -> Option<Self> {
Some(if let Some((Token { value: Value::Key($x), .. }, _)) = iter.next() { Some(if let Some((Token { value: Value::Key($x), .. }, _)) = iter.next() {
Self::x(state.get_content(&iter.next().expect("no content").0.value).expect("no content")) Self::x(state.get_content(&iter.next().expect("no content").0.value).expect("no content"))
} else if let Some((Token { value: Value::Key($y), .. }, _)) = iter.next() { } else if let Some((Token { value: Value::Key($y), .. }, _)) = iter.next() {
@ -51,20 +51,20 @@ macro_rules! transform_xy_unit {
pub fn y (y: U, item: T) -> Self { Self::Y(y, item) } pub fn y (y: U, item: T) -> Self { Self::Y(y, item) }
pub fn xy (x: U, y: U, item: T) -> Self { Self::XY(x, y, item) } pub fn xy (x: U, y: U, item: T) -> Self { Self::XY(x, y, item) }
} }
impl<'a, E: Output + 'a, T: ViewContext<'a, E>> TryFromAtom<T> impl<'a, E: Output + 'a, T: ViewContext<'a, E>> TryFromAtom<'a, T>
for $Enum<E::Unit, RenderBox<'a, E>> { for $Enum<E::Unit, RenderBox<'a, E>> {
fn try_from_expr (state: &T, iter: TokenIter) -> Option<Self> { fn try_from_expr (state: &'a T, iter: TokenIter<'a>) -> Option<Self> {
Some(if let Some((Token { value: Value::Key($x), .. }, _)) = iter.next() { Some(if let Some((Token { value: Value::Key($x), .. }, _)) = iter.next() {
let x = state.get_unit(&iter.next().expect("no x").0.value).expect("no x"); let x = state.get(&iter.next().expect("no x").0.value).expect("no x");
let c = state.get_content(&iter.next().expect("no content").0.value).expect("no content"); let c = state.get_content(&iter.next().expect("no content").0.value).expect("no content");
Self::x(x, c) Self::x(x, c)
} else if let Some((Token { value: Value::Key($y), .. }, _)) = iter.next() { } else if let Some((Token { value: Value::Key($y), .. }, _)) = iter.next() {
let y = state.get_unit(&iter.next().expect("no y").0.value).expect("no y"); let y = state.get(&iter.next().expect("no y").0.value).expect("no y");
let c = state.get_content(&iter.next().expect("no content").0.value).expect("no content"); let c = state.get_content(&iter.next().expect("no content").0.value).expect("no content");
Self::y(y, c) Self::y(y, c)
} else if let Some((Token { value: Value::Key($xy), .. }, _)) = iter.next() { } else if let Some((Token { value: Value::Key($xy), .. }, _)) = iter.next() {
let x = state.get_unit(&iter.next().expect("no x").0.value).expect("no x"); let x = state.get(&iter.next().expect("no x").0.value).expect("no x");
let y = state.get_unit(&iter.next().expect("no y").0.value).expect("no y"); let y = state.get(&iter.next().expect("no y").0.value).expect("no y");
let c = state.get_content(&iter.next().expect("no content").0.value).expect("no content"); let c = state.get_content(&iter.next().expect("no content").0.value).expect("no content");
Self::xy(x, y, c) Self::xy(x, y, c)
} else { } else {

View file

@ -1,28 +1,25 @@
use crate::*; use crate::*;
use std::{sync::Arc, fmt::Debug};
use Value::*;
/// Define an EDN-backed view.
///
/// This consists of:
/// * render callback (implementation of [Content])
/// * value providers (implementations of [Context])
#[macro_export] macro_rules! view { #[macro_export] macro_rules! view {
($Output:ty: |$self:ident: $App:ty| $content:expr $(;{ ($Output:ty: |$self:ident: $State:ty| $expr:expr; {
$( $type:ty { $($sym:literal => $value:expr),* } );* $($sym:literal => $body:expr),* $(,)?
})?) => { }) => {
impl Content<$Output> for $App { impl Content<$Output> for $State {
fn content(&$self) -> impl Render<$Output> { $content } fn content (&$self) -> impl Render<$Output> { $expr }
} }
$($( impl<'a> ViewContext<'a, $Output> for $State {
impl Context<$type> for $App { fn get_content_custom (&'a $self, value: &Value<'a>) -> Option<RenderBox<'a, $Output>> {
fn get (&$self, atom: &Value) -> Option<$type> { if let Value::Sym(s) = value {
Some(match atom.to_ref() { $(Atom::Sym($sym) => $value,)* _ => return None }) match *s { $($sym => Some($body),)* _ => None }
} else {
panic!("expected symbol")
} }
} }
)*)? }
} }
} }
// An ephemeral wrapper around view state and view description,
// that is meant to be constructed and returned from [Content::content].
pub struct View<'a, T>(pub &'a T, pub TokenIter<'a>); pub struct View<'a, T>(pub &'a T, pub TokenIter<'a>);
impl<'a, O: Output + 'a, T: ViewContext<'a, O>> Content<O> for View<'a, T> { impl<'a, O: Output + 'a, T: ViewContext<'a, O>> Content<O> for View<'a, T> {
fn content (&self) -> impl Render<O> { fn content (&self) -> impl Render<O> {
@ -35,97 +32,36 @@ impl<'a, O: Output + 'a, T: ViewContext<'a, O>> Content<O> for View<'a, T> {
return None return None
} }
} }
// Provides components to the view.
/// Renders from EDN source and context. pub trait ViewContext<'a, E: Output + 'a>: Send + Sync
///
/// Generic over:
///
/// * `O` - Output target.
/// * `S` - State provider.
/// * `A` - Atom storage type.
#[derive(Default, Clone)] pub enum AtomView<'a, O, S, A> {
_Unused(std::marker::PhantomData<&'a O>),
#[default] Inert,
Src(S, &'a str),
Ref(S, &'a A),
Own(S, A),
Err(Arc<str>)
}
impl<'a, O, S, A> Debug for AtomView<'a, O, S, A>
where S: Debug, A: Debug {
fn fmt (&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
Self::Inert =>
write!(f, "AtomView::Inert"),
Self::Src(state, view) =>
write!(f, "AtomView::Src(state={state:?} view={view:?}"),
Self::Ref(state, view) =>
write!(f, "AtomView::Ref(state={state:?} view={view:?}"),
Self::Own(state, view) =>
write!(f, "AtomView::Arc(state={state:?} view={view:?}"),
Self::Err(error) =>
write!(f, "AtomView::Err({error})"),
_ => unreachable!()
}
}
}
impl<'a, O, S, A> Content<O> for AtomView<'a, O, S, A>
where O: Output, S: ViewContext<'a, O>, A: Send + Sync {
fn content (&self) -> impl Render<O> {
match self {
Self::Inert => { panic!("inert rendered") },
Self::Err(e) => { panic!("render error: {e}") },
Self::Src(state, source) => {},
Self::Ref(state, atom) => {},
Self::Own(state, atom) => {},
_ => unreachable!()
}
}
}
impl<'a, E: Output, T> ViewContext<'a, E> for T where T: Sized + Send + Sync
+ Context<bool> + Context<bool>
+ Context<usize> + Context<usize>
+ Context<E::Unit> + Context<E::Unit>
+ Context<Box<dyn Render<E> + 'a>> {}
/// Provides values to the template
pub trait ViewContext<'a, E: Output>: Sized + Send + Sync
+ Context<bool>
+ Context<usize>
+ Context<E::Unit>
+ Context<Box<dyn Render<E> + 'a>>
{ {
fn get_bool (&self, atom: &Value) -> Option<bool> { fn get_content (&'a self, value: &Value<'a>) -> Option<RenderBox<'a, E>> {
Some(match atom { if let Some(builtin) = self.get_content_builtin(value) {
Num(n) => match *n { 0 => false, _ => true }, Some(builtin)
Sym(x) => match *x { } else {
":false" | ":f" => false, ":true" | ":t" => true, self.get_content_custom(value)
_ => return Context::get(self, atom) }
},
_ => return Context::get(self, atom)
})
} }
fn get_usize (&self, atom: &Value) -> Option<usize> { fn get_content_custom (&'a self, value: &Value<'a>) -> Option<RenderBox<'a, E>>;
Some(match atom {Num(n) => *n, _ => return Context::get(self, atom)}) fn get_content_builtin (&'a self, value: &Value<'a>) -> Option<RenderBox<'a, E>> {
} try_delegate!(self, *value, When::<RenderBox<'a, E>>);
fn get_unit (&self, atom: &Value) -> Option<E::Unit> { try_delegate!(self, *value, Either::<RenderBox<'a, E>, RenderBox<'a, E>>);
Some(match atom {Num(n) => E::Unit::from(*n as u16), _ => return Context::get(self, atom)}) try_delegate!(self, *value, Align::<RenderBox<'a, E>>);
} try_delegate!(self, *value, Bsp::<RenderBox<'a, E>, RenderBox<'a, E>>);
fn get_content (&self, atom: &Value) -> Option<Box<dyn Render<E> + 'a>> where E: 'a { try_delegate!(self, *value, Fill::<RenderBox<'a, E>>);
try_delegate!(self, *atom, When::<RenderBox<'a, E>>); try_delegate!(self, *value, Fixed::<_, RenderBox<'a, E>>);
try_delegate!(self, *atom, Either::<RenderBox<'a, E>, RenderBox<'a, E>>); try_delegate!(self, *value, Min::<_, RenderBox<'a, E>>);
try_delegate!(self, *atom, Align::<RenderBox<'a, E>>); try_delegate!(self, *value, Max::<_, RenderBox<'a, E>>);
try_delegate!(self, *atom, Bsp::<RenderBox<'a, E>, RenderBox<'a, E>>); try_delegate!(self, *value, Shrink::<_, RenderBox<'a, E>>);
try_delegate!(self, *atom, Fill::<RenderBox<'a, E>>); try_delegate!(self, *value, Expand::<_, RenderBox<'a, E>>);
try_delegate!(self, *atom, Fixed::<_, RenderBox<'a, E>>); try_delegate!(self, *value, Push::<_, RenderBox<'a, E>>);
try_delegate!(self, *atom, Min::<_, RenderBox<'a, E>>); try_delegate!(self, *value, Pull::<_, RenderBox<'a, E>>);
try_delegate!(self, *atom, Max::<_, RenderBox<'a, E>>); try_delegate!(self, *value, Margin::<_, RenderBox<'a, E>>);
try_delegate!(self, *atom, Shrink::<_, RenderBox<'a, E>>); try_delegate!(self, *value, Padding::<_, RenderBox<'a, E>>);
try_delegate!(self, *atom, Expand::<_, RenderBox<'a, E>>); None
try_delegate!(self, *atom, Push::<_, RenderBox<'a, E>>);
try_delegate!(self, *atom, Pull::<_, RenderBox<'a, E>>);
try_delegate!(self, *atom, Margin::<_, RenderBox<'a, E>>);
try_delegate!(self, *atom, Padding::<_, RenderBox<'a, E>>);
Some(Context::get_or_fail(self, atom))
} }
} }
#[macro_export] macro_rules! try_delegate { #[macro_export] macro_rules! try_delegate {
@ -135,17 +71,10 @@ pub trait ViewContext<'a, E: Output>: Sized + Send + Sync
} }
} }
} }
// A function that returns a `RenderBox.
pub type AtomCallback<'a, O, State> =
dyn Fn(&'a State)-> RenderBox<'a, O> + Send + Sync + 'a;
// A box containing a function that returns a `RenderBox.
pub type AtomRenderCallback<'a, O, State> =
Box<AtomCallback<'a, O, State>>;
#[macro_export] macro_rules! try_from_expr { #[macro_export] macro_rules! try_from_expr {
(<$l:lifetime, $E:ident>: $Struct:ty: |$state:ident, $atoms:ident|$body:expr) => { (<$l:lifetime, $E:ident>: $Struct:ty: |$state:ident, $atoms:ident|$body:expr) => {
impl<$l, $E: Output + $l, T: ViewContext<$l, $E>> TryFromAtom<T> for $Struct { impl<$l, $E: Output + $l, T: ViewContext<$l, $E>> TryFromAtom<$l, T> for $Struct {
fn try_from_atom ($state: &T, atom: Value) -> Option<Self> { fn try_from_atom ($state: &$l T, atom: Value<$l>) -> Option<Self> {
if let Value::Exp(0, $atoms) = atom { if let Value::Exp(0, $atoms) = atom {
$body; $body;
} }
@ -154,28 +83,3 @@ pub type AtomRenderCallback<'a, O, State> =
} }
} }
} }
/// Implement `Context` for a context and content type.
///
/// This enables support for layout expressions.
#[macro_export] macro_rules! provide_content {
(|$self:ident:$State:ty|{ $($pat:pat => $expr:expr),* $(,)? }) => {
impl<E: Output> Context<Box<dyn Render<E> + '_>> for $State {
fn get (&$self, atom: &Value) -> Option<Box<dyn Render<E> + '_>> {
Some(match atom {
$(Value::Sym($pat) => $expr,)*
_ => return None
})
}
}
};
($Output:ty: |$self:ident:$State:ty|{ $($pat:pat => $expr:expr),* $(,)? }) => {
impl Context<Box<dyn Render<$Output> + '_>> for $State {
fn get (&$self, atom: &Value) -> Option<Box<dyn Render<$Output> + '_>> {
Some(match atom {
$(Value::Sym($pat) => $expr,)*
_ => return None
})
}
}
}
}

View file

@ -175,7 +175,21 @@ provide_num!(usize: |self: Tek| {
":track" => self.selected.track().unwrap_or(0), ":track" => self.selected.track().unwrap_or(0),
":track-next" => (self.selected.track().unwrap_or(0) + 1).min(self.tracks.len()), ":track-next" => (self.selected.track().unwrap_or(0) + 1).min(self.tracks.len()),
":track-prev" => self.selected.track().unwrap_or(0).saturating_sub(1) }); ":track-prev" => self.selected.track().unwrap_or(0).saturating_sub(1) });
view!(TuiOut: |self: Tek| self.size.of(View(self, self.view))); view!(TuiOut: |self: Tek| self.size.of(View(self, self.view)); {
":editor" => (&self.editor).boxed(),
":pool" => self.view_pool().boxed(),
":sample" => self.view_sample(self.is_editing()).boxed(),
":sampler" => self.view_sampler(self.is_editing(), &self.editor).boxed(),
":status" => self.view_editor().boxed(),
":toolbar" => self.view_clock().boxed(),
":tracks" => self.view_row(self.w(), 3, self.track_header(), self.track_cells()).boxed(),
":inputs" => self.view_row(self.w(), 3, self.input_header(), self.input_cells()).boxed(),
":outputs" => self.view_row(self.w(), 3, self.output_header(), self.output_cells()).boxed(),
":scenes" => Outer(false, Style::default().fg(TuiTheme::g(0))).enclose_bg(self.view_row(
self.w(), self.size.h().saturating_sub(12) as u16,
self.scene_header(), self.clip_columns()
)).boxed()
});
provide_bool!(bool: |self: Tek| {}); provide_bool!(bool: |self: Tek| {});
provide_num!(isize: |self: Tek| {}); provide_num!(isize: |self: Tek| {});
provide!(Color: |self: Tek| {}); provide!(Color: |self: Tek| {});
@ -191,20 +205,6 @@ provide_num!(u16: |self: Tek| {
let w = self.size.w(); let w = self.size.w();
if w > 60 { 20 } else if w > 40 { 15 } else { 10 } } if w > 60 { 20 } else if w > 40 { 15 } else { 10 } }
}); });
provide_content!(TuiOut: |self: Tek| {
":editor" => (&self.editor).boxed(),
":pool" => self.view_pool().boxed(),
":sample" => self.view_sample(self.is_editing()).boxed(),
":sampler" => self.view_sampler(self.is_editing(), &self.editor).boxed(),
":status" => self.view_editor().boxed(),
":toolbar" => self.view_clock().boxed(),
":tracks" => self.view_row(self.w(), 3, self.track_header(), self.track_cells()).boxed(),
":inputs" => self.view_row(self.w(), 3, self.input_header(), self.input_cells()).boxed(),
":outputs" => self.view_row(self.w(), 3, self.output_header(), self.output_cells()).boxed(),
":scenes" => Outer(false, Style::default().fg(TuiTheme::g(0))).enclose_bg(self.view_row(
self.w(), self.size.h().saturating_sub(12) as u16,
self.scene_header(), self.clip_columns()
)).boxed() });
impl Tek { impl Tek {
fn new_clock ( fn new_clock (
jack: &Arc<RwLock<JackConnection>>, jack: &Arc<RwLock<JackConnection>>,