From 72975c861a978201573d0590b71c3b41a13f729a Mon Sep 17 00:00:00 2001 From: unspeaker Date: Thu, 7 Aug 2025 22:46:50 +0300 Subject: [PATCH 1/5] huh. --- Cargo.lock | 1 + Cargo.toml | 1 + bacon.toml | 55 ++++ config/{bindings.edn => binds.edn} | 0 config/{profiles.edn => views.edn} | 12 +- crates/app/Cargo.toml | 1 + crates/app/app.rs | 486 +++++++++++------------------ crates/app/app_view.rs | 159 ++++++++++ crates/cli/tek.rs | 2 +- deps/tengri | 2 +- 10 files changed, 410 insertions(+), 309 deletions(-) create mode 100644 bacon.toml rename config/{bindings.edn => binds.edn} (100%) rename config/{profiles.edn => views.edn} (90%) create mode 100644 crates/app/app_view.rs diff --git a/Cargo.lock b/Cargo.lock index f0a12eed..18fb7be7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2386,6 +2386,7 @@ version = "0.2.1" dependencies = [ "backtrace", "clap", + "konst", "palette", "proptest", "proptest-derive", diff --git a/Cargo.toml b/Cargo.toml index 35b9e4ac..c9386a0a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,6 +41,7 @@ atomic_float = { version = "1.0.0" } backtrace = { version = "0.3.72" } clap = { version = "4.5.4", features = [ "derive" ] } gtk = { version = "0.18.1" } +konst = { version = "0.3.16", features = [ "rust_1_83" ] } livi = { version = "0.7.4" } midly = { version = "0.5" } palette = { version = "0.7.6", features = [ "random" ] } diff --git a/bacon.toml b/bacon.toml new file mode 100644 index 00000000..e2eeae40 --- /dev/null +++ b/bacon.toml @@ -0,0 +1,55 @@ +# https://dystroy.org/bacon/config/ +default_job = "check" +env.CARGO_TERM_COLOR = "always" +[keybindings] +c = "job:check" +l = "job:clippy" +[jobs] +[jobs.check] +command = ["cargo", "check"] +need_stdout = false +watch = ["crates", "deps"] +[jobs.check-all] +command = ["cargo", "check", "--all-targets"] +need_stdout = false +[jobs.clippy] +command = ["cargo", "clippy"] +need_stdout = false +[jobs.clippy-all] +command = ["cargo", "clippy", "--all-targets"] +need_stdout = false +[jobs.test] +command = ["cargo", "test"] +need_stdout = true +[jobs.nextest] +command = [ + "cargo", "nextest", "run", + "--hide-progress-bar", "--failure-output", "final" +] +need_stdout = true +analyzer = "nextest" +[jobs.doc] +command = ["cargo", "doc", "--no-deps"] +need_stdout = false +[jobs.doc-open] +command = ["cargo", "doc", "--no-deps", "--open"] +need_stdout = false +on_success = "back" # so that we don't open the browser at each change +[jobs.run] +command = [ + "cargo", "run", + # put launch parameters for your program behind a `--` separator +] +need_stdout = true +allow_warnings = true +background = true +[jobs.run-long] +command = [ "cargo", "run", ] +need_stdout = true +allow_warnings = true +background = false +on_change_strategy = "kill_then_restart" +[jobs.ex] +command = ["cargo", "run", "--example"] +need_stdout = true +allow_warnings = true diff --git a/config/bindings.edn b/config/binds.edn similarity index 100% rename from config/bindings.edn rename to config/binds.edn diff --git a/config/profiles.edn b/config/views.edn similarity index 90% rename from config/profiles.edn rename to config/views.edn index 918d4d60..435a11e9 100644 --- a/config/profiles.edn +++ b/config/views.edn @@ -11,7 +11,7 @@ (mode :editor (keys :editor)) (mode :dialog (keys :dialog)) (mode :message (keys :message)) - (mode :device-add (keys :device-add)) + (mode :add-device (keys :add-device)) (mode :browser (keys :browser)) (mode :rename (keys :pool-rename)) (mode :length (keys :pool-length)) @@ -22,7 +22,6 @@ (keys :clock) (keys :arranger) (keys :global) - :view/dialog (bsp/w :view/meters/output (bsp/e :view/meters/input (stack/n (fixed/y 2 :view/status/h2) :view/tracks/inputs @@ -41,7 +40,6 @@ (keys :editor) (keys :sampler) (keys :global) - :view/dialog (bsp/w :view/meters/output (bsp/e :view/meters/input (bsp/w @@ -61,7 +59,6 @@ (info "A sampling soundboard.") (keys :sampler) (keys :global) - :view/dialog (bsp/s (fixed/y 1 :view/transport) (bsp/n (fixed/y 1 :view/status) (fill/xy :view/samples/grid)))) @@ -75,6 +72,7 @@ (keys :editor) (keys :clock) (keys :global) - :view/dialog - (bsp/s (fixed/y 1 :view/transport) (bsp/n (fixed/y 1 :view/status) - (fill/xy (bsp/a (fill/xy (align/e :view/pool)) :view/editor))))) + (bsp/s (fixed/y 1 :view/transport) + (bsp/n (fixed/y 1 :view/status) + (fill/xy (bsp/a (fill/xy (align/e :view/pool)) + :view/editor))))) diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml index 4283e9a9..06ce641b 100644 --- a/crates/app/Cargo.toml +++ b/crates/app/Cargo.toml @@ -12,6 +12,7 @@ tek_device = { workspace = true } backtrace = { workspace = true } clap = { workspace = true, optional = true } +konst = { workspace = true } palette = { workspace = true } rand = { workspace = true } toml = { workspace = true } diff --git a/crates/app/app.rs b/crates/app/app.rs index 176514ec..a3e195c4 100644 --- a/crates/app/app.rs +++ b/crates/app/app.rs @@ -16,6 +16,8 @@ #![feature(type_changing_struct_update)] #![feature(let_chains)] #![feature(closure_lifetime_binder)] +#![feature(generic_const_exprs)] +#![feature(generic_arg_infer)] pub use ::tek_engine:: *; pub use ::tek_device::{self, *}; pub use ::tengri::{Usually, Perhaps, Has, MaybeHas}; @@ -38,6 +40,7 @@ use std::collections::BTreeMap; use std::fmt::Write; use ::tengri::tui::ratatui::prelude::Position; use xdg::BaseDirectories; +mod app_view; pub use self::app_view::*; #[cfg(test)] mod app_test; /// Total state #[derive(Default, Debug)] @@ -51,7 +54,7 @@ pub struct App { /// Available view profiles and input bindings pub config: Config, /// Currently selected profile - pub profile: Option, + pub profile: Profile, /// Contains the currently edited musical arrangement pub project: Arrangement, /// Contains all recently created clips. @@ -59,34 +62,10 @@ pub struct App { /// Undo history pub history: Vec<(AppCommand, Option)>, /// Dialog overlay - pub dialog: Option, + pub dialog: Dialog, /// Base color. pub color: ItemTheme, } -/// Configuration -#[derive(Default, Debug)] -pub struct Config { - /// XDG basedirs - pub dirs: BaseDirectories, - /// Available view profiles - pub profiles: Arc, Profile>>>, - /// Available input bindings - pub bindings: Arc, Binding>>>, -} -/// Profile -#[derive(Default, Debug)] -pub struct Profile { - /// Path of configuration entrypoint - pub path: PathBuf, - /// Name of configuration - pub name: Option>, - /// Description of configuration - pub info: Option>, - /// View definition - pub view: Arc, - // Input keymap - pub keys: EventMap, -} macro_rules!dsl_expose(($Struct:ident { $($fn:ident: $ret:ty = |$self:ident|$body:expr);* $(;)? })=>{ #[tengri_proc::expose] impl $Struct { $(fn $fn (&$self) -> $ret { $body })* } }); @@ -96,9 +75,9 @@ dsl_expose!(App { w_sidebar: u16 = |self|self.project.w_sidebar(self.editor().is_some()); h_sample_detail: u16 = |self|6.max(self.height() as u16 * 3 / 9); focus_editor: bool = |self|self.project.editor.is_some(); - focus_dialog: bool = |self|self.dialog.is_some(); - focus_message: bool = |self|matches!(self.dialog, Some(Dialog::Message(..))); - focus_device_add: bool = |self|matches!(self.dialog, Some(Dialog::Device(..))); + focus_dialog: bool = |self|!matches!(self.dialog, Dialog::None); + focus_message: bool = |self|matches!(self.dialog, Dialog::Message(..)); + focus_add_device: bool = |self|matches!(self.dialog, Dialog::Device(..)); focus_browser: bool = |self|self.browser().is_some(); focus_clip: bool = |self|!self.focus_editor() && matches!(self.selection(), Selection::TrackClip{..}); focus_track: bool = |self|!self.focus_editor() && matches!(self.selection(), Selection::Track(..)); @@ -134,19 +113,152 @@ dsl_expose!(App { select_track_prev: Selection = |self|self.selection().select_track_prev(); clip_selected: Option>> = |self|match self.selection() { Selection::TrackClip { track, scene } => self.scenes()[*scene].clips[*track].clone(), - _ => None - }; - device_kind: usize = |self|if let Some(Dialog::Device(index)) = self.dialog { + _ => None }; + device_kind: usize = |self|if let Dialog::Device(index) = self.dialog { index } else { 0 }; - device_kind_next: usize = |self|if let Some(Dialog::Device(index)) = self.dialog { + device_kind_next: usize = |self|if let Dialog::Device(index) = self.dialog { (index + 1) % device_kinds().len() } else { 0 }; - device_kind_prev: usize = |self|if let Some(Dialog::Device(index)) = self.dialog { + device_kind_prev: usize = |self|if let Dialog::Device(index) = self.dialog { index.overflowing_sub(1).0.min(device_kinds().len().saturating_sub(1)) } else { 0 }; }); +type ModuleMap = Arc, T>>>; +/// Configuration +#[derive(Default, Debug)] +pub struct Config { + /// XDG basedirs + pub dirs: BaseDirectories, + /// Available view profiles + pub views: ModuleMap, + /// Available input bindings + pub binds: ModuleMap, Arc>>, +} +impl Config { + const VIEWS: &'static str = "views.edn"; + const BINDS: &'static str = "binds.edn"; + const DEFAULT_VIEWS: &'static str = include_str!("../../config/views.edn"); + const DEFAULT_BINDS: &'static str = include_str!("../../config/binds.edn"); + pub fn init () -> Usually { + let mut cfgs: Self = Default::default(); + cfgs.dirs = BaseDirectories::with_profile("tek", "v0"); + cfgs.load(Self::VIEWS, Self::DEFAULT_VIEWS, |cfgs, dsl|cfgs.load_view(dsl))?; + cfgs.load(Self::BINDS, Self::DEFAULT_BINDS, |cfgs, dsl|cfgs.load_bind(dsl))?; + println!("{cfgs:#?}"); + Ok(cfgs) + } + pub fn load ( + &mut self, path: &str, defaults: &str, mut each: impl FnMut(&mut Self, &str)->Usually<()> + ) -> Usually<()> { + if self.dirs.find_config_file(path).is_none() { + println!("init: {path}"); + std::fs::write(self.dirs.place_config_file(path)?, defaults); + } + Ok(if let Some(path) = self.dirs.find_config_file(path) { + let src = std::fs::read_to_string(&path)?; + src.as_str().each(move|item|each(self, item))?; + } else { + return Err(format!("{path}: not found").into()) + }) + } + pub fn load_view (&mut self, dsl: D) -> Usually<()> { + load_mod(dsl, |id, tail|Ok(self.views.write().unwrap().insert(id.into(), + Profile::from_dsl(tail)?))) + } + pub fn load_bind (&mut self, dsl: D) -> Usually<()> { + load_mod(dsl, |id, tail|Ok(self.binds.write().unwrap().insert(id.into(), { + let mut map = EventMap::new(); + tail.each(|item|{ + println!("{item:?}"); + map.add(TuiEvent::from_dsl(item.exp()?.head()?)?, Binding { + command: item.exp()?.tail()?.unwrap_or_default().into(), + condition: None, + description: None, + source: None + }); + Ok(()) + })?; + map + }))) + } +} +fn load_mod (dsl: D, cb: impl Fn(&str, &str)->Usually) -> Usually<()> { + //dsl!(dsl|module :id ..body|dsl!(body|@bind #info? ..commands|) + if let Some(exp) = dsl.exp()? + && Some("module") == exp.head().key()? + && let Some(tail) = exp.tail()? + && let Some(id) = tail.head().sym()? + && let Some(body) = tail.tail()? + { + let _ = cb(id, body)?; + Ok(()) + } else { + return Err("unexpected: {exp:?}".into()); + } +} +/// Profile +#[derive(Default, Debug)] +pub struct Profile { + /// Path of configuration entrypoint + pub path: PathBuf, + /// Name of configuration + pub name: Option>, + /// Description of configuration + pub info: Option>, + /// View definition + pub view: Arc, + // Input keymap + pub keys: EventMap, +} +impl Profile { + fn from_dsl (dsl: impl Dsl) -> Usually { + let mut profile = Self { ..Default::default() }; + dsl.each(|dsl|{ + let head = dsl.head(); + let exp = dsl.exp(); + Ok(if exp.head().key() == Ok(Some("name")) { + profile.name = Some(exp.tail()?.unwrap_or_default().into()); + } else if exp.head().key() == Ok(Some("info")) { + profile.info = Some(exp.tail()?.unwrap_or_default().into()); + }) + })?; + Ok(profile) + } +} +impl Profile { + fn load_template (&mut self, dsl: impl Dsl) -> Usually<&mut Self> { + //dsl.src()?.unwrap_or_default().each(|item|Ok(match () { + //_ if let Some(exp) = dsl.exp()? => match exp.head()?.key()? { + //Some("name") => match exp.tail()?.text()? { + //Some(name) => self.name = Some(name.into()), + //_ => return Err(format!("missing name definition").into()) + //}, + //Some("info") => match exp.tail()?.text()? { + //Some(info) => self.info = Some(info.into()), + //_ => return Err(format!("missing info definition").into()) + //}, + //Some("bind") => match exp.tail()? { + //Some(keys) => self.keys = EventMap::from_dsl(&mut &keys)?, + //_ => return Err(format!("missing keys definition").into()) + //}, + //Some("view") => match exp.tail()? { + //Some(tail) => self.view = tail.src()?.unwrap_or_default().into(), + //_ => return Err(format!("missing view definition").into()) + //}, + //dsl => return Err(format!("unexpected: {dsl:?}").into()) + //}, + //_ => return Err(format!("unexpected: {dsl:?}").into()) + //})); + Ok(self) + } + fn load_binding (&mut self, dsl: impl Dsl) -> Usually<&mut Self> { + todo!(); + Ok(self) + } +} /// Various possible dialog modes. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Default)] pub enum Dialog { + #[default] None, Help(usize), Menu(usize), Device(usize), @@ -155,129 +267,13 @@ pub enum Dialog { Options, } impl App { - pub fn view <'a> (&'a self) -> impl Content + 'a { - Fill::xy(Bsp::a(self.view_overlay(), self.view_content())) - } pub fn update_clock (&self) { ViewCache::update_clock(&self.project.clock.view_cache, self.clock(), self.size.w() > 80) } } -macro_rules!dsl_view(($Struct:ident { $($fn:ident = |$self:ident $(, $arg:ident:$ty:ty)*|$body:expr);* $(;)? })=>{ - content!(TuiOut: |self: $Struct| { - ErrorBoundary::new(Ok(Some(Tui::bg(Black, self.view())))) - }); - #[tengri_proc::view(TuiOut)] impl $Struct { $( - fn $fn (&$self $(, $arg: $ty)*) -> impl Content + '_ { $body } - )* } -}); -dsl_view!(App { - view_nil = |self|"·"; - view_content = |self|Fill::xy(ErrorBoundary::new(Ok(Some(self.view_nil())))); - view_overlay = |self|Fill::xy(ErrorBoundary::new(Ok(Some(Tui::bg(Black, ThunkRender::new(|to| - match self.dialog.as_ref() { - Some(Dialog::Help(scrolled)) => Render::render(&self.view_help(*scrolled), to), - Some(Dialog::Menu(selected)) => Render::render(&self.view_menu(*selected), to), - Some(Dialog::Device(selected)) => Render::render(&self.view_device(*selected), to), - Some(Dialog::Message(message)) => Render::render(&self.view_message(message.clone()), to), - Some(Dialog::Browser(target, browser)) => Render::render(&self.view_browser(target.clone(), browser.clone()), to), - Some(Dialog::Options) => Render::render(&self.view_options(), to), - _ => unimplemented!() })))))); - view_menu = |self, selected: usize|{ - let profiles = self.config.profiles.clone(); - wrap_dialog(wrap_dialog_menu(Stack::south(move|add: &mut dyn FnMut(&dyn Render)|{ - ////let options = ||["Projects", "Settings", "Help", "Quit"].iter(); - ////let option = |a,i|Tui::fg(Rgb(255,255,255), format!("{}", a)); - ////Bsp::s(Tui::bold(true, "tek!"), Bsp::s("", Map::south(1, options, option))) - for (index, (id, profile)) in profiles.read().unwrap().iter().enumerate() { - let bg = if index == 0 { Rgb(64,64,64) } else { Rgb(32,32,32) }; - let name = profile.name.as_ref().map(|x|unquote(unquote(x.as_ref()))); - let info = profile.info.as_ref().map(|x|unquote(unquote(x.as_ref()))); - add(&Fixed::y(3, Tui::bg(bg, Bsp::s( - Fill::x(Bsp::a( - Fill::x(Align::w(Tui::fg(Rgb(224,192,128), name))), - Fill::x(Align::e(Tui::fg(Rgb(224,128,32), &id))) - )), - Fill::x(Align::w(info)))))); } }))) }; - view_help = |self, scrolled: usize|wrap_dialog(Bsp::s(Tui::bold(true, "Help"), "TODO")); - view_options = |self|wrap_dialog("TODO"); - view_message = |self, message: Arc|wrap_dialog(Bsp::s(message.clone(), Bsp::s("", "[ OK ]"))); - view_browser = |self, target: BrowserTarget, browser: Browser|wrap_dialog(Bsp::s( - Padding::xy(3, 1, Fill::x(Align::w(FieldV( - Default::default(), - match target { - BrowserTarget::SaveProject => "Save project:", - BrowserTarget::LoadProject => "Load project:", - BrowserTarget::ImportSample(_) => "Import sample:", - BrowserTarget::ExportSample(_) => "Export sample:", - BrowserTarget::ImportClip(_) => "Import clip:", - BrowserTarget::ExportClip(_) => "Export clip:", - }, - Shrink::x(3, Fixed::y(1, Tui::fg(Tui::g(96), RepeatH("🭻")))))))), - Outer(true, Style::default().fg(Tui::g(96))) - .enclose(Fill::xy(browser)))); - view_device = |self, selected: usize|wrap_dialog(Bsp::s( - Tui::bold(true, "Add device"), - Map::south(1, - move||device_kinds().iter(), - move|label: &&'static str, i| - Fill::x(Tui::bg(if i == selected { Rgb(64,128,32) } else { Rgb(0,0,0) }, - Bsp::e(if i == selected { "[ " } else { " " }, - Bsp::w(if i == selected { " ]" } else { " " }, - "FIXME device name"))))))); - //Bsp::s("", - //Map::south(1, - //move||self.config.bindings.layers.iter() - //.filter_map(|a|(a.0)(self).then_some(a.1)) - //.flat_map(|a|a) - //.filter_map(|x|if let Value::Exp(_, iter)=x.value{ Some(iter) } else { None }) - //.skip(offset) - //.take(20), - //|mut b,i|Fixed::x(60, Align::w(Bsp::e("(", Bsp::e( - //b.next().map(|t|Fixed::x(16, Align::w(Tui::fg(Rgb(64,224,0), format!("{}", t.value))))), - //Bsp::e(" ", Align::w(format!("{}", b.0.0.trim()))))))))))), - - //Dialog::Browser(BrowserTarget::Load, browser) => { - //"bobcat".boxed() - ////Bsp::s( - ////Fill::x(Align::w(Margin::xy(1, 1, Bsp::e( - ////Tui::bold(true, " Load project: "), - ////Shrink::x(3, Fixed::y(1, RepeatH("🭻"))))))), - ////Outer(true, Style::default().fg(Tui::g(96))) - ////.enclose(Fill::xy(browser))) - //}, - //Dialog::Browser(BrowserTarget::Export, browser) => { - //"bobcat".boxed() - ////Bsp::s( - ////Fill::x(Align::w(Margin::xy(1, 1, Bsp::e( - ////Tui::bold(true, " Export: "), - ////Shrink::x(3, Fixed::y(1, RepeatH("🭻"))))))), - ////Outer(true, Style::default().fg(Tui::g(96))) - ////.enclose(Fill::xy(browser))) - //}, - //Dialog::Browser(BrowserTarget::Import, browser) => { - //"bobcat".boxed() - ////Bsp::s( - ////Fill::x(Align::w(Margin::xy(1, 1, Bsp::e( - ////Tui::bold(true, " Import: "), - ////Shrink::x(3, Fixed::y(1, RepeatH("🭻"))))))), - ////Outer(true, Style::default().fg(Tui::g(96))) - ////.enclose(Fill::xy(browser))) - //}, -}); -fn wrap_dialog <'a> (dialog: impl Content + 'a) -> Box + 'a> { - Fixed::xy(70, 23, Tui::fg_bg(Rgb(255,255,255), Rgb(16,16,16), Bsp::b( - Repeat(" "), Outer(true, Style::default().fg(Tui::g(96))).enclose(dialog)))).boxed() -} -fn wrap_dialog_menu <'a> (content: impl Content + 'a) -> Box + 'a> { - Tui::bg(Rgb(0,0,0), Bsp::s( - Fill::x(Fixed::y(3, Tui::bg(Rgb(33,33,33), Tui::bold(true, "tek 0.3.0-rc0")))), - Bsp::n( - Fill::x(Fixed::y(3, Tui::bg(Rgb(33,33,33), Bsp::e(Tui::fg(Rgb(255,192,48), "[Enter]"), " new session")))), - Fill::y(Align::n(Fill::x(content)))))).boxed() -} has!(Jack<'static>: |self: App|self.jack); has!(Pool: |self: App|self.pool); -has!(Option: |self: App|self.dialog); +has!(Dialog: |self: App|self.dialog); has!(Clock: |self: App|self.project.clock); has!(Option: |self: App|self.project.editor); has!(Selection: |self: App|self.project.selection); @@ -294,114 +290,6 @@ maybe_has!(Scene: |self: App| { MaybeHas::::get(&self.project) }; impl HasClipsSize for App { fn clips_size (&self) -> &Measure { &self.project.inner_size } } impl HasTrackScroll for App { fn track_scroll (&self) -> usize { self.project.track_scroll() } } impl HasSceneScroll for App { fn scene_scroll (&self) -> usize { self.project.scene_scroll() } } -impl Profile { - fn from_dsl (dsl: impl Dsl) -> Usually { - let mut profile = Self { ..Default::default() }; - dsl.each(|dsl|{ - let head = dsl.head(); - let exp = dsl.exp(); - Ok(if exp.head().key() == Ok(Some("name")) { - profile.name = Some(exp.tail()?.unwrap_or_default().into()); - } else if exp.head().key() == Ok(Some("info")) { - profile.info = Some(exp.tail()?.unwrap_or_default().into()); - }) - })?; - Ok(profile) - } -} -impl Config { - const PROFILES: &'static str = "profiles.edn"; - const BINDINGS: &'static str = "bindings.edn"; - const DEFAULT_PROFILES: &'static str = include_str!("../../config/profiles.edn"); - const DEFAULT_BINDINGS: &'static str = include_str!("../../config/bindings.edn"); - pub fn init () -> Usually { - let mut dirs = BaseDirectories::with_profile("tek", "v0"); - let mut cfgs = Self { dirs, ..Default::default() }; - cfgs.init_file(Self::PROFILES, Self::DEFAULT_PROFILES)?; - cfgs.load_file(Self::PROFILES, |cfgs, dsl|Ok( - if dsl.exp().head().key() == Ok(Some("module")) { - let exp = dsl.exp()?; - let tail = exp.tail()?; - let head = tail.head()?; - if let Some(id) = head.sym()? { - cfgs.profiles.write().unwrap().insert( - id.into(), - Profile::from_dsl(tail.tail()?)? - ); - } - } else { - return Err("unexpected: {exp:?}".into()); - } - ))?; - cfgs.init_file(Self::BINDINGS, Self::DEFAULT_BINDINGS)?; - cfgs.load_file(Self::BINDINGS, |cfgs, dsl|Ok( - if dsl.exp().head().key() == Ok(Some("module")) { - let exp = dsl.exp()?; - let tail = exp.tail()?; - let head = tail.head()?; - if let Some(id) = head.sym()? { - cfgs.bindings.write().unwrap().insert( - id.into(), - Binding::from_dsl(tail.tail()?)? - ); - } - } else { - return Err("unexpected: {exp:?}".into()); - } - ))?; - println!("{cfgs:#?}"); - Ok(cfgs) - } - fn init_file (&mut self, path: &str, val: &str) -> Usually<()> { - if self.dirs.find_config_file(path).is_none() { - std::fs::write(self.dirs.place_config_file(path)?, val); - } - Ok(()) - } - fn load_file ( - &mut self, - path: &str, - mut each: impl FnMut(&mut Self, &str)->Usually<()> - ) -> Usually<()> { - Ok(if let Some(path) = self.dirs.find_config_file(path) { - let src = std::fs::read_to_string(&path)?; - src.as_str().each(move|item|each(self, item))?; - } else { - return Err(format!("{path}: not found").into()) - }) - } -} -impl Profile { - fn load_template (&mut self, dsl: impl Dsl) -> Usually<&mut Self> { - dsl.src()?.unwrap_or_default().each(|item|Ok(match () { - _ if let Some(exp) = dsl.exp()? => match exp.head()?.key()? { - Some("name") => match exp.tail()?.text()? { - Some(name) => self.name = Some(name.into()), - _ => return Err(format!("missing name definition").into()) - }, - Some("info") => match exp.tail()?.text()? { - Some(info) => self.info = Some(info.into()), - _ => return Err(format!("missing info definition").into()) - }, - Some("bind") => match exp.tail()? { - Some(keys) => self.keys = EventMap::from_dsl(&mut &keys)?, - _ => return Err(format!("missing keys definition").into()) - }, - Some("view") => match exp.tail()? { - Some(tail) => self.view = tail.src()?.unwrap_or_default().into(), - _ => return Err(format!("missing view definition").into()) - }, - dsl => return Err(format!("unexpected: {dsl:?}").into()) - }, - _ => return Err(format!("unexpected: {dsl:?}").into()) - })); - Ok(self) - } - fn load_binding (&mut self, dsl: impl Dsl) -> Usually<&mut Self> { - todo!(); - Ok(self) - } -} fn unquote (x: &str) -> &str { let mut chars = x.chars(); chars.next(); @@ -423,17 +311,17 @@ impl ScenesView for App { impl App { fn handle_tui_key_with_history (&mut self, input: &TuiIn) -> Perhaps { panic!("{input:?}"); - Ok(if let Some(binding) = self.profile.as_ref() - .map(|c|c.keys.dispatch(input.event())).flatten() - { - let binding = binding.clone(); - let undo = binding.command.clone().execute(self)?; - // FIXME failed commands are not persisted in undo history - //self.history.push((binding.command.clone(), undo)); - Some(true) - } else { - None - }) + //Ok(if let Some(binding) = self.profile.as_ref() + //.map(|c|c.keys.dispatch(input.event())).flatten() + //{ + //let binding = binding.clone(); + //let undo = binding.command.clone().execute(self)?; + //// FIXME failed commands are not persisted in undo history + ////self.history.push((binding.command.clone(), undo)); + //Some(true) + //} else { + //None + //}) } } @@ -452,25 +340,20 @@ macro_rules!dsl_bind(($Command:ident: $State:ident { }); dsl_bind!(AppCommand: App { - enqueue = |app, clip: Option>>| { - todo!() }; - history = |app, delta: isize| { - todo!() }; - zoom = |app, zoom: usize| { - todo!() }; - stop_all = |app| { - app.tracks_stop_all(); Ok(None) }; - dialog = |app, command: DialogCommand|Ok( - command.delegate(&mut app.dialog, |command|Self::Dialog{command})?); - project = |app, command: ArrangementCommand|Ok( - command.delegate(&mut app.project, |command|Self::Project{command})?); - clock = |app, command: ClockCommand|Ok( - command.execute(app.clock_mut())?.map(|command|Self::Clock{command})); - sampler = |app, command: SamplerCommand|Ok(app.project.sampler_mut() - .map(|s|command.delegate(s, |command|Self::Sampler{command})) - .transpose()? - .flatten()); - pool = |app, command: PoolCommand| { + enqueue = |app, clip: Option>>| { todo!() }; + history = |app, delta: isize| { todo!() }; + zoom = |app, zoom: usize| { todo!() }; + stop_all = |app| { app.tracks_stop_all(); Ok(None) }; + //dialog = |app, command: DialogCommand| + //Ok(command.delegate(&mut app.dialog, |c|Self::Dialog{command: c})?); + project = |app, command: ArrangementCommand| + Ok(command.delegate(&mut app.project, |c|Self::Project{command: c})?); + clock = |app, command: ClockCommand| + Ok(command.execute(app.clock_mut())?.map(|c|Self::Clock{command: c})); + sampler = |app, command: SamplerCommand| + Ok(app.project.sampler_mut().map(|s|command.delegate(s, |command|Self::Sampler{command})) + .transpose()?.flatten()); + pool = |app, command: PoolCommand| { let undo = command.clone().delegate(&mut app.pool, |command|AppCommand::Pool{command})?; // update linked editor after pool action match command { @@ -547,6 +430,13 @@ dsl_bind!(AppCommand: App { //editor_h = 15; //is_editing = self.editor.is_some(); //}); +impl Dialog { + fn menu_selected (&self) -> Option { todo!() } + fn device_selected (&self) -> Option { todo!() } + fn message (&self) -> Option<&str> { todo!() } + fn browser (&self) -> Option<&Browser> { todo!() } + fn browser_target (&self) -> Option<&BrowserTarget> { todo!() } +} #[tengri_proc::command(Option)] impl DialogCommand { fn open (dialog: &mut Option, new: Dialog) -> Perhaps { *dialog = Some(new); @@ -613,7 +503,7 @@ audio!( ); impl App { - pub fn toggle_dialog (&mut self, mut dialog: Option) -> Option { + pub fn toggle_dialog (&mut self, mut dialog: Dialog) -> Dialog { std::mem::swap(&mut self.dialog, &mut dialog); dialog } @@ -656,15 +546,12 @@ impl App { } } pub fn browser (&self) -> Option<&Browser> { - self.dialog.as_ref().and_then(|dialog|match dialog { - Dialog::Browser(_, b) => Some(b), - _ => None - }) + if let Dialog::Browser(_, ref b) = self.dialog { Some(b) } else { None } } pub fn device_pick (&mut self, index: usize) { - self.dialog = Some(Dialog::Device(index)); + self.dialog = Dialog::Device(index); } - pub fn device_add (&mut self, index: usize) -> Usually<()> { + pub fn add_device (&mut self, index: usize) -> Usually<()> { match index { 0 => { let name = self.jack.with_client(|c|c.name().to_string()); @@ -675,10 +562,10 @@ impl App { let sampler = if let Ok(sampler) = Sampler::new( &self.jack, &port, &[connect], &[&[], &[]], &[&[], &[]] ) { - self.dialog = None; + self.dialog = Dialog::None; Device::Sampler(sampler) } else { - self.dialog = Some(Dialog::Message("Failed to add device.".into())); + self.dialog = Dialog::Message("Failed to add device.".into()); return Err("failed to add device".into()) }; let track = self.track_mut().expect("no active track"); @@ -908,4 +795,3 @@ impl App { //self.project.sampler().map(|s|Outer(true, Style::default().fg(Tui::g(96))).enclose( //Fill::y(Align::n(s.view_sample_status(self.editor().unwrap().get_note_pos()))))) //} -//} diff --git a/crates/app/app_view.rs b/crates/app/app_view.rs new file mode 100644 index 00000000..0f2244d6 --- /dev/null +++ b/crates/app/app_view.rs @@ -0,0 +1,159 @@ +use crate::*; +pub(crate) use std::marker::PhantomData; +content!(TuiOut:|self: App|"kyp");//VIEW.content(self, "(bg :color/black (fill/xy (bsp/a overlay content)))")); +struct DslView<'s, O: Output, T> { + symbol: &'s str, + callback: Option fn (&'t T) -> Box + 't>>, + next: Option<&'s Self> +} +pub const VIEW: DslView<'static, TuiOut, App> = DslView::new() + .def("browser", view_browser) + .def("content", view_content) + .def("device", view_device) + .def("menu", view_menu) + //.def("options", view_options) + .def("overlay", view_overlay); +impl<'s, O: Output, T> DslView<'s, O, T> { + pub const fn new () -> Self { + DslView { symbol: "", callback: None, next: None } + } + pub const fn def ( + &'static self, + symbol: &'static str, + callback: fn (&T) -> Box + '_> + ) -> Self { + DslView { symbol, callback: Some(callback), next: Some(self) } + } + pub fn content <'t> ( + &'static self, state: &'t T, src: impl Dsl) -> Usually + 't>> { + Ok(if src.sym()? == Some(self.symbol) && let Some(callback) = self.callback { + callback(&state) + } else if let Some(next) = self.next { + next.content(state, src)? + } else { + return Err("DslView::content: undefined".into()) + }) + } + //fn render (&self, state: &T, output: &mut O, src: impl Dsl) -> Usually<()> { + //Ok(if src.sym()? == Some(self.0) && let Some(callback) = self.1 { + //let view = callback(&state); + //output.place(output.area(), &view) + //} else if let Some(next) = self.2 { + //next.render(state, output, src)? + //} else { + //return Err("DslView::render: undefined".into()) + //}) + //} +} + + +fn view_content (app: &App) -> Box + '_> { + Fill::xy(ErrorBoundary::new(Ok(Some("·")))).boxed() +} +fn view_overlay <'s> (state: &'s App) -> Box + 's> { + match &state.dialog { + Dialog::Menu(_) => view_menu(state), + Dialog::Device(_) => view_device(state), + Dialog::Browser(_, _) => view_browser(state), + //Dialog::Help(_) => view_help, + //Dialog::Message(_) => view_message, + //Dialog::Options => view_options, + _ => unimplemented!() + } +} +fn wrap_dialog <'s> (dialog: impl Content + 's) -> impl Content + 's { + Fixed::xy(70, 23, Tui::fg_bg(Rgb(255,255,255), Rgb(16,16,16), Bsp::b( + Repeat(" "), Outer(true, Style::default().fg(Tui::g(96))).enclose(dialog)))) +} +fn wrap_dialog_menu <'a> (content: impl Content + 'a) -> Box + 'a> { + Box::new(Tui::bg(Rgb(0,0,0), Bsp::s( + Fill::x(Fixed::y(3, Tui::bg(Rgb(33,33,33), Tui::bold(true, "tek 0.3.0-rc0")))), + Bsp::n( + Fill::x(Fixed::y(3, Tui::bg(Rgb(33,33,33), Bsp::e(Tui::fg(Rgb(255,192,48), "[Enter]"), " new session")))), + Fill::y(Align::n(Fill::x(content))))))) +} +fn view_menu <'s> (state: &'s App) -> Box + 's> { + let views = state.config.views.clone(); + let selected = state.dialog.menu_selected(); + wrap_dialog_menu(Stack::south(move|add: &mut dyn FnMut(&dyn Render)|{ + ////let options = ||["Projects", "Settings", "Help", "Quit"].iter(); + ////let option = |a,i|Tui::fg(Rgb(255,255,255), format!("{}", a)); + ////Bsp::s(Tui::bold(true, "tek!"), Bsp::s("", Map::south(1, options, option))) + for (index, (id, profile)) in views.read().unwrap().iter().enumerate() { + let bg = if index == 0 { Rgb(64,64,64) } else { Rgb(32,32,32) }; + let name = profile.name.as_ref().map(|x|unquote(unquote(x.as_ref()))); + let info = profile.info.as_ref().map(|x|unquote(unquote(x.as_ref()))); + add(&Fixed::y(3, Tui::bg(bg, Bsp::s( + Fill::x(Bsp::a( + Fill::x(Align::w(Tui::fg(Rgb(224,192,128), name))), + Fill::x(Align::e(Tui::fg(Rgb(224,128,32), &id))) + )), + Fill::x(Align::w(info)))))); } })) +} +fn view_browser <'s> (state: &'s App) -> Box + 's> { + let target = &state.dialog.browser_target().clone().unwrap(); + Box::new(Bsp::s( + Padding::xy(3, 1, Fill::x(Align::w(FieldV( + Default::default(), + match &target { + BrowserTarget::SaveProject => "Save project:", + BrowserTarget::LoadProject => "Load project:", + BrowserTarget::ImportSample(_) => "Import sample:", + BrowserTarget::ExportSample(_) => "Export sample:", + BrowserTarget::ImportClip(_) => "Import clip:", + BrowserTarget::ExportClip(_) => "Export clip:", + }, + Shrink::x(3, Fixed::y(1, Tui::fg(Tui::g(96), RepeatH("🭻")))))))), + Outer(true, Style::default().fg(Tui::g(96))) + .enclose(Fill::xy(state.dialog.browser())))) +} +fn view_device <'s> (state: &'s App) -> Box + 's> { + let selected = state.dialog.device_selected().unwrap(); + Box::new(Bsp::s(Tui::bold(true, "Add device"), Map::south(1, + move||device_kinds().iter(), + move|label: &&'static str, i| + Fill::x(Tui::bg(if i == selected { Rgb(64,128,32) } else { Rgb(0,0,0) }, + Bsp::e(if i == state.dialog.device_selected().unwrap() { "[ " } else { " " }, + Bsp::w(if i == state.dialog.device_selected().unwrap() { " ]" } else { " " }, + "FIXME device name"))))))) +} + + //Bsp::s("", + //Map::south(1, + //move||app.config.binds.layers.iter() + //.filter_map(|a|(a.0)(app).then_some(a.1)) + //.flat_map(|a|a) + //.filter_map(|x|if let Value::Exp(_, iter)=x.value{ Some(iter) } else { None }) + //.skip(offset) + //.take(20), + //|mut b,i|Fixed::x(60, Align::w(Bsp::e("(", Bsp::e( + //b.next().map(|t|Fixed::x(16, Align::w(Tui::fg(Rgb(64,224,0), format!("{}", t.value))))), + //Bsp::e(" ", Align::w(format!("{}", b.0.0.trim()))))))))))), + + //Dialog::Browser(BrowserTarget::Load, browser) => { + //"bobcat".boxed() + ////Bsp::s( + ////Fill::x(Align::w(Margin::xy(1, 1, Bsp::e( + ////Tui::bold(true, " Load project: "), + ////Shrink::x(3, Fixed::y(1, RepeatH("🭻"))))))), + ////Outer(true, Style::default().fg(Tui::g(96))) + ////.enclose(Fill::xy(browser))) + //}, + //Dialog::Browser(BrowserTarget::Export, browser) => { + //"bobcat".boxed() + ////Bsp::s( + ////Fill::x(Align::w(Margin::xy(1, 1, Bsp::e( + ////Tui::bold(true, " Export: "), + ////Shrink::x(3, Fixed::y(1, RepeatH("🭻"))))))), + ////Outer(true, Style::default().fg(Tui::g(96))) + ////.enclose(Fill::xy(browser))) + //}, + //Dialog::Browser(BrowserTarget::Import, browser) => { + //"bobcat".boxed() + ////Bsp::s( + ////Fill::x(Align::w(Margin::xy(1, 1, Bsp::e( + ////Tui::bold(true, " Import: "), + ////Shrink::x(3, Fixed::y(1, RepeatH("🭻"))))))), + ////Outer(true, Style::default().fg(Tui::g(96))) + ////.enclose(Fill::xy(browser))) + //}, diff --git a/crates/cli/tek.rs b/crates/cli/tek.rs index fbd67aeb..529eb63a 100644 --- a/crates/cli/tek.rs +++ b/crates/cli/tek.rs @@ -78,7 +78,7 @@ impl Cli { jack: jack.clone(), config: Config::init()?, color: ItemTheme::random(), - dialog: Some(Dialog::Menu(0)), + dialog: Dialog::Menu(0), project: Arrangement { name: Default::default(), color: ItemTheme::random(), diff --git a/deps/tengri b/deps/tengri index b52c1f58..4515d2cc 160000 --- a/deps/tengri +++ b/deps/tengri @@ -1 +1 @@ -Subproject commit b52c1f582880d08e663411e9238d3fdacfda9473 +Subproject commit 4515d2cc6f9d8d67782c175ebc5b560923295314 From 525ed15466ead1be4c6567525cd5bf119746dffa Mon Sep 17 00:00:00 2001 From: unspeaker Date: Sun, 10 Aug 2025 02:06:26 +0300 Subject: [PATCH 2/5] dsl_ns! --- crates/app/app.rs | 554 +---------------------------------------- crates/app/app_ctrl.rs | 308 +++++++++++++++++++++++ crates/app/app_jack.rs | 57 +++++ crates/app/app_view.rs | 387 +++++++++++++++++++--------- deps/tengri | 2 +- 5 files changed, 643 insertions(+), 665 deletions(-) create mode 100644 crates/app/app_ctrl.rs create mode 100644 crates/app/app_jack.rs diff --git a/crates/app/app.rs b/crates/app/app.rs index a3e195c4..31ef27db 100644 --- a/crates/app/app.rs +++ b/crates/app/app.rs @@ -41,6 +41,8 @@ use std::fmt::Write; use ::tengri::tui::ratatui::prelude::Position; use xdg::BaseDirectories; mod app_view; pub use self::app_view::*; +mod app_ctrl; pub use self::app_ctrl::*; +mod app_jack; pub use self::app_jack::*; #[cfg(test)] mod app_test; /// Total state #[derive(Default, Debug)] @@ -66,62 +68,6 @@ pub struct App { /// Base color. pub color: ItemTheme, } -macro_rules!dsl_expose(($Struct:ident { $($fn:ident: $ret:ty = |$self:ident|$body:expr);* $(;)? })=>{ - #[tengri_proc::expose] impl $Struct { $(fn $fn (&$self) -> $ret { $body })* } -}); -dsl_expose!(App { - _isize_stub: isize = |self|todo!(); - _item_theme_stub: ItemTheme = |self|todo!(); - w_sidebar: u16 = |self|self.project.w_sidebar(self.editor().is_some()); - h_sample_detail: u16 = |self|6.max(self.height() as u16 * 3 / 9); - focus_editor: bool = |self|self.project.editor.is_some(); - focus_dialog: bool = |self|!matches!(self.dialog, Dialog::None); - focus_message: bool = |self|matches!(self.dialog, Dialog::Message(..)); - focus_add_device: bool = |self|matches!(self.dialog, Dialog::Device(..)); - focus_browser: bool = |self|self.browser().is_some(); - focus_clip: bool = |self|!self.focus_editor() && matches!(self.selection(), Selection::TrackClip{..}); - focus_track: bool = |self|!self.focus_editor() && matches!(self.selection(), Selection::Track(..)); - focus_scene: bool = |self|!self.focus_editor() && matches!(self.selection(), Selection::Scene(..)); - focus_mix: bool = |self|!self.focus_editor() && matches!(self.selection(), Selection::Mix); - focus_pool_import: bool = |self|matches!(self.pool.mode, Some(PoolMode::Import(..))); - focus_pool_export: bool = |self|matches!(self.pool.mode, Some(PoolMode::Export(..))); - focus_pool_rename: bool = |self|matches!(self.pool.mode, Some(PoolMode::Rename(..))); - focus_pool_length: bool = |self|matches!(self.pool.mode, Some(PoolMode::Length(..))); - dialog_none: Option = |self|None; - dialog_device: Option = |self|Some(Dialog::Device(0)); // TODO - dialog_device_prev: Option = |self|Some(Dialog::Device(0)); // TODO - dialog_device_next: Option = |self|Some(Dialog::Device(0)); // TODO - dialog_help: Option = |self|Some(Dialog::Help(0)); - dialog_menu: Option = |self|Some(Dialog::Menu(0)); - dialog_save: Option = |self|Some(Dialog::Browser(BrowserTarget::SaveProject, Browser::new(None).unwrap())); - dialog_load: Option = |self|Some(Dialog::Browser(BrowserTarget::LoadProject, Browser::new(None).unwrap())); - dialog_import_clip: Option = |self|Some(Dialog::Browser(BrowserTarget::ImportClip(Default::default()), Browser::new(None).unwrap())); - dialog_export_clip: Option = |self|Some(Dialog::Browser(BrowserTarget::ExportClip(Default::default()), Browser::new(None).unwrap())); - dialog_import_sample: Option = |self|Some(Dialog::Browser(BrowserTarget::ImportSample(Default::default()), Browser::new(None).unwrap())); - dialog_export_sample: Option = |self|Some(Dialog::Browser(BrowserTarget::ExportSample(Default::default()), Browser::new(None).unwrap())); - dialog_options: Option = |self|Some(Dialog::Options); - editor_pitch: Option = |self|Some((self.editor().as_ref().map(|e|e.get_note_pos()).unwrap() as u8).into()); - scene_count: usize = |self|self.scenes().len(); - scene_selected: Option = |self|self.selection().scene(); - track_count: usize = |self|self.tracks().len(); - track_selected: Option = |self|self.selection().track(); - select_scene: Selection = |self|self.selection().select_scene(self.tracks().len()); - select_scene_next: Selection = |self|self.selection().select_scene_next(self.scenes().len()); - select_scene_prev: Selection = |self|self.selection().select_scene_prev(); - select_track: Selection = |self|self.selection().select_track(self.tracks().len()); - select_track_next: Selection = |self|self.selection().select_track_next(self.tracks().len()); - select_track_prev: Selection = |self|self.selection().select_track_prev(); - clip_selected: Option>> = |self|match self.selection() { - Selection::TrackClip { track, scene } => self.scenes()[*scene].clips[*track].clone(), - _ => None }; - device_kind: usize = |self|if let Dialog::Device(index) = self.dialog { - index } else { 0 }; - device_kind_next: usize = |self|if let Dialog::Device(index) = self.dialog { - (index + 1) % device_kinds().len() } else { 0 }; - device_kind_prev: usize = |self|if let Dialog::Device(index) = self.dialog { - index.overflowing_sub(1).0.min(device_kinds().len().saturating_sub(1)) - } else { 0 }; -}); type ModuleMap = Arc, T>>>; /// Configuration #[derive(Default, Debug)] @@ -263,7 +209,7 @@ pub enum Dialog { Menu(usize), Device(usize), Message(Arc), - Browser(BrowserTarget, Browser), + Browser(BrowserTarget, Arc), Options, } impl App { @@ -296,502 +242,10 @@ fn unquote (x: &str) -> &str { //chars.next_back(); chars.as_str() } -impl ScenesView for App { - fn h_scenes (&self) -> u16 { - (self.height() as u16).saturating_sub(20) - } - fn w_side (&self) -> u16 { - 20 - } - fn w_mid (&self) -> u16 { - (self.width() as u16).saturating_sub(self.w_side()) - } -} - -impl App { - fn handle_tui_key_with_history (&mut self, input: &TuiIn) -> Perhaps { - panic!("{input:?}"); - //Ok(if let Some(binding) = self.profile.as_ref() - //.map(|c|c.keys.dispatch(input.event())).flatten() - //{ - //let binding = binding.clone(); - //let undo = binding.command.clone().execute(self)?; - //// FIXME failed commands are not persisted in undo history - ////self.history.push((binding.command.clone(), undo)); - //Some(true) - //} else { - //None - //}) - } -} - -type MaybeClip = Option>>; -macro_rules! ns { ($C:ty, $s:expr, $a:expr, $W:expr) => { <$C>::try_from_expr($s, $a).map($W) } } -macro_rules! cmd { ($cmd:expr) => {{ $cmd; None }}; } -macro_rules! cmd_todo { ($msg:literal) => {{ println!($msg); None }}; } - -macro_rules!dsl_bind(($Command:ident: $State:ident { - $($fn:ident = |$state:ident $(, $arg:ident:$ty:ty)*|$body:expr);* $(;)? -})=>{ - handle!(TuiIn: |self: $State, input|self.handle_tui_key_with_history(input)); - #[tengri_proc::command(App)] impl $Command { - $(fn $fn ($state: &mut $State $(, $arg:$ty)*) -> Perhaps { $body })* - } -}); - -dsl_bind!(AppCommand: App { - enqueue = |app, clip: Option>>| { todo!() }; - history = |app, delta: isize| { todo!() }; - zoom = |app, zoom: usize| { todo!() }; - stop_all = |app| { app.tracks_stop_all(); Ok(None) }; - //dialog = |app, command: DialogCommand| - //Ok(command.delegate(&mut app.dialog, |c|Self::Dialog{command: c})?); - project = |app, command: ArrangementCommand| - Ok(command.delegate(&mut app.project, |c|Self::Project{command: c})?); - clock = |app, command: ClockCommand| - Ok(command.execute(app.clock_mut())?.map(|c|Self::Clock{command: c})); - sampler = |app, command: SamplerCommand| - Ok(app.project.sampler_mut().map(|s|command.delegate(s, |command|Self::Sampler{command})) - .transpose()?.flatten()); - pool = |app, command: PoolCommand| { - let undo = command.clone().delegate(&mut app.pool, |command|AppCommand::Pool{command})?; - // update linked editor after pool action - match command { - // autoselect: automatically load selected clip in editor - PoolCommand::Select { .. } | - // autocolor: update color in all places simultaneously - PoolCommand::Clip { command: PoolClipCommand::SetColor { .. } } => { - let clip = app.pool.clip().clone(); - app.editor_mut().map(|editor|editor.set_clip(clip.as_ref())) - }, - _ => None - }; - Ok(undo) - }; - select = |app, selection: Selection| { - *app.project.selection_mut() = selection; - //todo! - //if let Some(ref mut editor) = app.editor_mut() { - //editor.set_clip(match selection { - //Selection::TrackClip { track, scene } if let Some(Some(Some(clip))) = app - //.project - //.scenes.get(scene) - //.map(|s|s.clips.get(track)) - //=> - //Some(clip), - //_ => - //None - //}); - //} - Ok(None) - //("select" [t: usize, s: usize] Some(match (t.expect("no track"), s.expect("no scene")) { - //(0, 0) => Self::Select(Selection::Mix), - //(t, 0) => Self::Select(Selection::Track(t)), - //(0, s) => Self::Select(Selection::Scene(s)), - //(t, s) => Self::Select(Selection::TrackClip { track: t, scene: s }) }))) - // autoedit: load focused clip in editor. - }; - //fn color (app: &mut App, theme: ItemTheme) -> Perhaps { - //Ok(app.set_color(Some(theme)).map(|theme|Self::Color{theme})) - //} - //fn launch (app: &mut App) -> Perhaps { - //app.project.launch(); - //Ok(None) - //} - toggle_editor = |app, value: bool|{ app.toggle_editor(Some(value)); Ok(None) }; - editor = |app, command: MidiEditCommand| Ok(if let Some(editor) = app.editor_mut() { - let undo = command.clone().delegate(editor, |command|AppCommand::Editor{command})?; - // update linked sampler after editor action - app.project.sampler_mut().map(|sampler|match command { - // autoselect: automatically select sample in sampler - MidiEditCommand::SetNotePos { pos } => { sampler.set_note_pos(pos); }, - _ => {} - }); - undo - } else { - None - }); -}); -//take!(ClockCommand |state: App, iter|Take::take(state.clock(), iter)); -//take!(MidiEditCommand |state: App, iter|Ok(state.editor().map(|x|Take::take(x, iter)).transpose()?.flatten())); -//take!(PoolCommand |state: App, iter|Take::take(&state.pool, iter)); -//take!(SamplerCommand |state: App, iter|Ok(state.project.sampler().map(|x|Take::take(x, iter)).transpose()?.flatten())); -//take!(ArrangementCommand |state: App, iter|Take::take(&state.project, iter)); -//take!(DialogCommand |state: App, iter|Take::take(&state.dialog, iter)); -//has_editor!(|self: App|{ - //editor = self.editor; - //editor_w = { - //let size = self.size.w(); - //let editor = self.editor.as_ref().expect("missing editor"); - //let time_len = editor.time_len().get(); - //let time_zoom = editor.time_zoom().get().max(1); - //(5 + (time_len / time_zoom)).min(size.saturating_sub(20)).max(16) - //}; - //editor_h = 15; - //is_editing = self.editor.is_some(); -//}); impl Dialog { fn menu_selected (&self) -> Option { todo!() } fn device_selected (&self) -> Option { todo!() } fn message (&self) -> Option<&str> { todo!() } - fn browser (&self) -> Option<&Browser> { todo!() } + fn browser (&self) -> Option<&Arc> { todo!() } fn browser_target (&self) -> Option<&BrowserTarget> { todo!() } } -#[tengri_proc::command(Option)] impl DialogCommand { - fn open (dialog: &mut Option, new: Dialog) -> Perhaps { - *dialog = Some(new); - Ok(None) - } - fn close (dialog: &mut Option) -> Perhaps { - *dialog = None; - Ok(None) - } -} -impl HasJack<'static> for App { - fn jack (&self) -> &Jack<'static> { - &self.jack - } -} -audio!( - |self: App, client, scope|{ - let t0 = self.perf.get_t0(); - self.clock().update_from_scope(scope).unwrap(); - let midi_in = self.project.midi_input_collect(scope); - if let Some(editor) = &self.editor() { - let mut pitch: Option = None; - for port in midi_in.iter() { - for event in port.iter() { - if let (_, Ok(LiveEvent::Midi {message: MidiMessage::NoteOn {ref key, ..}, ..})) - = event - { - pitch = Some(key.clone()); - } - } - } - if let Some(pitch) = pitch { - editor.set_note_pos(pitch.as_int() as usize); - } - } - let result = self.project.process_tracks(client, scope); - self.perf.update_from_jack_scope(t0, scope); - result - }; - |self, event|{ - use JackEvent::*; - match event { - SampleRate(sr) => { - self.clock().timebase.sr.set(sr as f64); - }, - PortRegistration(id, true) => { - //let port = self.jack().port_by_id(id); - //println!("\rport add: {id} {port:?}"); - //println!("\rport add: {id}"); - }, - PortRegistration(id, false) => { - /*println!("\rport del: {id}")*/ - }, - PortsConnected(a, b, true) => { /*println!("\rport conn: {a} {b}")*/ }, - PortsConnected(a, b, false) => { /*println!("\rport disc: {a} {b}")*/ }, - ClientRegistration(id, true) => {}, - ClientRegistration(id, false) => {}, - ThreadInit => {}, - XRun => {}, - GraphReorder => {}, - _ => { panic!("{event:?}"); } - } - } -); - -impl App { - pub fn toggle_dialog (&mut self, mut dialog: Dialog) -> Dialog { - std::mem::swap(&mut self.dialog, &mut dialog); - dialog - } - pub fn toggle_editor (&mut self, value: Option) { - //FIXME: self.editing.store(value.unwrap_or_else(||!self.is_editing()), Relaxed); - let value = value.unwrap_or_else(||!self.editor().is_some()); - if value { - // Create new clip in pool when entering empty cell - if let Selection::TrackClip { track, scene } = *self.selection() - && let Some(scene) = self.project.scenes.get_mut(scene) - && let Some(slot) = scene.clips.get_mut(track) - && slot.is_none() - && let Some(track) = self.project.tracks.get_mut(track) - { - let (index, mut clip) = self.pool.add_new_clip(); - // autocolor: new clip colors from scene and track color - let color = track.color.base.mix(scene.color.base, 0.5); - clip.write().unwrap().color = ItemColor::random_near(color, 0.2).into(); - if let Some(ref mut editor) = &mut self.project.editor { - editor.set_clip(Some(&clip)); - } - *slot = Some(clip.clone()); - //Some(clip) - } else { - //None - } - } else if let Selection::TrackClip { track, scene } = *self.selection() - && let Some(scene) = self.project.scenes.get_mut(scene) - && let Some(slot) = scene.clips.get_mut(track) - && let Some(clip) = slot.as_mut() - { - // Remove clip from arrangement when exiting empty clip editor - let mut swapped = None; - if clip.read().unwrap().count_midi_messages() == 0 { - std::mem::swap(&mut swapped, slot); - } - if let Some(clip) = swapped { - self.pool.delete_clip(&clip.read().unwrap()); - } - } - } - pub fn browser (&self) -> Option<&Browser> { - if let Dialog::Browser(_, ref b) = self.dialog { Some(b) } else { None } - } - pub fn device_pick (&mut self, index: usize) { - self.dialog = Dialog::Device(index); - } - pub fn add_device (&mut self, index: usize) -> Usually<()> { - match index { - 0 => { - let name = self.jack.with_client(|c|c.name().to_string()); - let midi = self.project.track().expect("no active track").sequencer.midi_outs[0].port_name(); - let track = self.track().expect("no active track"); - let port = format!("{}/Sampler", &track.name); - let connect = Connect::exact(format!("{name}:{midi}")); - let sampler = if let Ok(sampler) = Sampler::new( - &self.jack, &port, &[connect], &[&[], &[]], &[&[], &[]] - ) { - self.dialog = Dialog::None; - Device::Sampler(sampler) - } else { - self.dialog = Dialog::Message("Failed to add device.".into()); - return Err("failed to add device".into()) - }; - let track = self.track_mut().expect("no active track"); - track.devices.push(sampler); - Ok(()) - }, - 1 => { - todo!(); - Ok(()) - }, - _ => unreachable!(), - } - } -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// - -//#[derive(Clone, Debug)] -//pub enum DialogCommand { - //Open { dialog: Dialog }, - //Close -//} - -//impl Command> for DialogCommand { - //fn execute (self, state: &mut Option) -> Perhaps { - //match self { - //Self::Open { dialog } => { - //*state = Some(dialog); - //}, - //Self::Close => { - //*state = None; - //} - //}; - //Ok(None) - //} -//} - -//dsl!(DialogCommand: |self: Dialog, iter|todo!()); -//Dsl::take(&mut self.dialog, iter)); - -//#[tengri_proc::command(Option)]//Nope. -//impl DialogCommand { - //fn open (dialog: &mut Option, new: Dialog) -> Perhaps { - //*dialog = Some(new); - //Ok(None) - //} - //fn close (dialog: &mut Option) -> Perhaps { - //*dialog = None; - //Ok(None) - //} -//} -// -/////////////////////////////////////////////////////////////////////////////////////////////////// -// - //pub fn view_meters_input (&self) -> impl Content + use<'_> { - //self.project.sampler().map(|s| - //s.view_meters_input()) - //} - //pub fn view_meters_output (&self) -> impl Content + use<'_> { - //self.project.sampler().map(|s| - //s.view_meters_output()) - //} - //pub fn view_history (&self) -> impl Content { - //Fixed::y(1, Fill::x(Align::w(FieldH(self.color, - //format!("History ({})", self.history.len()), - //self.history.last().map(|last|Fill::x(Align::w(format!("{:?}", last.0)))))))) - //} - //pub fn view_status_h2 (&self) -> impl Content { - //self.update_clock(); - //let theme = self.color; - //let clock = self.clock(); - //let playing = clock.is_rolling(); - //let cache = clock.view_cache.clone(); - ////let selection = self.selection().describe(self.tracks(), self.scenes()); - //let hist_len = self.history.len(); - //let hist_last = self.history.last(); - //Fixed::y(2, Stack::east(move|add: &mut dyn FnMut(&dyn Render)|{ - //add(&Fixed::x(5, Tui::bg(if playing { Rgb(0, 128, 0) } else { Rgb(128, 64, 0) }, - //Either::new(false, // TODO - //Thunk::new(move||Fixed::x(9, Either::new(playing, - //Tui::fg(Rgb(0, 255, 0), " PLAYING "), - //Tui::fg(Rgb(255, 128, 0), " STOPPED "))) - //), - //Thunk::new(move||Fixed::x(5, Either::new(playing, - //Tui::fg(Rgb(0, 255, 0), Bsp::s(" 🭍🭑🬽 ", " 🭞🭜🭘 ",)), - //Tui::fg(Rgb(255, 128, 0), Bsp::s(" ▗▄▖ ", " ▝▀▘ ",)))) - //) - //) - //))); - //add(&" "); - //{ - //let cache = cache.read().unwrap(); - //add(&Fixed::x(15, Align::w(Bsp::s( - //FieldH(theme, "Beat", cache.beat.view.clone()), - //FieldH(theme, "Time", cache.time.view.clone()), - //)))); - //add(&Fixed::x(13, Align::w(Bsp::s( - //Fill::x(Align::w(FieldH(theme, "BPM", cache.bpm.view.clone()))), - //Fill::x(Align::w(FieldH(theme, "SR ", cache.sr.view.clone()))), - //)))); - //add(&Fixed::x(12, Align::w(Bsp::s( - //Fill::x(Align::w(FieldH(theme, "Buf", cache.buf.view.clone()))), - //Fill::x(Align::w(FieldH(theme, "Lat", cache.lat.view.clone()))), - //)))); - ////add(&Bsp::s( - //////Fill::x(Align::w(FieldH(theme, "Selected", Align::w(selection)))), - ////Fill::x(Align::w(FieldH(theme, format!("History ({})", hist_len), - ////hist_last.map(|last|Fill::x(Align::w(format!("{:?}", last.0))))))), - ////"" - ////)); - //////if let Some(last) = self.history.last() { - //////add(&FieldV(theme, format!("History ({})", self.history.len()), - //////Fill::x(Align::w(format!("{:?}", last.0))))); - //////} - //} - //})) - //} - //pub fn view_status_v (&self) -> impl Content + use<'_> { - //self.update_clock(); - //let cache = self.project.clock.view_cache.read().unwrap(); - //let theme = self.color; - //let playing = self.clock().is_rolling(); - //Tui::bg(theme.darker.rgb, Fixed::xy(20, 5, Outer(true, Style::default().fg(Tui::g(96))).enclose( - //col!( - //Fill::x(Align::w(Bsp::e( - //Align::w(Tui::bg(if playing { Rgb(0, 128, 0) } else { Rgb(128, 64, 0) }, - //Either::new(false, // TODO - //Thunk::new(move||Fixed::x(9, Either::new(playing, - //Tui::fg(Rgb(0, 255, 0), " PLAYING "), - //Tui::fg(Rgb(255, 128, 0), " STOPPED "))) - //), - //Thunk::new(move||Fixed::x(5, Either::new(playing, - //Tui::fg(Rgb(0, 255, 0), Bsp::s(" 🭍🭑🬽 ", " 🭞🭜🭘 ",)), - //Tui::fg(Rgb(255, 128, 0), Bsp::s(" ▗▄▖ ", " ▝▀▘ ",)))) - //) - //) - //)), - //Bsp::s( - //FieldH(theme, "Beat", cache.beat.view.clone()), - //FieldH(theme, "Time", cache.time.view.clone()), - //), - //))), - //Fill::x(Align::w(FieldH(theme, "BPM", cache.bpm.view.clone()))), - //Fill::x(Align::w(FieldH(theme, "SR ", cache.sr.view.clone()))), - //Fill::x(Align::w(FieldH(theme, "Buf", Bsp::e(cache.buf.view.clone(), Bsp::e(" = ", cache.lat.view.clone()))))), - //)))) - //} - //pub fn view_status (&self) -> impl Content + use<'_> { - //self.update_clock(); - //let cache = self.project.clock.view_cache.read().unwrap(); - //view_status(Some(self.project.selection.describe(self.tracks(), self.scenes())), - //cache.sr.view.clone(), cache.buf.view.clone(), cache.lat.view.clone()) - //} - //pub fn view_transport (&self) -> impl Content + use<'_> { - //self.update_clock(); - //let cache = self.project.clock.view_cache.read().unwrap(); - //view_transport(self.project.clock.is_rolling(), - //cache.bpm.view.clone(), cache.beat.view.clone(), cache.time.view.clone()) - //} - //pub fn view_editor (&self) -> impl Content + use<'_> { - //let bg = self.editor() - //.and_then(|editor|editor.clip().clone()) - //.map(|clip|clip.read().unwrap().color.darker) - //.unwrap_or(self.color.darker); - //Fill::xy(Tui::bg(bg.rgb, self.editor())) - //} - //pub fn view_editor_status (&self) -> impl Content + use<'_> { - //self.editor().map(|e|Fixed::x(20, Outer(true, Style::default().fg(Tui::g(96))).enclose( - //Fill::y(Align::n(Bsp::s(e.clip_status(), e.edit_status())))))) - //} - //pub fn view_midi_ins_status (&self) -> impl Content + use<'_> { - //self.project.view_midi_ins_status(self.color) - //} - //pub fn view_midi_outs_status (&self) -> impl Content + use<'_> { - //self.project.view_midi_outs_status(self.color) - //} - //pub fn view_audio_ins_status (&self) -> impl Content + use<'_> { - //self.project.view_audio_ins_status(self.color) - //} - //pub fn view_audio_outs_status (&self) -> impl Content + use<'_> { - //self.project.view_audio_outs_status(self.color) - //} - //pub fn view_scenes (&self) -> impl Content + use<'_> { - //Bsp::e( - //Fixed::x(20, Align::nw(self.project.view_scenes_names())), - //self.project.view_scenes_clips(), - //) - //} - //pub fn view_scenes_names (&self) -> impl Content + use<'_> { - //self.project.view_scenes_names() - //} - //pub fn view_scenes_clips (&self) -> impl Content + use<'_> { - //self.project.view_scenes_clips() - //} - //pub fn view_tracks_inputs <'a> (&'a self) -> impl Content + use<'a> { - //Fixed::y(1 + self.project.midi_ins.len() as u16, - //self.project.view_inputs(self.color)) - //} - //pub fn view_tracks_outputs <'a> (&'a self) -> impl Content + use<'a> { - //self.project.view_outputs(self.color) - //} - //pub fn view_tracks_devices <'a> (&'a self) -> impl Content + use<'a> { - //Fixed::y(4, self.project.view_track_devices(self.color)) - //} - //pub fn view_tracks_names <'a> (&'a self) -> impl Content + use<'a> { - //Fixed::y(2, self.project.view_track_names(self.color)) - //} - //pub fn view_pool (&self) -> impl Content + use<'_> { - //Fixed::x(20, Bsp::s( - //Fill::x(Align::w(FieldH(self.color, "Clip pool:", ""))), - //Fill::y(Align::n(Tui::bg(Rgb(0, 0, 0), Outer(true, Style::default().fg(Tui::g(96))) - //.enclose(PoolView(&self.pool))))))) - //} - //pub fn view_samples_keys (&self) -> impl Content + use<'_> { - //self.project.sampler().map(|s|s.view_list(true, self.editor().unwrap())) - //} - //pub fn view_samples_grid (&self) -> impl Content + use<'_> { - //self.project.sampler().map(|s|s.view_grid()) - //} - //pub fn view_sample_viewer (&self) -> impl Content + use<'_> { - //self.project.sampler().map(|s|s.view_sample(self.editor().unwrap().get_note_pos())) - //} - //pub fn view_sample_info (&self) -> impl Content + use<'_> { - //self.project.sampler().map(|s|s.view_sample_info(self.editor().unwrap().get_note_pos())) - //} - //pub fn view_sample_status (&self) -> impl Content + use<'_> { - //self.project.sampler().map(|s|Outer(true, Style::default().fg(Tui::g(96))).enclose( - //Fill::y(Align::n(s.view_sample_status(self.editor().unwrap().get_note_pos()))))) - //} diff --git a/crates/app/app_ctrl.rs b/crates/app/app_ctrl.rs new file mode 100644 index 00000000..ad562d74 --- /dev/null +++ b/crates/app/app_ctrl.rs @@ -0,0 +1,308 @@ +use crate::*; + +//handle!(TuiIn:|self: App, input|self. + +impl App { + fn handle_tui_key_with_history (&mut self, input: &TuiIn) -> Perhaps { + panic!("{input:?}"); + //Ok(if let Some(binding) = self.profile.as_ref() + //.map(|c|c.keys.dispatch(input.event())).flatten() + //{ + //let binding = binding.clone(); + //let undo = binding.command.clone().execute(self)?; + //// FIXME failed commands are not persisted in undo history + ////self.history.push((binding.command.clone(), undo)); + //Some(true) + //} else { + //None + //}) + } +} + +type MaybeClip = Option>>; + +macro_rules!dsl_expose(($Struct:ident { $($fn:ident: $ret:ty = |$self:ident|$body:expr);* $(;)? })=>{ + #[tengri_proc::expose] impl $Struct { $(fn $fn (&$self) -> $ret { $body })* } +}); + +dsl_expose!(App { + _isize_stub: isize = |self|todo!(); + _item_theme_stub: ItemTheme = |self|todo!(); + w_sidebar: u16 = |self|self.project.w_sidebar(self.editor().is_some()); + h_sample_detail: u16 = |self|6.max(self.height() as u16 * 3 / 9); + focus_editor: bool = |self|self.project.editor.is_some(); + focus_dialog: bool = |self|!matches!(self.dialog, Dialog::None); + focus_message: bool = |self|matches!(self.dialog, Dialog::Message(..)); + focus_add_device: bool = |self|matches!(self.dialog, Dialog::Device(..)); + focus_browser: bool = |self|self.dialog.browser().is_some(); + focus_clip: bool = |self|!self.focus_editor() && matches!(self.selection(), Selection::TrackClip{..}); + focus_track: bool = |self|!self.focus_editor() && matches!(self.selection(), Selection::Track(..)); + focus_scene: bool = |self|!self.focus_editor() && matches!(self.selection(), Selection::Scene(..)); + focus_mix: bool = |self|!self.focus_editor() && matches!(self.selection(), Selection::Mix); + focus_pool_import: bool = |self|matches!(self.pool.mode, Some(PoolMode::Import(..))); + focus_pool_export: bool = |self|matches!(self.pool.mode, Some(PoolMode::Export(..))); + focus_pool_rename: bool = |self|matches!(self.pool.mode, Some(PoolMode::Rename(..))); + focus_pool_length: bool = |self|matches!(self.pool.mode, Some(PoolMode::Length(..))); + dialog_none: Option = |self|None; + dialog_device: Option = |self|Some(Dialog::Device(0)); // TODO + dialog_device_prev: Option = |self|Some(Dialog::Device(0)); // TODO + dialog_device_next: Option = |self|Some(Dialog::Device(0)); // TODO + dialog_help: Option = |self|Some(Dialog::Help(0)); + dialog_menu: Option = |self|Some(Dialog::Menu(0)); + dialog_save: Option = |self|Some(Dialog::Browser(BrowserTarget::SaveProject, Browser::new(None).unwrap().into())); + dialog_load: Option = |self|Some(Dialog::Browser(BrowserTarget::LoadProject, Browser::new(None).unwrap().into())); + dialog_import_clip: Option = |self|Some(Dialog::Browser(BrowserTarget::ImportClip(Default::default()), Browser::new(None).unwrap().into())); + dialog_export_clip: Option = |self|Some(Dialog::Browser(BrowserTarget::ExportClip(Default::default()), Browser::new(None).unwrap().into())); + dialog_import_sample: Option = |self|Some(Dialog::Browser(BrowserTarget::ImportSample(Default::default()), Browser::new(None).unwrap().into())); + dialog_export_sample: Option = |self|Some(Dialog::Browser(BrowserTarget::ExportSample(Default::default()), Browser::new(None).unwrap().into())); + dialog_options: Option = |self|Some(Dialog::Options); + editor_pitch: Option = |self|Some((self.editor().as_ref().map(|e|e.get_note_pos()).unwrap() as u8).into()); + scene_count: usize = |self|self.scenes().len(); + scene_selected: Option = |self|self.selection().scene(); + track_count: usize = |self|self.tracks().len(); + track_selected: Option = |self|self.selection().track(); + select_scene: Selection = |self|self.selection().select_scene(self.tracks().len()); + select_scene_next: Selection = |self|self.selection().select_scene_next(self.scenes().len()); + select_scene_prev: Selection = |self|self.selection().select_scene_prev(); + select_track: Selection = |self|self.selection().select_track(self.tracks().len()); + select_track_next: Selection = |self|self.selection().select_track_next(self.tracks().len()); + select_track_prev: Selection = |self|self.selection().select_track_prev(); + clip_selected: Option>> = |self|match self.selection() { + Selection::TrackClip { track, scene } => self.scenes()[*scene].clips[*track].clone(), + _ => None }; + device_kind: usize = |self|if let Dialog::Device(index) = self.dialog { + index } else { 0 }; + device_kind_next: usize = |self|if let Dialog::Device(index) = self.dialog { + (index + 1) % device_kinds().len() } else { 0 }; + device_kind_prev: usize = |self|if let Dialog::Device(index) = self.dialog { + index.overflowing_sub(1).0.min(device_kinds().len().saturating_sub(1)) + } else { 0 }; +}); + +macro_rules!dsl_bind(($Command:ident: $State:ident { + $($fn:ident = |$state:ident $(, $arg:ident:$ty:ty)*|$body:expr);* $(;)? +})=>{ + handle!(TuiIn: |self: $State, input|self.handle_tui_key_with_history(input)); + #[tengri_proc::command(App)] impl $Command { + $(fn $fn ($state: &mut $State $(, $arg:$ty)*) -> Perhaps { $body })* + } +}); + +dsl_bind!(AppCommand: App { + enqueue = |app, clip: Option>>| { todo!() }; + history = |app, delta: isize| { todo!() }; + zoom = |app, zoom: usize| { todo!() }; + stop_all = |app| { app.tracks_stop_all(); Ok(None) }; + //dialog = |app, command: DialogCommand| + //Ok(command.delegate(&mut app.dialog, |c|Self::Dialog{command: c})?); + project = |app, command: ArrangementCommand| + Ok(command.delegate(&mut app.project, |c|Self::Project{command: c})?); + clock = |app, command: ClockCommand| + Ok(command.execute(app.clock_mut())?.map(|c|Self::Clock{command: c})); + sampler = |app, command: SamplerCommand| + Ok(app.project.sampler_mut().map(|s|command.delegate(s, |command|Self::Sampler{command})) + .transpose()?.flatten()); + pool = |app, command: PoolCommand| { + let undo = command.clone().delegate(&mut app.pool, |command|AppCommand::Pool{command})?; + // update linked editor after pool action + match command { + // autoselect: automatically load selected clip in editor + PoolCommand::Select { .. } | + // autocolor: update color in all places simultaneously + PoolCommand::Clip { command: PoolClipCommand::SetColor { .. } } => { + let clip = app.pool.clip().clone(); + app.editor_mut().map(|editor|editor.set_clip(clip.as_ref())) + }, + _ => None + }; + Ok(undo) + }; + select = |app, selection: Selection| { + *app.project.selection_mut() = selection; + //todo! + //if let Some(ref mut editor) = app.editor_mut() { + //editor.set_clip(match selection { + //Selection::TrackClip { track, scene } if let Some(Some(Some(clip))) = app + //.project + //.scenes.get(scene) + //.map(|s|s.clips.get(track)) + //=> + //Some(clip), + //_ => + //None + //}); + //} + Ok(None) + //("select" [t: usize, s: usize] Some(match (t.expect("no track"), s.expect("no scene")) { + //(0, 0) => Self::Select(Selection::Mix), + //(t, 0) => Self::Select(Selection::Track(t)), + //(0, s) => Self::Select(Selection::Scene(s)), + //(t, s) => Self::Select(Selection::TrackClip { track: t, scene: s }) }))) + // autoedit: load focused clip in editor. + }; + //fn color (app: &mut App, theme: ItemTheme) -> Perhaps { + //Ok(app.set_color(Some(theme)).map(|theme|Self::Color{theme})) + //} + //fn launch (app: &mut App) -> Perhaps { + //app.project.launch(); + //Ok(None) + //} + toggle_editor = |app, value: bool|{ app.toggle_editor(Some(value)); Ok(None) }; + editor = |app, command: MidiEditCommand| Ok(if let Some(editor) = app.editor_mut() { + let undo = command.clone().delegate(editor, |command|AppCommand::Editor{command})?; + // update linked sampler after editor action + app.project.sampler_mut().map(|sampler|match command { + // autoselect: automatically select sample in sampler + MidiEditCommand::SetNotePos { pos } => { sampler.set_note_pos(pos); }, + _ => {} + }); + undo + } else { + None + }); +}); +//take!(ClockCommand |state: App, iter|Take::take(state.clock(), iter)); +//take!(MidiEditCommand |state: App, iter|Ok(state.editor().map(|x|Take::take(x, iter)).transpose()?.flatten())); +//take!(PoolCommand |state: App, iter|Take::take(&state.pool, iter)); +//take!(SamplerCommand |state: App, iter|Ok(state.project.sampler().map(|x|Take::take(x, iter)).transpose()?.flatten())); +//take!(ArrangementCommand |state: App, iter|Take::take(&state.project, iter)); +//take!(DialogCommand |state: App, iter|Take::take(&state.dialog, iter)); +//has_editor!(|self: App|{ + //editor = self.editor; + //editor_w = { + //let size = self.size.w(); + //let editor = self.editor.as_ref().expect("missing editor"); + //let time_len = editor.time_len().get(); + //let time_zoom = editor.time_zoom().get().max(1); + //(5 + (time_len / time_zoom)).min(size.saturating_sub(20)).max(16) + //}; + //editor_h = 15; + //is_editing = self.editor.is_some(); +//}); +#[tengri_proc::command(Option)] impl DialogCommand { + fn open (dialog: &mut Option, new: Dialog) -> Perhaps { + *dialog = Some(new); + Ok(None) + } + fn close (dialog: &mut Option) -> Perhaps { + *dialog = None; + Ok(None) + } +} + +impl App { + pub fn toggle_dialog (&mut self, mut dialog: Dialog) -> Dialog { + std::mem::swap(&mut self.dialog, &mut dialog); + dialog + } + pub fn toggle_editor (&mut self, value: Option) { + //FIXME: self.editing.store(value.unwrap_or_else(||!self.is_editing()), Relaxed); + let value = value.unwrap_or_else(||!self.editor().is_some()); + if value { + // Create new clip in pool when entering empty cell + if let Selection::TrackClip { track, scene } = *self.selection() + && let Some(scene) = self.project.scenes.get_mut(scene) + && let Some(slot) = scene.clips.get_mut(track) + && slot.is_none() + && let Some(track) = self.project.tracks.get_mut(track) + { + let (index, mut clip) = self.pool.add_new_clip(); + // autocolor: new clip colors from scene and track color + let color = track.color.base.mix(scene.color.base, 0.5); + clip.write().unwrap().color = ItemColor::random_near(color, 0.2).into(); + if let Some(ref mut editor) = &mut self.project.editor { + editor.set_clip(Some(&clip)); + } + *slot = Some(clip.clone()); + //Some(clip) + } else { + //None + } + } else if let Selection::TrackClip { track, scene } = *self.selection() + && let Some(scene) = self.project.scenes.get_mut(scene) + && let Some(slot) = scene.clips.get_mut(track) + && let Some(clip) = slot.as_mut() + { + // Remove clip from arrangement when exiting empty clip editor + let mut swapped = None; + if clip.read().unwrap().count_midi_messages() == 0 { + std::mem::swap(&mut swapped, slot); + } + if let Some(clip) = swapped { + self.pool.delete_clip(&clip.read().unwrap()); + } + } + } + pub fn browser (&self) -> Option<&Browser> { + if let Dialog::Browser(_, ref b) = self.dialog { Some(b) } else { None } + } + pub fn device_pick (&mut self, index: usize) { + self.dialog = Dialog::Device(index); + } + pub fn add_device (&mut self, index: usize) -> Usually<()> { + match index { + 0 => { + let name = self.jack.with_client(|c|c.name().to_string()); + let midi = self.project.track().expect("no active track").sequencer.midi_outs[0].port_name(); + let track = self.track().expect("no active track"); + let port = format!("{}/Sampler", &track.name); + let connect = Connect::exact(format!("{name}:{midi}")); + let sampler = if let Ok(sampler) = Sampler::new( + &self.jack, &port, &[connect], &[&[], &[]], &[&[], &[]] + ) { + self.dialog = Dialog::None; + Device::Sampler(sampler) + } else { + self.dialog = Dialog::Message("Failed to add device.".into()); + return Err("failed to add device".into()) + }; + let track = self.track_mut().expect("no active track"); + track.devices.push(sampler); + Ok(()) + }, + 1 => { + todo!(); + Ok(()) + }, + _ => unreachable!(), + } + } +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// + +//#[derive(Clone, Debug)] +//pub enum DialogCommand { + //Open { dialog: Dialog }, + //Close +//} + +//impl Command> for DialogCommand { + //fn execute (self, state: &mut Option) -> Perhaps { + //match self { + //Self::Open { dialog } => { + //*state = Some(dialog); + //}, + //Self::Close => { + //*state = None; + //} + //}; + //Ok(None) + //} +//} + +//dsl!(DialogCommand: |self: Dialog, iter|todo!()); +//Dsl::take(&mut self.dialog, iter)); + +//#[tengri_proc::command(Option)]//Nope. +//impl DialogCommand { + //fn open (dialog: &mut Option, new: Dialog) -> Perhaps { + //*dialog = Some(new); + //Ok(None) + //} + //fn close (dialog: &mut Option) -> Perhaps { + //*dialog = None; + //Ok(None) + //} +//} +// diff --git a/crates/app/app_jack.rs b/crates/app/app_jack.rs new file mode 100644 index 00000000..1174b3b1 --- /dev/null +++ b/crates/app/app_jack.rs @@ -0,0 +1,57 @@ +use crate::*; + +impl HasJack<'static> for App { + fn jack (&self) -> &Jack<'static> { + &self.jack + } +} + +audio!( + |self: App, client, scope|{ + let t0 = self.perf.get_t0(); + self.clock().update_from_scope(scope).unwrap(); + let midi_in = self.project.midi_input_collect(scope); + if let Some(editor) = &self.editor() { + let mut pitch: Option = None; + for port in midi_in.iter() { + for event in port.iter() { + if let (_, Ok(LiveEvent::Midi {message: MidiMessage::NoteOn {ref key, ..}, ..})) + = event + { + pitch = Some(key.clone()); + } + } + } + if let Some(pitch) = pitch { + editor.set_note_pos(pitch.as_int() as usize); + } + } + let result = self.project.process_tracks(client, scope); + self.perf.update_from_jack_scope(t0, scope); + result + }; + |self, event|{ + use JackEvent::*; + match event { + SampleRate(sr) => { + self.clock().timebase.sr.set(sr as f64); + }, + PortRegistration(id, true) => { + //let port = self.jack().port_by_id(id); + //println!("\rport add: {id} {port:?}"); + //println!("\rport add: {id}"); + }, + PortRegistration(id, false) => { + /*println!("\rport del: {id}")*/ + }, + PortsConnected(a, b, true) => { /*println!("\rport conn: {a} {b}")*/ }, + PortsConnected(a, b, false) => { /*println!("\rport disc: {a} {b}")*/ }, + ClientRegistration(id, true) => {}, + ClientRegistration(id, false) => {}, + ThreadInit => {}, + XRun => {}, + GraphReorder => {}, + _ => { panic!("{event:?}"); } + } + } +); diff --git a/crates/app/app_view.rs b/crates/app/app_view.rs index 0f2244d6..5bc75d4b 100644 --- a/crates/app/app_view.rs +++ b/crates/app/app_view.rs @@ -1,127 +1,110 @@ use crate::*; -pub(crate) use std::marker::PhantomData; -content!(TuiOut:|self: App|"kyp");//VIEW.content(self, "(bg :color/black (fill/xy (bsp/a overlay content)))")); -struct DslView<'s, O: Output, T> { - symbol: &'s str, - callback: Option fn (&'t T) -> Box + 't>>, - next: Option<&'s Self> -} -pub const VIEW: DslView<'static, TuiOut, App> = DslView::new() - .def("browser", view_browser) - .def("content", view_content) - .def("device", view_device) - .def("menu", view_menu) - //.def("options", view_options) - .def("overlay", view_overlay); -impl<'s, O: Output, T> DslView<'s, O, T> { - pub const fn new () -> Self { - DslView { symbol: "", callback: None, next: None } - } - pub const fn def ( - &'static self, - symbol: &'static str, - callback: fn (&T) -> Box + '_> - ) -> Self { - DslView { symbol, callback: Some(callback), next: Some(self) } - } - pub fn content <'t> ( - &'static self, state: &'t T, src: impl Dsl) -> Usually + 't>> { - Ok(if src.sym()? == Some(self.symbol) && let Some(callback) = self.callback { - callback(&state) - } else if let Some(next) = self.next { - next.content(state, src)? - } else { - return Err("DslView::content: undefined".into()) - }) - } - //fn render (&self, state: &T, output: &mut O, src: impl Dsl) -> Usually<()> { - //Ok(if src.sym()? == Some(self.0) && let Some(callback) = self.1 { - //let view = callback(&state); - //output.place(output.area(), &view) - //} else if let Some(next) = self.2 { - //next.render(state, output, src)? - //} else { - //return Err("DslView::render: undefined".into()) - //}) - //} -} - - -fn view_content (app: &App) -> Box + '_> { - Fill::xy(ErrorBoundary::new(Ok(Some("·")))).boxed() -} -fn view_overlay <'s> (state: &'s App) -> Box + 's> { - match &state.dialog { - Dialog::Menu(_) => view_menu(state), - Dialog::Device(_) => view_device(state), - Dialog::Browser(_, _) => view_browser(state), - //Dialog::Help(_) => view_help, - //Dialog::Message(_) => view_message, - //Dialog::Options => view_options, - _ => unimplemented!() +content!(TuiOut:|self: App|VIEW[":view"](self));//if let Ok(Some(view)) = VIEW[":view"] { view(self) } else { panic!() }); +struct DslNs<'t, T: 't>(&'t [(&'t str, T)]); +type DslCb = fn (&App) -> Box>; +impl<'t, D: Dsl> std::ops::Index for DslNs<'t, DslCb> { + type Output = DslCb; + fn index (&self, index: D) -> &Self::Output { + if let Ok(Some(symbol)) = index.src() { + for (key, value) in self.0.iter() { + if symbol == *key { + return value + } + } + } + &(view_nil as DslCb) } } -fn wrap_dialog <'s> (dialog: impl Content + 's) -> impl Content + 's { +pub const VIEW: DslNs<'static, DslCb> = DslNs(&[ + (":view", |state|VIEW[":view/content"](state)), + (":view/content", |state|Fill::xy(ErrorBoundary::new(Ok(Some("·")))).boxed()), + (":view/overlay", |state|{ + match &state.dialog { + Dialog::Menu(_) => VIEW[":view/menu"](state), + Dialog::Device(_) => VIEW[":view/device"](state), + Dialog::Browser(_, _) => VIEW[":view/browser"](state), + //Dialog::Help(_) => view_help, + //Dialog::Message(_) => view_message, + //Dialog::Options => view_options, + _ => unimplemented!() + } + }), + (":view/browser", |state|{ + let browser = state.dialog.browser().cloned().unwrap(); + let target = state.dialog.browser_target().unwrap(); + Box::new(Bsp::s( + Padding::xy(3, 1, Fill::x(Align::w(FieldV( + Default::default(), + match target { + BrowserTarget::SaveProject => "Save project:", + BrowserTarget::LoadProject => "Load project:", + BrowserTarget::ImportSample(_) => "Import sample:", + BrowserTarget::ExportSample(_) => "Export sample:", + BrowserTarget::ImportClip(_) => "Import clip:", + BrowserTarget::ExportClip(_) => "Export clip:", + }, + Shrink::x(3, Fixed::y(1, Tui::fg(Tui::g(96), RepeatH("🭻")))))))), + Outer(true, Style::default().fg(Tui::g(96))) + .enclose(Fill::xy(browser)))) + }), + (":view/device", |state|{ + let selected = state.dialog.device_selected().unwrap(); + Box::new(Bsp::s(Tui::bold(true, "Add device"), Map::south(1, + move||device_kinds().iter(), + move|label: &&'static str, i|{ + let bg = if i == selected { Rgb(64,128,32) } else { Rgb(0,0,0) }; + let lb = if i == selected { "[ " } else { " " }; + let rb = if i == selected { " ]" } else { " " }; + Fill::x(Tui::bg(bg, Bsp::e(lb, Bsp::w(rb, "FIXME device name")))) + }))) + }), + (":view/menu", |state|{ + let views = state.config.views.clone(); + let selected = state.dialog.menu_selected(); + Box::new(Tui::bg(Rgb(0,0,0), Bsp::s( + Fill::x(Fixed::y(3, Tui::bg(Rgb(33,33,33), Tui::bold(true, "tek 0.3.0-rc0")))), + Bsp::n( + Fill::x(Fixed::y(3, Tui::bg(Rgb(33,33,33), Bsp::e(Tui::fg(Rgb(255,192,48), "[Enter]"), " new session")))), + Fill::y(Align::n(Fill::x(Stack::south(move|add: &mut dyn FnMut(&dyn Render)|{ + ////let options = ||["Projects", "Settings", "Help", "Quit"].iter(); + ////let option = |a,i|Tui::fg(Rgb(255,255,255), format!("{}", a)); + ////Bsp::s(Tui::bold(true, "tek!"), Bsp::s("", Map::south(1, options, option))) + for (index, (id, profile)) in views.read().unwrap().iter().enumerate() { + let bg = if index == 0 { Rgb(64,64,64) } else { Rgb(32,32,32) }; + let name = profile.name.as_ref().map(|x|unquote(unquote(x.as_ref()))); + let info = profile.info.as_ref().map(|x|unquote(unquote(x.as_ref()))); + add(&Fixed::y(3, Tui::bg(bg, Bsp::s( + Fill::x(Bsp::a( + Fill::x(Align::w(Tui::fg(Rgb(224,192,128), name))), + Fill::x(Align::e(Tui::fg(Rgb(224,128,32), &id))) + )), + Fill::x(Align::w(info)))))); } })))))))) + }), + //(":view/options", view_options), +]); +fn view_nil (_: &App) -> Box> { + "nil".boxed() +} +fn wrap_dialog (dialog: impl Content) -> impl Content { Fixed::xy(70, 23, Tui::fg_bg(Rgb(255,255,255), Rgb(16,16,16), Bsp::b( Repeat(" "), Outer(true, Style::default().fg(Tui::g(96))).enclose(dialog)))) } -fn wrap_dialog_menu <'a> (content: impl Content + 'a) -> Box + 'a> { - Box::new(Tui::bg(Rgb(0,0,0), Bsp::s( - Fill::x(Fixed::y(3, Tui::bg(Rgb(33,33,33), Tui::bold(true, "tek 0.3.0-rc0")))), - Bsp::n( - Fill::x(Fixed::y(3, Tui::bg(Rgb(33,33,33), Bsp::e(Tui::fg(Rgb(255,192,48), "[Enter]"), " new session")))), - Fill::y(Align::n(Fill::x(content))))))) -} -fn view_menu <'s> (state: &'s App) -> Box + 's> { - let views = state.config.views.clone(); - let selected = state.dialog.menu_selected(); - wrap_dialog_menu(Stack::south(move|add: &mut dyn FnMut(&dyn Render)|{ - ////let options = ||["Projects", "Settings", "Help", "Quit"].iter(); - ////let option = |a,i|Tui::fg(Rgb(255,255,255), format!("{}", a)); - ////Bsp::s(Tui::bold(true, "tek!"), Bsp::s("", Map::south(1, options, option))) - for (index, (id, profile)) in views.read().unwrap().iter().enumerate() { - let bg = if index == 0 { Rgb(64,64,64) } else { Rgb(32,32,32) }; - let name = profile.name.as_ref().map(|x|unquote(unquote(x.as_ref()))); - let info = profile.info.as_ref().map(|x|unquote(unquote(x.as_ref()))); - add(&Fixed::y(3, Tui::bg(bg, Bsp::s( - Fill::x(Bsp::a( - Fill::x(Align::w(Tui::fg(Rgb(224,192,128), name))), - Fill::x(Align::e(Tui::fg(Rgb(224,128,32), &id))) - )), - Fill::x(Align::w(info)))))); } })) -} -fn view_browser <'s> (state: &'s App) -> Box + 's> { - let target = &state.dialog.browser_target().clone().unwrap(); - Box::new(Bsp::s( - Padding::xy(3, 1, Fill::x(Align::w(FieldV( - Default::default(), - match &target { - BrowserTarget::SaveProject => "Save project:", - BrowserTarget::LoadProject => "Load project:", - BrowserTarget::ImportSample(_) => "Import sample:", - BrowserTarget::ExportSample(_) => "Export sample:", - BrowserTarget::ImportClip(_) => "Import clip:", - BrowserTarget::ExportClip(_) => "Export clip:", - }, - Shrink::x(3, Fixed::y(1, Tui::fg(Tui::g(96), RepeatH("🭻")))))))), - Outer(true, Style::default().fg(Tui::g(96))) - .enclose(Fill::xy(state.dialog.browser())))) -} -fn view_device <'s> (state: &'s App) -> Box + 's> { - let selected = state.dialog.device_selected().unwrap(); - Box::new(Bsp::s(Tui::bold(true, "Add device"), Map::south(1, - move||device_kinds().iter(), - move|label: &&'static str, i| - Fill::x(Tui::bg(if i == selected { Rgb(64,128,32) } else { Rgb(0,0,0) }, - Bsp::e(if i == state.dialog.device_selected().unwrap() { "[ " } else { " " }, - Bsp::w(if i == state.dialog.device_selected().unwrap() { " ]" } else { " " }, - "FIXME device name"))))))) +impl ScenesView for App { + fn h_scenes (&self) -> u16 { + (self.height() as u16).saturating_sub(20) + } + fn w_side (&self) -> u16 { + 20 + } + fn w_mid (&self) -> u16 { + (self.width() as u16).saturating_sub(self.w_side()) + } } //Bsp::s("", //Map::south(1, - //move||app.config.binds.layers.iter() - //.filter_map(|a|(a.0)(app).then_some(a.1)) + //move||state.config.binds.layers.iter() + //.filter_map(|a|(a.0)(state).then_some(a.1)) //.flat_map(|a|a) //.filter_map(|x|if let Value::Exp(_, iter)=x.value{ Some(iter) } else { None }) //.skip(offset) @@ -157,3 +140,179 @@ fn view_device <'s> (state: &'s App) -> Box + 's> { ////Outer(true, Style::default().fg(Tui::g(96))) ////.enclose(Fill::xy(browser))) //}, +// + //pub fn view_meters_input (&self) -> impl Content + use<'_> { + //self.project.sampler().map(|s| + //s.view_meters_input()) + //} + //pub fn view_meters_output (&self) -> impl Content + use<'_> { + //self.project.sampler().map(|s| + //s.view_meters_output()) + //} + //pub fn view_history (&self) -> impl Content { + //Fixed::y(1, Fill::x(Align::w(FieldH(self.color, + //format!("History ({})", self.history.len()), + //self.history.last().map(|last|Fill::x(Align::w(format!("{:?}", last.0)))))))) + //} + //pub fn view_status_h2 (&self) -> impl Content { + //self.update_clock(); + //let theme = self.color; + //let clock = self.clock(); + //let playing = clock.is_rolling(); + //let cache = clock.view_cache.clone(); + ////let selection = self.selection().describe(self.tracks(), self.scenes()); + //let hist_len = self.history.len(); + //let hist_last = self.history.last(); + //Fixed::y(2, Stack::east(move|add: &mut dyn FnMut(&dyn Render)|{ + //add(&Fixed::x(5, Tui::bg(if playing { Rgb(0, 128, 0) } else { Rgb(128, 64, 0) }, + //Either::new(false, // TODO + //Thunk::new(move||Fixed::x(9, Either::new(playing, + //Tui::fg(Rgb(0, 255, 0), " PLAYING "), + //Tui::fg(Rgb(255, 128, 0), " STOPPED "))) + //), + //Thunk::new(move||Fixed::x(5, Either::new(playing, + //Tui::fg(Rgb(0, 255, 0), Bsp::s(" 🭍🭑🬽 ", " 🭞🭜🭘 ",)), + //Tui::fg(Rgb(255, 128, 0), Bsp::s(" ▗▄▖ ", " ▝▀▘ ",)))) + //) + //) + //))); + //add(&" "); + //{ + //let cache = cache.read().unwrap(); + //add(&Fixed::x(15, Align::w(Bsp::s( + //FieldH(theme, "Beat", cache.beat.view.clone()), + //FieldH(theme, "Time", cache.time.view.clone()), + //)))); + //add(&Fixed::x(13, Align::w(Bsp::s( + //Fill::x(Align::w(FieldH(theme, "BPM", cache.bpm.view.clone()))), + //Fill::x(Align::w(FieldH(theme, "SR ", cache.sr.view.clone()))), + //)))); + //add(&Fixed::x(12, Align::w(Bsp::s( + //Fill::x(Align::w(FieldH(theme, "Buf", cache.buf.view.clone()))), + //Fill::x(Align::w(FieldH(theme, "Lat", cache.lat.view.clone()))), + //)))); + ////add(&Bsp::s( + //////Fill::x(Align::w(FieldH(theme, "Selected", Align::w(selection)))), + ////Fill::x(Align::w(FieldH(theme, format!("History ({})", hist_len), + ////hist_last.map(|last|Fill::x(Align::w(format!("{:?}", last.0))))))), + ////"" + ////)); + //////if let Some(last) = self.history.last() { + //////add(&FieldV(theme, format!("History ({})", self.history.len()), + //////Fill::x(Align::w(format!("{:?}", last.0))))); + //////} + //} + //})) + //} + //pub fn view_status_v (&self) -> impl Content + use<'_> { + //self.update_clock(); + //let cache = self.project.clock.view_cache.read().unwrap(); + //let theme = self.color; + //let playing = self.clock().is_rolling(); + //Tui::bg(theme.darker.rgb, Fixed::xy(20, 5, Outer(true, Style::default().fg(Tui::g(96))).enclose( + //col!( + //Fill::x(Align::w(Bsp::e( + //Align::w(Tui::bg(if playing { Rgb(0, 128, 0) } else { Rgb(128, 64, 0) }, + //Either::new(false, // TODO + //Thunk::new(move||Fixed::x(9, Either::new(playing, + //Tui::fg(Rgb(0, 255, 0), " PLAYING "), + //Tui::fg(Rgb(255, 128, 0), " STOPPED "))) + //), + //Thunk::new(move||Fixed::x(5, Either::new(playing, + //Tui::fg(Rgb(0, 255, 0), Bsp::s(" 🭍🭑🬽 ", " 🭞🭜🭘 ",)), + //Tui::fg(Rgb(255, 128, 0), Bsp::s(" ▗▄▖ ", " ▝▀▘ ",)))) + //) + //) + //)), + //Bsp::s( + //FieldH(theme, "Beat", cache.beat.view.clone()), + //FieldH(theme, "Time", cache.time.view.clone()), + //), + //))), + //Fill::x(Align::w(FieldH(theme, "BPM", cache.bpm.view.clone()))), + //Fill::x(Align::w(FieldH(theme, "SR ", cache.sr.view.clone()))), + //Fill::x(Align::w(FieldH(theme, "Buf", Bsp::e(cache.buf.view.clone(), Bsp::e(" = ", cache.lat.view.clone()))))), + //)))) + //} + //pub fn view_status (&self) -> impl Content + use<'_> { + //self.update_clock(); + //let cache = self.project.clock.view_cache.read().unwrap(); + //view_status(Some(self.project.selection.describe(self.tracks(), self.scenes())), + //cache.sr.view.clone(), cache.buf.view.clone(), cache.lat.view.clone()) + //} + //pub fn view_transport (&self) -> impl Content + use<'_> { + //self.update_clock(); + //let cache = self.project.clock.view_cache.read().unwrap(); + //view_transport(self.project.clock.is_rolling(), + //cache.bpm.view.clone(), cache.beat.view.clone(), cache.time.view.clone()) + //} + //pub fn view_editor (&self) -> impl Content + use<'_> { + //let bg = self.editor() + //.and_then(|editor|editor.clip().clone()) + //.map(|clip|clip.read().unwrap().color.darker) + //.unwrap_or(self.color.darker); + //Fill::xy(Tui::bg(bg.rgb, self.editor())) + //} + //pub fn view_editor_status (&self) -> impl Content + use<'_> { + //self.editor().map(|e|Fixed::x(20, Outer(true, Style::default().fg(Tui::g(96))).enclose( + //Fill::y(Align::n(Bsp::s(e.clip_status(), e.edit_status())))))) + //} + //pub fn view_midi_ins_status (&self) -> impl Content + use<'_> { + //self.project.view_midi_ins_status(self.color) + //} + //pub fn view_midi_outs_status (&self) -> impl Content + use<'_> { + //self.project.view_midi_outs_status(self.color) + //} + //pub fn view_audio_ins_status (&self) -> impl Content + use<'_> { + //self.project.view_audio_ins_status(self.color) + //} + //pub fn view_audio_outs_status (&self) -> impl Content + use<'_> { + //self.project.view_audio_outs_status(self.color) + //} + //pub fn view_scenes (&self) -> impl Content + use<'_> { + //Bsp::e( + //Fixed::x(20, Align::nw(self.project.view_scenes_names())), + //self.project.view_scenes_clips(), + //) + //} + //pub fn view_scenes_names (&self) -> impl Content + use<'_> { + //self.project.view_scenes_names() + //} + //pub fn view_scenes_clips (&self) -> impl Content + use<'_> { + //self.project.view_scenes_clips() + //} + //pub fn view_tracks_inputs <'a> (&'a self) -> impl Content + use<'a> { + //Fixed::y(1 + self.project.midi_ins.len() as u16, + //self.project.view_inputs(self.color)) + //} + //pub fn view_tracks_outputs <'a> (&'a self) -> impl Content + use<'a> { + //self.project.view_outputs(self.color) + //} + //pub fn view_tracks_devices <'a> (&'a self) -> impl Content + use<'a> { + //Fixed::y(4, self.project.view_track_devices(self.color)) + //} + //pub fn view_tracks_names <'a> (&'a self) -> impl Content + use<'a> { + //Fixed::y(2, self.project.view_track_names(self.color)) + //} + //pub fn view_pool (&self) -> impl Content + use<'_> { + //Fixed::x(20, Bsp::s( + //Fill::x(Align::w(FieldH(self.color, "Clip pool:", ""))), + //Fill::y(Align::n(Tui::bg(Rgb(0, 0, 0), Outer(true, Style::default().fg(Tui::g(96))) + //.enclose(PoolView(&self.pool))))))) + //} + //pub fn view_samples_keys (&self) -> impl Content + use<'_> { + //self.project.sampler().map(|s|s.view_list(true, self.editor().unwrap())) + //} + //pub fn view_samples_grid (&self) -> impl Content + use<'_> { + //self.project.sampler().map(|s|s.view_grid()) + //} + //pub fn view_sample_viewer (&self) -> impl Content + use<'_> { + //self.project.sampler().map(|s|s.view_sample(self.editor().unwrap().get_note_pos())) + //} + //pub fn view_sample_info (&self) -> impl Content + use<'_> { + //self.project.sampler().map(|s|s.view_sample_info(self.editor().unwrap().get_note_pos())) + //} + //pub fn view_sample_status (&self) -> impl Content + use<'_> { + //self.project.sampler().map(|s|Outer(true, Style::default().fg(Tui::g(96))).enclose( + //Fill::y(Align::n(s.view_sample_status(self.editor().unwrap().get_note_pos()))))) + //} diff --git a/deps/tengri b/deps/tengri index 4515d2cc..24ac52d8 160000 --- a/deps/tengri +++ b/deps/tengri @@ -1 +1 @@ -Subproject commit 4515d2cc6f9d8d67782c175ebc5b560923295314 +Subproject commit 24ac52d8079140b2b9f363d1568597bb5600a166 From 525a455f7aa043b39c7fb7a309bd0eb72c31d779 Mon Sep 17 00:00:00 2001 From: unspeaker Date: Sun, 10 Aug 2025 02:24:11 +0300 Subject: [PATCH 3/5] woohoo! --- crates/app/app.rs | 20 ++++++--- crates/app/app_view.rs | 98 +++++++++++++++++++++++------------------- 2 files changed, 69 insertions(+), 49 deletions(-) diff --git a/crates/app/app.rs b/crates/app/app.rs index 31ef27db..80194910 100644 --- a/crates/app/app.rs +++ b/crates/app/app.rs @@ -243,9 +243,19 @@ fn unquote (x: &str) -> &str { chars.as_str() } impl Dialog { - fn menu_selected (&self) -> Option { todo!() } - fn device_selected (&self) -> Option { todo!() } - fn message (&self) -> Option<&str> { todo!() } - fn browser (&self) -> Option<&Arc> { todo!() } - fn browser_target (&self) -> Option<&BrowserTarget> { todo!() } + fn menu_selected (&self) -> Option { + if let Self::Menu(selected) = self { Some(*selected) } else { None } + } + fn device_selected (&self) -> Option { + if let Self::Device(selected) = self { Some(*selected) } else { None } + } + fn message (&self) -> Option<&str> { + todo!() + } + fn browser (&self) -> Option<&Arc> { + todo!() + } + fn browser_target (&self) -> Option<&BrowserTarget> { + todo!() + } } diff --git a/crates/app/app_view.rs b/crates/app/app_view.rs index 5bc75d4b..8285967a 100644 --- a/crates/app/app_view.rs +++ b/crates/app/app_view.rs @@ -16,38 +16,41 @@ impl<'t, D: Dsl> std::ops::Index for DslNs<'t, DslCb> { } } pub const VIEW: DslNs<'static, DslCb> = DslNs(&[ - (":view", |state|VIEW[":view/content"](state)), - (":view/content", |state|Fill::xy(ErrorBoundary::new(Ok(Some("·")))).boxed()), - (":view/overlay", |state|{ - match &state.dialog { - Dialog::Menu(_) => VIEW[":view/menu"](state), - Dialog::Device(_) => VIEW[":view/device"](state), - Dialog::Browser(_, _) => VIEW[":view/browser"](state), - //Dialog::Help(_) => view_help, - //Dialog::Message(_) => view_message, - //Dialog::Options => view_options, - _ => unimplemented!() - } - }), - (":view/browser", |state|{ + + (":view", |state|Box::new( + Fill::xy(Bsp::a(VIEW[":view/content"](state), VIEW[":view/overlay"](state))))), + + (":view/content", |state|Box::new( + Fill::xy(ErrorBoundary::new(Ok(Some("·")))))), + + (":view/overlay", |state|match &state.dialog { + Dialog::Menu(_) => VIEW[":view/menu"](state), + Dialog::Device(_) => VIEW[":view/device"](state), + Dialog::Browser(_, _) => VIEW[":view/browse"](state), + //Dialog::Help(_) => view_help, + //Dialog::Message(_) => view_message, + //Dialog::Options => view_options, + _ => unimplemented!() }), + + (":view/browse", |state|{ let browser = state.dialog.browser().cloned().unwrap(); - let target = state.dialog.browser_target().unwrap(); Box::new(Bsp::s( - Padding::xy(3, 1, Fill::x(Align::w(FieldV( - Default::default(), - match target { - BrowserTarget::SaveProject => "Save project:", - BrowserTarget::LoadProject => "Load project:", - BrowserTarget::ImportSample(_) => "Import sample:", - BrowserTarget::ExportSample(_) => "Export sample:", - BrowserTarget::ImportClip(_) => "Import clip:", - BrowserTarget::ExportClip(_) => "Export clip:", - }, - Shrink::x(3, Fixed::y(1, Tui::fg(Tui::g(96), RepeatH("🭻")))))))), + Padding::xy(3, 1, VIEW[":view/browse-title"](state)), Outer(true, Style::default().fg(Tui::g(96))) - .enclose(Fill::xy(browser)))) - }), - (":view/device", |state|{ + .enclose(Fill::xy(browser)))) }), + + (":view/browse-title", |state: &App|{ + let target = state.dialog.browser_target().unwrap(); + Box::new(Fill::x(Align::w(FieldV(Default::default(), match target { + BrowserTarget::SaveProject => "Save project:", + BrowserTarget::LoadProject => "Load project:", + BrowserTarget::ImportSample(_) => "Import sample:", + BrowserTarget::ExportSample(_) => "Export sample:", + BrowserTarget::ImportClip(_) => "Import clip:", + BrowserTarget::ExportClip(_) => "Export clip:", + }, Shrink::x(3, Fixed::y(1, Tui::fg(Tui::g(96), RepeatH("🭻"))))))))}), + + (":view/device", |state: &App|{ let selected = state.dialog.device_selected().unwrap(); Box::new(Bsp::s(Tui::bold(true, "Add device"), Map::south(1, move||device_kinds().iter(), @@ -55,20 +58,23 @@ pub const VIEW: DslNs<'static, DslCb> = DslNs(&[ let bg = if i == selected { Rgb(64,128,32) } else { Rgb(0,0,0) }; let lb = if i == selected { "[ " } else { " " }; let rb = if i == selected { " ]" } else { " " }; - Fill::x(Tui::bg(bg, Bsp::e(lb, Bsp::w(rb, "FIXME device name")))) - }))) - }), - (":view/menu", |state|{ - let views = state.config.views.clone(); + Fill::x(Tui::bg(bg, Bsp::e(lb, Bsp::w(rb, "FIXME device name")))) }))) }), + + (":view/menu", |state|{ let selected = state.dialog.menu_selected(); - Box::new(Tui::bg(Rgb(0,0,0), Bsp::s( + let outputs = Fill::x(Fixed::y(3, + Bsp::a(Fill::x(Align::w(" L AUDIO OUTS")), Bsp::a("MIDI OUT", Fill::x(Align::e("AUDIO OUTS R ")))))); + let inputs = Fill::x(Fixed::y(3, + Bsp::a(Fill::x(Align::w(" L AUDIO INS")), Bsp::a("MIDI INS", Fill::x(Align::e("AUDIO INS R ")))))); + Box::new(Tui::bg(Rgb(0,0,0), Bsp::s(outputs, Bsp::s( Fill::x(Fixed::y(3, Tui::bg(Rgb(33,33,33), Tui::bold(true, "tek 0.3.0-rc0")))), - Bsp::n( + Bsp::n(inputs, Bsp::n( Fill::x(Fixed::y(3, Tui::bg(Rgb(33,33,33), Bsp::e(Tui::fg(Rgb(255,192,48), "[Enter]"), " new session")))), - Fill::y(Align::n(Fill::x(Stack::south(move|add: &mut dyn FnMut(&dyn Render)|{ - ////let options = ||["Projects", "Settings", "Help", "Quit"].iter(); - ////let option = |a,i|Tui::fg(Rgb(255,255,255), format!("{}", a)); - ////Bsp::s(Tui::bold(true, "tek!"), Bsp::s("", Map::south(1, options, option))) + Fill::y(Align::n(Fill::x(VIEW[":view/profiles"](state)))))))))) }), + + (":view/profiles", |state|Box::new({ + let views = state.config.views.clone(); + Stack::south(move|add: &mut dyn FnMut(&dyn Render)|{ for (index, (id, profile)) in views.read().unwrap().iter().enumerate() { let bg = if index == 0 { Rgb(64,64,64) } else { Rgb(32,32,32) }; let name = profile.name.as_ref().map(|x|unquote(unquote(x.as_ref()))); @@ -76,12 +82,13 @@ pub const VIEW: DslNs<'static, DslCb> = DslNs(&[ add(&Fixed::y(3, Tui::bg(bg, Bsp::s( Fill::x(Bsp::a( Fill::x(Align::w(Tui::fg(Rgb(224,192,128), name))), - Fill::x(Align::e(Tui::fg(Rgb(224,128,32), &id))) - )), - Fill::x(Align::w(info)))))); } })))))))) - }), + Fill::x(Align::e(Tui::fg(Rgb(224,128,32), &id))))), + Fill::x(Align::w(info)))))); } })})) + + //(":view/options", view_options), ]); + fn view_nil (_: &App) -> Box> { "nil".boxed() } @@ -316,3 +323,6 @@ impl ScenesView for App { //self.project.sampler().map(|s|Outer(true, Style::default().fg(Tui::g(96))).enclose( //Fill::y(Align::n(s.view_sample_status(self.editor().unwrap().get_note_pos()))))) //} + ////let options = ||["Projects", "Settings", "Help", "Quit"].iter(); + ////let option = |a,i|Tui::fg(Rgb(255,255,255), format!("{}", a)); + ////Bsp::s(Tui::bold(true, "tek!"), Bsp::s("", Map::south(1, options, option))) From f2d6e7724b20223dc39ed03068b380db7a1e4b95 Mon Sep 17 00:00:00 2001 From: unspeaker Date: Sun, 10 Aug 2025 02:36:48 +0300 Subject: [PATCH 4/5] wip: namespaces --- crates/app/app.rs | 41 ++++++++--- crates/app/app_ctrl.rs | 164 ++++++++++++++++++++--------------------- crates/app/app_dsl.rs | 32 ++++++++ crates/app/app_view.rs | 106 +++++++++----------------- 4 files changed, 174 insertions(+), 169 deletions(-) create mode 100644 crates/app/app_dsl.rs diff --git a/crates/app/app.rs b/crates/app/app.rs index 80194910..b371a796 100644 --- a/crates/app/app.rs +++ b/crates/app/app.rs @@ -40,6 +40,12 @@ use std::collections::BTreeMap; use std::fmt::Write; use ::tengri::tui::ratatui::prelude::Position; use xdg::BaseDirectories; +mod app_dsl; pub use self::app_dsl::*; +macro_rules!dsl_sym( + (|$state:ident:$State:ty| -> $type:ty {$($lit:literal => $exp:expr),* $(,)?})=>{ + impl<'t> DslSymNs<'t, $type> for $State { + const NS: DslNs<'t, fn (&'t $State)->$type> = + DslNs(&[$(($lit, |$state: &$State|$exp)),*]); } }); mod app_view; pub use self::app_view::*; mod app_ctrl; pub use self::app_ctrl::*; mod app_jack; pub use self::app_jack::*; @@ -202,20 +208,13 @@ impl Profile { } } /// Various possible dialog modes. -#[derive(Debug, Clone, Default)] -pub enum Dialog { - #[default] None, - Help(usize), - Menu(usize), - Device(usize), - Message(Arc), - Browser(BrowserTarget, Arc), - Options, -} impl App { pub fn update_clock (&self) { ViewCache::update_clock(&self.project.clock.view_cache, self.clock(), self.size.w() > 80) } + pub fn focused_editor (&self) -> bool { + false + } } has!(Jack<'static>: |self: App|self.jack); has!(Pool: |self: App|self.pool); @@ -242,12 +241,30 @@ fn unquote (x: &str) -> &str { //chars.next_back(); chars.as_str() } + +#[derive(Debug, Clone, Default)] +pub enum Dialog { + #[default] None, + Help(usize), + Menu(usize), + Device(usize), + Message(Arc), + Browser(BrowserTarget, Arc), + Options, +} + impl Dialog { fn menu_selected (&self) -> Option { if let Self::Menu(selected) = self { Some(*selected) } else { None } } - fn device_selected (&self) -> Option { - if let Self::Device(selected) = self { Some(*selected) } else { None } + fn device_kind (&self) -> Option { + if let Self::Device(index) = self { Some(*index) } else { None } + } + fn device_kind_next (&self) -> Option { + self.device_kind().map(|index|(index + 1) % device_kinds().len()) + } + fn device_kind_prev (&self) -> Option { + self.device_kind().map(|index|index.overflowing_sub(1).0.min(device_kinds().len().saturating_sub(1))) } fn message (&self) -> Option<&str> { todo!() diff --git a/crates/app/app_ctrl.rs b/crates/app/app_ctrl.rs index ad562d74..b24dc862 100644 --- a/crates/app/app_ctrl.rs +++ b/crates/app/app_ctrl.rs @@ -1,93 +1,87 @@ use crate::*; - -//handle!(TuiIn:|self: App, input|self. - -impl App { - fn handle_tui_key_with_history (&mut self, input: &TuiIn) -> Perhaps { - panic!("{input:?}"); - //Ok(if let Some(binding) = self.profile.as_ref() - //.map(|c|c.keys.dispatch(input.event())).flatten() - //{ - //let binding = binding.clone(); - //let undo = binding.command.clone().execute(self)?; - //// FIXME failed commands are not persisted in undo history - ////self.history.push((binding.command.clone(), undo)); - //Some(true) - //} else { - //None - //}) - } -} - -type MaybeClip = Option>>; - -macro_rules!dsl_expose(($Struct:ident { $($fn:ident: $ret:ty = |$self:ident|$body:expr);* $(;)? })=>{ - #[tengri_proc::expose] impl $Struct { $(fn $fn (&$self) -> $ret { $body })* } +handle!(TuiIn:|self: App, input|{ + panic!("{input:?}"); + //Ok(if let Some(binding) = self.profile.as_ref() + //.map(|c|c.keys.dispatch(input.event())).flatten() + //{ + //let binding = binding.clone(); + //let undo = binding.command.clone().execute(self)?; + //// FIXME failed commands are not persisted in undo history + ////self.history.push((binding.command.clone(), undo)); + //Some(true) + //} else { + //None + //}) +}) +dsl_sym!(|app: App| -> isize { + ":_isize_stub" => -1 }); - -dsl_expose!(App { - _isize_stub: isize = |self|todo!(); - _item_theme_stub: ItemTheme = |self|todo!(); - w_sidebar: u16 = |self|self.project.w_sidebar(self.editor().is_some()); - h_sample_detail: u16 = |self|6.max(self.height() as u16 * 3 / 9); - focus_editor: bool = |self|self.project.editor.is_some(); - focus_dialog: bool = |self|!matches!(self.dialog, Dialog::None); - focus_message: bool = |self|matches!(self.dialog, Dialog::Message(..)); - focus_add_device: bool = |self|matches!(self.dialog, Dialog::Device(..)); - focus_browser: bool = |self|self.dialog.browser().is_some(); - focus_clip: bool = |self|!self.focus_editor() && matches!(self.selection(), Selection::TrackClip{..}); - focus_track: bool = |self|!self.focus_editor() && matches!(self.selection(), Selection::Track(..)); - focus_scene: bool = |self|!self.focus_editor() && matches!(self.selection(), Selection::Scene(..)); - focus_mix: bool = |self|!self.focus_editor() && matches!(self.selection(), Selection::Mix); - focus_pool_import: bool = |self|matches!(self.pool.mode, Some(PoolMode::Import(..))); - focus_pool_export: bool = |self|matches!(self.pool.mode, Some(PoolMode::Export(..))); - focus_pool_rename: bool = |self|matches!(self.pool.mode, Some(PoolMode::Rename(..))); - focus_pool_length: bool = |self|matches!(self.pool.mode, Some(PoolMode::Length(..))); - dialog_none: Option = |self|None; - dialog_device: Option = |self|Some(Dialog::Device(0)); // TODO - dialog_device_prev: Option = |self|Some(Dialog::Device(0)); // TODO - dialog_device_next: Option = |self|Some(Dialog::Device(0)); // TODO - dialog_help: Option = |self|Some(Dialog::Help(0)); - dialog_menu: Option = |self|Some(Dialog::Menu(0)); - dialog_save: Option = |self|Some(Dialog::Browser(BrowserTarget::SaveProject, Browser::new(None).unwrap().into())); - dialog_load: Option = |self|Some(Dialog::Browser(BrowserTarget::LoadProject, Browser::new(None).unwrap().into())); - dialog_import_clip: Option = |self|Some(Dialog::Browser(BrowserTarget::ImportClip(Default::default()), Browser::new(None).unwrap().into())); - dialog_export_clip: Option = |self|Some(Dialog::Browser(BrowserTarget::ExportClip(Default::default()), Browser::new(None).unwrap().into())); - dialog_import_sample: Option = |self|Some(Dialog::Browser(BrowserTarget::ImportSample(Default::default()), Browser::new(None).unwrap().into())); - dialog_export_sample: Option = |self|Some(Dialog::Browser(BrowserTarget::ExportSample(Default::default()), Browser::new(None).unwrap().into())); - dialog_options: Option = |self|Some(Dialog::Options); - editor_pitch: Option = |self|Some((self.editor().as_ref().map(|e|e.get_note_pos()).unwrap() as u8).into()); - scene_count: usize = |self|self.scenes().len(); - scene_selected: Option = |self|self.selection().scene(); - track_count: usize = |self|self.tracks().len(); - track_selected: Option = |self|self.selection().track(); - select_scene: Selection = |self|self.selection().select_scene(self.tracks().len()); - select_scene_next: Selection = |self|self.selection().select_scene_next(self.scenes().len()); - select_scene_prev: Selection = |self|self.selection().select_scene_prev(); - select_track: Selection = |self|self.selection().select_track(self.tracks().len()); - select_track_next: Selection = |self|self.selection().select_track_next(self.tracks().len()); - select_track_prev: Selection = |self|self.selection().select_track_prev(); - clip_selected: Option>> = |self|match self.selection() { - Selection::TrackClip { track, scene } => self.scenes()[*scene].clips[*track].clone(), - _ => None }; - device_kind: usize = |self|if let Dialog::Device(index) = self.dialog { - index } else { 0 }; - device_kind_next: usize = |self|if let Dialog::Device(index) = self.dialog { - (index + 1) % device_kinds().len() } else { 0 }; - device_kind_prev: usize = |self|if let Dialog::Device(index) = self.dialog { - index.overflowing_sub(1).0.min(device_kinds().len().saturating_sub(1)) - } else { 0 }; +dsl_sym!(|app: App| -> ItemTheme { + ":_theme_stub" => Default::default() }); - -macro_rules!dsl_bind(($Command:ident: $State:ident { - $($fn:ident = |$state:ident $(, $arg:ident:$ty:ty)*|$body:expr);* $(;)? -})=>{ - handle!(TuiIn: |self: $State, input|self.handle_tui_key_with_history(input)); - #[tengri_proc::command(App)] impl $Command { - $(fn $fn ($state: &mut $State $(, $arg:$ty)*) -> Perhaps { $body })* +dsl_sym!(|app: App| -> u16{ + ":w/sidebar" => app.project.w_sidebar(app.editor().is_some()), + ":h/sample-detail" => 6.max(app.height() as u16 * 3 / 9), +}); +dsl_sym!(|app: App| -> usize { + ":scene-count" => app.scenes().len(), + ":track-count" => app.tracks().len(), + ":device-kind" => app.dialog.device_kind().unwrap_or(0), + ":device-kind/next" => app.dialog.device_kind_next().unwrap_or(0), + ":device-kind/prev" => app.dialog.device_kind_prev().unwrap_or(0), +}); +dsl_sym!(|app: App| -> bool { + ":focused/editor" => app.project.editor.is_some(), + ":focused/dialog" => !matches!(app.dialog, Dialog::None), + ":focused/message" => matches!(app.dialog, Dialog::Message(..)), + ":focused/add_device" => matches!(app.dialog, Dialog::Device(..)), + ":focused/browser" => app.dialog.browser().is_some(), + ":focused/clip" => !app.focused_editor() && matches!(app.selection(), Selection::TrackClip{..}), + ":focused/track" => !app.focused_editor() && matches!(app.selection(), Selection::Track(..)), + ":focused/scene" => !app.focused_editor() && matches!(app.selection(), Selection::Scene(..)), + ":focused/mix" => !app.focused_editor() && matches!(app.selection(), Selection::Mix), + ":focused/pool/import" => matches!(app.pool.mode, Some(PoolMode::Import(..))), + ":focused/pool/export" => matches!(app.pool.mode, Some(PoolMode::Export(..))), + ":focused/pool/rename" => matches!(app.pool.mode, Some(PoolMode::Rename(..))), + ":focused/pool/length" => matches!(app.pool.mode, Some(PoolMode::Length(..))), +}); +dsl_sym!(|app: App| -> Dialog { + ":dialog/none" => Dialog::None, + ":dialog/options" => Dialog::Options, + ":dialog/device" => Dialog::Device(0), + ":dialog/device/prev" => Dialog::Device(0), + ":dialog/device/next" => Dialog::Device(0), + ":dialog/help" => Dialog::Help(0), + ":dialog/menu" => Dialog::Menu(0), + ":dialog/save" => Dialog::Browser(BrowserTarget::SaveProject, Browser::new(None).unwrap().into()), + ":dialog/load" => Dialog::Browser(BrowserTarget::LoadProject, Browser::new(None).unwrap().into()), + ":dialog/import/clip" => Dialog::Browser(BrowserTarget::ImportClip(Default::default()), Browser::new(None).unwrap().into()), + ":dialog/export/clip" => Dialog::Browser(BrowserTarget::ExportClip(Default::default()), Browser::new(None).unwrap().into()), + ":dialog/import/sample" => Dialog::Browser(BrowserTarget::ImportSample(Default::default()), Browser::new(None).unwrap().into()), + ":dialog/export/sample" => Dialog::Browser(BrowserTarget::ExportSample(Default::default()), Browser::new(None).unwrap().into()), +}); +dsl_sym!(|app: App| -> Selection { + ":select/scene" => app.selection().select_scene(app.tracks().len()), + ":select/scene/next" => app.selection().select_scene_next(app.scenes().len()), + ":select/scene/prev" => app.selection().select_scene_prev(), + ":select/track" => app.selection().select_track(app.tracks().len()), + ":select/track/next" => app.selection().select_track_next(app.tracks().len()), + ":select/track/prev" => app.selection().select_track_prev(), +}); +dsl_sym!(|app: App| -> Option { + ":editor/pitch" => Some((app.editor().as_ref().map(|e|e.get_note_pos()).unwrap() as u8).into()) +}) +dsl_sym!(|app: App| -> Option { + ":selected/scene" => app.selection().scene(), + ":selected/track" => app.selection().track(), +}); +dsl_sym!(|app: App| -> Option>> { + ":selected/clip" => if let Selection::TrackClip { track, scene } = app.selection() { + app.scenes()[*scene].clips[*track].clone(), + } else { + None } }); - dsl_bind!(AppCommand: App { enqueue = |app, clip: Option>>| { todo!() }; history = |app, delta: isize| { todo!() }; diff --git a/crates/app/app_dsl.rs b/crates/app/app_dsl.rs new file mode 100644 index 00000000..21a1be6d --- /dev/null +++ b/crates/app/app_dsl.rs @@ -0,0 +1,32 @@ +use crate::*; + +macro_rules!dsl_sym( + (|$state:ident:$State:ty| -> $type:ty {$($lit:literal => $exp:expr),* $(,)?})=>{ + impl<'t> DslSymNs<'t, $type> for $State { + const NS: DslNs<'t, fn (&'t $State)->$type> = + DslNs(&[$(($lit, |$state: &$State|$exp)),*]); } }); + +pub trait DslSymNs<'t, T: 't>: 't { + const NS: DslNs<'t, fn (&'t Self)->T>; +} + +pub struct DslNs<'t, T: 't>(pub &'t [(&'t str, T)]); + +pub type DslCb = fn (&App) -> Box>; + +impl<'t, D: Dsl> std::ops::Index for DslNs<'t, DslCb> { + type Output = DslCb; + fn index (&self, index: D) -> &Self::Output { + if let Ok(Some(symbol)) = index.src() { + for (key, value) in self.0.iter() { + if symbol == *key { + return value + } + } + } + &(view_nil as DslCb) + } +} +fn view_nil (_: &App) -> Box> { + Box::new(Fill::xy("·")) +} diff --git a/crates/app/app_view.rs b/crates/app/app_view.rs index 8285967a..3e9d15c8 100644 --- a/crates/app/app_view.rs +++ b/crates/app/app_view.rs @@ -1,78 +1,21 @@ use crate::*; content!(TuiOut:|self: App|VIEW[":view"](self));//if let Ok(Some(view)) = VIEW[":view"] { view(self) } else { panic!() }); -struct DslNs<'t, T: 't>(&'t [(&'t str, T)]); -type DslCb = fn (&App) -> Box>; -impl<'t, D: Dsl> std::ops::Index for DslNs<'t, DslCb> { - type Output = DslCb; - fn index (&self, index: D) -> &Self::Output { - if let Ok(Some(symbol)) = index.src() { - for (key, value) in self.0.iter() { - if symbol == *key { - return value - } - } - } - &(view_nil as DslCb) - } -} pub const VIEW: DslNs<'static, DslCb> = DslNs(&[ - - (":view", |state|Box::new( - Fill::xy(Bsp::a(VIEW[":view/content"](state), VIEW[":view/overlay"](state))))), - - (":view/content", |state|Box::new( - Fill::xy(ErrorBoundary::new(Ok(Some("·")))))), - - (":view/overlay", |state|match &state.dialog { - Dialog::Menu(_) => VIEW[":view/menu"](state), - Dialog::Device(_) => VIEW[":view/device"](state), - Dialog::Browser(_, _) => VIEW[":view/browse"](state), - //Dialog::Help(_) => view_help, - //Dialog::Message(_) => view_message, - //Dialog::Options => view_options, - _ => unimplemented!() }), - - (":view/browse", |state|{ - let browser = state.dialog.browser().cloned().unwrap(); - Box::new(Bsp::s( - Padding::xy(3, 1, VIEW[":view/browse-title"](state)), - Outer(true, Style::default().fg(Tui::g(96))) - .enclose(Fill::xy(browser)))) }), - - (":view/browse-title", |state: &App|{ - let target = state.dialog.browser_target().unwrap(); - Box::new(Fill::x(Align::w(FieldV(Default::default(), match target { - BrowserTarget::SaveProject => "Save project:", - BrowserTarget::LoadProject => "Load project:", - BrowserTarget::ImportSample(_) => "Import sample:", - BrowserTarget::ExportSample(_) => "Export sample:", - BrowserTarget::ImportClip(_) => "Import clip:", - BrowserTarget::ExportClip(_) => "Export clip:", - }, Shrink::x(3, Fixed::y(1, Tui::fg(Tui::g(96), RepeatH("🭻"))))))))}), - - (":view/device", |state: &App|{ - let selected = state.dialog.device_selected().unwrap(); - Box::new(Bsp::s(Tui::bold(true, "Add device"), Map::south(1, - move||device_kinds().iter(), - move|label: &&'static str, i|{ - let bg = if i == selected { Rgb(64,128,32) } else { Rgb(0,0,0) }; - let lb = if i == selected { "[ " } else { " " }; - let rb = if i == selected { " ]" } else { " " }; - Fill::x(Tui::bg(bg, Bsp::e(lb, Bsp::w(rb, "FIXME device name")))) }))) }), - + (":view", |state|VIEW[":view/menu"](state)), (":view/menu", |state|{ let selected = state.dialog.menu_selected(); - let outputs = Fill::x(Fixed::y(3, - Bsp::a(Fill::x(Align::w(" L AUDIO OUTS")), Bsp::a("MIDI OUT", Fill::x(Align::e("AUDIO OUTS R ")))))); - let inputs = Fill::x(Fixed::y(3, - Bsp::a(Fill::x(Align::w(" L AUDIO INS")), Bsp::a("MIDI INS", Fill::x(Align::e("AUDIO INS R ")))))); + let outputs = VIEW[":view/ports/outs"](state); + let inputs = VIEW[":view/ports/ins"](state); Box::new(Tui::bg(Rgb(0,0,0), Bsp::s(outputs, Bsp::s( Fill::x(Fixed::y(3, Tui::bg(Rgb(33,33,33), Tui::bold(true, "tek 0.3.0-rc0")))), Bsp::n(inputs, Bsp::n( Fill::x(Fixed::y(3, Tui::bg(Rgb(33,33,33), Bsp::e(Tui::fg(Rgb(255,192,48), "[Enter]"), " new session")))), Fill::y(Align::n(Fill::x(VIEW[":view/profiles"](state)))))))))) }), - - (":view/profiles", |state|Box::new({ + (":view/ports/outs", |state|Box::new(Fill::x(Fixed::y(3, + Bsp::a(Fill::x(Align::w(" L AUDIO OUTS")), Bsp::a("MIDI OUT", Fill::x(Align::e("AUDIO OUTS R ")))))))), + (":view/ports/ins", |state|Box::new(Fill::x(Fixed::y(3, + Bsp::a(Fill::x(Align::w(" L AUDIO INS")), Bsp::a("MIDI INS", Fill::x(Align::e("AUDIO INS R ")))))))), + (":view/profiles", |state: &App|Box::new({ let views = state.config.views.clone(); Stack::south(move|add: &mut dyn FnMut(&dyn Render)|{ for (index, (id, profile)) in views.read().unwrap().iter().enumerate() { @@ -83,15 +26,34 @@ pub const VIEW: DslNs<'static, DslCb> = DslNs(&[ Fill::x(Bsp::a( Fill::x(Align::w(Tui::fg(Rgb(224,192,128), name))), Fill::x(Align::e(Tui::fg(Rgb(224,128,32), &id))))), - Fill::x(Align::w(info)))))); } })})) - - + Fill::x(Align::w(info)))))); } })})), + (":view/browse", |state: &App|{ + let browser = state.dialog.browser().cloned().unwrap(); + Box::new(Bsp::s( + Padding::xy(3, 1, VIEW[":view/browse-title"](state)), + Outer(true, Style::default().fg(Tui::g(96))) + .enclose(Fill::xy(browser)))) }), + (":view/browse-title", |state: &App|{ + let target = state.dialog.browser_target().unwrap(); + Box::new(Fill::x(Align::w(FieldV(Default::default(), match target { + BrowserTarget::SaveProject => "Save project:", + BrowserTarget::LoadProject => "Load project:", + BrowserTarget::ImportSample(_) => "Import sample:", + BrowserTarget::ExportSample(_) => "Export sample:", + BrowserTarget::ImportClip(_) => "Import clip:", + BrowserTarget::ExportClip(_) => "Export clip:", + }, Shrink::x(3, Fixed::y(1, Tui::fg(Tui::g(96), RepeatH("🭻"))))))))}), + (":view/device", |state: &App|{ + let selected = state.dialog.device_kind().unwrap(); + Box::new(Bsp::s(Tui::bold(true, "Add device"), Map::south(1, + move||device_kinds().iter(), + move|label: &&'static str, i|{ + let bg = if i == selected { Rgb(64,128,32) } else { Rgb(0,0,0) }; + let lb = if i == selected { "[ " } else { " " }; + let rb = if i == selected { " ]" } else { " " }; + Fill::x(Tui::bg(bg, Bsp::e(lb, Bsp::w(rb, "FIXME device name")))) }))) }), //(":view/options", view_options), ]); - -fn view_nil (_: &App) -> Box> { - "nil".boxed() -} fn wrap_dialog (dialog: impl Content) -> impl Content { Fixed::xy(70, 23, Tui::fg_bg(Rgb(255,255,255), Rgb(16,16,16), Bsp::b( Repeat(" "), Outer(true, Style::default().fg(Tui::g(96))).enclose(dialog)))) From b991a49ad7b74a3dbf9d360807574ac84c1ba6af Mon Sep 17 00:00:00 2001 From: unspeaker Date: Sun, 10 Aug 2025 03:53:46 +0300 Subject: [PATCH 5/5] gluing --- crates/app/app.rs | 5 -- crates/app/app_ctrl.rs | 169 +++++++++++++++++++++++------------------ crates/app/app_dsl.rs | 19 +++-- 3 files changed, 106 insertions(+), 87 deletions(-) diff --git a/crates/app/app.rs b/crates/app/app.rs index b371a796..9731d67e 100644 --- a/crates/app/app.rs +++ b/crates/app/app.rs @@ -41,11 +41,6 @@ use std::fmt::Write; use ::tengri::tui::ratatui::prelude::Position; use xdg::BaseDirectories; mod app_dsl; pub use self::app_dsl::*; -macro_rules!dsl_sym( - (|$state:ident:$State:ty| -> $type:ty {$($lit:literal => $exp:expr),* $(,)?})=>{ - impl<'t> DslSymNs<'t, $type> for $State { - const NS: DslNs<'t, fn (&'t $State)->$type> = - DslNs(&[$(($lit, |$state: &$State|$exp)),*]); } }); mod app_view; pub use self::app_view::*; mod app_ctrl; pub use self::app_ctrl::*; mod app_jack; pub use self::app_jack::*; diff --git a/crates/app/app_ctrl.rs b/crates/app/app_ctrl.rs index b24dc862..a1240359 100644 --- a/crates/app/app_ctrl.rs +++ b/crates/app/app_ctrl.rs @@ -1,4 +1,6 @@ use crate::*; +#[derive(Debug)] +pub enum AppCommand {} handle!(TuiIn:|self: App, input|{ panic!("{input:?}"); //Ok(if let Some(binding) = self.profile.as_ref() @@ -12,7 +14,7 @@ handle!(TuiIn:|self: App, input|{ //} else { //None //}) -}) +}); dsl_sym!(|app: App| -> isize { ":_isize_stub" => -1 }); @@ -70,91 +72,108 @@ dsl_sym!(|app: App| -> Selection { }); dsl_sym!(|app: App| -> Option { ":editor/pitch" => Some((app.editor().as_ref().map(|e|e.get_note_pos()).unwrap() as u8).into()) -}) +}); dsl_sym!(|app: App| -> Option { ":selected/scene" => app.selection().scene(), ":selected/track" => app.selection().track(), }); dsl_sym!(|app: App| -> Option>> { ":selected/clip" => if let Selection::TrackClip { track, scene } = app.selection() { - app.scenes()[*scene].clips[*track].clone(), + app.scenes()[*scene].clips[*track].clone() } else { None } }); -dsl_bind!(AppCommand: App { - enqueue = |app, clip: Option>>| { todo!() }; - history = |app, delta: isize| { todo!() }; - zoom = |app, zoom: usize| { todo!() }; - stop_all = |app| { app.tracks_stop_all(); Ok(None) }; - //dialog = |app, command: DialogCommand| - //Ok(command.delegate(&mut app.dialog, |c|Self::Dialog{command: c})?); - project = |app, command: ArrangementCommand| - Ok(command.delegate(&mut app.project, |c|Self::Project{command: c})?); - clock = |app, command: ClockCommand| - Ok(command.execute(app.clock_mut())?.map(|c|Self::Clock{command: c})); - sampler = |app, command: SamplerCommand| - Ok(app.project.sampler_mut().map(|s|command.delegate(s, |command|Self::Sampler{command})) - .transpose()?.flatten()); - pool = |app, command: PoolCommand| { - let undo = command.clone().delegate(&mut app.pool, |command|AppCommand::Pool{command})?; - // update linked editor after pool action - match command { - // autoselect: automatically load selected clip in editor - PoolCommand::Select { .. } | - // autocolor: update color in all places simultaneously - PoolCommand::Clip { command: PoolClipCommand::SetColor { .. } } => { - let clip = app.pool.clip().clone(); - app.editor_mut().map(|editor|editor.set_clip(clip.as_ref())) - }, - _ => None - }; - Ok(undo) - }; - select = |app, selection: Selection| { - *app.project.selection_mut() = selection; - //todo! - //if let Some(ref mut editor) = app.editor_mut() { - //editor.set_clip(match selection { - //Selection::TrackClip { track, scene } if let Some(Some(Some(clip))) = app - //.project - //.scenes.get(scene) - //.map(|s|s.clips.get(track)) - //=> - //Some(clip), - //_ => - //None - //}); - //} - Ok(None) - //("select" [t: usize, s: usize] Some(match (t.expect("no track"), s.expect("no scene")) { - //(0, 0) => Self::Select(Selection::Mix), - //(t, 0) => Self::Select(Selection::Track(t)), - //(0, s) => Self::Select(Selection::Scene(s)), - //(t, s) => Self::Select(Selection::TrackClip { track: t, scene: s }) }))) - // autoedit: load focused clip in editor. - }; - //fn color (app: &mut App, theme: ItemTheme) -> Perhaps { - //Ok(app.set_color(Some(theme)).map(|theme|Self::Color{theme})) - //} - //fn launch (app: &mut App) -> Perhaps { - //app.project.launch(); - //Ok(None) - //} - toggle_editor = |app, value: bool|{ app.toggle_editor(Some(value)); Ok(None) }; - editor = |app, command: MidiEditCommand| Ok(if let Some(editor) = app.editor_mut() { - let undo = command.clone().delegate(editor, |command|AppCommand::Editor{command})?; - // update linked sampler after editor action - app.project.sampler_mut().map(|sampler|match command { - // autoselect: automatically select sample in sampler - MidiEditCommand::SetNotePos { pos } => { sampler.set_note_pos(pos); }, - _ => {} - }); - undo - } else { - None - }); +dsl_exp!(|app: App| -> AppCommand { + ["stop-all"] => app.project.stop_all(), + ["enqueue", clip?: Option>>] => todo!(), + ["history", delta: isize] => todo!(), + ["zoom", zoom: usize] => todo!(), + ["select", selection: Selection] => todo!(), + ["dialog" / command: DialogCommand] => todo!(), + ["project" / command: ArrangementCommand] => todo!(), + ["clock" / command: ClockCommand] => todo!(), + ["sampler" / command: SamplerCommand] => todo!(), + ["pool" / command: PoolCommand] => todo!(), }); +dsl_exp!(|app: App| -> DialogCommand {}); +dsl_exp!(|app: App| -> ArrangementCommand {}); +dsl_exp!(|app: App| -> ClockCommand {}); +dsl_exp!(|app: App| -> SamplerCommand {}); +dsl_exp!(|app: App| -> PoolCommand {}); +//dsl_bind!(AppCommand: App { + //enqueue = |app, clip: Option>>| { todo!() }; + //history = |app, delta: isize| { todo!() }; + //zoom = |app, zoom: usize| { todo!() }; + //stop_all = |app| { app.tracks_stop_all(); Ok(None) }; + ////dialog = |app, command: DialogCommand| + ////Ok(command.delegate(&mut app.dialog, |c|Self::Dialog{command: c})?); + //project = |app, command: ArrangementCommand| + //Ok(command.delegate(&mut app.project, |c|Self::Project{command: c})?); + //clock = |app, command: ClockCommand| + //Ok(command.execute(app.clock_mut())?.map(|c|Self::Clock{command: c})); + //sampler = |app, command: SamplerCommand| + //Ok(app.project.sampler_mut().map(|s|command.delegate(s, |command|Self::Sampler{command})) + //.transpose()?.flatten()); + //pool = |app, command: PoolCommand| { + //let undo = command.clone().delegate(&mut app.pool, |command|AppCommand::Pool{command})?; + //// update linked editor after pool action + //match command { + //// autoselect: automatically load selected clip in editor + //PoolCommand::Select { .. } | + //// autocolor: update color in all places simultaneously + //PoolCommand::Clip { command: PoolClipCommand::SetColor { .. } } => { + //let clip = app.pool.clip().clone(); + //app.editor_mut().map(|editor|editor.set_clip(clip.as_ref())) + //}, + //_ => None + //}; + //Ok(undo) + //}; + //select = |app, selection: Selection| { + //*app.project.selection_mut() = selection; + ////todo! + ////if let Some(ref mut editor) = app.editor_mut() { + ////editor.set_clip(match selection { + ////Selection::TrackClip { track, scene } if let Some(Some(Some(clip))) = app + ////.project + ////.scenes.get(scene) + ////.map(|s|s.clips.get(track)) + ////=> + ////Some(clip), + ////_ => + ////None + ////}); + ////} + //Ok(None) + ////("select" [t: usize, s: usize] Some(match (t.expect("no track"), s.expect("no scene")) { + ////(0, 0) => Self::Select(Selection::Mix), + ////(t, 0) => Self::Select(Selection::Track(t)), + ////(0, s) => Self::Select(Selection::Scene(s)), + ////(t, s) => Self::Select(Selection::TrackClip { track: t, scene: s }) }))) + //// autoedit: load focused clip in editor. + //}; + ////fn color (app: &mut App, theme: ItemTheme) -> Perhaps { + ////Ok(app.set_color(Some(theme)).map(|theme|Self::Color{theme})) + ////} + ////fn launch (app: &mut App) -> Perhaps { + ////app.project.launch(); + ////Ok(None) + ////} + //toggle_editor = |app, value: bool|{ app.toggle_editor(Some(value)); Ok(None) }; + //editor = |app, command: MidiEditCommand| Ok(if let Some(editor) = app.editor_mut() { + //let undo = command.clone().delegate(editor, |command|AppCommand::Editor{command})?; + //// update linked sampler after editor action + //app.project.sampler_mut().map(|sampler|match command { + //// autoselect: automatically select sample in sampler + //MidiEditCommand::SetNotePos { pos } => { sampler.set_note_pos(pos); }, + //_ => {} + //}); + //undo + //} else { + //None + //}); +//}); //take!(ClockCommand |state: App, iter|Take::take(state.clock(), iter)); //take!(MidiEditCommand |state: App, iter|Ok(state.editor().map(|x|Take::take(x, iter)).transpose()?.flatten())); //take!(PoolCommand |state: App, iter|Take::take(&state.pool, iter)); diff --git a/crates/app/app_dsl.rs b/crates/app/app_dsl.rs index 21a1be6d..745da9a6 100644 --- a/crates/app/app_dsl.rs +++ b/crates/app/app_dsl.rs @@ -1,19 +1,24 @@ use crate::*; -macro_rules!dsl_sym( +pub struct DslNs<'t, T: 't>(pub &'t [(&'t str, T)]); + +pub trait DslSymNs<'t, T: 't>: 't { const NS: DslNs<'t, fn (&'t Self)->T>; } +#[macro_export] macro_rules! dsl_sym ( (|$state:ident:$State:ty| -> $type:ty {$($lit:literal => $exp:expr),* $(,)?})=>{ impl<'t> DslSymNs<'t, $type> for $State { const NS: DslNs<'t, fn (&'t $State)->$type> = DslNs(&[$(($lit, |$state: &$State|$exp)),*]); } }); -pub trait DslSymNs<'t, T: 't>: 't { - const NS: DslNs<'t, fn (&'t Self)->T>; -} - -pub struct DslNs<'t, T: 't>(pub &'t [(&'t str, T)]); +pub trait DslExpNs<'t, T: 't>: 't { const NS: DslNs<'t, fn (&'t Self, &str)->T>; } +#[macro_export] macro_rules! dsl_exp ( + (|$state:ident:$State:ty|->$type:ty { $( + [$key:literal $(/ $sub:ident: $Sub:ty)? $(, $arg:ident $(?)? :$argtype:ty)*] => $body:expr + ),* $(,)? }) => { + impl<'t> DslExpNs<'t, $type> for $State { + const NS: DslNs<'t, fn (&'t $State, &str)->$type> = + DslNs(&[]); } }); pub type DslCb = fn (&App) -> Box>; - impl<'t, D: Dsl> std::ops::Index for DslNs<'t, DslCb> { type Output = DslCb; fn index (&self, index: D) -> &Self::Output {