tek/crates/app/src/view.rs
2025-05-08 02:54:26 +03:00

1345 lines
51 KiB
Rust

use crate::*;
pub(crate) use std::fmt::Write;
pub(crate) use ::tengri::tui::ratatui::prelude::Position;
#[tengri_proc::view(TuiOut)]
impl Tek {
fn view_nil (&self) -> impl Content<TuiOut> + use<'_> {
"nil"
}
fn view_status (&self) -> impl Content<TuiOut> + use<'_> {
self.update_clock();
let cache = self.view_cache.read().unwrap();
view_status(
self.selected.describe(&self.tracks, &self.scenes),
cache.sr.view.clone(), cache.buf.view.clone(), cache.lat.view.clone(),
)
}
fn view_transport (&self) -> impl Content<TuiOut> + use<'_> {
self.update_clock();
let cache = self.view_cache.read().unwrap();
view_transport(
self.clock.is_rolling(),
cache.bpm.view.clone(), cache.beat.view.clone(), cache.time.view.clone(),
)
}
fn view_arranger (&self) -> impl Content<TuiOut> + use<'_> {
ArrangerView::new(self)
}
fn view_pool (&self) -> impl Content<TuiOut> + use<'_> {
self.pool().map(|p|Fixed::x(self.w_sidebar(), PoolView(self.is_editing(), p)))
}
fn view_editor (&self) -> impl Content<TuiOut> + use<'_> {
self.editor().map(|e|Bsp::n(Bsp::e(e.clip_status(), e.edit_status()), e))
}
fn view_samples_keys (&self) -> impl Content<TuiOut> + use<'_> {
self.sampler().map(|s|s.view_list(false, self.editor().unwrap()))
}
fn view_samples_grid (&self) -> impl Content<TuiOut> + use<'_> {
self.sampler().map(|s|s.view_grid())
}
fn view_sample_viewer (&self) -> impl Content<TuiOut> + use<'_> {
self.sampler().map(|s|s.view_sample(self.editor().unwrap().note_pos()))
}
fn view_dialog (&self) -> impl Content<TuiOut> + use<'_> {
When::new(self.dialog.is_some(), Bsp::b(
Fill::xy(Tui::fg_bg(Rgb(64,64,64), Rgb(32,32,32), "")),
Fixed::xy(30, 15, Tui::fg_bg(Rgb(255,255,255), Rgb(16,16,16), Bsp::b(
Repeat(" "),
Outer(true, Style::default().fg(Tui::g(96)))
.enclose(self.dialog.as_ref().map(|dialog|match dialog {
Dialog::Menu => self.view_dialog_menu().boxed(),
Dialog::Help => self.view_dialog_help().boxed(),
Dialog::Device(index) => self.view_dialog_device(*index).boxed(),
Dialog::Message(message) => self.view_dialog_message(message).boxed(),
}))
)))
))
}
}
impl Tek {
fn view_dialog_menu (&self) -> impl Content<TuiOut> {
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)))
}
fn view_dialog_help (&self) -> impl Content<TuiOut> + use<'_> {
let bindings = ||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
});
let binding = |mut binding: TokenIter, _|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, bindings, binding)))
}
fn view_dialog_device (&self, index: usize) -> impl Content<TuiOut> + 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 view_dialog_message <'a> (&'a self, message: &'a Message) -> impl Content<TuiOut> + use<'a> {
Bsp::s(message, Bsp::s("", "[ OK ]"))
}
/// 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;
/// Width of display
pub(crate) fn w (&self) -> u16 {
self.size.w() as u16
}
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 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)
}
/// 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)
}
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 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
})
}
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 + Tek::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 Tek,
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<Fixed<u16, ScrollbarV>>,
scene_selected: Option<usize>,
scenes_height: u16,
track_scroll: Fill<Fixed<u16, ScrollbarH>>,
track_count: usize,
track_selected: Option<usize>,
tracks_height: u16,
show_debug_info: bool,
}
impl<'a> Content<TuiOut> for ArrangerView<'a> {
fn content (&self) -> impl Render<TuiOut> {
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 Tek) -> 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<TuiOut> + '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<TuiOut> + '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 device switches.
pub(crate) fn devices (&'a self) -> impl Content<TuiOut> + 'a {
let Self { width_side, width_mid, track_count, track_selected, is_editing, .. } = self;
Tryptich::top(1)
.left(*width_side, button_3("z", "devices", format!("{}", 0), *is_editing))
.right(*width_side, button_2("Z", "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()))
}))
}
/// Render track headers
pub(crate) fn tracks (&'a self) -> impl Content<TuiOut> + '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)))
)))
}
fn input_routes (&'a self) -> impl Content<TuiOut> + '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()
)))
}
fn input_ports (&'a self) -> impl Content<TuiOut> + '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.player.recording;
let mon = track.player.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 "),
))))
}))
}
fn input_intos (&'a self) -> impl Content<TuiOut> + '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(), " ------ ")))))
}
fn output_nexts (&'a self) -> impl Content<TuiOut> + 'a {
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())))))
}
fn output_froms (&'a self) -> impl Content<TuiOut> + '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.player.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.player.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<TuiOut> + 'a {
Tryptich::top(1)
.left(self.width_side,
button_3("o", "midi outs", format!("{}", self.outputs_count), self.is_editing))
.right(self.width_side,
button_2("O", "add midi out", self.is_editing))
.middle(self.width_mid,
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<TuiOut> + '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()
)))
}
/// Render scenes with clips
pub(crate) fn scenes (&'a self) -> impl Content<TuiOut> + 'a {
let Self {
width, width_side, width_mid,
scenes_height, scene_last, scene_selected,
track_selected, is_editing, app: Tek { 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(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(crate) fn scenes_with_scene_colors (&self)
-> impl ScenesColors<'_>
{
self.app.scenes_with_sizes(self.is_editing, Tek::H_SCENE, Tek::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, Tek::H_SCENE, Tek::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]))
}))
}
)
}
}
trait ScenesColors<'a> = Iterator<Item=SceneWithColor<'a>>;
type SceneWithColor<'a> = (usize, &'a Scene, usize, usize, Option<ItemTheme>);
/// 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<Item=(usize, $(&'a $Item,)+ usize, usize)> + 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<str>, [PortConnect]);
fn view_transport (
play: bool,
bpm: Arc<RwLock<String>>,
beat: Arc<RwLock<String>>,
time: Arc<RwLock<String>>,
) -> impl Content<TuiOut> {
let theme = ItemTheme::G[96];
Tui::bg(Black, row!(Bsp::a(
Fill::xy(Align::w(button_play_pause(play))),
Fill::xy(Align::e(row!(
FieldH(theme, "BPM", bpm),
FieldH(theme, "Beat", beat),
FieldH(theme, "Time", time),
)))
)))
}
fn view_status (
sel: Arc<str>,
sr: Arc<RwLock<String>>,
buf: Arc<RwLock<String>>,
lat: Arc<RwLock<String>>,
) -> impl Content<TuiOut> {
let theme = ItemTheme::G[96];
Tui::bg(Black, row!(Bsp::a(
Fill::xy(Align::w(FieldH(theme, "Selected", sel))),
Fill::xy(Align::e(row!(
FieldH(theme, "SR", sr),
FieldH(theme, "Buf", buf),
FieldH(theme, "Lat", lat),
)))
)))
}
pub(crate) fn button_play_pause (playing: bool) -> impl Content<TuiOut> {
let compact = true;//self.is_editing();
Tui::bg(if playing { Rgb(0, 128, 0) } else { Rgb(128, 64, 0) },
Either::new(compact,
Thunk::new(move||Fixed::x(9, Either::new(playing,
Tui::fg(Rgb(0, 255, 0), " PLAYING "),
Tui::fg(Rgb(255, 128, 0), " STOPPED ")))
),
Thunk::new(move||Fixed::x(5, Either::new(playing,
Tui::fg(Rgb(0, 255, 0), Bsp::s(" 🭍🭑🬽 ", " 🭞🭜🭘 ",)),
Tui::fg(Rgb(255, 128, 0), Bsp::s(" ▗▄▖ ", " ▝▀▘ ",))))
)
)
)
}
pub (crate) fn view_meter <'a> (label: &'a str, value: f32) -> impl Content<TuiOut> + 'a {
col!(
FieldH(ItemTheme::G[128], label, format!("{:>+9.3}", value)),
Fixed::xy(if value >= 0.0 { 13 }
else if value >= -1.0 { 12 }
else if value >= -2.0 { 11 }
else if value >= -3.0 { 10 }
else if value >= -4.0 { 9 }
else if value >= -6.0 { 8 }
else if value >= -9.0 { 7 }
else if value >= -12.0 { 6 }
else if value >= -15.0 { 5 }
else if value >= -20.0 { 4 }
else if value >= -25.0 { 3 }
else if value >= -30.0 { 2 }
else if value >= -40.0 { 1 }
else { 0 }, 1, Tui::bg(if value >= 0.0 { Red }
else if value >= -3.0 { Yellow }
else { Green }, ())))
}
pub(crate) fn view_meters (values: &[f32;2]) -> impl Content<TuiOut> + use<'_> {
let left = format!("L/{:>+9.3}", values[0]);
let right = format!("R/{:>+9.3}", values[1]);
Bsp::s(left, right)
}
pub(crate) fn wrap (bg: Color, fg: Color, content: impl Content<TuiOut>) -> impl Content<TuiOut> {
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<TuiOut> + 'a, label: impl Content<TuiOut> + 'a, editing: bool,
) -> impl Content<TuiOut> + '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<TuiOut> + 'a where
K: Content<TuiOut> + 'a,
L: Content<TuiOut> + 'a,
V: Content<TuiOut> + '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> (
key: &'a str,
label: &'a str,
count: usize,
content: impl Content<TuiOut> + Send + Sync + 'a,
editing: bool,
) -> impl Content<TuiOut> + 'a {
let count = format!("{count}");
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<TuiOut> + 'a {
Map::new(iter, move|(
index, name, connections, y, y2
): (usize, &'a Arc<str>, &'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<TuiOut> + 'a {
Map::new(iter, move|(
index, name, connections, y, y2
): (usize, &'a Arc<str>, &'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<TuiOut> + '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<TuiOut> + '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<TuiOut> + '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<TuiOut> + '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)*) } }
}
#[derive(Debug, Default)] pub(crate) struct ViewMemo<T, U> {
pub(crate) value: T,
pub(crate) view: Arc<RwLock<U>>
}
impl<T: PartialEq, U> ViewMemo<T, U> {
fn new (value: T, view: U) -> Self {
Self { value, view: Arc::new(view.into()) }
}
pub(crate) fn update <R> (
&mut self,
newval: T,
render: impl Fn(&mut U, &T, &T)->R
) -> Option<R> {
if newval != self.value {
let result = render(&mut*self.view.write().unwrap(), &newval, &self.value);
self.value = newval;
return Some(result);
}
None
}
}
#[derive(Debug)] pub struct ViewCache {
pub(crate) sr: ViewMemo<Option<(bool, f64)>, String>,
pub(crate) buf: ViewMemo<Option<f64>, String>,
pub(crate) lat: ViewMemo<Option<f64>, String>,
pub(crate) bpm: ViewMemo<Option<f64>, String>,
pub(crate) beat: ViewMemo<Option<f64>, String>,
pub(crate) time: ViewMemo<Option<f64>, String>,
pub(crate) scns: ViewMemo<Option<(usize, usize)>, String>,
pub(crate) trks: ViewMemo<Option<(usize, usize)>, String>,
pub(crate) stop: Arc<str>,
pub(crate) edit: Arc<str>,
}
impl Default for ViewCache {
fn default () -> Self {
let mut beat = String::with_capacity(16);
write!(beat, "{}", Self::BEAT_EMPTY);
let mut time = String::with_capacity(16);
write!(time, "{}", Self::TIME_EMPTY);
let mut bpm = String::with_capacity(16);
write!(bpm, "{}", Self::BPM_EMPTY);
Self {
beat: ViewMemo::new(None, beat),
time: ViewMemo::new(None, time),
bpm: ViewMemo::new(None, bpm),
sr: ViewMemo::new(None, String::with_capacity(16)),
buf: ViewMemo::new(None, String::with_capacity(16)),
lat: ViewMemo::new(None, String::with_capacity(16)),
scns: ViewMemo::new(None, String::with_capacity(16)),
trks: ViewMemo::new(None, String::with_capacity(16)),
stop: "".into(),
edit: "edit".into(),
}
}
}
impl ViewCache {
pub const BEAT_EMPTY: &'static str = "-.-.--";
pub const TIME_EMPTY: &'static str = "-.---s";
pub const BPM_EMPTY: &'static str = "---.---";
pub fn track_counter (cache: &Arc<RwLock<Self>>, track: usize, tracks: usize)
-> Arc<RwLock<String>>
{
let data = (track, tracks);
cache.write().unwrap().trks.update(Some(data), rewrite!(buf, "{}/{}", data.0, data.1));
cache.read().unwrap().trks.view.clone()
}
pub fn scene_add (cache: &Arc<RwLock<Self>>, scene: usize, scenes: usize, is_editing: bool)
-> impl Content<TuiOut>
{
let data = (scene, scenes);
cache.write().unwrap().scns.update(Some(data), rewrite!(buf, "({}/{})", data.0, data.1));
button_3("S", "add scene", cache.read().unwrap().scns.view.clone(), is_editing)
}
pub fn update_clock (cache: &Arc<RwLock<Self>>, clock: &Clock, compact: bool) {
let rate = clock.timebase.sr.get();
let chunk = clock.chunk.load(Relaxed) as f64;
let lat = chunk / rate * 1000.;
let delta = |start: &Moment|clock.global.usec.get() - start.usec.get();
let mut cache = cache.write().unwrap();
cache.buf.update(Some(chunk), rewrite!(buf, "{chunk}"));
cache.lat.update(Some(lat), rewrite!(buf, "{lat:.1}ms"));
cache.sr.update(Some((compact, rate)), |buf,_,_|{
buf.clear();
if compact {
write!(buf, "{:.1}kHz", rate / 1000.)
} else {
write!(buf, "{:.0}Hz", rate)
}
});
if let Some(now) = clock.started.read().unwrap().as_ref().map(delta) {
let pulse = clock.timebase.usecs_to_pulse(now);
let time = now/1000000.;
let bpm = clock.timebase.bpm.get();
cache.beat.update(Some(pulse), |buf, _, _|{
buf.clear();
clock.timebase.format_beats_1_to(buf, pulse)
});
cache.time.update(Some(time), rewrite!(buf, "{:.3}s", time));
cache.bpm.update(Some(bpm), rewrite!(buf, "{:.3}", bpm));
} else {
cache.beat.update(None, rewrite!(buf, "{}", ViewCache::BEAT_EMPTY));
cache.time.update(None, rewrite!(buf, "{}", ViewCache::TIME_EMPTY));
cache.bpm.update(None, rewrite!(buf, "{}", ViewCache::BPM_EMPTY));
}
}
}
pub struct PoolView<'a>(pub bool, pub &'a MidiPool);
content!(TuiOut: |self: PoolView<'a>| {
let Self(compact, model) = self;
let MidiPool { clips, .. } = self.1;
//let color = self.1.clip().map(|c|c.read().unwrap().color).unwrap_or_else(||Tui::g(32).into());
let on_bg = |x|x;//Bsp::b(Repeat(" "), Tui::bg(color.darkest.rgb, x));
let border = |x|x;//Outer(Style::default().fg(color.dark.rgb).bg(color.darkest.rgb)).enclose(x);
let iter = | |model.clips().clone().into_iter();
let height = clips.read().unwrap().len() as u16;
Tui::bg(Reset, Fixed::y(height, on_bg(border(Map::new(iter, move|clip: Arc<RwLock<MidiClip>>, i|{
let item_height = 1;
let item_offset = i as u16 * item_height;
let selected = i == model.clip_index();
let MidiClip { ref name, color, length, .. } = *clip.read().unwrap();
let bg = if selected { color.light.rgb } else { color.base.rgb };
let fg = color.lightest.rgb;
let name = if *compact { format!(" {i:>3}") } else { format!(" {i:>3} {name}") };
let length = if *compact { String::default() } else { format!("{length} ") };
Fixed::y(1, map_south(item_offset, item_height, Tui::bg(bg, lay!(
Fill::x(Align::w(Tui::fg(fg, Tui::bold(selected, name)))),
Fill::x(Align::e(Tui::fg(fg, Tui::bold(selected, length)))),
Fill::x(Align::w(When::new(selected, Tui::bold(true, Tui::fg(Tui::g(255), ""))))),
Fill::x(Align::e(When::new(selected, Tui::bold(true, Tui::fg(Tui::g(255), ""))))),
))))
})))))
});
content!(TuiOut: |self: ClipLength| {
use ClipLengthFocus::*;
let bars = ||self.bars_string();
let beats = ||self.beats_string();
let ticks = ||self.ticks_string();
match self.focus {
None => row!(" ", bars(), ".", beats(), ".", ticks()),
Some(Bar) => row!("[", bars(), "]", beats(), ".", ticks()),
Some(Beat) => row!(" ", bars(), "[", beats(), "]", ticks()),
Some(Tick) => row!(" ", bars(), ".", beats(), "[", ticks()),
}
});
/// A clip, rendered as a horizontal piano roll.
#[derive(Clone)]
pub struct PianoHorizontal {
pub clip: Option<Arc<RwLock<MidiClip>>>,
/// Buffer where the whole clip is rerendered on change
pub buffer: Arc<RwLock<BigBuffer>>,
/// Size of actual notes area
pub size: Measure<TuiOut>,
/// 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,
}
impl PianoHorizontal {
pub fn new (clip: Option<&Arc<RwLock<MidiClip>>>) -> 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<Item=(usize, u16, usize)>
{
(note_lo..=note_hi).rev().enumerate().map(move|(y, n)|(y, y0 + y as u16, n))
}
content!(TuiOut:|self: PianoHorizontal| Tui::bg(Tui::g(40), Bsp::s(
Bsp::e(
Fixed::x(5, format!("{}x{}", self.size.w(), self.size.h())),
self.timeline()
),
Bsp::e(
self.keys(),
self.size.of(Tui::bg(Tui::g(32), 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) {
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();
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<TuiOut> {
let time_start = self.time_start().get();
let note_lo = self.note_lo().get();
let note_hi = self.note_hi();
let buffer = self.buffer.clone();
ThunkRender::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<TuiOut> {
let style = Some(Style::default().fg(self.color.lightest.rgb));
let note_hi = self.note_hi();
let note_lo = self.note_lo().get();
let note_pos = self.note_pos();
let note_len = self.note_len();
let time_pos = self.time_pos();
let time_start = self.time_start().get();
let time_zoom = self.time_zoom().get();
ThunkRender::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<TuiOut> {
let state = self;
let color = state.color;
let note_lo = state.note_lo().get();
let note_hi = state.note_hi();
let note_pos = state.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, ThunkRender::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<TuiOut> + '_ {
Fill::x(Fixed::y(1, ThunkRender::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);
}
}
})))
}
}
has_size!(<TuiOut>|self:PianoHorizontal|&self.size);
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) -> usize { self.point.note_len() }
fn set_note_len (&self, x: usize) -> usize { self.point.set_note_len(x) }
fn note_pos (&self) -> usize { self.point.note_pos() }
fn set_note_pos (&self, x: usize) -> usize { self.point.set_note_pos(x) }
}
impl TimePoint for PianoHorizontal {
fn time_pos (&self) -> usize { self.point.time_pos() }
fn set_time_pos (&self, x: usize) -> usize { self.point.set_time_pos(x) }
}
impl MidiViewer for PianoHorizontal {
fn clip (&self) -> &Option<Arc<RwLock<MidiClip>>> {
&self.clip
}
fn clip_mut (&mut self) -> &mut Option<Arc<RwLock<MidiClip>>> {
&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 note_len = self.note_len();
let time_zoom = self.time_zoom().get();
self.time_len().set(clip.length);
PianoHorizontal::draw_bg(&mut buffer, &clip, time_zoom, note_len);
PianoHorizontal::draw_fg(&mut buffer, &clip, time_zoom);
buffer
} else {
Default::default()
}
}
fn set_clip (&mut self, clip: Option<&Arc<RwLock<MidiClip>>>) {
*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 std::fmt::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()
}
}
// Update sequencer playhead indicator
//self.now().set(0.);
//if let Some((ref started_at, Some(ref playing))) = self.player.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);
//}
//}
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 Content<TuiOut> for OctaveVertical {
fn content (&self) -> impl Render<TuiOut> {
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), ""),
)
}
}