use crate::*; #[macro_export] macro_rules! has_editor { (|$self:ident: $Struct:ident|{ editor = $e0:expr; editor_w = $e1:expr; editor_h = $e2:expr; is_editing = $e3:expr; }) => { impl HasEditor for $Struct { fn editor (&$self) -> Option<&MidiEditor> { $e0.as_ref() } fn editor_mut (&mut $self) -> Option<&mut MidiEditor> { $e0.as_mut() } fn editor_w (&$self) -> usize { $e1 } fn editor_h (&$self) -> usize { $e2 } fn is_editing (&$self) -> bool { $e3 } } }; } impl>> HasEditor for T {} pub trait HasEditor: Has> { fn editor (&self) -> Option<&MidiEditor> { self.get().as_ref() } fn editor_mut (&mut self) -> Option<&mut MidiEditor> { self.get_mut().as_mut() } fn is_editing (&self) -> bool { self.editor().is_some() } fn editor_w (&self) -> usize { self.editor().map(|e|e.size.w()).unwrap_or(0) } fn editor_h (&self) -> usize { self.editor().map(|e|e.size.h()).unwrap_or(0) } } /// Contains state for viewing and editing a clip pub struct MidiEditor { /// Size of editor on screen pub size: Measure, /// View mode and state of editor pub mode: PianoHorizontal, } has!(Measure: |self: MidiEditor|self.size); impl Default for MidiEditor { fn default () -> Self { Self { size: Measure::new(), mode: PianoHorizontal::new(None), } } } impl std::fmt::Debug for MidiEditor { fn fmt (&self, f: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> { f.debug_struct("MidiEditor").field("mode", &self.mode).finish() } } from!(|clip: &Arc>|MidiEditor = { let model = Self::from(Some(clip.clone())); model.redraw(); model }); from!(|clip: Option>>|MidiEditor = { let mut model = Self::default(); *model.clip_mut() = clip; model.redraw(); model }); impl MidiEditor { /// Put note at current position pub fn put_note (&mut self, advance: bool) { let mut redraw = false; if let Some(clip) = self.clip() { let mut clip = clip.write().unwrap(); let note_start = self.get_time_pos(); let note_pos = self.get_note_pos(); let note_len = self.get_note_len(); let note_end = note_start + (note_len.saturating_sub(1)); let key: u7 = u7::from(note_pos as u8); let vel: u7 = 100.into(); let length = clip.length; let note_end = note_end % length; let note_on = MidiMessage::NoteOn { key, vel }; if !clip.notes[note_start].iter().any(|msg|*msg == note_on) { clip.notes[note_start].push(note_on); } let note_off = MidiMessage::NoteOff { key, vel }; if !clip.notes[note_end].iter().any(|msg|*msg == note_off) { clip.notes[note_end].push(note_off); } if advance { self.set_time_pos((note_end + 1) % clip.length); } redraw = true; } if redraw { self.mode.redraw(); } } } impl TimeRange for MidiEditor { fn time_len (&self) -> &AtomicUsize { self.mode.time_len() } fn time_zoom (&self) -> &AtomicUsize { self.mode.time_zoom() } fn time_lock (&self) -> &AtomicBool { self.mode.time_lock() } fn time_start (&self) -> &AtomicUsize { self.mode.time_start() } fn time_axis (&self) -> &AtomicUsize { self.mode.time_axis() } } impl NoteRange for MidiEditor { fn note_lo (&self) -> &AtomicUsize { self.mode.note_lo() } fn note_axis (&self) -> &AtomicUsize { self.mode.note_axis() } } impl NotePoint for MidiEditor { fn note_len (&self) -> &AtomicUsize { self.mode.note_len() } fn note_pos (&self) -> &AtomicUsize { self.mode.note_pos() } } impl TimePoint for MidiEditor { fn time_pos (&self) -> &AtomicUsize { self.mode.time_pos() } } impl MidiViewer for MidiEditor { fn buffer_size (&self, clip: &MidiClip) -> (usize, usize) { self.mode.buffer_size(clip) } fn redraw (&self) { self.mode.redraw() } fn clip (&self) -> &Option>> { self.mode.clip() } fn clip_mut (&mut self) -> &mut Option>> { self.mode.clip_mut() } fn set_clip (&mut self, p: Option<&Arc>>) { self.mode.set_clip(p) } } def_command!(MidiEditCommand: |editor: MidiEditor| { Show { clip: Option>> } => { editor.set_clip(clip.as_ref()); editor.redraw(); Ok(None) }, DeleteNote => { editor.redraw(); todo!() }, AppendNote { advance: bool } => { editor.put_note(*advance); editor.redraw(); Ok(None) }, SetNotePos { pos: usize } => { editor.set_note_pos((*pos).min(127)); editor.redraw(); Ok(None) }, SetNoteLen { len: usize } => { editor.set_note_len(*len); editor.redraw(); Ok(None) }, SetNoteScroll { scroll: usize } => { editor.set_note_lo((*scroll).min(127)); editor.redraw(); Ok(None) }, SetTimePos { pos: usize } => { editor.set_time_pos(*pos); editor.redraw(); Ok(None) }, SetTimeScroll { scroll: usize } => { editor.set_time_start(*scroll); editor.redraw(); Ok(None) }, SetTimeZoom { zoom: usize } => { editor.set_time_zoom(*zoom); editor.redraw(); Ok(None) }, SetTimeLock { lock: bool } => { editor.set_time_lock(*lock); editor.redraw(); Ok(None) }, // TODO: 1-9 seek markers that by default start every 8th of the clip }); impl MidiEditor { fn _todo_opt_clip_stub (&self) -> Option>> { todo!() } fn clip_length (&self) -> usize { self.clip().as_ref().map(|p|p.read().unwrap().length).unwrap_or(1) } fn note_length (&self) -> usize { self.get_note_len() } fn note_pos (&self) -> usize { self.get_note_pos() } fn note_pos_next (&self) -> usize { self.get_note_pos() + 1 } fn note_pos_next_octave (&self) -> usize { self.get_note_pos() + 12 } fn note_pos_prev (&self) -> usize { self.get_note_pos().saturating_sub(1) } fn note_pos_prev_octave (&self) -> usize { self.get_note_pos().saturating_sub(12) } fn note_len (&self) -> usize { self.get_note_len() } fn note_len_next (&self) -> usize { self.get_note_len() + 1 } fn note_len_prev (&self) -> usize { self.get_note_len().saturating_sub(1) } fn note_range (&self) -> usize { self.get_note_axis() } fn note_range_next (&self) -> usize { self.get_note_axis() + 1 } fn note_range_prev (&self) -> usize { self.get_note_axis().saturating_sub(1) } fn time_zoom (&self) -> usize { self.get_time_zoom() } fn time_zoom_next (&self) -> usize { self.get_time_zoom() + 1 } fn time_zoom_next_fine (&self) -> usize { self.get_time_zoom() + 1 } fn time_zoom_prev (&self) -> usize { self.get_time_zoom().saturating_sub(1).max(1) } fn time_zoom_prev_fine (&self) -> usize { self.get_time_zoom().saturating_sub(1).max(1) } fn time_lock (&self) -> bool { self.get_time_lock() } fn time_lock_toggled (&self) -> bool { !self.get_time_lock() } fn time_pos (&self) -> usize { self.get_time_pos() } fn time_pos_next (&self) -> usize { (self.get_time_pos() + self.get_note_len()) % self.clip_length() } fn time_pos_next_fine (&self) -> usize { (self.get_time_pos() + 1) % self.clip_length() } fn time_pos_prev (&self) -> usize { let step = self.get_note_len(); self.get_time_pos().overflowing_sub(step) .0.min(self.clip_length().saturating_sub(step)) } fn time_pos_prev_fine (&self) -> usize { self.get_time_pos().overflowing_sub(1) .0.min(self.clip_length().saturating_sub(1)) } } impl Draw for MidiEditor { fn draw (&self, to: &mut TuiOut) { self.content().draw(to) } } impl Layout for MidiEditor { fn layout (&self, to: [u16;4]) -> [u16;4] { self.content().layout(to) } } impl HasContent for MidiEditor { fn content (&self) -> impl Content { self.autoscroll(); /*self.autozoom();*/ self.size.of(&self.mode) } } impl MidiEditor { pub fn clip_status (&self) -> impl Content + '_ { let (_color, name, length, looped) = if let Some(clip) = self.clip().as_ref().map(|p|p.read().unwrap()) { (clip.color, clip.name.clone(), clip.length, clip.looped) } else { (ItemTheme::G[64], String::new().into(), 0, false) }; Fixed::X(20, col!( Fill::X(Align::w(Bsp::e( button_2("f2", "name ", false), Fill::X(Align::e(Tui::fg(Rgb(255, 255, 255), format!("{name} "))))))), Fill::X(Align::w(Bsp::e( button_2("l", "ength ", false), Fill::X(Align::e(Tui::fg(Rgb(255, 255, 255), format!("{length} "))))))), Fill::X(Align::w(Bsp::e( button_2("r", "epeat ", false), Fill::X(Align::e(Tui::fg(Rgb(255, 255, 255), format!("{looped} "))))))), )) } pub fn edit_status (&self) -> impl Content + '_ { let (_color, length) = if let Some(clip) = self.clip().as_ref().map(|p|p.read().unwrap()) { (clip.color, clip.length) } else { (ItemTheme::G[64], 0) }; let time_pos = self.get_time_pos(); let time_zoom = self.get_time_zoom(); let time_lock = if self.get_time_lock() { "[lock]" } else { " " }; let note_pos = self.get_note_pos(); let note_name = format!("{:4}", Note::pitch_to_name(note_pos)); let note_pos = format!("{:>3}", note_pos); let note_len = format!("{:>4}", self.get_note_len()); Fixed::X(20, col!( Fill::X(Align::w(Bsp::e( button_2("t", "ime ", false), Fill::X(Align::e(Tui::fg(Rgb(255, 255, 255), format!("{length} /{time_zoom} +{time_pos} "))))))), Fill::X(Align::w(Bsp::e( button_2("z", "lock ", false), Fill::X(Align::e(Tui::fg(Rgb(255, 255, 255), format!("{time_lock}"))))))), Fill::X(Align::w(Bsp::e( button_2("x", "note ", false), Fill::X(Align::e(Tui::fg(Rgb(255, 255, 255), format!("{note_name} {note_pos} {note_len}"))))))), )) } } /// A clip, rendered as a horizontal piano roll. #[derive(Clone)] pub struct PianoHorizontal { pub clip: Option>>, /// Buffer where the whole clip is rerendered on change pub buffer: Arc>, /// Size of actual notes area pub size: Measure, /// The display window pub range: MidiRangeModel, /// The note cursor pub point: MidiPointModel, /// The highlight color palette pub color: ItemTheme, /// Width of the keyboard pub keys_width: u16, } has!(Measure:|self:PianoHorizontal|self.size); impl PianoHorizontal { pub fn new (clip: Option<&Arc>>) -> Self { let size = Measure::new(); let mut range = MidiRangeModel::from((12, true)); range.time_axis = size.x.clone(); range.note_axis = size.y.clone(); let piano = Self { keys_width: 5, size, range, buffer: RwLock::new(Default::default()).into(), point: MidiPointModel::default(), clip: clip.cloned(), color: clip.as_ref().map(|p|p.read().unwrap().color).unwrap_or(ItemTheme::G[64]), }; piano.redraw(); piano } } pub(crate) fn note_y_iter (note_lo: usize, note_hi: usize, y0: u16) -> impl Iterator { (note_lo..=note_hi).rev().enumerate().map(move|(y, n)|(y, y0 + y as u16, n)) } impl Draw for PianoHorizontal { fn draw (&self, to: &mut TuiOut) { self.content().draw(to) } } impl Layout for PianoHorizontal { fn layout (&self, to: [u16;4]) -> [u16;4] { self.content().layout(to) } } impl HasContent for PianoHorizontal { fn content (&self) -> impl Content { Bsp::s( Bsp::e(Fixed::X(5, format!("{}x{}", self.size.w(), self.size.h())), self.timeline()), Bsp::e(self.keys(), self.size.of(Bsp::b(Fill::XY(self.notes()), Fill::XY(self.cursor())))), ) } } impl PianoHorizontal { /// Draw the piano roll background. /// /// This mode uses full blocks on note on and half blocks on legato: █▄ █▄ █▄ fn draw_bg (buf: &mut BigBuffer, clip: &MidiClip, zoom: usize, note_len: usize, note_point: usize, time_point: usize) { for (y, note) in (0..=127).rev().enumerate() { for (x, time) in (0..buf.width).map(|x|(x, x*zoom)) { let cell = buf.get_mut(x, y).unwrap(); if note == (127-note_point) || time == time_point { cell.set_bg(Rgb(0,0,0)); } else { cell.set_bg(clip.color.darkest.rgb); } if time % 384 == 0 { cell.set_fg(clip.color.darker.rgb); cell.set_char('│'); } else if time % 96 == 0 { cell.set_fg(clip.color.dark.rgb); cell.set_char('╎'); } else if time % note_len == 0 { cell.set_fg(clip.color.darker.rgb); cell.set_char('┊'); } else if (127 - note) % 12 == 0 { cell.set_fg(clip.color.darker.rgb); cell.set_char('='); } else if (127 - note) % 6 == 0 { cell.set_fg(clip.color.darker.rgb); cell.set_char('—'); } else { cell.set_fg(clip.color.darker.rgb); cell.set_char('·'); } } } } /// Draw the piano roll foreground. /// /// This mode uses full blocks on note on and half blocks on legato: █▄ █▄ █▄ fn draw_fg (buf: &mut BigBuffer, clip: &MidiClip, zoom: usize) { let style = Style::default().fg(clip.color.base.rgb);//.bg(Rgb(0, 0, 0)); let mut notes_on = [false;128]; for (x, time_start) in (0..clip.length).step_by(zoom).enumerate() { for (_y, note) in (0..=127).rev().enumerate() { if let Some(cell) = buf.get_mut(x, note) { if notes_on[note] { cell.set_char('▂'); cell.set_style(style); } } } let time_end = time_start + zoom; for time in time_start..time_end.min(clip.length) { for event in clip.notes[time].iter() { match event { MidiMessage::NoteOn { key, .. } => { let note = key.as_int() as usize; if let Some(cell) = buf.get_mut(x, note) { cell.set_char('█'); cell.set_style(style); } notes_on[note] = true }, MidiMessage::NoteOff { key, .. } => { notes_on[key.as_int() as usize] = false }, _ => {} } } } } } fn notes (&self) -> impl Content { let time_start = self.get_time_start(); let note_lo = self.get_note_lo(); let note_hi = self.get_note_hi(); let buffer = self.buffer.clone(); Thunk::new(move|to: &mut TuiOut|{ let source = buffer.read().unwrap(); let [x0, y0, w, _h] = to.area().xywh(); //if h as usize != note_axis { //panic!("area height mismatch: {h} <> {note_axis}"); //} for (area_x, screen_x) in (x0..x0+w).enumerate() { for (area_y, screen_y, _note) in note_y_iter(note_lo, note_hi, y0) { let source_x = time_start + area_x; let source_y = note_hi - area_y; // TODO: enable loop rollover: //let source_x = (time_start + area_x) % source.width.max(1); //let source_y = (note_hi - area_y) % source.height.max(1); let is_in_x = source_x < source.width; let is_in_y = source_y < source.height; if is_in_x && is_in_y { if let Some(source_cell) = source.get(source_x, source_y) { if let Some(cell) = to.buffer.cell_mut(ratatui::prelude::Position::from((screen_x, screen_y))) { *cell = source_cell.clone(); } } } } } }) } fn cursor (&self) -> impl Content { let note_hi = self.get_note_hi(); let note_lo = self.get_note_lo(); let note_pos = self.get_note_pos(); let note_len = self.get_note_len(); let time_pos = self.get_time_pos(); let time_start = self.get_time_start(); let time_zoom = self.get_time_zoom(); let style = Some(Style::default().fg(self.color.lightest.rgb)); Thunk::new(move|to: &mut TuiOut|{ let [x0, y0, w, _] = to.area().xywh(); for (_area_y, screen_y, note) in note_y_iter(note_lo, note_hi, y0) { if note == note_pos { for x in 0..w { let screen_x = x0 + x; let time_1 = time_start + x as usize * time_zoom; let time_2 = time_1 + time_zoom; if time_1 <= time_pos && time_pos < time_2 { to.blit(&"█", screen_x, screen_y, style); let tail = note_len as u16 / time_zoom as u16; for x_tail in (screen_x + 1)..(screen_x + tail) { to.blit(&"▂", x_tail, screen_y, style); } break } } break } } }) } fn keys (&self) -> impl Content { let state = self; let color = state.color; let note_lo = state.get_note_lo(); let note_hi = state.get_note_hi(); let note_pos = state.get_note_pos(); let key_style = Some(Style::default().fg(Rgb(192, 192, 192)).bg(Rgb(0, 0, 0))); let off_style = Some(Style::default().fg(Tui::g(255))); let on_style = Some(Style::default().fg(Rgb(255,0,0)).bg(color.base.rgb).bold()); Fill::Y(Fixed::X(self.keys_width, Thunk::new(move|to: &mut TuiOut|{ let [x, y0, _w, _h] = to.area().xywh(); for (_area_y, screen_y, note) in note_y_iter(note_lo, note_hi, y0) { to.blit(&to_key(note), x, screen_y, key_style); if note > 127 { continue } if note == note_pos { to.blit(&format!("{:<5}", Note::pitch_to_name(note)), x, screen_y, on_style) } else { to.blit(&Note::pitch_to_name(note), x, screen_y, off_style) }; } }))) } fn timeline (&self) -> impl Content + '_ { Fill::X(Fixed::Y(1, Thunk::new(move|to: &mut TuiOut|{ let [x, y, w, _h] = to.area(); let style = Some(Style::default().dim()); let length = self.clip.as_ref().map(|p|p.read().unwrap().length).unwrap_or(1); for (area_x, screen_x) in (0..w).map(|d|(d, d+x)) { let t = area_x as usize * self.time_zoom().get(); if t < length { to.blit(&"|", screen_x, y, style); } } }))) } } impl TimeRange for PianoHorizontal { fn time_len (&self) -> &AtomicUsize { self.range.time_len() } fn time_zoom (&self) -> &AtomicUsize { self.range.time_zoom() } fn time_lock (&self) -> &AtomicBool { self.range.time_lock() } fn time_start (&self) -> &AtomicUsize { self.range.time_start() } fn time_axis (&self) -> &AtomicUsize { self.range.time_axis() } } impl NoteRange for PianoHorizontal { fn note_lo (&self) -> &AtomicUsize { self.range.note_lo() } fn note_axis (&self) -> &AtomicUsize { self.range.note_axis() } } impl NotePoint for PianoHorizontal { fn note_len (&self) -> &AtomicUsize { self.point.note_len() } fn note_pos (&self) -> &AtomicUsize { self.point.note_pos() } } impl TimePoint for PianoHorizontal { fn time_pos (&self) -> &AtomicUsize { self.point.time_pos() } } impl MidiViewer for PianoHorizontal { fn clip (&self) -> &Option>> { &self.clip } fn clip_mut (&mut self) -> &mut Option>> { &mut self.clip } /// Determine the required space to render the clip. fn buffer_size (&self, clip: &MidiClip) -> (usize, usize) { (clip.length / self.range.time_zoom().get(), 128) } fn redraw (&self) { *self.buffer.write().unwrap() = if let Some(clip) = self.clip.as_ref() { let clip = clip.read().unwrap(); let buf_size = self.buffer_size(&clip); let mut buffer = BigBuffer::from(buf_size); let time_zoom = self.get_time_zoom(); self.time_len().set(clip.length); PianoHorizontal::draw_bg(&mut buffer, &clip, time_zoom,self.get_note_len(), self.get_note_pos(), self.get_time_pos()); PianoHorizontal::draw_fg(&mut buffer, &clip, time_zoom); buffer } else { Default::default() } } fn set_clip (&mut self, clip: Option<&Arc>>) { *self.clip_mut() = clip.cloned(); self.color = clip.map(|p|p.read().unwrap().color).unwrap_or(ItemTheme::G[64]); self.redraw(); } } impl std::fmt::Debug for PianoHorizontal { fn fmt (&self, f: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> { let buffer = self.buffer.read().unwrap(); f.debug_struct("PianoHorizontal") .field("time_zoom", &self.range.time_zoom) .field("buffer", &format!("{}x{}", buffer.width, buffer.height)) .finish() } } fn to_key (note: usize) -> &'static str { match note % 12 { 11 | 9 | 7 | 5 | 4 | 2 | 0 => "████▌", 10 | 8 | 6 | 3 | 1 => " ", _ => unreachable!(), } } pub struct OctaveVertical { on: [bool; 12], colors: [Color; 3] } impl Default for OctaveVertical { fn default () -> Self { Self { on: [false; 12], colors: [Rgb(255,255,255), Rgb(0,0,0), Rgb(255,0,0)] } } } impl OctaveVertical { fn color (&self, pitch: usize) -> Color { let pitch = pitch % 12; self.colors[if self.on[pitch] { 2 } else { match pitch { 0 | 2 | 4 | 5 | 6 | 8 | 10 => 0, _ => 1 } }] } } impl HasContent for OctaveVertical { fn content (&self) -> impl Content + '_ { row!( Tui::fg_bg(self.color(0), self.color(1), "▙"), Tui::fg_bg(self.color(2), self.color(3), "▙"), Tui::fg_bg(self.color(4), self.color(5), "▌"), Tui::fg_bg(self.color(6), self.color(7), "▟"), Tui::fg_bg(self.color(8), self.color(9), "▟"), Tui::fg_bg(self.color(10), self.color(11), "▟"), ) } } // Update sequencer playhead indicator //self.now().set(0.); //if let Some((ref started_at, Some(ref playing))) = self.sequencer.play_clip { //let clip = clip.read().unwrap(); //if *playing.read().unwrap() == *clip { //let pulse = self.current().pulse.get(); //let start = started_at.pulse.get(); //let now = (pulse - start) % clip.length as f64; //self.now().set(now); //} //}