From 89288f2920172ca28354025b7812bcc9da7b4001 Mon Sep 17 00:00:00 2001 From: unspeaker Date: Wed, 14 May 2025 00:46:33 +0300 Subject: [PATCH] wip: refactor arranger to device --- config/config_arranger.edn | 2 +- config/config_groovebox.edn | 2 +- config/config_sequencer.edn | 2 +- config/keys_arranger.edn | 2 +- config/keys_device_add.edn | 5 +- crates/app/src/api.rs | 308 --------- crates/app/src/audio.rs | 83 +-- crates/app/src/model.rs | 615 ++++++------------ crates/app/src/model/dialog.rs | 36 - crates/app/src/model/pool.rs | 0 crates/app/src/model/scene.rs | 76 --- crates/app/src/model/track.rs | 161 ----- crates/app/src/view.rs | 559 ++-------------- crates/app/src/view/view_dialog.rs | 99 --- crates/app/src/view/view_output.rs | 92 --- crates/cli/tek.rs | 43 +- crates/device/Cargo.toml | 3 +- crates/device/src/arranger.rs | 86 +++ crates/device/src/arranger/arranger_api.rs | 207 ++++++ crates/device/src/arranger/arranger_audio.rs | 7 + crates/device/src/arranger/arranger_clip.rs | 35 + crates/device/src/arranger/arranger_device.rs | 27 + crates/device/src/arranger/arranger_edit.rs | 62 ++ crates/device/src/arranger/arranger_model.rs | 74 +++ crates/device/src/arranger/arranger_port.rs | 134 ++++ crates/device/src/arranger/arranger_scene.rs | 261 ++++++++ .../src/arranger/arranger_select.rs} | 74 ++- crates/device/src/arranger/arranger_track.rs | 290 +++++++++ crates/device/src/arranger/arranger_view.rs | 217 ++++++ crates/device/src/browser/browser_api.rs | 30 +- crates/device/src/browser/browser_model.rs | 16 +- crates/device/src/lib.rs | 7 +- crates/device/src/sequencer/seq_audio.rs | 4 +- crates/device/src/sequencer/seq_model.rs | 13 +- crates/engine/src/jack/jack_port.rs | 176 ++--- crates/engine/src/lib.rs | 21 +- crates/engine/src/midi.rs | 28 +- crates/engine/src/midi/midi_in.rs | 42 ++ crates/engine/src/midi/midi_out.rs | 33 + deps/tengri | 2 +- 40 files changed, 2015 insertions(+), 1919 deletions(-) delete mode 100644 crates/app/src/model/dialog.rs delete mode 100644 crates/app/src/model/pool.rs delete mode 100644 crates/app/src/model/scene.rs delete mode 100644 crates/app/src/model/track.rs delete mode 100644 crates/app/src/view/view_dialog.rs delete mode 100644 crates/app/src/view/view_output.rs create mode 100644 crates/device/src/arranger.rs create mode 100644 crates/device/src/arranger/arranger_api.rs create mode 100644 crates/device/src/arranger/arranger_audio.rs create mode 100644 crates/device/src/arranger/arranger_clip.rs create mode 100644 crates/device/src/arranger/arranger_device.rs create mode 100644 crates/device/src/arranger/arranger_edit.rs create mode 100644 crates/device/src/arranger/arranger_model.rs create mode 100644 crates/device/src/arranger/arranger_port.rs create mode 100644 crates/device/src/arranger/arranger_scene.rs rename crates/{app/src/model/selection.rs => device/src/arranger/arranger_select.rs} (67%) create mode 100644 crates/device/src/arranger/arranger_track.rs create mode 100644 crates/device/src/arranger/arranger_view.rs create mode 100644 crates/engine/src/midi/midi_in.rs create mode 100644 crates/engine/src/midi/midi_out.rs diff --git a/config/config_arranger.edn b/config/config_arranger.edn index a35182bf..cffba38f 100644 --- a/config/config_arranger.edn +++ b/config/config_arranger.edn @@ -13,7 +13,7 @@ (keys (layer-if :focus-message "./keys_message.edn") (layer-if :focus-device-add "./keys_device_add.edn") - (layer-if :focus-browser "./keys_browser") + (layer-if :focus-browser "./keys_browser.edn") (layer-if :focus-pool-rename "./keys_rename.edn") (layer-if :focus-pool-length "./keys_length.edn") (layer "./keys_global.edn") diff --git a/config/config_groovebox.edn b/config/config_groovebox.edn index 67b0e5f9..fec1ca2d 100644 --- a/config/config_groovebox.edn +++ b/config/config_groovebox.edn @@ -15,7 +15,7 @@ (fill/y :view-editor))))))))))) (keys - (layer-if :focus-browser "./keys_browser") + (layer-if :focus-browser "./keys_browser.edn") (layer-if :focus-pool-rename "./keys_rename.edn") (layer-if :focus-pool-length "./keys_length.edn") (layer "./keys_global.edn") diff --git a/config/config_sequencer.edn b/config/config_sequencer.edn index e09c0e7b..f20e2fcd 100644 --- a/config/config_sequencer.edn +++ b/config/config_sequencer.edn @@ -11,7 +11,7 @@ :view-editor))))) (keys - (layer-if :focus-browser "./keys_browser") + (layer-if :focus-browser "./keys_browser.edn") (layer-if :mode-pool-rename "./keys_rename.edn") (layer-if :mode-pool-length "./keys_length.edn") (layer "./keys_global.edn") diff --git a/config/keys_arranger.edn b/config/keys_arranger.edn index 4f52a767..40ffc742 100644 --- a/config/keys_arranger.edn +++ b/config/keys_arranger.edn @@ -6,7 +6,7 @@ (@shift-O output add) (@shift-S scene add) (@shift-T track add) -(@shift-D device picker) +(@shift-D toggle-dialog :dialog-device) (@up select :select-scene-prev) (@down select :select-scene-next) diff --git a/config/keys_device_add.edn b/config/keys_device_add.edn index 6e557b0b..9ad4b197 100644 --- a/config/keys_device_add.edn +++ b/config/keys_device_add.edn @@ -1,3 +1,2 @@ -(@up device pick :device-kind-prev) -(@down device pick :device-kind-next) -(@enter device add :device-kind) +(@up toggle-dialog :dialog-device-prev) +(@down toggle-dialog :dialog-device-next) diff --git a/crates/app/src/api.rs b/crates/app/src/api.rs index 28076419..17ef811a 100644 --- a/crates/app/src/api.rs +++ b/crates/app/src/api.rs @@ -17,173 +17,6 @@ handle!(TuiIn: |self: App, input|Ok(if let Some(command) = self.config.keys.comm None })); -#[tengri_proc::expose] impl App { - fn _todo_isize_stub (&self) -> isize { - todo!() - } - fn _todo_item_theme_stub (&self) -> ItemTheme { - todo!() - } - fn focus_editor (&self) -> bool { - self.is_editing() - } - fn focus_message (&self) -> bool { - matches!(self.dialog, Some(Dialog::Message(..))) - } - fn focus_device_add (&self) -> bool { - matches!(self.dialog, Some(Dialog::Device(..))) - } - fn focus_clip (&self) -> bool { - !self.is_editing() && self.selected.is_clip() - } - fn focus_track (&self) -> bool { - !self.is_editing() && self.selected.is_track() - } - fn focus_scene (&self) -> bool { - !self.is_editing() && self.selected.is_scene() - } - fn focus_mix (&self) -> bool { - !self.is_editing() && self.selected.is_mix() - } - fn focus_pool_import (&self) -> bool { - matches!(self.pool.as_ref().map(|p|p.mode.as_ref()).flatten(), Some(PoolMode::Import(..))) - } - fn focus_pool_export (&self) -> bool { - matches!(self.pool.as_ref().map(|p|p.mode.as_ref()).flatten(), Some(PoolMode::Export(..))) - } - fn focus_pool_rename (&self) -> bool { - matches!(self.pool.as_ref().map(|p|p.mode.as_ref()).flatten(), Some(PoolMode::Rename(..))) - } - fn focus_pool_length (&self) -> bool { - matches!(self.pool.as_ref().map(|p|p.mode.as_ref()).flatten(), Some(PoolMode::Length(..))) - } - fn dialog_help (&self) -> Dialog { - Dialog::Help - } - fn dialog_menu (&self) -> Dialog { - Dialog::Menu - } - fn dialog_save (&self) -> Dialog { - Dialog::Save - } - fn dialog_load (&self) -> Dialog { - Dialog::Load - } - fn dialog_options (&self) -> Dialog { - Dialog::Options - } - fn editor_pitch (&self) -> Option { - Some((self.editor().map(|e|e.get_note_pos()).unwrap() as u8).into()) - } - /// Width of display - pub(crate) fn w (&self) -> u16 { - self.size.w() as u16 - } - /// Width allocated for sidebar. - pub(crate) fn w_sidebar (&self) -> u16 { - self.w() / if self.is_editing() { 16 } else { 8 } as u16 - } - /// Width taken by all tracks. - pub(crate) fn w_tracks (&self) -> u16 { - self.tracks_with_sizes().last().map(|(_, _, _, x)|x as u16).unwrap_or(0) - } - /// Width available to display tracks. - pub(crate) fn w_tracks_area (&self) -> u16 { - self.w().saturating_sub(2 * self.w_sidebar()) - } - /// Height of display - pub(crate) fn h (&self) -> u16 { - self.size.h() as u16 - } - /// Height available to display track headers. - pub(crate) fn h_tracks_area (&self) -> u16 { - 5 // FIXME - //self.h().saturating_sub(self.h_inputs() + self.h_outputs()) - } - /// Height available to display tracks. - pub(crate) fn h_scenes_area (&self) -> u16 { - //15 - self.h().saturating_sub( - self.h_inputs() + - self.h_outputs() + - self.h_devices() + - 13 // FIXME - ) - } - /// Height taken by all scenes. - pub(crate) fn h_scenes (&self) -> u16 { - self.scenes_with_sizes(self.is_editing(), Self::H_SCENE, Self::H_EDITOR).last() - .map(|(_, _, _, y)|y as u16).unwrap_or(0) - } - /// Height taken by all inputs. - pub(crate) fn h_inputs (&self) -> u16 { - self.inputs_with_sizes().last().map(|(_, _, _, _, y)|y as u16).unwrap_or(0) - } - /// Height taken by all outputs. - pub(crate) fn h_outputs (&self) -> u16 { - self.outputs_with_sizes().last().map(|(_, _, _, _, y)|y as u16).unwrap_or(0) - } - /// Height taken by visible device slots. - pub(crate) fn h_devices (&self) -> u16 { - 2 - //1 + self.devices_with_sizes().last().map(|(_, _, _, _, y)|y as u16).unwrap_or(0) - } - fn scene_count (&self) -> usize { - self.scenes.len() - } - fn scene_selected (&self) -> Option { - self.selected.scene() - } - fn track_count (&self) -> usize { - self.tracks.len() - } - fn track_selected (&self) -> Option { - self.selected.track() - } - fn select_scene_next (&self) -> Selection { - self.selected.scene_next(self.scenes.len()) - } - fn select_scene_prev (&self) -> Selection { - self.selected.scene_prev() - } - fn select_track_header (&self) -> Selection { - self.selected.track_header(self.tracks.len()) - } - fn select_track_next (&self) -> Selection { - self.selected.track_next(self.tracks.len()) - } - fn select_track_prev (&self) -> Selection { - self.selected.track_prev() - } - fn clip_selected (&self) -> Option>> { - match self.selected { - Selection::TrackClip { track, scene } => self.scenes[scene].clips[track].clone(), - _ => None - } - } - fn device_kind (&self) -> usize { - if let Some(Dialog::Device(index)) = self.dialog { - index - } else { - 0 - } - } - fn device_kind_prev (&self) -> usize { - if let Some(Dialog::Device(index)) = self.dialog { - index.overflowing_sub(1).0.min(self.device_kinds().len().saturating_sub(1)) - } else { - 0 - } - } - fn device_kind_next (&self) -> usize { - if let Some(Dialog::Device(index)) = self.dialog { - (index + 1) % self.device_kinds().len() - } else { - 0 - } - } -} - #[tengri_proc::command(App)] impl AppCommand { fn toggle_dialog (app: &mut App, dialog: Dialog) -> Perhaps { app.toggle_dialog(Some(dialog)); @@ -313,150 +146,9 @@ impl<'state> Context<'state, SamplerCommand> for App { } } -#[tengri_proc::command(App)] impl InputCommand { - fn add (app: &mut App) -> Perhaps { - app.midi_in_add()?; - Ok(None) - } -} - -#[tengri_proc::command(App)] impl OutputCommand { - fn add (app: &mut App) -> Perhaps { - app.midi_out_add()?; - Ok(None) - } -} - -#[tengri_proc::command(App)] impl DeviceCommand { - fn cancel (app: &mut App) -> Perhaps { - app.dialog = None; - Ok(None) - } - fn picker (app: &mut App) -> Perhaps { - app.device_picker_show(); - Ok(None) - } - fn pick (app: &mut App, i: usize) -> Perhaps { - app.device_pick(i); - Ok(None) - } - fn add (app: &mut App, i: usize) -> Perhaps { - app.device_add(i); - Ok(None) - } -} - #[tengri_proc::command(App)] impl MessageCommand { fn dismiss (app: &mut App) -> Perhaps { app.message_dismiss(); Ok(None) } } - -#[tengri_proc::command(App)] impl TrackCommand { - fn toggle_play (app: &mut App) -> Perhaps { - todo!() - } - fn toggle_solo (app: &mut App) -> Perhaps { - todo!() - } - fn toggle_rec (app: &mut App) -> Perhaps { - app.track_toggle_record(); - Ok(Some(Self::ToggleRec)) - } - fn toggle_mon (app: &mut App) -> Perhaps { - app.track_toggle_monitor(); - Ok(Some(Self::ToggleMon)) - } - fn set_size (app: &mut App, size: usize) -> Perhaps { - todo!() - } - fn set_zoom (app: &mut App, zoom: usize) -> Perhaps { - todo!() - } - fn swap (app: &mut App, index: usize, other: usize) -> Perhaps { - todo!(); - Ok(Some(Self::Swap { index, other })) - } - fn del (app: &mut App, index: usize) -> Perhaps { - app.track_del(index); - Ok(None) - } - fn stop (app: &mut App, index: usize) -> Perhaps { - app.tracks[index].sequencer.enqueue_next(None); - Ok(None) - } - fn add (app: &mut App) -> Perhaps { - Ok(Some(Self::Del { index: app.track_add_focus()? })) - } - fn set_color (app: &mut App, index: usize, color: ItemTheme) -> Perhaps { - Ok(Some(Self::SetColor { index, color: app.track_set_color(index, color) })) - } -} - -#[tengri_proc::command(App)] impl SceneCommand { - fn add (app: &mut App) -> Perhaps { - todo!() - } - fn del (app: &mut App, index: usize) -> Perhaps { - app.scene_del(index); - Ok(None) - } - fn enqueue (app: &mut App, index: usize) -> Perhaps { - app.scene_enqueue(index); - Ok(None) - } - fn set_color (app: &mut App, index: usize, color: ItemTheme) -> Perhaps { - Ok(Some(Self::SetColor { index, color: app.scene_set_color(index, color) })) - } - fn set_size (app: &mut App, index: usize, size: usize) -> Perhaps { - todo!() - } - fn set_zoom (app: &mut App, index: usize, zoom: usize) -> Perhaps { - todo!() - } - fn swap (app: &mut App, index: usize, other: usize) -> Perhaps { - todo!(); - Ok(Some(Self::Swap { index, other })) - } -} - -#[tengri_proc::command(App)] impl ClipCommand { - fn get (app: &mut App, a: usize, b: usize) -> Perhaps { - //(Get [a: usize, b: usize] cmd_todo!("\n\rtodo: clip: get: {a} {b}")) - //("get" [a: usize, b: usize] Some(Self::Get(a.unwrap(), b.unwrap()))) - todo!() - } - fn edit (app: &mut App, a: usize, b: usize) -> Perhaps { - //(Edit [clip: MaybeClip] cmd_todo!("\n\rtodo: clip: edit: {clip:?}")) - //("edit" [a: MaybeClip] Some(Self::Edit(a.unwrap()))) - todo!() - } - fn set_loop (app: &mut App, a: usize, b: usize) -> Perhaps { - //(SetLoop [t: usize, s: usize, l: bool] cmd_todo!("\n\rtodo: {self:?}")) - //("loop" [a: usize, b: usize, c: bool] Some(Self::SetLoop(a.unwrap(), b.unwrap(), c.unwrap()))) - todo!() - } - fn put (app: &mut App, a: usize, b: usize) -> Perhaps { - //(Put [t: usize, s: usize, c: MaybeClip] - //Some(Self::Put(t, s, app.clip_put(t, s, c)))) - //("put" [a: usize, b: usize, c: MaybeClip] Some(Self::Put(a.unwrap(), b.unwrap(), c.unwrap()))) - todo!() - } - fn del (app: &mut App, a: usize, b: usize) -> Perhaps { - //("delete" [a: usize, b: usize] Some(Self::Put(a.unwrap(), b.unwrap(), None)))) - todo!() - } - fn enqueue (app: &mut App, a: usize, b: usize) -> Perhaps { - //(Enqueue [t: usize, s: usize] - //cmd!(app.tracks[t].sequencer.enqueue_next(app.scenes[s].clips[t].as_ref()))) - //("enqueue" [a: usize, b: usize] Some(Self::Enqueue(a.unwrap(), b.unwrap()))) - todo!() - } - fn set_color (app: &mut App, a: usize, b: usize) -> Perhaps { - //(SetColor [t: usize, s: usize, c: ItemTheme] - //app.clip_set_color(t, s, c).map(|o|Self::SetColor(t, s, o))))); - //("color" [a: usize, b: usize] Some(Self::SetColor(a.unwrap(), b.unwrap(), ItemTheme::random()))) - todo!() - } -} diff --git a/crates/app/src/audio.rs b/crates/app/src/audio.rs index 39d23f13..15d15232 100644 --- a/crates/app/src/audio.rs +++ b/crates/app/src/audio.rs @@ -1,12 +1,32 @@ use crate::*; +impl HasJack for App { + fn jack (&self) -> &Jack { + &self.jack + } +} + audio!( |self: App, client, scope|{ let t0 = self.perf.get_t0(); self.clock().update_from_scope(scope).unwrap(); - let midi_in = self.collect_midi_input(scope); - self.update_editor_cursor(&midi_in); - let result = self.render_tracks(client, scope); + let midi_in = self.arranger.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.arranger.tracks_render(client, scope); self.perf.update_from_jack_scope(t0, scope); result }; @@ -33,60 +53,3 @@ audio!( } } ); - -type CollectedMidiInput<'a> = Vec, MidiError>)>>; - -impl App { - - /// Collect MIDI input from app ports (TODO preallocate large buffers) - fn collect_midi_input <'a> (&'a self, scope: &'a ProcessScope) -> CollectedMidiInput<'a> { - self.midi_ins.iter() - .map(|port|port.port().iter(scope) - .map(|RawMidi { time, bytes }|(time, LiveEvent::parse(bytes))) - .collect::>()) - .collect::>() - } - - /// Update cursor in MIDI editor - fn update_editor_cursor (&self, midi_in: &CollectedMidiInput) { - 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); - } - } - } - - /// Run audio callbacks for every track and every device - fn render_tracks (&mut self, client: &Client, scope: &ProcessScope) -> Control { - for track in self.tracks.iter_mut() { - if Control::Quit == PlayerAudio( - track.sequencer_mut(), &mut self.note_buf, &mut self.midi_buf - ).process(client, scope) { - return Control::Quit - } - for device in track.devices.iter_mut() { - if Control::Quit == DeviceAudio(device).process(client, scope) { - return Control::Quit - } - } - } - Control::Continue - } - -} - -impl HasJack for App { - fn jack (&self) -> &Jack { - &self.jack - } -} diff --git a/crates/app/src/model.rs b/crates/app/src/model.rs index 074ca999..e7411bea 100644 --- a/crates/app/src/model.rs +++ b/crates/app/src/model.rs @@ -1,445 +1,95 @@ use crate::*; -mod dialog; pub use self::dialog::*; -mod pool; pub use self::pool::*; -mod selection; pub use self::selection::*; -mod track; pub use self::track::*; -mod scene; pub use self::scene::*; - #[derive(Default, Debug)] pub struct App { /// Must not be dropped for the duration of the process - pub jack: Jack, + pub jack: Jack, + /// Port handles + pub ports: std::collections::BTreeMap>, /// Source of time pub clock: Clock, - /// Theme - pub color: ItemTheme, - /// Contains all clips in the project - pub pool: Option, - /// Contains the currently edited MIDI clip - pub editor: Option, - /// Contains a render of the project arrangement, redrawn on update. - pub arranger: Arc>, - /// List of global midi inputs - pub midi_ins: Vec, - /// List of global midi outputs - pub midi_outs: Vec, - /// List of global audio inputs - pub audio_ins: Vec, - /// List of global audio outputs - pub audio_outs: Vec, - /// Buffer for writing a midi event - pub note_buf: Vec, - /// Buffer for writing a chunk of midi events - pub midi_buf: Vec>>, - /// Last track number (to avoid duplicate port names) - pub track_last: usize, - /// List of tracks - pub tracks: Vec, - /// Scroll offset of tracks - pub track_scroll: usize, - /// List of scenes - pub scenes: Vec, - /// Scroll offset of scenes - pub scene_scroll: usize, - /// Selected UI element - pub selected: Selection, /// Display size pub size: Measure, /// Performance counter pub perf: PerfModel, - /// Whether in edit mode - pub editing: AtomicBool, + + // View and input definition + pub config: Configuration, /// Undo history - pub history: Vec, - /// Port handles - pub ports: std::collections::BTreeMap>, + pub history: Vec, + // Dialog overlay + pub dialog: Option, + /// Browses external resources, such as directories + pub browser: Option, + /// Contains the currently edited musical arrangement + pub arranger: Option, + /// Contains all clips in the project + pub pool: Option, + /// Contains the currently edited MIDI clip + pub editor: Option, + // Cache of formatted strings pub view_cache: Arc>, - // Dialog overlay - pub dialog: Option, - // View and input definition - pub config: Configuration + /// Base color. + pub color: ItemTheme, } impl App { - - /// Add multiple tracks - pub fn tracks_add ( - &mut self, - count: usize, - width: Option, - mins: &[PortConnect], - mouts: &[PortConnect], - ) -> Usually<()> { - let jack = self.jack().clone(); - let track_color_1 = ItemColor::random(); - let track_color_2 = ItemColor::random(); - for i in 0..count { - let color = track_color_1.mix(track_color_2, i as f32 / count as f32).into(); - let mut track = self.track_add(None, Some(color), mins, mouts)?.1; - if let Some(width) = width { - track.width = width; - } - } - Ok(()) - } - - /// Add a track - pub fn track_add ( - &mut self, - name: Option<&str>, - color: Option, - mins: &[PortConnect], - mouts: &[PortConnect], - ) -> Usually<(usize, &mut Track)> { - self.track_last += 1; - let name: Arc = name.map_or_else( - ||format!("Track{:02}", self.track_last).into(), - |x|x.to_string().into() - ); - let mut track = Track { - width: (name.len() + 2).max(12), - color: color.unwrap_or_else(ItemTheme::random), - sequencer: Sequencer::new( - &format!("{name}"), - self.jack(), - Some(self.clock()), - None, - mins, - mouts - )?, - name, - ..Default::default() - }; - self.tracks_mut().push(track); - let len = self.tracks().len(); - let index = len - 1; - for scene in self.scenes_mut().iter_mut() { - while scene.clips.len() < len { - scene.clips.push(None); - } - } - Ok((index, &mut self.tracks_mut()[index])) - } - - /// Add and focus a track - pub(crate) fn track_add_focus (&mut self) -> Usually { - use Selection::*; - let index = self.track_add(None, None, &[], &[])?.0; - self.selected = match self.selected { - Track(_) => Track(index), - TrackClip { track, scene } => TrackClip { track: index, scene }, - _ => self.selected - }; - Ok(index) - } - - /// Delete a track - pub fn track_del (&mut self, index: usize) -> Usually<()> { - let exists = self.tracks().get(index).is_some(); - if exists { - let track = self.tracks_mut().remove(index); - let Track { sequencer: Sequencer { midi_ins, midi_outs, .. }, .. } = track; - for port in midi_ins.into_iter() { - port.close()?; - } - for port in midi_outs.into_iter() { - port.close()?; - } - for scene in self.scenes_mut().iter_mut() { - scene.clips.remove(index); - } - } - Ok(()) - } - - /// Add multiple scenes - pub fn scenes_add (&mut self, n: usize) -> Usually<()> { - let scene_color_1 = ItemColor::random(); - let scene_color_2 = ItemColor::random(); - for i in 0..n { - let _ = self.scene_add(None, Some( - scene_color_1.mix(scene_color_2, i as f32 / n as f32).into() - ))?; - } - Ok(()) - } - - /// Add a scene - pub fn scene_add (&mut self, name: Option<&str>, color: Option) - -> Usually<(usize, &mut Scene)> - { - let scene = Scene { - name: name.map_or_else(||self.scene_default_name(), |x|x.to_string().into()), - clips: vec![None;self.tracks().len()], - color: color.unwrap_or_else(ItemTheme::random), - }; - self.scenes_mut().push(scene); - let index = self.scenes().len() - 1; - Ok((index, &mut self.scenes_mut()[index])) - } - - /// Add and focus an empty scene - pub fn scene_add_focus (&mut self) -> Usually { - use Selection::*; - let index = self.scene_add(None, None)?.0; - self.selected = match self.selected { - Scene(_) => Scene(index), - TrackClip { track, scene } => TrackClip { track, scene: index }, - _ => self.selected - }; - Ok(index) - } - - /// Enqueue clips from a scene across all tracks - pub fn scene_enqueue (&mut self, scene: usize) { - for track in 0..self.tracks.len() { - self.tracks[track].sequencer.enqueue_next(self.scenes[scene].clips[track].as_ref()); - } - } - - pub fn toggle_editor (&mut self, value: Option) { - let editing = self.is_editing(); - let value = value.unwrap_or_else(||!self.is_editing()); - self.editing.store(value, Relaxed); - if value { - self.clip_auto_create(); + pub fn toggle_dialog (&mut self, dialog: Option) { + self.dialog = if self.dialog == dialog { + None } else { - self.clip_auto_remove(); + dialog } } - - // Create new clip in pool when entering empty cell - pub fn clip_auto_create (&mut self) { - if let Some(ref pool) = self.pool - && let Selection::TrackClip { track, scene } = self.selected - && let Some(scene) = self.scenes.get_mut(scene) - && let Some(slot) = scene.clips.get_mut(track) - && slot.is_none() - { - let (index, mut clip) = pool.add_new_clip(); - // autocolor: new clip colors from scene and track color - clip.write().unwrap().color = ItemColor::random_near( - self.tracks[track].color.base.mix( - scene.color.base, - 0.5 - ), - 0.2 - ).into(); - if let Some(ref mut editor) = self.editor { - editor.set_clip(Some(&clip)); - } - *slot = Some(clip); - } + pub fn toggle_editor (&mut self, value: Option) { + self.editing.store(value.unwrap_or_else(||!self.is_editing()), Relaxed); + self.arranger.map(|arranger|if value { + arranger.clip_auto_create(); + } else { + arranger.clip_auto_remove(); + }); } - - // Remove clip from arrangement when exiting empty clip editor - pub fn clip_auto_remove (&mut self) { - if let Some(ref mut pool) = self.pool - && let Selection::TrackClip { track, scene } = self.selected - && let Some(scene) = self.scenes.get_mut(scene) - && let Some(slot) = scene.clips.get_mut(track) - && let Some(clip) = slot.as_mut() - { - let mut swapped = None; - if clip.read().unwrap().count_midi_messages() == 0 { - std::mem::swap(&mut swapped, slot); - } - if let Some(clip) = swapped { - pool.delete_clip(&clip.read().unwrap()); - } - } + pub(crate) fn device_pick (&mut self, index: usize) { + self.dialog = Some(Dialog::Device(index)); } - - /// Put a clip in a slot - pub(crate) fn clip_put ( - &mut self, track: usize, scene: usize, clip: Option>> - ) -> Option>> { - let old = self.scenes[scene].clips[track].clone(); - self.scenes[scene].clips[track] = clip; - old - } - - /// Change the color of a clip, returning the previous one - pub(crate) fn clip_set_color ( - &self, track: usize, scene: usize, color: ItemTheme - ) -> Option { - self.scenes[scene].clips[track].as_ref().map(|clip|{ - let mut clip = clip.write().unwrap(); - let old = clip.color.clone(); - clip.color = color.clone(); - panic!("{color:?} {old:?}"); - old - }) - } - - /// Get the clip pool, if present - pub(crate) fn pool (&self) -> Option<&Pool> { - self.pool.as_ref() - } - - /// Get the active clip - pub(crate) fn clip (&self) -> Option>> { - self.scene()?.clips.get(self.selected().track()?)?.clone() - } - - /// Get the active editor - pub(crate) fn editor (&self) -> Option<&MidiEditor> { - self.editor.as_ref() - } - - /// Toggle looping for the active clip - pub(crate) fn toggle_loop (&mut self) { - if let Some(clip) = self.clip() { - clip.write().unwrap().toggle_loop() - } - } - - /// Set the selection - pub(crate) fn select (&mut self, s: Selection) { - self.selected = s; - // autoedit: load focused clip in editor. - if let Some(ref mut editor) = self.editor { - editor.set_clip(match self.selected { - Selection::TrackClip { track, scene } - if let Some(Some(Some(clip))) = self - .scenes.get(scene) - .map(|s|s.clips.get(track)) => Some(clip), - _ => None - }); - } - } - - /// Stop all playing clips - pub(crate) fn stop_all (&mut self) { - for track in 0..self.tracks.len() { - self.tracks[track].sequencer.enqueue_next(None); - } - } - - /// Launch a clip or scene - pub(crate) fn launch (&mut self) { - use Selection::*; - match self.selected { - Track(t) => { - self.tracks[t].sequencer.enqueue_next(None) - }, - TrackClip { track, scene } => { - self.tracks[track].sequencer.enqueue_next(self.scenes[scene].clips[track].as_ref()) - }, - Scene(s) => { - for t in 0..self.tracks.len() { - self.tracks[t].sequencer.enqueue_next(self.scenes[s].clips[t].as_ref()) - } - }, - _ => {} - }; - } - - /// Get the first sampler of the active track - pub fn sampler (&self) -> Option<&Sampler> { - self.track().map(|t|t.sampler(0)).flatten() - } - - /// Get the first sampler of the active track - pub fn sampler_mut (&mut self) -> Option<&mut Sampler> { - self.track_mut().map(|t|t.sampler_mut(0)).flatten() - } - - /// Set the color of the selected entity - pub fn set_color (&mut self, palette: Option) -> Option { - use Selection::*; - let palette = palette.unwrap_or_else(||ItemTheme::random()); - Some(match self.selected { - Mix => { - let old = self.color; - self.color = palette; - old - }, - Scene(s) => { - let old = self.scenes[s].color; - self.scenes[s].color = palette; - old - } - Track(t) => { - let old = self.tracks[t].color; - self.tracks[t].color = palette; - old - } - TrackClip { track, scene } => { - if let Some(ref clip) = self.scenes[scene].clips[track] { - let mut clip = clip.write().unwrap(); - let old = clip.color; - clip.color = palette; - old - } else { - return None - } - }, - _ => todo!() - }) - } - - pub(crate) fn midi_in_add (&mut self) -> Usually<()> { - self.midi_ins.push(JackMidiIn::new(&self.jack, &format!("M/{}", self.midi_ins.len()), &[])?); - Ok(()) - } - - pub(crate) fn midi_out_add (&mut self) -> Usually<()> { - self.midi_outs.push(JackMidiOut::new(&self.jack, &format!("{}/M", self.midi_outs.len()), &[])?); - Ok(()) - } - pub(crate) fn device_kinds (&self) -> &'static [&'static str] { &[ "Sampler", "Plugin (LV2)", ] } - - pub(crate) fn device_picker_show (&mut self) { - self.dialog = Some(Dialog::Device(0)); - } - - pub(crate) fn device_pick (&mut self, index: usize) { - self.dialog = Some(Dialog::Device(index)); - } - pub(crate) fn device_add (&mut self, index: usize) -> Usually<()> { match index { - 0 => self.device_add_sampler(), - 1 => self.device_add_lv2(), + 0 => self.arrangement.device_add_sampler(), + 1 => self.arrangement.device_add_lv2(), _ => unreachable!(), } } - - fn device_add_sampler (&mut self) -> Usually<()> { - let name = self.jack.with_client(|c|c.name().to_string()); - let midi = self.track().expect("no active track").sequencer.midi_outs[0].name(); - let sampler = if let Ok(sampler) = Sampler::new( - &self.jack, - &format!("{}/Sampler", &self.track().expect("no active track").name), - &[PortConnect::exact(format!("{name}:{midi}"))], - &[&[], &[]], - &[&[], &[]] - ) { - self.dialog = None; - Device::Sampler(sampler) - } else { - self.dialog = Some(Dialog::Message(Message::FailedToAddDevice)); - return Err("failed to add device".into()) - }; - self.track_mut().expect("no active track").devices.push(sampler); - Ok(()) - } - - fn device_add_lv2 (&mut self) -> Usually<()> { - todo!(); - Ok(()) - } } +/// Various possible dialog overlays +#[derive(PartialEq, Clone, Copy, Debug)] +pub enum Dialog { + Help, + Menu, + Device(usize), + Message(Message), + Save, + Load, + Options, +} + +/// Various possible messages +#[derive(PartialEq, Clone, Copy, Debug)] +pub enum Message { + FailedToAddDevice, +} + +content!(TuiOut: |self: Message| match self { + Self::FailedToAddDevice => "Failed to add device." +}); + has_size!(|self: App|&self.size); has_clock!(|self: App|self.clock); @@ -458,3 +108,154 @@ has_editor!(|self: App|{ editor_h = 15; is_editing = self.editing.load(Relaxed); }); + +impl HasTracks for App { + fn midi_ins (&self) -> &Vec { + &self.arranger.midi_ins + } + fn midi_outs (&self) -> &Vec { + &self.arranger.midi_outs + } + fn tracks (&self) -> &Vec { + &self.arranger.tracks + } + fn tracks_mut (&mut self) -> &mut Vec { + &mut self.arranger.tracks + } +} + +impl HasScenes for Arrangement { + fn scenes (&self) -> &Vec { + &self.arranger.scenes + } + fn scenes_mut (&mut self) -> &mut Vec { + &mut self.arranger.scenes + } +}if + +#[tengri_proc::expose] +impl App { + fn _todo_isize_stub (&self) -> isize { + todo!() + } + fn _todo_item_theme_stub (&self) -> ItemTheme { + todo!() + } + fn focus_editor (&self) -> bool { + self.is_editing() + } + fn focus_message (&self) -> bool { + matches!(self.dialog, Some(Dialog::Message(..))) + } + fn focus_device_add (&self) -> bool { + matches!(self.dialog, Some(Dialog::Device(..))) + } + fn focus_browser (&self) -> bool { + self.browser.is_visible + } + fn focus_clip (&self) -> bool { + !self.is_editing() && self.selected.is_clip() + } + fn focus_track (&self) -> bool { + !self.is_editing() && self.selected.is_track() + } + fn focus_scene (&self) -> bool { + !self.is_editing() && self.selected.is_scene() + } + fn focus_mix (&self) -> bool { + !self.is_editing() && self.selected.is_mix() + } + fn focus_pool_import (&self) -> bool { + matches!(self.pool.as_ref().map(|p|p.mode.as_ref()).flatten(), Some(PoolMode::Import(..))) + } + fn focus_pool_export (&self) -> bool { + matches!(self.pool.as_ref().map(|p|p.mode.as_ref()).flatten(), Some(PoolMode::Export(..))) + } + fn focus_pool_rename (&self) -> bool { + matches!(self.pool.as_ref().map(|p|p.mode.as_ref()).flatten(), Some(PoolMode::Rename(..))) + } + fn focus_pool_length (&self) -> bool { + matches!(self.pool.as_ref().map(|p|p.mode.as_ref()).flatten(), Some(PoolMode::Length(..))) + } + fn dialog_device (&self) -> Dialog { + Dialog::Device(0) // TODO + } + fn dialog_device_prev (&self) -> Dialog { + Dialog::Device(0) // TODO + } + fn dialog_device_next (&self) -> Dialog { + Dialog::Device(0) // TODO + } + fn dialog_help (&self) -> Dialog { + Dialog::Help + } + fn dialog_menu (&self) -> Dialog { + Dialog::Menu + } + fn dialog_save (&self) -> Dialog { + Dialog::Save + } + fn dialog_load (&self) -> Dialog { + Dialog::Load + } + fn dialog_options (&self) -> Dialog { + Dialog::Options + } + fn editor_pitch (&self) -> Option { + Some((self.editor().map(|e|e.get_note_pos()).unwrap() as u8).into()) + } + fn scene_count (&self) -> usize { + self.scenes.len() + } + fn scene_selected (&self) -> Option { + self.selected.scene() + } + fn track_count (&self) -> usize { + self.tracks.len() + } + fn track_selected (&self) -> Option { + self.selected.track() + } + fn select_scene_next (&self) -> Selection { + self.selected.scene_next(self.scenes.len()) + } + fn select_scene_prev (&self) -> Selection { + self.selected.scene_prev() + } + fn select_track_header (&self) -> Selection { + self.selected.track_header(self.tracks.len()) + } + fn select_track_next (&self) -> Selection { + self.selected.track_next(self.tracks.len()) + } + fn select_track_prev (&self) -> Selection { + self.selected.track_prev() + } + fn clip_selected (&self) -> Option>> { + match self.selected { + Selection::TrackClip { track, scene } => self.scenes[scene].clips[track].clone(), + _ => None + } + } + fn device_kind (&self) -> usize { + if let Some(Dialog::Device(index)) = self.dialog { + index + } else { + 0 + } + } + fn device_kind_prev (&self) -> usize { + if let Some(Dialog::Device(index)) = self.dialog { + index.overflowing_sub(1).0.min(self.device_kinds().len().saturating_sub(1)) + } else { + 0 + } + } + fn device_kind_next (&self) -> usize { + if let Some(Dialog::Device(index)) = self.dialog { + (index + 1) % self.device_kinds().len() + } else { + 0 + } + } +} diff --git a/crates/app/src/model/dialog.rs b/crates/app/src/model/dialog.rs deleted file mode 100644 index c2149659..00000000 --- a/crates/app/src/model/dialog.rs +++ /dev/null @@ -1,36 +0,0 @@ -use crate::*; - -impl App { - pub fn toggle_dialog (&mut self, dialog: Option) { - self.dialog = if self.dialog == dialog { - None - } else { - dialog - } - } - pub(crate) fn message_dismiss (&mut self) { - self.dialog = None; - } -} - -/// Various possible dialog overlays -#[derive(PartialEq, Clone, Copy, Debug)] -pub enum Dialog { - Help, - Menu, - Device(usize), - Message(Message), - Save, - Load, - Options, -} - -/// Various possible messages -#[derive(PartialEq, Clone, Copy, Debug)] -pub enum Message { - FailedToAddDevice, -} - -content!(TuiOut: |self: Message| match self { - Self::FailedToAddDevice => "Failed to add device." -}); diff --git a/crates/app/src/model/pool.rs b/crates/app/src/model/pool.rs deleted file mode 100644 index e69de29b..00000000 diff --git a/crates/app/src/model/scene.rs b/crates/app/src/model/scene.rs deleted file mode 100644 index 21d4f4ee..00000000 --- a/crates/app/src/model/scene.rs +++ /dev/null @@ -1,76 +0,0 @@ -use crate::*; - -#[derive(Debug, Default)] pub struct Scene { - /// Name of scene - pub name: Arc, - /// Clips in scene, one per track - pub clips: Vec>>>, - /// Identifying color of scene - pub color: ItemTheme, -} - -impl Scene { - /// Returns the pulse length of the longest clip in the scene - pub fn pulses (&self) -> usize { - self.clips.iter().fold(0, |a, p|{ - a.max(p.as_ref().map(|q|q.read().unwrap().length).unwrap_or(0)) - }) - } - /// Returns true if all clips in the scene are - /// currently playing on the given collection of tracks. - pub fn is_playing (&self, tracks: &[Track]) -> bool { - self.clips.iter().any(|clip|clip.is_some()) && self.clips.iter().enumerate() - .all(|(track_index, clip)|match clip { - Some(c) => tracks - .get(track_index) - .map(|track|{ - if let Some((_, Some(clip))) = track.sequencer().play_clip() { - *clip.read().unwrap() == *c.read().unwrap() - } else { - false - } - }) - .unwrap_or(false), - None => true - }) - } - pub fn clip (&self, index: usize) -> Option<&Arc>> { - match self.clips.get(index) { Some(Some(clip)) => Some(clip), _ => None } - } -} - -pub trait HasScenes: HasSelection + HasEditor + Send + Sync { - fn scenes (&self) -> &Vec; - fn scenes_mut (&mut self) -> &mut Vec; - fn scene_longest (&self) -> usize { - self.scenes().iter().map(|s|s.name.len()).fold(0, usize::max) - } - fn scene (&self) -> Option<&Scene> { - self.selected().scene() - .and_then(|s|self.scenes().get(s)) - } - fn scene_mut (&mut self) -> Option<&mut Scene> { - self.selected().scene() - .and_then(|s|self.scenes_mut().get_mut(s)) - } - fn scene_del (&mut self, index: usize) -> Option { - self.selected().scene() - .and_then(|s|Some(self.scenes_mut().remove(index))) - } - /// Set the color of a scene, returning the previous one. - fn scene_set_color (&mut self, index: usize, color: ItemTheme) -> ItemTheme { - let scenes = self.scenes_mut(); - let old = scenes[index].color; - scenes[index].color = color; - old - } - /// Generate the default name for a new scene - fn scene_default_name (&self) -> Arc { - format!("Sc{:3>}", self.scenes().len() + 1).into() - } -} - -impl HasScenes for App { - fn scenes (&self) -> &Vec { &self.scenes } - fn scenes_mut (&mut self) -> &mut Vec { &mut self.scenes } -} diff --git a/crates/app/src/model/track.rs b/crates/app/src/model/track.rs deleted file mode 100644 index a94e5b0f..00000000 --- a/crates/app/src/model/track.rs +++ /dev/null @@ -1,161 +0,0 @@ -use crate::*; - -#[derive(Debug, Default)] pub struct Track { - /// Name of track - pub name: Arc, - /// Identifying color of track - pub color: ItemTheme, - /// Preferred width of track column - pub width: usize, - /// MIDI sequencer state - pub sequencer: Sequencer, - /// Device chain - pub devices: Vec, -} - -has_clock!(|self: Track|self.sequencer.clock); - -has_sequencer!(|self: Track|self.sequencer); - -impl Track { - /// Create a new track with only the default [Sequencer]. - pub fn new ( - name: &impl AsRef, - color: Option, - jack: &Jack, - clock: Option<&Clock>, - clip: Option<&Arc>>, - midi_from: &[PortConnect], - midi_to: &[PortConnect], - ) -> Usually { - Ok(Self { - name: name.as_ref().into(), - color: color.unwrap_or_default(), - sequencer: Sequencer::new( - format!("{}/sequencer", name.as_ref()), - jack, - clock, - clip, - midi_from, - midi_to - )?, - ..Default::default() - }) - } - /// Create a new track connecting the [Sequencer] to a [Sampler]. - pub fn new_with_sampler ( - name: &impl AsRef, - color: Option, - jack: &Jack, - clock: Option<&Clock>, - clip: Option<&Arc>>, - midi_from: &[PortConnect], - midi_to: &[PortConnect], - audio_from: &[&[PortConnect];2], - audio_to: &[&[PortConnect];2], - ) -> Usually { - let mut track = Self::new(name, color, jack, clock, clip, midi_from, midi_to)?; - track.devices.push(Device::Sampler(Sampler::new( - jack, - &format!("{}/sampler", name.as_ref()), - &[PortConnect::exact(format!("{}:{}", - jack.with_client(|c|c.name().to_string()), - track.sequencer.midi_outs[0].name() - ))], - audio_from, - audio_to - )?)); - Ok(track) - } - pub fn sampler (&self, mut nth: usize) -> Option<&Sampler> { - for device in self.devices.iter() { - match device { - Device::Sampler(s) => if nth == 0 { - return Some(s); - } else { - nth -= 1; - }, - _ => {} - } - } - None - } - pub fn sampler_mut (&mut self, mut nth: usize) -> Option<&mut Sampler> { - for device in self.devices.iter_mut() { - match device { - Device::Sampler(s) => if nth == 0 { - return Some(s); - } else { - nth -= 1; - }, - _ => {} - } - } - None - } -} - -pub trait HasWidth { - const MIN_WIDTH: usize; - /// Increment track width. - fn width_inc (&mut self); - /// Decrement track width, down to a hardcoded minimum of [Self::MIN_WIDTH]. - fn width_dec (&mut self); -} - -impl HasWidth for Track { - const MIN_WIDTH: usize = 9; - fn width_inc (&mut self) { - self.width += 1; - } - fn width_dec (&mut self) { - if self.width > Track::MIN_WIDTH { - self.width -= 1; - } - } -} - -pub trait HasTracks: HasSelection + HasClock + HasJack + HasEditor + Send + Sync { - fn midi_ins (&self) -> &Vec; - fn midi_outs (&self) -> &Vec; - fn tracks (&self) -> &Vec; - fn tracks_mut (&mut self) -> &mut Vec; - fn track_longest (&self) -> usize { - self.tracks().iter().map(|s|s.name.len()).fold(0, usize::max) - } - const WIDTH_OFFSET: usize = 1; - fn track (&self) -> Option<&Track> { - self.selected().track().and_then(|s|self.tracks().get(s)) - } - fn track_mut (&mut self) -> Option<&mut Track> { - self.selected().track().and_then(|s|self.tracks_mut().get_mut(s)) - } - /// Set the color of a track - fn track_set_color (&mut self, index: usize, color: ItemTheme) -> ItemTheme { - let tracks = self.tracks_mut(); - let old = tracks[index].color; - tracks[index].color = color; - old - } - /// Toggle track recording - fn track_toggle_record (&mut self) { - if let Some(t) = self.selected().track() { - let tracks = self.tracks_mut(); - tracks[t-1].sequencer.recording = !tracks[t-1].sequencer.recording; - } - } - /// Toggle track monitoring - fn track_toggle_monitor (&mut self) { - if let Some(t) = self.selected().track() { - let tracks = self.tracks_mut(); - tracks[t-1].sequencer.monitoring = !tracks[t-1].sequencer.monitoring; - } - } -} - -impl HasTracks for App { - fn midi_ins (&self) -> &Vec { &self.midi_ins } - fn midi_outs (&self) -> &Vec { &self.midi_outs } - fn tracks (&self) -> &Vec { &self.tracks } - fn tracks_mut (&mut self) -> &mut Vec { &mut self.tracks } -} diff --git a/crates/app/src/view.rs b/crates/app/src/view.rs index de290bcf..ff8a7c07 100644 --- a/crates/app/src/view.rs +++ b/crates/app/src/view.rs @@ -2,8 +2,12 @@ use crate::*; pub(crate) use std::fmt::Write; pub(crate) use ::tengri::tui::ratatui::prelude::Position; -mod view_dialog; pub use self::view_dialog::*; -mod view_output; pub use self::view_output::*; +impl App { + + pub fn update_clock (&self) { + ViewCache::update_clock(&self.view_cache, self.clock(), self.size.w() > 80) + } +} #[tengri_proc::view(TuiOut)] impl App { @@ -23,7 +27,7 @@ impl App { cache.bpm.view.clone(), cache.beat.view.clone(), cache.time.view.clone()) } pub fn view_arranger (&self) -> impl Content + use<'_> { - ArrangerView::new(self) + ArrangerView::new(self, self.editor.as_ref()) } pub fn view_pool (&self) -> impl Content + use<'_> { self.pool().map(|p|Fixed::x(self.w_sidebar(), PoolView(self.is_editing(), p))) @@ -50,453 +54,75 @@ impl App { self.sampler().map(|s|s.view_meters_output()) } pub fn view_dialog (&self) -> impl Content + use<'_> { - view_dialog(self) - } -} - -impl App { - - /// Spacing between tracks. - pub(crate) const TRACK_SPACING: usize = 0; - - /// Default scene height. - pub(crate) const H_SCENE: usize = 2; - - /// Default editor height. - pub(crate) const H_EDITOR: usize = 15; - - pub(crate) fn inputs_with_sizes (&self) -> impl PortsSizes<'_> { - let mut y = 0; - self.midi_ins.iter().enumerate().map(move|(i, input)|{ - let height = 1 + input.conn().len(); - let data = (i, input.name(), input.conn(), y, y + height); - y += height; - data - }) - } - - pub(crate) fn tracks_with_sizes (&self) -> impl TracksSizes<'_> { - use Selection::*; - let mut x = 0; - let editing = self.is_editing(); - let active = match self.selected() { - Track(t) if editing => Some(t), - TrackClip { track, .. } if editing => Some(track), - _ => None - }; - let bigger = self.editor_w(); - self.tracks().iter().enumerate().map(move |(index, track)|{ - let width = if Some(index) == active.copied() { bigger } else { track.width.max(8) }; - let data = (index, track, x, x + width); - x += width + App::TRACK_SPACING; - data - }) - } - - pub(crate) fn scenes_with_sizes (&self, editing: bool, height: usize, larger: usize) - -> impl ScenesSizes<'_> - { - use Selection::*; - let (selected_track, selected_scene) = match self.selected() { - Track(t) => (Some(*t), None), - Scene(s) => (None, Some(*s)), - TrackClip { track, scene } => (Some(*track), Some(*scene)), - _ => (None, None) - }; - let mut y = 0; - self.scenes().iter().enumerate().map(move|(s, scene)|{ - let active = editing && selected_track.is_some() && selected_scene == Some(s); - let height = if active { larger } else { height }; - let data = (s, scene, y, y + height); - y += height; - data - }) - } - - pub fn update_clock (&self) { - ViewCache::update_clock(&self.view_cache, self.clock(), self.size.w() > 80) - } - -} - -pub(crate) struct ArrangerView<'a> { - app: &'a App, - - is_editing: bool, - - width: u16, - width_mid: u16, - width_side: u16, - - inputs_count: usize, - inputs_height: u16, - - outputs_count: usize, - outputs_height: u16, - - scene_last: usize, - scene_count: usize, - scene_scroll: Fill>, - scene_selected: Option, - scenes_height: u16, - - track_scroll: Fill>, - track_count: usize, - track_selected: Option, - tracks_height: u16, - - show_debug_info: bool, -} - -impl<'a> Content for ArrangerView<'a> { - fn content (&self) -> impl Render { - let ins = |x|Bsp::n(self.inputs(), x); - let tracks = |x|Bsp::s(self.tracks(), x); - let devices = |x|Bsp::s(self.devices(), x); - let outs = |x|Bsp::s(self.outputs(), x); - let bg = |x|Tui::bg(Reset, x); - //let track_scroll = |x|Bsp::s(&self.track_scroll, x); - //let scene_scroll = |x|Bsp::e(&self.scene_scroll, x); - outs(tracks(devices(ins(bg(self.scenes()))))) - } -} - -impl<'a> ArrangerView<'a> { - pub fn new (app: &'a App) -> Self { - Self { - app, - is_editing: app.is_editing(), - - width: app.w(), - width_mid: app.w_tracks_area(), - width_side: app.w_sidebar(), - - inputs_height: app.h_inputs(), - inputs_count: app.midi_ins.len(), - - outputs_height: app.h_outputs(), - outputs_count: app.midi_outs.len(), - - scenes_height: app.h_scenes_area(), - scene_selected: app.selected().scene(), - scene_count: app.scenes.len(), - scene_last: app.scenes.len().saturating_sub(1), - scene_scroll: Fill::y(Fixed::x(1, ScrollbarV { - offset: app.scene_scroll, - length: app.h_scenes_area() as usize, - total: app.h_scenes() as usize, - })), - - tracks_height: app.h_tracks_area(), - track_count: app.tracks.len(), - track_selected: app.selected().track(), - track_scroll: Fill::x(Fixed::y(1, ScrollbarH { - offset: app.track_scroll, - length: app.h_tracks_area() as usize, - total: app.h_scenes() as usize, - })), - - show_debug_info: false - } - } - - /// Render input matrix. - pub(crate) fn inputs (&'a self) -> impl Content + 'a { - Tui::bg(Reset, Bsp::s( - self.input_intos(), - Bsp::s(self.input_routes(), self.input_ports()), + When(app.dialog.is_some(), Bsp::b( "", + 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(app.dialog.as_ref().map(|dialog|match dialog { + Dialog::Menu => + app.view_dialog_menu().boxed(), + Dialog::Help => + app.view_dialog_help().boxed(), + Dialog::Save => + app.view_dialog_save().boxed(), + Dialog::Load => + app.view_dialog_load().boxed(), + Dialog::Options => + app.view_dialog_options().boxed(), + Dialog::Device(index) => + app.view_dialog_device(*index).boxed(), + Dialog::Message(message) => + app.view_dialog_message(message).boxed(), + })) + ))) )) } - - /// Render device switches. - pub(crate) fn devices (&'a self) -> impl Content + 'a { - let Self { width_side, width_mid, track_count, track_selected, is_editing, .. } = self; - Tryptich::top(1) - .left(*width_side, button_3("d", "devices", format!("{}", 0), *is_editing)) - .right(*width_side, button_2("D", "add device", *is_editing)) - .middle(*width_mid, per_track_top(*width_mid, ||self.tracks_with_sizes_scrolled(), - move|index, track|{ - let bg = if *track_selected == Some(index) { - track.color.light - } else { - track.color.base - }; - let fg = Tui::g(224); - track.devices.get(0).map(|device|wrap(bg.rgb, fg, device.name())) - })) + pub fn view_dialog_menu (&self) -> impl Content { + 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))) } - - /// Render track headers - pub(crate) fn tracks (&'a self) -> impl Content + 'a { - let Self { width_side, width_mid, track_count, track_selected, is_editing, .. } = self; - Tryptich::center(3) - .left(*width_side, button_3("t", "track", format!("{}", *track_count), *is_editing)) - .right(*width_side, button_2("T", "add track", *is_editing)) - .middle(*width_mid, per_track(*width_mid, ||self.tracks_with_sizes_scrolled(), - |index, track|wrap( - if *track_selected == Some(index) { - track.color.light - } else { - track.color.base - }.rgb, - track.color.lightest.rgb, - Tui::bold(true, Fill::xy(Align::nw(&track.name))) - ))) + pub fn view_dialog_help <'a> (&'a self) -> impl Content + use<'a> { + Bsp::s(Tui::bold(true, "Help"), Bsp::s("", Map::south(1, + ||self.config.keys.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 }) + .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())))))))))) } - - fn input_routes (&'a self) -> impl Content + 'a { - Tryptich::top(self.inputs_height) - .left(self.width_side, - io_ports(Tui::g(224), Tui::g(32), ||self.app.inputs_with_sizes())) - .middle(self.width_mid, - per_track_top(self.width_mid, ||self.tracks_with_sizes_scrolled(), - move|_, &Track { color, .. }|io_conns( - color.dark.rgb, - color.darker.rgb, - ||self.app.inputs_with_sizes() - ))) + pub fn view_dialog_device (&self, index: usize) -> impl Content + use<'_> { + let choices = ||self.device_kinds().iter(); + let choice = move|label, i| + Fill::x(Tui::bg(if i == index { Rgb(64,128,32) } else { Rgb(0,0,0) }, + Bsp::e(if i == index { "[ " } else { " " }, + Bsp::w(if i == index { " ]" } else { " " }, + label)))); + Bsp::s(Tui::bold(true, "Add device"), Map::south(1, choices, choice)) } - - fn input_ports (&'a self) -> impl Content + 'a { - Tryptich::top(1) - .left(self.width_side, - button_3("i", "midi ins", format!("{}", self.inputs_count), self.is_editing)) - .right(self.width_side, - button_2("I", "add midi in", self.is_editing)) - .middle(self.width_mid, - per_track_top( - self.width_mid, - ||self.tracks_with_sizes_scrolled(), - move|t, track|{ - let rec = track.sequencer.recording; - let mon = track.sequencer.monitoring; - let rec = if rec { White } else { track.color.darkest.rgb }; - let mon = if mon { White } else { track.color.darkest.rgb }; - let bg = if self.track_selected == Some(t) { - track.color.light.rgb - } else { - track.color.base.rgb - }; - //let bg2 = if t > 0 { track.color.base.rgb } else { Reset }; - wrap(bg, Tui::g(224), Tui::bold(true, Fill::x(Bsp::e( - Tui::fg_bg(rec, bg, "Rec "), - Tui::fg_bg(mon, bg, "Mon "), - )))) - })) + pub fn view_dialog_message <'a> (&'a self, message: &'a Message) -> impl Content + use<'a> { + Bsp::s(message, Bsp::s("", "[ OK ]")) } - - fn input_intos (&'a self) -> impl Content + 'a { - Tryptich::top(2) - .left(self.width_side, - Bsp::s(Align::e("Input:"), Align::e("Into clip:"))) - .middle(self.width_mid, - per_track_top( - self.width_mid, - ||self.tracks_with_sizes_scrolled(), - |_, _|Tui::bg(Reset, Align::c(Bsp::s(OctaveVertical::default(), " ------ "))))) + pub fn view_dialog_save <'a> (&'a self) -> impl Content + use<'a> { + Bsp::s( + Fill::x(Align::w(Margin::xy(1, 1, Bsp::e( + Tui::bold(true, " Save project: "), + Shrink::x(3, Fixed::y(1, RepeatH("🭻"))))))), + Outer(true, Style::default().fg(Tui::g(96))) + .enclose(Fill::xy("todo file browser"))) } - - /// Render scenes with clips - pub(crate) fn scenes (&'a self) -> impl Content + 'a { - - let Self { - width, width_side, width_mid, - scenes_height, scene_last, scene_selected, - track_selected, is_editing, app: App { editor, .. }, .. - } = self; - - let scene_headers = Map::new(||self.scenes_with_scene_colors(), - move|(s, scene, y1, y2, previous): SceneWithColor, _|{ - let height = (1 + y2 - y1) as u16; - let name = Some(scene.name.clone()); - let content = Fill::x(Align::w(Tui::bold(true, Bsp::e(" ⯈ ", name)))); - let same_track = true; - let selected = same_track && *scene_selected == Some(s); - let neighbor = same_track && s > 0 && *scene_selected == Some(s - 1); - let is_last = *scene_last == s; - let theme = scene.color; - let fg = theme.lightest.rgb; - let bg = if selected { theme.light } else { theme.base }.rgb; - let hi = if let Some(previous) = previous { - if neighbor { - previous.light.rgb - } else { - previous.base.rgb - } - } else { - Reset - }; - let lo = if is_last { - Reset - } else if selected { - theme.light.rgb - } else { - theme.base.rgb - }; - Fill::x(map_south(y1 as u16, height, Fixed::y(height, Phat { - width: 0, height: 0, content, colors: [fg, bg, hi, lo] - }))) - }); - - let scene_track_clips = per_track(*width_mid, ||self.tracks_with_sizes_scrolled(), - move|track_index, track|Map::new(move||self.scenes_with_track_colors(track_index), - move|(s, scene, y1, y2, previous): SceneWithColor<'a>, _|{ - let (name, theme) = if let Some(clip) = &scene.clips[track_index] { - let clip = clip.read().unwrap(); - (Some(clip.name.clone()), clip.color) - } else { - (None, ItemTheme::G[32]) - }; - let height = (1 + y2 - y1) as u16; - let content = Fill::x(Align::w(Tui::bold(true, Bsp::e(" ⏹ ", name)))); - let same_track = *track_selected == Some(track_index); - let selected = same_track && *scene_selected == Some(s); - let neighbor = same_track && s > 0 && *scene_selected == Some(s - 1); - let is_last = *scene_last == s; - let fg = theme.lightest.rgb; - let bg = if selected { theme.light } else { theme.base }.rgb; - let hi = if let Some(previous) = previous { - if neighbor { - previous.light.rgb - } else { - previous.base.rgb - } - } else { - Reset - }; - let lo = if is_last { - Reset - } else if selected { - theme.light.rgb - } else { - theme.base.rgb - }; - map_south(y1 as u16, height, Bsp::b(Fixed::y(height, Phat { - width: 0, height: 0, content, colors: [fg, bg, hi, lo] - }), When( - *is_editing && same_track && *scene_selected == Some(s), - editor - ))) - })); - - Tryptich::center(*scenes_height) - .left(*width_side, scene_headers) - .middle(*width_mid, scene_track_clips) + pub fn view_dialog_load <'a> (&'a self) -> impl Content + use<'a> { + 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("todo file browser"))) } - - pub(crate) fn tracks_with_sizes_scrolled (&'a self) - -> impl TracksSizes<'a> - { - let width = self.width_mid; - self.app.tracks_with_sizes().map_while(move|(t, track, x1, x2)|{ - (width > x2 as u16).then_some((t, track, x1, x2)) - }) + pub fn view_dialog_options <'a> (&'a self) -> impl Content + use<'a> { + "TODO" } - - pub(crate) fn scenes_with_scene_colors (&self) - -> impl ScenesColors<'_> - { - self.app.scenes_with_sizes(self.is_editing, App::H_SCENE, App::H_EDITOR).map_while( - move|(s, scene, y1, y2)|if y2 as u16 > self.scenes_height { - None - } else { - Some((s, scene, y1, y2, if s == 0 { - None - } else { - Some(self.app.scenes()[s-1].color) - })) - }) - } - - pub(crate) fn scenes_with_track_colors (&self, track: usize) - -> impl ScenesColors<'_> - { - self.app.scenes_with_sizes(self.is_editing, App::H_SCENE, App::H_EDITOR).map_while( - move|(s, scene, y1, y2)|if y2 as u16 > self.scenes_height { - None - } else { - Some((s, scene, y1, y2, if s == 0 { - None - } else { - Some(self.app.scenes[s-1].clips[track].as_ref() - .map(|c|c.read().unwrap().color) - .unwrap_or(ItemTheme::G[32])) - })) - } - ) - } - -} - -/// Iterator over scenes with their sizes and colors. -pub(crate) trait ScenesColors<'a> = - Iterator>; - -/// A scene with size and color. -pub(crate) type SceneWithColor<'a> = - (usize, &'a Scene, usize, usize, Option); - -/// Define a type alias for iterators of sized items (columns). -macro_rules! def_sizes_iter { - ($Type:ident => $($Item:ty),+) => { - pub(crate) trait $Type<'a> = - Iterator + Send + Sync + 'a; - } -} - -def_sizes_iter!(ScenesSizes => Scene); - -def_sizes_iter!(TracksSizes => Track); - -def_sizes_iter!(InputsSizes => JackMidiIn); - -def_sizes_iter!(OutputsSizes => JackMidiOut); - -def_sizes_iter!(PortsSizes => Arc, [PortConnect]); - -pub(crate) fn wrap (bg: Color, fg: Color, content: impl Content) -> impl Content { - let left = Tui::fg_bg(bg, Reset, Fixed::x(1, RepeatV("▐"))); - let right = Tui::fg_bg(bg, Reset, Fixed::x(1, RepeatV("▌"))); - Bsp::e(left, Bsp::w(right, Tui::fg_bg(fg, bg, content))) -} - -pub(crate) fn button_2 <'a> ( - key: impl Content + 'a, label: impl Content + 'a, editing: bool, -) -> impl Content + 'a { - let key = Tui::fg_bg(Tui::g(0), Tui::orange(), Bsp::e( - Tui::fg_bg(Tui::orange(), Reset, "▐"), - Bsp::e(key, Tui::fg(Tui::g(96), "▐")) - )); - let label = When::new(!editing, Tui::fg_bg(Tui::g(255), Tui::g(96), label)); - Tui::bold(true, Bsp::e(key, label)) -} - -pub(crate) fn button_3 <'a, K, L, V> ( - key: K, - label: L, - value: V, - editing: bool, -) -> impl Content + 'a where - K: Content + 'a, - L: Content + 'a, - V: Content + 'a, -{ - let key = Tui::fg_bg(Tui::g(0), Tui::orange(), - Bsp::e(Tui::fg_bg(Tui::orange(), Reset, "▐"), Bsp::e(key, Tui::fg(if editing { - Tui::g(128) - } else { - Tui::g(96) - }, "▐")))); - let label = Bsp::e( - When::new(!editing, Bsp::e( - Tui::fg_bg(Tui::g(255), Tui::g(96), label), - Tui::fg_bg(Tui::g(128), Tui::g(96), "▐"), - )), - Bsp::e( - Tui::fg_bg(Tui::g(224), Tui::g(128), value), - Tui::fg_bg(Tui::g(128), Reset, "▌"), - )); - Tui::bold(true, Bsp::e(key, label)) } pub(crate) fn heading <'a> ( @@ -510,57 +136,6 @@ pub(crate) fn heading <'a> ( Fill::xy(Align::w(Bsp::s(Fill::x(Align::w(button_3(key, label, count, editing))), content))) } -pub(crate) fn io_ports <'a, T: PortsSizes<'a>> ( - fg: Color, bg: Color, iter: impl Fn()->T + Send + Sync + 'a -) -> impl Content + 'a { - Map::new(iter, move|( - index, name, connections, y, y2 - ): (usize, &'a Arc, &'a [PortConnect], usize, usize), _| - map_south(y as u16, (y2-y) as u16, Bsp::s( - Fill::x(Tui::bold(true, Tui::fg_bg(fg, bg, Align::w(Bsp::e(" 󰣲 ", name))))), - Map::new(||connections.iter(), move|connect: &'a PortConnect, index|map_south(index as u16, 1, - Fill::x(Align::w(Tui::bold(false, Tui::fg_bg(fg, bg, - &connect.info))))))))) -} - -pub(crate) fn io_conns <'a, T: PortsSizes<'a>> ( - fg: Color, bg: Color, iter: impl Fn()->T + Send + Sync + 'a -) -> impl Content + 'a { - Map::new(iter, move|( - index, name, connections, y, y2 - ): (usize, &'a Arc, &'a [PortConnect], usize, usize), _| - map_south(y as u16, (y2-y) as u16, Bsp::s( - Fill::x(Tui::bold(true, wrap(bg, fg, Fill::x(Align::w("▞▞▞▞ ▞▞▞▞"))))), - Map::new(||connections.iter(), move|connect, index|map_south(index as u16, 1, - Fill::x(Align::w(Tui::bold(false, wrap(bg, fg, Fill::x("")))))))))) -} - -pub(crate) fn per_track_top <'a, T: Content + 'a, U: TracksSizes<'a>> ( - width: u16, - tracks: impl Fn() -> U + Send + Sync + 'a, - callback: impl Fn(usize, &'a Track)->T + Send + Sync + 'a -) -> impl Content + 'a { - Align::x(Tui::bg(Reset, Map::new(tracks, - move|(index, track, x1, x2): (usize, &'a Track, usize, usize), _|{ - let width = (x2 - x1) as u16; - map_east(x1 as u16, width, Fixed::x(width, Tui::fg_bg( - track.color.lightest.rgb, - track.color.base.rgb, - callback(index, track))))}))) -} - -pub(crate) fn per_track <'a, T: Content + 'a, U: TracksSizes<'a>> ( - width: u16, - tracks: impl Fn() -> U + Send + Sync + 'a, - callback: impl Fn(usize, &'a Track)->T + Send + Sync + 'a -) -> impl Content + 'a { - per_track_top( - width, - tracks, - move|index, track|Fill::y(Align::y(callback(index, track))) - ) -} - /// Clear a pre-allocated buffer, then write into it. #[macro_export] macro_rules! rewrite { ($buf:ident, $($rest:tt)*) => { |$buf,_,_|{ $buf.clear(); write!($buf, $($rest)*) } } diff --git a/crates/app/src/view/view_dialog.rs b/crates/app/src/view/view_dialog.rs deleted file mode 100644 index 5ab8f1ef..00000000 --- a/crates/app/src/view/view_dialog.rs +++ /dev/null @@ -1,99 +0,0 @@ -use crate::*; - -pub(crate) fn view_dialog (app: &App) -> impl Content + use<'_> { - When::new(app.dialog.is_some(), Bsp::b( - "", - 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(app.dialog.as_ref().map(|dialog|match dialog { - Dialog::Menu => app.view_dialog_menu().boxed(), - Dialog::Help => app.view_dialog_help().boxed(), - Dialog::Save => app.view_dialog_save().boxed(), - Dialog::Load => app.view_dialog_load().boxed(), - Dialog::Options => app.view_dialog_options().boxed(), - Dialog::Device(index) => app.view_dialog_device(*index).boxed(), - Dialog::Message(message) => app.view_dialog_message(message).boxed(), - })) - ))) - )) -} - -impl App { - pub fn view_dialog_menu (&self) -> impl Content { - 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))) - } - pub fn view_dialog_help <'a> (&'a self) -> impl Content + use<'a> { - //let bindings = ; - //let binding = ;[> Bsp::e( - //Fixed::x(15, Align::w(Tui::bold(true, Tui::fg(Rgb(255,192,0), if let Some(Token { - //value: Value::Sym(key), .. - //}) = binding.next() { - //Some(key.to_string()) - //} else { - //None - //})))), - //Bsp::e(" ", Tui::fg(Rgb(255,255,255), if let Some(Token { - //value: Value::Key(command), .. - //}) = binding.next() { - //Some(command.to_string()) - //} else { - //None - //})), - //);*/ - Bsp::s(Tui::bold(true, "Help"), Bsp::s("", Map::south(1, - ||self.config.keys.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 - }) - .take(20), - |mut b,i|Bsp::e( - Min::x(30, Max::x(60, format!("?"))), - b.next().map(|t|Min::x(16, Tui::fg(Rgb(224,64,0), format!("{}", t.value)))), - )))) - //format!("{b:?}"))))) - //|mut binding: TokenIter, _|Map::east(5, move||binding.clone(), |_,_|"kyp")))) - } - - pub fn view_dialog_device (&self, index: usize) -> impl Content + use<'_> { - let choices = ||self.device_kinds().iter(); - let choice = move|label, i| - Fill::x(Tui::bg(if i == index { Rgb(64,128,32) } else { Rgb(0,0,0) }, - Bsp::e(if i == index { "[ " } else { " " }, - Bsp::w(if i == index { " ]" } else { " " }, - label)))); - Bsp::s(Tui::bold(true, "Add device"), Map::south(1, choices, choice)) - } - - pub fn view_dialog_message <'a> (&'a self, message: &'a Message) -> impl Content + use<'a> { - Bsp::s(message, Bsp::s("", "[ OK ]")) - } - - pub fn view_dialog_save <'a> (&'a self) -> impl Content + use<'a> { - Bsp::s( - Fill::x(Align::w(Margin::xy(1, 1, Bsp::e( - Tui::bold(true, " Save project: "), - Shrink::x(3, Fixed::y(1, RepeatH("🭻"))))))), - Outer(true, Style::default().fg(Tui::g(96))) - .enclose(Fill::xy("todo file browser"))) - } - - pub fn view_dialog_load <'a> (&'a self) -> impl Content + use<'a> { - 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("todo file browser"))) - } - - pub fn view_dialog_options <'a> (&'a self) -> impl Content + use<'a> { - "TODO" - } -} diff --git a/crates/app/src/view/view_output.rs b/crates/app/src/view/view_output.rs deleted file mode 100644 index 938b90fb..00000000 --- a/crates/app/src/view/view_output.rs +++ /dev/null @@ -1,92 +0,0 @@ -use crate::*; - -/// Outputs. -impl App { - pub(crate) fn outputs_with_sizes (&self) -> impl PortsSizes<'_> { - let mut y = 0; - self.midi_outs.iter().enumerate().map(move|(i, output)|{ - let height = 1 + output.conn().len(); - let data = (i, output.name(), output.conn(), y, y + height); - y += height; - data - }) - } -} -impl<'a> ArrangerView<'a> { - fn output_nexts (&self) -> impl Content + '_ { - Tryptich::top(2) - .left(self.width_side, Align::ne("From clip:")) - .middle(self.width_mid, per_track_top( - self.width_mid, - ||self.tracks_with_sizes_scrolled(), - |_, _|Tui::bg(Reset, Align::c(Bsp::s(" ------ ", OctaveVertical::default()))))) - } - /// Render output matrix. - pub(crate) fn outputs (&'a self) -> impl Content + 'a { - Tui::bg(Reset, Align::n(Bsp::s( - Bsp::s(self.output_ports(), self.output_conns()), - Bsp::s(self.output_nexts(), self.output_froms()), - ))) - } - fn output_froms (&'a self) -> impl Content + 'a { - let label = Align::ne("Next clip:"); - Tryptich::top(2).left(self.width_side, label).middle(self.width_mid, per_track_top( - self.width_mid, ||self.tracks_with_sizes_scrolled(), |t, track|{ - let queued = track.sequencer.next_clip.is_some(); - let queued_blank = Thunk::new(||Tui::bg(Reset, " ------ ")); - let queued_clip = Thunk::new(||{ - Tui::bg(Reset, if let Some((_, clip)) = track.sequencer.next_clip.as_ref() { - if let Some(clip) = clip { - clip.read().unwrap().name.clone() - } else { - "Stop".into() - } - } else { - "".into() - }) - }); - Either(queued, queued_clip, queued_blank) - })) - } - fn output_ports (&'a self) -> impl Content + 'a { - Tryptich::top(1) - .left(self.width_side, self.output_count()) - .right(self.width_side, self.output_add()) - .middle(self.width_mid, self.output_map()) - } - fn output_count (&'a self) -> impl Content + 'a { - button_3("o", "midi outs", format!("{}", self.outputs_count), self.is_editing) - } - fn output_add (&'a self) -> impl Content + 'a { - button_2("O", "add midi out", self.is_editing) - } - fn output_map (&'a self) -> impl Content + 'a { - per_track_top(self.width_mid, ||self.tracks_with_sizes_scrolled(), move|i, t|{ - let mute = false; - let solo = false; - let mute = if mute { White } else { t.color.darkest.rgb }; - let solo = if solo { White } else { t.color.darkest.rgb }; - let bg_1 = if self.track_selected == Some(i) { - t.color.light.rgb - } else { - t.color.base.rgb - }; - let bg_2 = if i > 0 { t.color.base.rgb } else { Reset }; - let mute = Tui::fg_bg(mute, bg_1, "Play "); - let solo = Tui::fg_bg(solo, bg_1, "Solo "); - wrap(bg_1, Tui::g(224), Tui::bold(true, Fill::x(Bsp::e(mute, solo)))) - }) - } - fn output_conns (&'a self) -> impl Content + 'a { - Tryptich::top(self.outputs_height) - .left(self.width_side, io_ports(Tui::g(224), Tui::g(32), ||self.app.outputs_with_sizes())) - .middle(self.width_mid, per_track_top( - self.width_mid, - ||self.tracks_with_sizes_scrolled(), - |_, t|io_conns( - t.color.dark.rgb, - t.color.darker.rgb, - ||self.app.outputs_with_sizes() - ))) - } -} diff --git a/crates/cli/tek.rs b/crates/cli/tek.rs index 3f7fdfcb..c1954cb7 100644 --- a/crates/cli/tek.rs +++ b/crates/cli/tek.rs @@ -91,6 +91,21 @@ impl Cli { _ => None, }; let scenes = vec![]; + let mut tracks = vec![]; + match mode { + LaunchMode::Sequencer => tracks.push(Track::new( + &name, None, jack, + Some(&clock), clip.as_ref(), + midi_froms.as_slice(), midi_tos.as_slice() + )?), + LaunchMode::Groovebox | LaunchMode::Sampler => tracks.push(Track::new_with_sampler( + &name, None, jack, + Some(&clock), clip.as_ref(), + midi_froms.as_slice(), midi_tos.as_slice(), + audio_froms, audio_tos, + )?), + _ => {} + } Tui::new()?.run(&Jack::new(name)?.run(|jack|{ let mut midi_ins = vec![]; let mut midi_outs = vec![]; @@ -137,33 +152,7 @@ impl Cli { vec![vec![];65536], _ => todo!("{mode:?}"), }, - tracks: match mode { - LaunchMode::Sequencer => vec![ - Track::new( - &name, - None, - jack, - Some(&clock), - clip.as_ref(), - midi_froms.as_slice(), - midi_tos.as_slice() - )? - ], - LaunchMode::Groovebox | LaunchMode::Sampler => vec![ - Track::new_with_sampler( - &name, - None, - jack, - Some(&clock), - clip.as_ref(), - midi_froms.as_slice(), - midi_tos.as_slice(), - audio_froms, - audio_tos, - )? - ], - _ => vec![] - }, + tracks, scenes, selected: Selection::TrackClip { track: 0, scene: 0 }, config, diff --git a/crates/device/Cargo.toml b/crates/device/Cargo.toml index eff1dea7..6b702f98 100644 --- a/crates/device/Cargo.toml +++ b/crates/device/Cargo.toml @@ -16,8 +16,9 @@ wavers = { workspace = true, optional = true } winit = { workspace = true, optional = true } [features] -default = [ "browser", "clock", "editor", "sequencer", "sampler", "lv2" ] +default = [ "browser", "clock", "editor", "sequencer", "sampler", "lv2", "arranger" ] clock = [] +arranger = [ "editor" ] editor = [] meter = [] mixer = [] diff --git a/crates/device/src/arranger.rs b/crates/device/src/arranger.rs new file mode 100644 index 00000000..396aebe7 --- /dev/null +++ b/crates/device/src/arranger.rs @@ -0,0 +1,86 @@ +use crate::*; + +/// Define a type alias for iterators of sized items (columns). +macro_rules! def_sizes_iter { + ($Type:ident => $($Item:ty),+) => { + pub(crate) trait $Type<'a> = + Iterator + Send + Sync + 'a; + } +} + +mod arranger_api; pub use self::arranger_api::*; +mod arranger_clip; pub use self::arranger_clip::*; +mod arranger_device; pub use self::arranger_device::*; +mod arranger_port; pub use self::arranger_port::*; +mod arranger_model; pub use self::arranger_model::*; +mod arranger_scene; pub use self::arranger_scene::*; +mod arranger_select; pub use self::arranger_select::*; +mod arranger_track; pub use self::arranger_track::*; +mod arranger_view; pub use self::arranger_view::*; + +def_sizes_iter!(ScenesSizes => Scene); +def_sizes_iter!(TracksSizes => Track); +def_sizes_iter!(InputsSizes => JackMidiIn); +def_sizes_iter!(OutputsSizes => JackMidiOut); +def_sizes_iter!(PortsSizes => Arc, [PortConnect]); + +pub(crate) fn wrap (bg: Color, fg: Color, content: impl Content) -> impl Content { + let left = Tui::fg_bg(bg, Reset, Fixed::x(1, RepeatV("▐"))); + let right = Tui::fg_bg(bg, Reset, Fixed::x(1, RepeatV("▌"))); + Bsp::e(left, Bsp::w(right, Tui::fg_bg(fg, bg, content))) +} + +pub(crate) fn io_ports <'a, T: PortsSizes<'a>> ( + fg: Color, bg: Color, iter: impl Fn()->T + Send + Sync + 'a +) -> impl Content + 'a { + Map::new(iter, move|( + index, name, connections, y, y2 + ): (usize, &'a Arc, &'a [PortConnect], usize, usize), _| + map_south(y as u16, (y2-y) as u16, Bsp::s( + Fill::x(Tui::bold(true, Tui::fg_bg(fg, bg, Align::w(Bsp::e(" 󰣲 ", name))))), + Map::new(||connections.iter(), move|connect: &'a PortConnect, index|map_south(index as u16, 1, + Fill::x(Align::w(Tui::bold(false, Tui::fg_bg(fg, bg, + &connect.info))))))))) +} + +pub(crate) fn io_conns <'a, T: PortsSizes<'a>> ( + fg: Color, bg: Color, iter: impl Fn()->T + Send + Sync + 'a +) -> impl Content + 'a { + Map::new(iter, move|( + index, name, connections, y, y2 + ): (usize, &'a Arc, &'a [PortConnect], usize, usize), _| + map_south(y as u16, (y2-y) as u16, Bsp::s( + Fill::x(Tui::bold(true, wrap(bg, fg, Fill::x(Align::w("▞▞▞▞ ▞▞▞▞"))))), + Map::new(||connections.iter(), move|connect, index|map_south(index as u16, 1, + Fill::x(Align::w(Tui::bold(false, wrap(bg, fg, Fill::x("")))))))))) +} + +pub trait HasWidth { + const MIN_WIDTH: usize; + /// Increment track width. + fn width_inc (&mut self); + /// Decrement track width, down to a hardcoded minimum of [Self::MIN_WIDTH]. + fn width_dec (&mut self); +} + +impl HasWidth for Track { + const MIN_WIDTH: usize = 9; + fn width_inc (&mut self) { + self.width += 1; + } + fn width_dec (&mut self) { + if self.width > Track::MIN_WIDTH { + self.width -= 1; + } + } +} + +pub trait Has: Send + Sync { + fn get (&self) -> &T; + fn get_mut (&mut self) -> &mut T; +} + +pub trait HasMany: Send + Sync { + fn get (&self, key: U) -> &T; + fn get_mut (&mut self, key: U) -> &mut T; +} diff --git a/crates/device/src/arranger/arranger_api.rs b/crates/device/src/arranger/arranger_api.rs new file mode 100644 index 00000000..d13d3885 --- /dev/null +++ b/crates/device/src/arranger/arranger_api.rs @@ -0,0 +1,207 @@ +use crate::*; + +#[tengri_proc::command(Arrangement)] +impl ArrangementCommand { + fn track (arranger: &mut Arrangement, track: TrackCommand) -> Perhaps { + todo!("delegate") + } + fn track_add (arranger: &mut Arrangement) -> Perhaps { + let index = arranger.track_add(None, None, &[], &[])?.0; + arranger.selected = match arranger.selected { + Some(Selection::Track(_)) => + Selection::Track(index), + Some(Selection::TrackClip { track, scene }) => + Selection::TrackClip { track: index, scene }, + _ => arranger.selected + }; + Ok(Some(Self::TrackDelete { index })) + } + fn track_swap (arranger: &mut Arrangement, index: usize, other: usize) -> Perhaps { + todo!(); + Ok(Some(Self::TrackSwap { index, other })) + } + fn track_delete (arranger: &mut Arrangement, index: usize) -> Perhaps { + let exists = arranger.tracks().get(index).is_some(); + if exists { + let track = arranger.tracks_mut().remove(index); + let Track { sequencer: Sequencer { midi_ins, midi_outs, .. }, .. } = track; + for port in midi_ins.into_iter() { + port.close()?; + } + for port in midi_outs.into_iter() { + port.close()?; + } + for scene in arranger.scenes_mut().iter_mut() { + scene.clips.remove(index); + } + } + Ok(None) + //TODO:Ok(Some(Self::TrackAdd ( index, track: Some(deleted_track) }) + } + fn midi_in (arranger: &mut Arrangement, input: InputCommand) -> Perhaps { + todo!("delegate") + } + fn midi_in_add (arranger: &mut Arrangement) -> Perhaps { + arranger.midi_in_add()?; + Ok(None) + } + fn midi_out (arranger: &mut Arrangement, input: OutputCommand) -> Perhaps { + todo!("delegate") + } + fn midi_out_add (arranger: &mut Arrangement) -> Perhaps { + arranger.midi_out_add()?; + Ok(None) + } + fn device (arranger: &mut Arrangement, input: DeviceCommand) -> Perhaps { + todo!("delegate") + } + fn device_add (arranger: &mut Arrangement, i: usize) -> Perhaps { + arranger.device_add(i); + Ok(None) + } + fn scene (arranger: &mut Arrangement, scene: SceneCommand) -> Perhaps { + todo!("delegate") + } + fn scene_add (arranger: &mut Arrangement) -> Perhaps { + let index = arranger.scene_add(None, None)?.0; + arranger.selected = match arranger.selected { + Selection::Scene(_) => + Selection::Scene(index), + Selection::TrackClip { track, scene } => + Selection::TrackClip { track, scene: index }, + _ => arranger.selected + }; + Ok(None) // TODO + } + fn scene_swap (arranger: &mut Arrangement, index: usize, other: usize) -> Perhaps { + todo!(); + Ok(Some(Self::SceneSwap { index, other })) + } + fn scene_delete (arranger: &mut Arrangement, index: usize) -> Perhaps { + let scenes = arranger.scenes_mut(); + Ok(if scenes.get(index).is_some() { + Some(scenes.remove(index)) + } else { + None + }) + } + fn scene_launch (arranger: &mut Arrangement, index: usize) -> Perhaps { + for track in 0..arranger.tracks.len() { + let clip = arranger.scenes[index].clips[track].as_ref(); + arranger.tracks[track].sequencer.enqueue_next(clip); + } + } + fn clip (arranger: &mut Arrangement, scene: ClipCommand) -> Perhaps { + todo!("delegate") + } + fn clip_get (arranger: &mut Arrangement, a: usize, b: usize) -> Perhaps { + //(Get [a: usize, b: usize] cmd_todo!("\n\rtodo: clip: get: {a} {b}")) + //("get" [a: usize, b: usize] Some(Self::Get(a.unwrap(), b.unwrap()))) + todo!() + } + fn clip_put (arranger: &mut Arrangement, a: usize, b: usize) -> Perhaps { + //(Put [t: usize, s: usize, c: MaybeClip] + //Some(Self::Put(t, s, arranger.clip_put(t, s, c)))) + //("put" [a: usize, b: usize, c: MaybeClip] Some(Self::Put(a.unwrap(), b.unwrap(), c.unwrap()))) + todo!() + } + fn clip_del (arranger: &mut Arrangement, a: usize, b: usize) -> Perhaps { + //("delete" [a: usize, b: usize] Some(Self::Put(a.unwrap(), b.unwrap(), None)))) + todo!() + } + fn clip_enqueue (arranger: &mut Arrangement, a: usize, b: usize) -> Perhaps { + //(Enqueue [t: usize, s: usize] + //cmd!(arranger.tracks[t].sequencer.enqueue_next(arranger.scenes[s].clips[t].as_ref()))) + //("enqueue" [a: usize, b: usize] Some(Self::Enqueue(a.unwrap(), b.unwrap()))) + todo!() + } + fn clip_edit (arranger: &mut Arrangement, a: usize, b: usize) -> Perhaps { + //(Edit [clip: MaybeClip] cmd_todo!("\n\rtodo: clip: edit: {clip:?}")) + //("edit" [a: MaybeClip] Some(Self::Edit(a.unwrap()))) + todo!() + } + +} + +#[tengri_proc::command(MidiClip)] +impl ClipCommand { + fn set_color (clip: &mut MidiClip, color: Option) -> Perhaps { + //(SetColor [t: usize, s: usize, c: ItemTheme] + //clip.clip_set_color(t, s, c).map(|o|Self::SetColor(t, s, o))))); + //("color" [a: usize, b: usize] Some(Self::SetColor(a.unwrap(), b.unwrap(), ItemTheme::random()))) + todo!() + } + fn set_loop (clip: &mut MidiClip, looping: Option) -> Perhaps { + //(SetLoop [t: usize, s: usize, l: bool] cmd_todo!("\n\rtodo: {self:?}")) + //("loop" [a: usize, b: usize, c: bool] Some(Self::SetLoop(a.unwrap(), b.unwrap(), c.unwrap()))) + todo!() + } +} + +#[tengri_proc::command(Device)] +impl DeviceCommand { +} + +#[tengri_proc::command(JackMidiIn)] +impl InputCommand { +} + +#[tengri_proc::command(JackMidiOut)] +impl OutputCommand { +} + +#[tengri_proc::command(Scene)] +impl SceneCommand { + fn set_name (scene: &mut Scene, mut name: Arc) -> Perhaps { + std::mem::swap(&mut scene.name, &mut name); + Ok(Some(Self::SetName { name })) + } + fn set_color (scene: &mut Scene, mut color: ItemTheme) -> Perhaps { + std::mem::swap(&mut scene.color, &mut color); + Ok(Some(Self::SetColor { color })) + } + fn set_size (scene: &mut Scene, size: usize) -> Perhaps { + todo!() + } + fn set_zoom (scene: &mut Scene, zoom: usize) -> Perhaps { + todo!() + } +} + +#[tengri_proc::command(Track)] +impl TrackCommand { + fn set_name (track: &mut Track, mut name: Arc) -> Perhaps { + std::mem::swap(&mut name, &mut track.name); + Ok(Some(Self::SetName { name })) + } + fn set_color (track: &mut Track, color: ItemTheme) -> Perhaps { + std::mem::swap(color, track.color); + Ok(Some(Self::SetColor { color })) + } + fn set_mute (track: &mut Track, value: Option) -> Perhaps { + todo!() + } + fn set_solo (track: &mut Track, value: Option) -> Perhaps { + todo!() + } + fn set_rec (track: &mut Track, value: Option) -> Perhaps { + let current = track.sequencer.recording; + let value = value.unwrap_or(!current); + Ok((value != current).then_some(Self::SetRec { value: Some(current) })) + } + fn set_mon (track: &mut Track, value: Option) -> Perhaps { + let current = track.sequencer.monitoring; + let value = value.unwrap_or(!current); + Ok((value != current).then_some(Self::SetRec { value: Some(current) })) + } + fn set_size (track: &mut Track, size: usize) -> Perhaps { + todo!() + } + fn set_zoom (track: &mut Track, zoom: usize) -> Perhaps { + todo!() + } + fn stop (track: &mut Track) -> Perhaps { + track.sequencer.enqueue_next(None); + Ok(None) + } +} diff --git a/crates/device/src/arranger/arranger_audio.rs b/crates/device/src/arranger/arranger_audio.rs new file mode 100644 index 00000000..71139cf5 --- /dev/null +++ b/crates/device/src/arranger/arranger_audio.rs @@ -0,0 +1,7 @@ +use crate::*; + +pub trait RenderTracks { +} + +impl Audio for T { +} diff --git a/crates/device/src/arranger/arranger_clip.rs b/crates/device/src/arranger/arranger_clip.rs new file mode 100644 index 00000000..ba5fe2bc --- /dev/null +++ b/crates/device/src/arranger/arranger_clip.rs @@ -0,0 +1,35 @@ +use crate::*; + + +impl Arrangement { + /// Put a clip in a slot + pub(crate) fn clip_put ( + &mut self, track: usize, scene: usize, clip: Option>> + ) -> Option>> { + let old = self.scenes[scene].clips[track].clone(); + self.scenes[scene].clips[track] = clip; + old + } + /// Change the color of a clip, returning the previous one + pub(crate) fn clip_set_color ( + &self, track: usize, scene: usize, color: ItemTheme + ) -> Option { + self.scenes[scene].clips[track].as_ref().map(|clip|{ + let mut clip = clip.write().unwrap(); + let old = clip.color.clone(); + clip.color = color.clone(); + panic!("{color:?} {old:?}"); + old + }) + } + /// Get the active clip + pub(crate) fn clip (&self) -> Option>> { + self.scene()?.clips.get(self.selected().track()?)?.clone() + } + /// Toggle looping for the active clip + pub(crate) fn toggle_loop (&mut self) { + if let Some(clip) = self.clip() { + clip.write().unwrap().toggle_loop() + } + } +} diff --git a/crates/device/src/arranger/arranger_device.rs b/crates/device/src/arranger/arranger_device.rs new file mode 100644 index 00000000..60894ab5 --- /dev/null +++ b/crates/device/src/arranger/arranger_device.rs @@ -0,0 +1,27 @@ +use crate::*; + +impl Arrangement { + fn device_add_lv2 (&mut self) -> Usually<()> { + todo!(); + Ok(()) + } + fn device_add_sampler (&mut self) -> Usually<()> { + let name = self.jack.with_client(|c|c.name().to_string()); + let midi = self.track().expect("no active track").sequencer.midi_outs[0].name(); + let sampler = if let Ok(sampler) = Sampler::new( + &self.jack, + &format!("{}/Sampler", &self.track().expect("no active track").name), + &[PortConnect::exact(format!("{name}:{midi}"))], + &[&[], &[]], + &[&[], &[]] + ) { + self.dialog = None; + Device::Sampler(sampler) + } else { + self.dialog = Some(Dialog::Message(Message::FailedToAddDevice)); + return Err("failed to add device".into()) + }; + self.track_mut().expect("no active track").devices.push(sampler); + Ok(()) + } +} diff --git a/crates/device/src/arranger/arranger_edit.rs b/crates/device/src/arranger/arranger_edit.rs new file mode 100644 index 00000000..715623f1 --- /dev/null +++ b/crates/device/src/arranger/arranger_edit.rs @@ -0,0 +1,62 @@ +use crate::*; + +#[cfg(all(feature = "pool", feature = "editor"))] +pub trait AutoCreate: + Has> + + Has> + + Has> + + Has> + + Has> + + Send + Sync +{ + // Create new clip in pool when entering empty cell + fn clip_auto_create (&mut self) -> Option>> { + if let Some(pool) = Has::::get(self) + && let Some(Selection::TrackClip { track, scene }) = self.get() + && let Some(scene) = Has::>::get_mut(self).get_mut(scene) + && let Some(slot) = scene.clips.get_mut(track) + && slot.is_none() + && let Some(track) = Has::>::get_mut(self).get_mut(track) + { + let (index, mut clip) = 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) = Has::>::get_mut(self) { + editor.set_clip(Some(&clip)); + } + *slot = Some(clip.clone()); + Some(clip) + } else { + None + } + } +} + +#[cfg(all(feature = "pool", feature = "editor"))] +pub trait AutoRemove: + Has> + + Has> + + Has> + + Has> + + Has> + + Send + Sync +{ + // Remove clip from arrangement when exiting empty clip editor + fn clip_auto_remove (&mut self) { + if let Some(ref mut pool) = Has::::get(self) + && let Some(Selection::TrackClip { track, scene }) = self.get() + && let Some(scene) = Has::>::get_mut(self).get_mut(scene) + && let Some(slot) = scene.clips.get_mut(track) + && let Some(clip) = slot.as_mut() + { + let mut swapped = None; + if clip.read().unwrap().count_midi_messages() == 0 { + std::mem::swap(&mut swapped, slot); + } + if let Some(clip) = swapped { + pool.delete_clip(&clip.read().unwrap()); + } + } + } +} diff --git a/crates/device/src/arranger/arranger_model.rs b/crates/device/src/arranger/arranger_model.rs new file mode 100644 index 00000000..0be3e78b --- /dev/null +++ b/crates/device/src/arranger/arranger_model.rs @@ -0,0 +1,74 @@ +use crate::*; + +#[derive(Default, Debug)] +pub struct Arrangement { + /// Project name. + pub name: Arc, + /// Base color. + pub color: ItemTheme, + /// List of global midi inputs + pub midi_ins: Vec, + /// List of global midi outputs + pub midi_outs: Vec, + /// List of global audio inputs + pub audio_ins: Vec, + /// List of global audio outputs + pub audio_outs: Vec, + /// Buffer for writing a midi event + pub note_buf: Vec, + /// Buffer for writing a chunk of midi events + pub midi_buf: Vec>>, + /// Last track number (to avoid duplicate port names) + pub track_last: usize, + /// List of tracks + pub tracks: Vec, + /// Scroll offset of tracks + pub track_scroll: usize, + /// List of scenes + pub scenes: Vec, + /// Scroll offset of scenes + pub scene_scroll: usize, + /// Selected UI element + pub selected: Option, + /// Contains a render of the project arrangement, redrawn on update. + /// TODO rename to "render_cache" or smth + pub arranger: Arc>, + /// Display size + pub size: Measure, +} + +has!(Option: |self: Arrangement|self.selected); +has!(Vec: |self: Arrangement|self.midi_ins); +has!(Vec: |self: Arrangement|self.midi_outs); +has!(Vec: |self: Arrangement|self.scenes); +has!(Vec: |self: Arrangement|self.tracks); + +impl Has> for Arrangement { + fn get (&self) -> &Option { + Has::::get(self) + .and_then(|selection|selection.track()) + .and_then(|index|Has::>::get(self).get(index)) + .flatten() + } + fn get_mut (&mut self) -> &mut Option { + Has::::get(self) + .and_then(|selection|selection.track()) + .and_then(|index|Has::>::get_mut(self).get_mut(index)) + .flatten() + } +} + +impl Has> for Arrangement { + fn get (&self) -> &Option { + Has::::get(self) + .and_then(|selection|selection.track()) + .and_then(|index|Has::>::get(self).get(index)) + .flatten() + } + fn get_mut (&mut self) -> &mut Option { + Has::::get(self) + .and_then(|selection|selection.track()) + .and_then(|index|Has::>::get_mut(self).get_mut(index)) + .flatten() + } +} diff --git a/crates/device/src/arranger/arranger_port.rs b/crates/device/src/arranger/arranger_port.rs new file mode 100644 index 00000000..9b09ba84 --- /dev/null +++ b/crates/device/src/arranger/arranger_port.rs @@ -0,0 +1,134 @@ +use crate::*; + +impl<'a> ArrangerView<'a> { + + pub(crate) fn input_routes (&'a self) -> impl Content + 'a { + Tryptich::top(self.inputs_height) + .left(self.width_side, + io_ports(Tui::g(224), Tui::g(32), ||self.arrangement.midi_ins_with_sizes())) + .middle(self.width_mid, + per_track_top(self.width_mid, ||self.tracks_with_sizes_scrolled(), + move|_, &Track { color, .. }|io_conns( + color.dark.rgb, + color.darker.rgb, + ||self.arrangement.midi_ins_with_sizes() + ))) + } + + pub(crate) fn input_ports (&'a self) -> impl Content + 'a { + Tryptich::top(1) + .left(self.width_side, + button_3("i", "midi ins", format!("{}", self.inputs_count), self.is_editing)) + .right(self.width_side, + button_2("I", "add midi in", self.is_editing)) + .middle(self.width_mid, + per_track_top( + self.width_mid, + ||self.tracks_with_sizes_scrolled(), + move|t, track|{ + let rec = track.sequencer.recording; + let mon = track.sequencer.monitoring; + let rec = if rec { White } else { track.color.darkest.rgb }; + let mon = if mon { White } else { track.color.darkest.rgb }; + let bg = if self.track_selected == Some(t) { + track.color.light.rgb + } else { + track.color.base.rgb + }; + //let bg2 = if t > 0 { track.color.base.rgb } else { Reset }; + wrap(bg, Tui::g(224), Tui::bold(true, Fill::x(Bsp::e( + Tui::fg_bg(rec, bg, "Rec "), + Tui::fg_bg(mon, bg, "Mon "), + )))) + })) + } + + pub(crate) fn input_intos (&'a self) -> impl Content + 'a { + Tryptich::top(2) + .left(self.width_side, + Bsp::s(Align::e("Input:"), Align::e("Into clip:"))) + .middle(self.width_mid, + per_track_top( + self.width_mid, + ||self.tracks_with_sizes_scrolled(), + |_, _|Tui::bg(Reset, Align::c(Bsp::s(OctaveVertical::default(), " ------ "))))) + } + + pub(crate) fn output_nexts (&self) -> impl Content + '_ { + Tryptich::top(2) + .left(self.width_side, Align::ne("From clip:")) + .middle(self.width_mid, per_track_top( + self.width_mid, + ||self.tracks_with_sizes_scrolled(), + |_, _|Tui::bg(Reset, Align::c(Bsp::s(" ------ ", OctaveVertical::default()))))) + } + + pub(crate) fn output_froms (&'a self) -> impl Content + 'a { + let label = Align::ne("Next clip:"); + Tryptich::top(2).left(self.width_side, label).middle(self.width_mid, per_track_top( + self.width_mid, ||self.tracks_with_sizes_scrolled(), |t, track|{ + let queued = track.sequencer.next_clip.is_some(); + let queued_blank = Thunk::new(||Tui::bg(Reset, " ------ ")); + let queued_clip = Thunk::new(||{ + Tui::bg(Reset, if let Some((_, clip)) = track.sequencer.next_clip.as_ref() { + if let Some(clip) = clip { + clip.read().unwrap().name.clone() + } else { + "Stop".into() + } + } else { + "".into() + }) + }); + Either(queued, queued_clip, queued_blank) + })) + } + + pub(crate) fn output_ports (&'a self) -> impl Content + 'a { + Tryptich::top(1) + .left(self.width_side, self.output_count()) + .right(self.width_side, self.output_add()) + .middle(self.width_mid, self.output_map()) + } + + pub(crate) fn output_count (&'a self) -> impl Content + 'a { + button_3("o", "midi outs", format!("{}", self.outputs_count), self.is_editing) + } + + pub(crate) fn output_add (&'a self) -> impl Content + 'a { + button_2("O", "add midi out", self.is_editing) + } + + pub(crate) fn output_map (&'a self) -> impl Content + 'a { + per_track_top(self.width_mid, ||self.tracks_with_sizes_scrolled(), move|i, t|{ + let mute = false; + let solo = false; + let mute = if mute { White } else { t.color.darkest.rgb }; + let solo = if solo { White } else { t.color.darkest.rgb }; + let bg_1 = if self.track_selected == Some(i) { + t.color.light.rgb + } else { + t.color.base.rgb + }; + let bg_2 = if i > 0 { t.color.base.rgb } else { Reset }; + let mute = Tui::fg_bg(mute, bg_1, "Play "); + let solo = Tui::fg_bg(solo, bg_1, "Solo "); + wrap(bg_1, Tui::g(224), Tui::bold(true, Fill::x(Bsp::e(mute, solo)))) + }) + } + + pub(crate) fn output_conns (&'a self) -> impl Content + 'a { + Tryptich::top(self.outputs_height) + .left(self.width_side, io_ports( + Tui::g(224), Tui::g(32), ||self.arrangement.midi_outs_with_sizes())) + .middle(self.width_mid, per_track_top( + self.width_mid, + ||self.tracks_with_sizes_scrolled(), + |_, t|io_conns( + t.color.dark.rgb, + t.color.darker.rgb, + ||self.arrangement.midi_outs_with_sizes() + ))) + } + +} diff --git a/crates/device/src/arranger/arranger_scene.rs b/crates/device/src/arranger/arranger_scene.rs new file mode 100644 index 00000000..6fb3401c --- /dev/null +++ b/crates/device/src/arranger/arranger_scene.rs @@ -0,0 +1,261 @@ +use crate::*; + +#[derive(Debug, Default)] +pub struct Scene { + /// Name of scene + pub name: Arc, + /// Identifying color of scene + pub color: ItemTheme, + /// Clips in scene, one per track + pub clips: Vec>>>, +} + +impl Scene { + /// Returns the pulse length of the longest clip in the scene + pub fn pulses (&self) -> usize { + self.clips.iter().fold(0, |a, p|{ + a.max(p.as_ref().map(|q|q.read().unwrap().length).unwrap_or(0)) + }) + } + /// Returns true if all clips in the scene are + /// currently playing on the given collection of tracks. + pub fn is_playing (&self, tracks: &[Track]) -> bool { + self.clips.iter().any(|clip|clip.is_some()) && self.clips.iter().enumerate() + .all(|(track_index, clip)|match clip { + Some(c) => tracks + .get(track_index) + .map(|track|{ + if let Some((_, Some(clip))) = track.sequencer().play_clip() { + *clip.read().unwrap() == *c.read().unwrap() + } else { + false + } + }) + .unwrap_or(false), + None => true + }) + } + pub fn clip (&self, index: usize) -> Option<&Arc>> { + match self.clips.get(index) { Some(Some(clip)) => Some(clip), _ => None } + } +} + +impl> + Send + Sync> HasScenes for T {} + +pub trait HasScenes: Has> + Send + Sync { + fn scenes (&self) -> &Vec { + Has::>::get(self) + } + fn scenes_mut (&self) -> &mut Vec { + Has::>::get_mut(self) + } + fn scenes_with_sizes ( + &self, + editing: bool, + height: usize, + larger: usize, + selected_track: Option, + selected_scene: Option, + ) -> impl ScenesSizes<'_> { + let mut y = 0; + self.scenes().iter().enumerate().map(move|(s, scene)|{ + let active = editing && selected_track.is_some() && selected_scene == Some(s); + let height = if active { larger } else { height }; + let data = (s, scene, y, y + height); + y += height; + data + }) + } + /// Generate the default name for a new scene + fn scene_default_name (&self) -> Arc { + format!("Sc{:3>}", self.scenes().len() + 1).into() + } + fn scene_longest_name (&self) -> usize { + self.scenes().iter().map(|s|s.name.len()).fold(0, usize::max) + } +} + +impl> + Send + Sync> HasScene for T {} + +pub trait HasScene: Has> + Send + Sync { + fn scene (&self) -> Option<&Scene> { + Has::>::get(self) + } + fn scene_mut (&mut self) -> Option<&mut Scene> { + Has::>::get_mut(self) + } +} + +impl<'a> ArrangerView<'a> { + /// Default scene height. + pub(crate) const H_SCENE: usize = 2; + /// Default editor height. + pub(crate) const H_EDITOR: usize = 15; + + /// Render scenes with clips + pub(crate) fn scenes (&'a self, editor: Option) -> impl Content + 'a { + + /// A scene with size and color. + type SceneWithColor<'a> = (usize, &'a Scene, usize, usize, Option); + + let Self { + arrangement, + width, width_side, width_mid, + scenes_height, scene_last, scene_selected, + track_selected, is_editing, .. + } = self; + + let selection = Has::>::get(*arrangement); + let (selected_track, selected_scene) = match selection { + Some(Selection::Track(t)) => (Some(*t), None), + Some(Selection::Scene(s)) => (None, Some(*s)), + Some(Selection::TrackClip { track, scene }) => (Some(*track), Some(*scene)), + _ => (None, None) + }; + + let scenes_with_scene_colors = ||arrangement.scenes_with_sizes( + *is_editing, + Self::H_SCENE, + Self::H_EDITOR, + selected_track, + selected_scene, + ).map_while(|(s, scene, y1, y2)|if y2 as u16 > *scenes_height { + None + } else { + Some((s, scene, y1, y2, if s == 0 { + None + } else { + Some(arrangement.scenes()[s-1].color) + })) + }); + + let scene_header = |(s, scene, y1, y2, previous): SceneWithColor, _|{ + let height = (1 + y2 - y1) as u16; + let name = Some(scene.name.clone()); + let content = Fill::x(Align::w(Tui::bold(true, Bsp::e(" ⯈ ", name)))); + let same_track = true; + let selected = same_track && *scene_selected == Some(s); + let neighbor = same_track && s > 0 && *scene_selected == Some(s - 1); + let is_last = *scene_last == s; + let theme = scene.color; + let fg = theme.lightest.rgb; + let bg = if selected { theme.light } else { theme.base }.rgb; + let hi = if let Some(previous) = previous { + if neighbor { + previous.light.rgb + } else { + previous.base.rgb + } + } else { + Reset + }; + let lo = if is_last { + Reset + } else if selected { + theme.light.rgb + } else { + theme.base.rgb + }; + Fill::x(map_south(y1 as u16, height, Fixed::y(height, Phat { + width: 0, height: 0, content, colors: [fg, bg, hi, lo] + }))) + }; + + let scenes_with_track_colors = |track: usize| arrangement.scenes_with_sizes( + self.is_editing, + Self::H_SCENE, + Self::H_EDITOR, + selected_track, + selected_scene, + ).map_while(|(s, scene, y1, y2)|if y2 as u16 > self.scenes_height { + None + } else { + Some((s, scene, y1, y2, if s == 0 { + None + } else { + Some(self.arrangement.scenes[s-1].clips[track].as_ref() + .map(|c|c.read().unwrap().color) + .unwrap_or(ItemTheme::G[32])) + })) + }); + + let scene_track_clips = |track_index, track|Map::new( + ||scenes_with_track_colors(track_index), + |(s, scene, y1, y2, previous): SceneWithColor<'a>, _|{ + let (name, theme) = if let Some(clip) = &scene.clips[track_index] { + let clip = clip.read().unwrap(); + (Some(clip.name.clone()), clip.color) + } else { + (None, ItemTheme::G[32]) + }; + let height = (1 + y2 - y1) as u16; + let content = Fill::x(Align::w(Tui::bold(true, Bsp::e(" ⏹ ", name)))); + let same_track = *track_selected == Some(track_index); + let selected = same_track && *scene_selected == Some(s); + let neighbor = same_track && s > 0 && *scene_selected == Some(s - 1); + let is_last = *scene_last == s; + let fg = theme.lightest.rgb; + let bg = if selected { theme.light } else { theme.base }.rgb; + let hi = if let Some(previous) = previous { + if neighbor { + previous.light.rgb + } else { + previous.base.rgb + } + } else { + Reset + }; + let lo = if is_last { + Reset + } else if selected { + theme.light.rgb + } else { + theme.base.rgb + }; + map_south(y1 as u16, height, Bsp::b(Fixed::y(height, Phat { + width: 0, height: 0, content, colors: [fg, bg, hi, lo] + }), When( + *is_editing && same_track && *scene_selected == Some(s), + editor + ))) + }); + + Tryptich::center(*scenes_height) + .left(*width_side, Map::new( + ||scenes_with_scene_colors(), + scene_header)) + .middle(*width_mid, per_track( + *width_mid, + ||self.tracks_with_sizes_scrolled(), + scene_track_clips)) + } + +} + +impl Arrangement { + /// Add multiple scenes + pub fn scenes_add (&mut self, n: usize) -> Usually<()> { + let scene_color_1 = ItemColor::random(); + let scene_color_2 = ItemColor::random(); + for i in 0..n { + let _ = self.scene_add(None, Some( + scene_color_1.mix(scene_color_2, i as f32 / n as f32).into() + ))?; + } + Ok(()) + } + + /// Add a scene + pub fn scene_add (&mut self, name: Option<&str>, color: Option) + -> Usually<(usize, &mut Scene)> + { + let scene = Scene { + name: name.map_or_else(||self.scene_default_name(), |x|x.to_string().into()), + clips: vec![None;self.tracks().len()], + color: color.unwrap_or_else(ItemTheme::random), + }; + self.scenes_mut().push(scene); + let index = self.scenes().len() - 1; + Ok((index, &mut self.scenes_mut()[index])) + } +} diff --git a/crates/app/src/model/selection.rs b/crates/device/src/arranger/arranger_select.rs similarity index 67% rename from crates/app/src/model/selection.rs rename to crates/device/src/arranger/arranger_select.rs index d4560a94..6105c200 100644 --- a/crates/app/src/model/selection.rs +++ b/crates/device/src/arranger/arranger_select.rs @@ -1,10 +1,5 @@ use crate::*; -pub trait HasSelection { - fn selected (&self) -> &Selection; - fn selected_mut (&mut self) -> &mut Selection; -} - /// Represents the current user selection in the arranger #[derive(PartialEq, Clone, Copy, Debug, Default)] pub enum Selection { @@ -151,7 +146,70 @@ impl Selection { } } -impl HasSelection for App { - fn selected (&self) -> &Selection { &self.selected } - fn selected_mut (&mut self) -> &mut Selection { &mut self.selected } +impl Arrangement { + /// Set the selection + pub(crate) fn select (&mut self, s: Selection) { + self.selected = s; + // autoedit: load focused clip in editor. + if let Some(ref mut editor) = self.editor { + editor.set_clip(match self.selected { + Selection::TrackClip { track, scene } + if let Some(Some(Some(clip))) = self + .scenes.get(scene) + .map(|s|s.clips.get(track)) => Some(clip), + _ => None + }); + } + } + /// Launch a clip or scene + pub(crate) fn launch (&mut self) { + use Selection::*; + match self.selected { + Track(t) => { + self.tracks[t].sequencer.enqueue_next(None) + }, + TrackClip { track, scene } => { + self.tracks[track].sequencer.enqueue_next(self.scenes[scene].clips[track].as_ref()) + }, + Scene(s) => { + for t in 0..self.tracks.len() { + self.tracks[t].sequencer.enqueue_next(self.scenes[s].clips[t].as_ref()) + } + }, + _ => {} + }; + } + /// Set the color of the selected entity + pub fn set_color (&mut self, palette: Option) -> Option { + use Selection::*; + let palette = palette.unwrap_or_else(||ItemTheme::random()); + Some(match self.selected { + Mix => { + let old = self.color; + self.color = palette; + old + }, + Scene(s) => { + let old = self.scenes[s].color; + self.scenes[s].color = palette; + old + } + Track(t) => { + let old = self.tracks[t].color; + self.tracks[t].color = palette; + old + } + TrackClip { track, scene } => { + if let Some(ref clip) = self.scenes[scene].clips[track] { + let mut clip = clip.write().unwrap(); + let old = clip.color; + clip.color = palette; + old + } else { + return None + } + }, + _ => todo!() + }) + } } diff --git a/crates/device/src/arranger/arranger_track.rs b/crates/device/src/arranger/arranger_track.rs new file mode 100644 index 00000000..fc028ee5 --- /dev/null +++ b/crates/device/src/arranger/arranger_track.rs @@ -0,0 +1,290 @@ +use crate::*; + +#[derive(Debug, Default)] +pub struct Track { + /// Name of track + pub name: Arc, + /// Identifying color of track + pub color: ItemTheme, + /// Preferred width of track column + pub width: usize, + /// MIDI sequencer state + pub sequencer: Sequencer, + /// Device chain + pub devices: Vec, +} +has_clock!(|self: Track|self.sequencer.clock); +has_sequencer!(|self: Track|self.sequencer); + +impl Track { + /// Create a new track with only the default [Sequencer]. + pub fn new ( + name: &impl AsRef, + color: Option, + jack: &Jack, + clock: Option<&Clock>, + clip: Option<&Arc>>, + midi_from: &[PortConnect], + midi_to: &[PortConnect], + ) -> Usually { + Ok(Self { + name: name.as_ref().into(), + color: color.unwrap_or_default(), + sequencer: Sequencer::new( + format!("{}/sequencer", name.as_ref()), + jack, + clock, + clip, + midi_from, + midi_to + )?, + ..Default::default() + }) + } + /// Create a new track connecting the [Sequencer] to a [Sampler]. + pub fn new_with_sampler ( + name: &impl AsRef, + color: Option, + jack: &Jack, + clock: Option<&Clock>, + clip: Option<&Arc>>, + midi_from: &[PortConnect], + midi_to: &[PortConnect], + audio_from: &[&[PortConnect];2], + audio_to: &[&[PortConnect];2], + ) -> Usually { + let mut track = Self::new(name, color, jack, clock, clip, midi_from, midi_to)?; + track.devices.push(Device::Sampler(Sampler::new( + jack, + &format!("{}/sampler", name.as_ref()), + &[PortConnect::exact(format!("{}:{}", + jack.with_client(|c|c.name().to_string()), + track.sequencer.midi_outs[0].name() + ))], + audio_from, + audio_to + )?)); + Ok(track) + } + #[cfg(feature = "sampler")] + pub fn sampler (&self, mut nth: usize) -> Option<&Sampler> { + for device in self.devices.iter() { + match device { + Device::Sampler(s) => if nth == 0 { + return Some(s); + } else { + nth -= 1; + }, + _ => {} + } + } + None + } + #[cfg(feature = "sampler")] + pub fn sampler_mut (&mut self, mut nth: usize) -> Option<&mut Sampler> { + for device in self.devices.iter_mut() { + match device { + Device::Sampler(s) => if nth == 0 { + return Some(s); + } else { + nth -= 1; + }, + _ => {} + } + } + None + } +} + +impl> + Send + Sync> HasTracks for T {} + +pub trait HasTracks: Send + Sync { + fn tracks (&self) -> &Vec { + Has::>::get(self) + } + fn tracks_mut (&mut self) -> &mut Vec { + Has::>::get_mut(self) + } + /// Run audio callbacks for every track and every device + fn tracks_render (&mut self, client: &Client, scope: &ProcessScope) -> Control { + for track in self.tracks.iter_mut() { + if Control::Quit == PlayerAudio( + track.sequencer_mut(), &mut self.note_buf, &mut self.midi_buf + ).process(client, scope) { + return Control::Quit + } + for device in track.devices.iter_mut() { + if Control::Quit == DeviceAudio(device).process(client, scope) { + return Control::Quit + } + } + } + Control::Continue + } + fn track_longest_name (&self) -> usize { + self.tracks().iter().map(|s|s.name.len()).fold(0, usize::max) + } + /// Stop all playing clips + fn tracks_stop_all (&mut self) { + for track in self.tracks_mut().iter_mut() { + track.sequencer.enqueue_next(None); + } + } + /// Stop all playing clips + fn tracks_launch (&mut self, clips: Option>>>) { + if let Some(clips) = clips { + for (clip, track) in clips.iter().zip(self.tracks_mut()) { + track.sequencer.enqueue_next(clip); + } + } else { + for track in self.tracks_mut().iter_mut() { + track.sequencer.enqueue_next(None); + } + } + } + /// Iterate over tracks with their corresponding sizes. + fn tracks_with_sizes ( + &self, + selection: &Option, + editor_width: Option + ) -> impl TracksSizes<'_> { + let mut x = 0; + let active_track = if let Some(width) = editor_width && let Some(selection) = selection { + selection.track() + } else { + None + }; + self.tracks().iter().enumerate().map(move |(index, track)|{ + let width = active_track + .and_then(|_|editor_width) + .unwrap_or(track.width.max(8)); + let data = (index, track, x, x + width); + x += width + Self::TRACK_SPACING; + data + }) + } + /// Spacing between tracks. + const TRACK_SPACING: usize = 0; +} + +impl> + Send + Sync> HasTrack for T {} + +pub trait HasTrack: Has> + Send + Sync { + fn scene (&self) -> Option<&Track> { + Has::>::get(self) + } + fn scene_mut (&mut self) -> Option<&mut Track> { + Has::>::get_mut(self) + } +} + +impl<'a> ArrangerView<'a> { + pub(crate) fn tracks_with_sizes_scrolled (&'a self) + -> impl TracksSizes<'a> + { + self.arrangement + .tracks_with_sizes(&self.arrangement.selected, self.is_editing.then_some(20/*FIXME*/)) + .map_while(move|(t, track, x1, x2)|{ + (self.width_mid > x2 as u16).then_some((t, track, x1, x2)) + }) + } +} + +pub(crate) fn per_track_top <'a, T: Content + 'a, U: TracksSizes<'a>> ( + width: u16, + tracks: impl Fn() -> U + Send + Sync + 'a, + callback: impl Fn(usize, &'a Track)->T + Send + Sync + 'a +) -> impl Content + 'a { + Align::x(Tui::bg(Reset, Map::new(tracks, + move|(index, track, x1, x2): (usize, &'a Track, usize, usize), _|{ + let width = (x2 - x1) as u16; + map_east(x1 as u16, width, Fixed::x(width, Tui::fg_bg( + track.color.lightest.rgb, + track.color.base.rgb, + callback(index, track))))}))) +} + +pub(crate) fn per_track <'a, T: Content + 'a, U: TracksSizes<'a>> ( + width: u16, + tracks: impl Fn() -> U + Send + Sync + 'a, + callback: impl Fn(usize, &'a Track)->T + Send + Sync + 'a +) -> impl Content + 'a { + per_track_top( + width, + tracks, + move|index, track|Fill::y(Align::y(callback(index, track))) + ) +} + +impl Arrangement { + /// Add multiple tracks + pub fn tracks_add ( + &mut self, + count: usize, + width: Option, + mins: &[PortConnect], + mouts: &[PortConnect], + ) -> Usually<()> { + let jack = self.jack().clone(); + let track_color_1 = ItemColor::random(); + let track_color_2 = ItemColor::random(); + for i in 0..count { + let color = track_color_1.mix(track_color_2, i as f32 / count as f32).into(); + let mut track = self.track_add(None, Some(color), mins, mouts)?.1; + if let Some(width) = width { + track.width = width; + } + } + Ok(()) + } + + /// Add a track + pub fn track_add ( + &mut self, + name: Option<&str>, + color: Option, + mins: &[PortConnect], + mouts: &[PortConnect], + ) -> Usually<(usize, &mut Track)> { + self.track_last += 1; + let name: Arc = name.map_or_else( + ||format!("Track{:02}", self.track_last).into(), + |x|x.to_string().into() + ); + let mut track = Track { + width: (name.len() + 2).max(12), + color: color.unwrap_or_else(ItemTheme::random), + sequencer: Sequencer::new( + &format!("{name}"), + self.jack(), + Some(self.clock()), + None, + mins, + mouts + )?, + name, + ..Default::default() + }; + self.tracks_mut().push(track); + let len = self.tracks().len(); + let index = len - 1; + for scene in self.scenes_mut().iter_mut() { + while scene.clips.len() < len { + scene.clips.push(None); + } + } + Ok((index, &mut self.tracks_mut()[index])) + } +} + +#[cfg(feature = "sampler")] +impl Arrangement { + /// Get the first sampler of the active track + pub fn sampler (&self) -> Option<&Sampler> { + self.track().map(|t|t.sampler(0)).flatten() + } + /// Get the first sampler of the active track + pub fn sampler_mut (&mut self) -> Option<&mut Sampler> { + self.track_mut().map(|t|t.sampler_mut(0)).flatten() + } +} diff --git a/crates/device/src/arranger/arranger_view.rs b/crates/device/src/arranger/arranger_view.rs new file mode 100644 index 00000000..f94b89aa --- /dev/null +++ b/crates/device/src/arranger/arranger_view.rs @@ -0,0 +1,217 @@ +use crate::*; + +impl Arrangement { + /// Width of display + pub(crate) fn w (&self) -> u16 { + self.size.w() as u16 + } + /// Width allocated for sidebar. + pub(crate) fn w_sidebar (&self) -> u16 { + self.w() / if self.is_editing() { 16 } else { 8 } as u16 + } + /// Width taken by all tracks. + pub(crate) fn w_tracks (&self) -> u16 { + self.tracks_with_sizes().last().map(|(_, _, _, x)|x as u16).unwrap_or(0) + } + /// Width available to display tracks. + pub(crate) fn w_tracks_area (&self) -> u16 { + self.w().saturating_sub(2 * self.w_sidebar()) + } + /// Height of display + pub(crate) fn h (&self) -> u16 { + self.size.h() as u16 + } + /// Height available to display track headers. + pub(crate) fn h_tracks_area (&self) -> u16 { + 5 // FIXME + //self.h().saturating_sub(self.h_inputs() + self.h_outputs()) + } + /// Height available to display tracks. + pub(crate) fn h_scenes_area (&self) -> u16 { + //15 + self.h().saturating_sub( + self.h_inputs() + + self.h_outputs() + + self.h_devices() + + 13 // FIXME + ) + } + /// Height taken by all scenes. + pub(crate) fn h_scenes (&self) -> u16 { + let (selected_track, selected_scene) = match Has::>::get(self) { + Some(Selection::Track(t)) => (Some(*t), None), + Some(Selection::Scene(s)) => (None, Some(*s)), + Some(Selection::TrackClip { track, scene }) => (Some(*track), Some(*scene)), + _ => (None, None) + }; + self.scenes_with_sizes( + self.is_editing, + ArrangerView::H_SCENE, + ArrangerView::H_EDITOR, + selected_track, + selected_scene + ) + .last() + .map(|(_, _, _, y)|y as u16).unwrap_or(0) + } + /// Height taken by all inputs. + pub(crate) fn h_inputs (&self) -> u16 { + self.inputs_with_sizes() + .last() + .map(|(_, _, _, _, y)|y as u16).unwrap_or(0) + } + /// Height taken by all outputs. + pub(crate) fn h_outputs (&self) -> u16 { + self.outputs_with_sizes() + .last() + .map(|(_, _, _, _, y)|y as u16).unwrap_or(0) + } + /// Height taken by visible device slots. + pub(crate) fn h_devices (&self) -> u16 { + 2 + //1 + self.devices_with_sizes().last().map(|(_, _, _, _, y)|y as u16).unwrap_or(0) + } +} + +pub(crate) struct ArrangerView<'a> { + pub arrangement: &'a Arrangement, + + pub is_editing: bool, + + pub width: u16, + pub width_mid: u16, + pub width_side: u16, + + pub inputs_count: usize, + pub inputs_height: u16, + + pub outputs_count: usize, + pub outputs_height: u16, + + pub scene_last: usize, + pub scene_count: usize, + pub scene_scroll: Fill>, + pub scene_selected: Option, + pub scenes_height: u16, + + pub track_scroll: Fill>, + pub track_count: usize, + pub track_selected: Option, + pub tracks_height: u16, + + pub show_debug_info: bool, +} + +impl<'a> ArrangerView<'a> { + pub fn new ( + arrangement: &'a Arrangement, + editor: Option<&'a MidiEditor> + ) -> Self { + let selected = arrangement.selected; + let h_tracks_area = arrangement.h_tracks_area(); + let h_scenes_area = arrangement.h_scenes_area(); + let h_scenes = arrangement.h_scenes(); + Self { + arrangement, + is_editing: editor.is_some(), + + width: arrangement.w(), + width_mid: arrangement.w_tracks_area(), + width_side: arrangement.w_sidebar(), + + inputs_height: arrangement.h_inputs(), + inputs_count: arrangement.midi_ins.len(), + + outputs_height: arrangement.h_outputs(), + outputs_count: arrangement.midi_outs.len(), + + scenes_height: h_scenes_area, + scene_selected: selected.map(|s|s.scene()).flatten(), + scene_count: arrangement.scenes.len(), + scene_last: arrangement.scenes.len().saturating_sub(1), + scene_scroll: Fill::y(Fixed::x(1, ScrollbarV { + offset: arrangement.scene_scroll, + length: h_scenes_area as usize, + total: h_scenes as usize, + })), + + tracks_height: h_tracks_area, + track_count: arrangement.tracks.len(), + track_selected: selected.map(|s|s.track()).flatten(), + track_scroll: Fill::x(Fixed::y(1, ScrollbarH { + offset: arrangement.track_scroll, + length: h_tracks_area as usize, + total: h_scenes as usize, + })), + + show_debug_info: false + } + } +} + +impl<'a> Content for ArrangerView<'a> { + fn content (&self) -> impl Render { + let ins = |x|Bsp::n(self.inputs(), x); + let tracks = |x|Bsp::s(self.tracks(), x); + let devices = |x|Bsp::s(self.devices(), x); + let outs = |x|Bsp::s(self.outputs(), x); + let bg = |x|Tui::bg(Reset, x); + //let track_scroll = |x|Bsp::s(&self.track_scroll, x); + //let scene_scroll = |x|Bsp::e(&self.scene_scroll, x); + outs(tracks(devices(ins(bg(self.scenes(None)))))) + } +} + +impl<'a> ArrangerView<'a> { + /// Render input matrix. + pub(crate) fn inputs (&'a self) -> impl Content + 'a { + Tui::bg(Reset, Bsp::s( + self.input_intos(), + Bsp::s(self.input_routes(), self.input_ports()), + )) + } + + /// Render output matrix. + pub(crate) fn outputs (&'a self) -> impl Content + 'a { + Tui::bg(Reset, Align::n(Bsp::s( + Bsp::s(self.output_ports(), self.output_conns()), + Bsp::s(self.output_nexts(), self.output_froms()), + ))) + } + + /// Render track headers + pub(crate) fn tracks (&'a self) -> impl Content + 'a { + let Self { width_side, width_mid, track_count, track_selected, is_editing, .. } = self; + Tryptich::center(3) + .left(*width_side, button_3("t", "track", format!("{}", *track_count), *is_editing)) + .right(*width_side, button_2("T", "add track", *is_editing)) + .middle(*width_mid, per_track(*width_mid, ||self.tracks_with_sizes_scrolled(), + |index, track|wrap( + if *track_selected == Some(index) { + track.color.light + } else { + track.color.base + }.rgb, + track.color.lightest.rgb, + Tui::bold(true, Fill::xy(Align::nw(&track.name))) + ))) + } + + /// Render device switches. + pub(crate) fn devices (&'a self) -> impl Content + 'a { + let Self { width_side, width_mid, track_count, track_selected, is_editing, .. } = self; + Tryptich::top(1) + .left(*width_side, button_3("d", "devices", format!("{}", 0), *is_editing)) + .right(*width_side, button_2("D", "add device", *is_editing)) + .middle(*width_mid, per_track_top(*width_mid, ||self.tracks_with_sizes_scrolled(), + move|index, track|{ + let bg = if *track_selected == Some(index) { + track.color.light + } else { + track.color.base + }; + let fg = Tui::g(224); + track.devices.get(0).map(|device|wrap(bg.rgb, fg, device.name())) + })) + } +} diff --git a/crates/device/src/browser/browser_api.rs b/crates/device/src/browser/browser_api.rs index 349a895b..1f80e1f8 100644 --- a/crates/device/src/browser/browser_api.rs +++ b/crates/device/src/browser/browser_api.rs @@ -2,19 +2,31 @@ use crate::*; #[tengri_proc::expose] impl Browser { + fn _todo_stub_path_buf (&self) -> PathBuf { + todo!() + } + fn _todo_stub_usize (&self) -> usize { + todo!() + } + fn _todo_stub_arc_str (&self) -> Arc { + todo!() + } } #[tengri_proc::command(Browser)] impl BrowserCommand { - //fn set_address (browser: &mut Browser, address: PathBuf) -> Perhaps { - //Ok(None) - //} - //fn set_search (browser: &mut Browser, filter: Arc) -> Perhaps { - //Ok(None) - //} - //fn set_cursor (browser: &mut Browser, cursor: usize) -> Perhaps { - //Ok(None) - //} + fn set_visible (browser: &mut Browser) -> Perhaps { + Ok(None) + } + fn set_path (browser: &mut Browser, address: PathBuf) -> Perhaps { + Ok(None) + } + fn set_search (browser: &mut Browser, filter: Arc) -> Perhaps { + Ok(None) + } + fn set_cursor (browser: &mut Browser, cursor: usize) -> Perhaps { + Ok(None) + } } // Commands supported by [Browser] diff --git a/crates/device/src/browser/browser_model.rs b/crates/device/src/browser/browser_model.rs index 053ecbce..c06caff6 100644 --- a/crates/device/src/browser/browser_model.rs +++ b/crates/device/src/browser/browser_model.rs @@ -1,15 +1,17 @@ use crate::*; +use std::path::PathBuf; +use std::ffi::OsString; /// Browses for phrase to import/export #[derive(Debug, Clone)] pub struct Browser { - pub cwd: PathBuf, - pub dirs: Vec<(OsString, String)>, - pub files: Vec<(OsString, String)>, - pub filter: String, - pub index: usize, - pub scroll: usize, - pub size: Measure, + pub cwd: PathBuf, + pub dirs: Vec<(OsString, String)>, + pub files: Vec<(OsString, String)>, + pub filter: String, + pub index: usize, + pub scroll: usize, + pub size: Measure, } impl Browser { diff --git a/crates/device/src/lib.rs b/crates/device/src/lib.rs index 7bc424a2..7c2a0c01 100644 --- a/crates/device/src/lib.rs +++ b/crates/device/src/lib.rs @@ -1,4 +1,6 @@ #![feature(let_chains)] +#![feature(trait_alias)] +#![feature(if_let_guard)] pub(crate) use std::cmp::Ord; pub(crate) use std::fmt::{Debug, Formatter}; @@ -10,7 +12,7 @@ pub(crate) use std::path::PathBuf; pub(crate) use std::error::Error; pub(crate) use std::ffi::OsString; -pub(crate) use ::tengri::{Usually, Perhaps, dsl::*, input::*, output::*, tui::{*, ratatui::prelude::*}}; +pub(crate) use ::tengri::{from, Usually, Perhaps, dsl::*, input::*, output::*, tui::{*, ratatui::prelude::*}}; pub(crate) use ::tek_engine::*; pub(crate) use ::tek_engine::midi::{u7, LiveEvent, MidiMessage}; pub(crate) use ::tek_engine::jack::{Control, ProcessScope, MidiWriter, RawMidi}; @@ -20,6 +22,9 @@ pub(crate) use Color::*; mod device; pub use self::device::*; +#[cfg(feature = "arranger")] mod arranger; +#[cfg(feature = "arranger")] pub use self::arranger::*; + #[cfg(feature = "browser")] mod browser; #[cfg(feature = "browser")] pub use self::browser::*; diff --git a/crates/device/src/sequencer/seq_audio.rs b/crates/device/src/sequencer/seq_audio.rs index 0b78b210..c96b7cdc 100644 --- a/crates/device/src/sequencer/seq_audio.rs +++ b/crates/device/src/sequencer/seq_audio.rs @@ -22,11 +22,11 @@ impl Audio for PlayerAudio<'_, T> { if model.play(scope, note_buf, midi_buf) { model.switchover(scope, note_buf, midi_buf); } - if model.has_midi_ins() { + if !model.midi_ins().is_empty() { if model.recording() || model.monitoring() { // Record and/or monitor input model.record(scope, midi_buf) - } else if model.has_midi_outs() && model.monitoring() { + } else if model.midi_outs().is_empty() && model.monitoring() { // Monitor input to output model.monitor(scope, midi_buf) } diff --git a/crates/device/src/sequencer/seq_model.rs b/crates/device/src/sequencer/seq_model.rs index 298364ac..2282edb1 100644 --- a/crates/device/src/sequencer/seq_model.rs +++ b/crates/device/src/sequencer/seq_model.rs @@ -103,17 +103,8 @@ impl std::fmt::Debug for Sequencer { } has_clock!(|self: Sequencer|self.clock); - -impl HasMidiIns for Sequencer { - fn midi_ins (&self) -> &Vec { &self.midi_ins } - fn midi_ins_mut (&mut self) -> &mut Vec { &mut self.midi_ins } -} - -impl HasMidiOuts for Sequencer { - fn midi_outs (&self) -> &Vec { &self.midi_outs } - fn midi_outs_mut (&mut self) -> &mut Vec { &mut self.midi_outs } - fn midi_note (&mut self) -> &mut Vec { &mut self.note_buf } -} +has!(Vec: |self:Sequencer| self.midi_ins); +has!(Vec: |self:Sequencer| self.midi_outs); impl MidiRecorder for Sequencer { fn recording (&self) -> bool { diff --git a/crates/engine/src/jack/jack_port.rs b/crates/engine/src/jack/jack_port.rs index 925d9fb8..85136cb9 100644 --- a/crates/engine/src/jack/jack_port.rs +++ b/crates/engine/src/jack/jack_port.rs @@ -1,94 +1,6 @@ use crate::*; use super::*; -macro_rules! impl_port { - ($Name:ident : $Spec:ident -> $Pair:ident |$jack:ident, $name:ident|$port:expr) => { - #[derive(Debug)] pub struct $Name { - /// Handle to JACK client, for receiving reconnect events. - jack: Jack, - /// Port name - name: Arc, - /// Port handle. - port: Port<$Spec>, - /// List of ports to connect to. - conn: Vec - } - impl AsRef> for $Name { fn as_ref (&self) -> &Port<$Spec> { &self.port } } - impl $Name { - pub fn new ($jack: &Jack, name: impl AsRef, connect: &[PortConnect]) - -> Usually - { - let $name = name.as_ref(); - let jack = $jack.clone(); - let port = $port?; - let name = $name.into(); - let conn = connect.to_vec(); - let port = Self { jack, port, name, conn }; - port.connect_to_matching()?; - Ok(port) - } - pub fn name (&self) -> &Arc { &self.name } - pub fn port (&self) -> &Port<$Spec> { &self.port } - pub fn port_mut (&mut self) -> &mut Port<$Spec> { &mut self.port } - pub fn into_port (self) -> Port<$Spec> { self.port } - pub fn close (self) -> Usually<()> { - let Self { jack, port, .. } = self; - Ok(jack.with_client(|client|client.unregister_port(port))?) - } - } - impl HasJack for $Name { fn jack (&self) -> &Jack { &self.jack } } - impl JackPort for $Name { - type Port = $Spec; - type Pair = $Pair; - fn port (&self) -> &Port<$Spec> { &self.port } - } - impl JackPortConnect<&str> for $Name { - fn connect_to (&self, to: &str) -> Usually { - self.with_client(|c|if let Some(ref port) = c.port_by_name(to.as_ref()) { - self.connect_to(port) - } else { - Ok(Missing) - }) - } - } - impl JackPortConnect<&Port> for $Name { - fn connect_to (&self, port: &Port) -> Usually { - self.with_client(|c|Ok(if let Ok(_) = c.connect_ports(&self.port, port) { - Connected - } else if let Ok(_) = c.connect_ports(port, &self.port) { - Connected - } else { - Mismatch - })) - } - } - impl JackPortConnect<&Port<$Pair>> for $Name { - fn connect_to (&self, port: &Port<$Pair>) -> Usually { - self.with_client(|c|Ok(if let Ok(_) = c.connect_ports(&self.port, port) { - Connected - } else if let Ok(_) = c.connect_ports(port, &self.port) { - Connected - } else { - Mismatch - })) - } - } - impl JackPortAutoconnect for $Name { - fn conn (&self) -> &[PortConnect] { - &self.conn - } - } - }; -} - -impl_port!(JackAudioIn: AudioIn -> AudioOut |j, n|j.register_port::(n)); - -impl_port!(JackAudioOut: AudioOut -> AudioIn |j, n|j.register_port::(n)); - -impl_port!(JackMidiIn: MidiIn -> MidiOut |j, n|j.register_port::(n)); - -impl_port!(JackMidiOut: MidiOut -> MidiIn |j, n|j.register_port::(n)); - pub trait JackPort: HasJack { type Port: PortSpec; type Pair: PortSpec; @@ -235,3 +147,91 @@ impl PortConnect { format!(" ({}) {} {}", status, scope, name).into() } } + +macro_rules! impl_port { + ($Name:ident : $Spec:ident -> $Pair:ident |$jack:ident, $name:ident|$port:expr) => { + #[derive(Debug)] pub struct $Name { + /// Handle to JACK client, for receiving reconnect events. + jack: Jack, + /// Port name + name: Arc, + /// Port handle. + port: Port<$Spec>, + /// List of ports to connect to. + conn: Vec + } + impl AsRef> for $Name { fn as_ref (&self) -> &Port<$Spec> { &self.port } } + impl $Name { + pub fn new ($jack: &Jack, name: impl AsRef, connect: &[PortConnect]) + -> Usually + { + let $name = name.as_ref(); + let jack = $jack.clone(); + let port = $port?; + let name = $name.into(); + let conn = connect.to_vec(); + let port = Self { jack, port, name, conn }; + port.connect_to_matching()?; + Ok(port) + } + pub fn name (&self) -> &Arc { &self.name } + pub fn port (&self) -> &Port<$Spec> { &self.port } + pub fn port_mut (&mut self) -> &mut Port<$Spec> { &mut self.port } + pub fn into_port (self) -> Port<$Spec> { self.port } + pub fn close (self) -> Usually<()> { + let Self { jack, port, .. } = self; + Ok(jack.with_client(|client|client.unregister_port(port))?) + } + } + impl HasJack for $Name { fn jack (&self) -> &Jack { &self.jack } } + impl JackPort for $Name { + type Port = $Spec; + type Pair = $Pair; + fn port (&self) -> &Port<$Spec> { &self.port } + } + impl JackPortConnect<&str> for $Name { + fn connect_to (&self, to: &str) -> Usually { + self.with_client(|c|if let Some(ref port) = c.port_by_name(to.as_ref()) { + self.connect_to(port) + } else { + Ok(Missing) + }) + } + } + impl JackPortConnect<&Port> for $Name { + fn connect_to (&self, port: &Port) -> Usually { + self.with_client(|c|Ok(if let Ok(_) = c.connect_ports(&self.port, port) { + Connected + } else if let Ok(_) = c.connect_ports(port, &self.port) { + Connected + } else { + Mismatch + })) + } + } + impl JackPortConnect<&Port<$Pair>> for $Name { + fn connect_to (&self, port: &Port<$Pair>) -> Usually { + self.with_client(|c|Ok(if let Ok(_) = c.connect_ports(&self.port, port) { + Connected + } else if let Ok(_) = c.connect_ports(port, &self.port) { + Connected + } else { + Mismatch + })) + } + } + impl JackPortAutoconnect for $Name { + fn conn (&self) -> &[PortConnect] { + &self.conn + } + } + }; +} + +impl_port!(JackAudioIn: AudioIn -> AudioOut |j, n|j.register_port::(n)); + +impl_port!(JackAudioOut: AudioOut -> AudioIn |j, n|j.register_port::(n)); + +impl_port!(JackMidiIn: MidiIn -> MidiOut |j, n|j.register_port::(n)); + +impl_port!(JackMidiOut: MidiOut -> MidiIn |j, n|j.register_port::(n)); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index db0bf96e..67482aa5 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -9,10 +9,29 @@ pub(crate) use std::sync::{Arc, atomic::{AtomicUsize, AtomicBool, Ordering::Rela pub(crate) use std::fmt::Debug; pub(crate) use std::ops::{Add, Sub, Mul, Div, Rem}; -pub(crate) use ::tengri::{Usually, tui::*}; +pub(crate) use ::tengri::{from, Usually, tui::*}; pub use ::atomic_float; pub(crate) use atomic_float::*; +pub trait Has: Send + Sync { + fn get (&self) -> &T; + fn get_mut (&mut self) -> &mut T; +} + +#[macro_export] macro_rules! has { + ($T:ty: |$self:ident : $S:ty| $x:expr) => { + impl Has<$T> for $S { + fn get (&$self) -> &$T { &$x } + fn get_mut (&mut $self) -> &mut $T { &mut $x } + } + }; +} + +pub trait HasN: Send + Sync { + fn get_nth (&self, key: usize) -> &T; + fn get_nth_mut (&mut self, key: usize) -> &mut T; +} + pub trait Gettable { /// Returns current value fn get (&self) -> T; diff --git a/crates/engine/src/midi.rs b/crates/engine/src/midi.rs index 216e253c..e6a656b0 100644 --- a/crates/engine/src/midi.rs +++ b/crates/engine/src/midi.rs @@ -9,6 +9,9 @@ pub use ::midly::{ live::*, }; +mod midi_in; pub use self::midi_in::*; +mod midi_out; pub use self::midi_out::*; + /// Update notes_in array pub fn update_keys (keys: &mut[bool;128], message: &MidiMessage) { match message { @@ -35,28 +38,3 @@ pub fn all_notes_off (output: &mut [Vec>]) { evt.write(&mut buf).unwrap(); output[0].push(buf); } - -/// Trait for thing that may receive MIDI. -pub trait HasMidiIns { - fn midi_ins (&self) -> &Vec; - - fn midi_ins_mut (&mut self) -> &mut Vec; - - fn has_midi_ins (&self) -> bool { - !self.midi_ins().is_empty() - } -} - -/// Trait for thing that may output MIDI. -pub trait HasMidiOuts { - fn midi_outs (&self) -> &Vec; - - fn midi_outs_mut (&mut self) -> &mut Vec; - - fn has_midi_outs (&self) -> bool { - !self.midi_outs().is_empty() - } - - /// Buffer for serializing a MIDI event. FIXME rename - fn midi_note (&mut self) -> &mut Vec; -} diff --git a/crates/engine/src/midi/midi_in.rs b/crates/engine/src/midi/midi_in.rs new file mode 100644 index 00000000..800bf2bc --- /dev/null +++ b/crates/engine/src/midi/midi_in.rs @@ -0,0 +1,42 @@ +use crate::*; + +impl>> HasMidiIns for T { + fn midi_ins (&self) -> &Vec { + self.get() + } + fn midi_ins_mut (&mut self) -> &mut Vec { + self.get_mut() + } +} + +/// Trait for thing that may receive MIDI. +pub trait HasMidiIns { + fn midi_ins (&self) -> &Vec; + fn midi_ins_mut (&mut self) -> &mut Vec; + /// Collect MIDI input from app ports (TODO preallocate large buffers) + fn midi_input_collect <'a> (&'a self, scope: &'a ProcessScope) -> CollectedMidiInput<'a> { + self.midi_ins().iter() + .map(|port|port.port().iter(scope) + .map(|RawMidi { time, bytes }|(time, LiveEvent::parse(bytes))) + .collect::>()) + .collect::>() + } + fn midi_ins_with_sizes <'a> (&'a self) -> + impl Iterator, &[PortConnect], usize, usize)> + Send + Sync + 'a + { + let mut y = 0; + self.midi_ins().iter().enumerate().map(move|(i, input)|{ + let height = 1 + input.conn().len(); + let data = (i, input.name(), input.conn(), y, y + height); + y += height; + data + }) + } + fn midi_in_add (&mut self, jack: &Jack) -> Usually<()> { + let index = self.midi_ins().len(); + self.midi_ins_mut().push(JackMidiIn::new(jack, &format!("M/{index}"), &[])?); + Ok(()) + } +} + +pub type CollectedMidiInput<'a> = Vec, MidiError>)>>; diff --git a/crates/engine/src/midi/midi_out.rs b/crates/engine/src/midi/midi_out.rs new file mode 100644 index 00000000..1bc3a74d --- /dev/null +++ b/crates/engine/src/midi/midi_out.rs @@ -0,0 +1,33 @@ +use crate::*; + +impl>> HasMidiOuts for T { + fn midi_outs (&self) -> &Vec { + self.get() + } + fn midi_outs_mut (&mut self) -> &mut Vec { + self.get_mut() + } +} + + +/// Trait for thing that may output MIDI. +pub trait HasMidiOuts { + fn midi_outs (&self) -> &Vec; + fn midi_outs_mut (&mut self) -> &mut Vec; + fn midi_outs_with_sizes <'a> (&'a self) -> + impl Iterator, &[PortConnect], usize, usize)> + Send + Sync + 'a + { + let mut y = 0; + self.midi_outs().iter().enumerate().map(move|(i, output)|{ + let height = 1 + output.conn().len(); + let data = (i, output.name(), output.conn(), y, y + height); + y += height; + data + }) + } + fn midi_out_add (&mut self, jack: &Jack) -> Usually<()> { + let index = self.midi_outs().len(); + self.midi_outs_mut().push(JackMidiOut::new(&jack, &format!("{index}/M"), &[])?); + Ok(()) + } +} diff --git a/deps/tengri b/deps/tengri index b45ac8f4..bad20f50 160000 --- a/deps/tengri +++ b/deps/tengri @@ -1 +1 @@ -Subproject commit b45ac8f417b2f4e83e116a9ee5fe4bf3ad57a726 +Subproject commit bad20f5037dc22d572a8381840fab871ce65f565