wip: sample selector

This commit is contained in:
🪞👃🪞 2024-07-20 19:47:42 +03:00
parent 4603bbd0da
commit f303a8d552
13 changed files with 278 additions and 125 deletions

View file

@ -1,95 +1,100 @@
//! Sampler (currently 16bit WAVs at system rate; TODO convert/resample)
use crate::core::*;
/// Key bindings for sampler device.
pub const KEYMAP_SAMPLER: &'static [KeyBinding<Sampler>] = keymap!(Sampler {
[Up, NONE, "cursor_up", "move cursor up", cursor_up],
[Down, NONE, "cursor_down", "move cursor down", cursor_down],
[Char('t'), NONE, "sample_play", "play current sample", trigger],
[Char('a'), NONE, "sample_add", "add a new sample", add_sample],
[Enter, NONE, "sample_edit", "edit selected sample", edit_sample],
});
fn cursor_up (state: &mut Sampler) -> Usually<bool> {
state.cursor.0 = if state.cursor.0 == 0 {
state.mapped.len() - 1
} else {
state.cursor.0 - 1
};
Ok(true)
}
fn cursor_down (state: &mut Sampler) -> Usually<bool> {
state.cursor.0 = (state.cursor.0 + 1) % state.mapped.len();
Ok(true)
}
fn trigger (state: &mut Sampler) -> Usually<bool> {
if let Some(sample) = state.sample() {
state.voices.push(sample.play(0, &100.into()))
}
Ok(true)
}
fn add_sample (state: &mut Sampler) -> Usually<bool> {
state.unmapped.push(Sample::new("", 0, 0, vec![]));
Ok(true)
}
fn edit_sample (state: &mut Sampler) -> Usually<bool> {
if let Some(sample) = state.sample() {
state.editing = Some(sample.clone());
}
Ok(true)
}
use crate::{core::*, view::*, model::MODAL};
/// The sampler plugin plays sounds.
pub struct Sampler {
pub name: String,
pub cursor: (usize, usize),
pub editing: Option<Arc<Sample>>,
pub mapped: BTreeMap<u7, Arc<Sample>>,
pub unmapped: Vec<Arc<Sample>>,
pub voices: Vec<Voice>,
pub ports: JackPorts,
pub buffer: Vec<Vec<f32>>,
pub name: String,
pub cursor: (usize, usize),
pub editing: Option<Arc<Sample>>,
pub mapped: BTreeMap<u7, Arc<Sample>>,
pub unmapped: Vec<Arc<Sample>>,
pub voices: Vec<Voice>,
pub ports: JackPorts,
pub buffer: Vec<Vec<f32>>,
pub output_gain: f32
}
process!(Sampler = Sampler::process);
handle!(Sampler |self, event| {
handle_keymap(self, event, KEYMAP_SAMPLER)
});
render!(Sampler |self, buf, area| {
let Rect { x, y, height, .. } = area;
let style = Style::default().gray();
let title = format!(" {} ({})", self.name, self.voices.len());
title.blit(buf, x+1, y, Some(style.white().bold().not_dim()))?;
let mut width = title.len() + 2;
for (i, (note, sample)) in self.mapped.iter().enumerate() {
let style = if i == self.cursor.0 {
Style::default().green()
} else {
Style::default()
};
let i = i as u16;
let y1 = y+1+i;
if y1 >= y + height {
let mut y1 = 1;
let mut j = 0;
for (note, sample) in self.mapped.iter()
.map(|(note, sample)|(Some(note), sample))
.chain(self.unmapped.iter().map(|sample|(None, sample)))
{
if y1 >= height {
break
}
if i as usize == self.cursor.0 {
"".blit(buf, x+1, y1, Some(style.bold()))?;
}
let label1 = format!("{note:3} {:12}", sample.name);
let label2 = format!("{:>6} {:>6} +0.0", sample.start, sample.end);
label1.blit(buf, x+2, y1, Some(style.bold()))?;
label2.blit(buf, x+3+label1.len()as u16, y1, Some(style))?;
width = width.max(label1.len() + label2.len() + 4);
let active = j == self.cursor.0;
width = width.max(draw_sample(buf, x, y + y1, note, sample, active)?);
y1 = y1 + 1;
j = j + 1;
}
let height = ((2 + self.mapped.len()) as u16).min(height);
let height = ((2 + y1) as u16).min(height);
Ok(Rect { x, y, width: (width as u16).min(area.width), height })
});
fn draw_sample (
buf: &mut Buffer, x: u16, y: u16, note: Option<&u7>, sample: &Sample, focus: bool
) -> Usually<usize> {
let style = if focus { Style::default().green() } else { Style::default() };
if focus {
"🬴".blit(buf, x+1, y, Some(style.bold()))?;
}
let label1 = format!("{:3} {:12}",
note.map(|n|n.to_string()).unwrap_or(String::default()),
sample.name);
let label2 = format!("{:>6} {:>6} +0.0",
sample.start,
sample.end);
label1.blit(buf, x+2, y, Some(style.bold()))?;
label2.blit(buf, x+3+label1.len()as u16, y, Some(style))?;
Ok(label1.len() + label2.len() + 4)
}
handle!(Sampler |self, event| handle_keymap(self, event, KEYMAP_SAMPLER));
/// Key bindings for sampler device.
pub const KEYMAP_SAMPLER: &'static [KeyBinding<Sampler>] = keymap!(Sampler {
[Up, NONE, "cursor_up", "move cursor up", |state: &mut Sampler| {
state.cursor.0 = if state.cursor.0 == 0 {
state.mapped.len() + state.unmapped.len() - 1
} else {
state.cursor.0 - 1
};
Ok(true)
}],
[Down, NONE, "cursor_down", "move cursor down", |state: &mut Sampler| {
state.cursor.0 = (state.cursor.0 + 1) % (state.mapped.len() + state.unmapped.len());
Ok(true)
}],
[Char('t'), NONE, "sample_play", "play current sample", |state: &mut Sampler| {
if let Some(sample) = state.sample() {
state.voices.push(sample.play(0, &100.into()))
}
Ok(true)
}],
[Char('a'), NONE, "sample_add", "add a new sample", |state: &mut Sampler| {
let sample = Sample::new("", 0, 0, vec![]);
*MODAL.lock().unwrap() = Some(Exit::boxed(AddSampleModal::new(&sample)?));
state.unmapped.push(sample);
Ok(true)
}],
[Enter, NONE, "sample_edit", "edit selected sample", |state: &mut Sampler| {
if let Some(sample) = state.sample() {
state.editing = Some(sample.clone());
}
Ok(true)
}],
});
process!(Sampler = Sampler::process);
impl Sampler {
pub fn new (name: &str, mapped: Option<BTreeMap<u7, Arc<Sample>>>) -> Usually<JackDevice> {
Jack::new(name)?
@ -257,3 +262,124 @@ impl Iterator for Voice {
None
}
}
pub struct AddSampleModal {
exited: bool,
dir: PathBuf,
subdirs: Vec<OsString>,
files: Vec<OsString>,
cursor: usize,
offset: usize,
sample: Arc<Sample>,
search: Option<String>,
}
exit!(AddSampleModal);
render!(AddSampleModal |self,buf,area|{
make_dim(buf);
let area = center_box(area, 64, 20);
fill_fg(buf, area, Color::Reset);
fill_bg(buf, area, Nord::bg_lo(true, true));
fill_char(buf, area, ' ');
format!("{}", &self.dir.to_string_lossy())
.blit(buf, area.x+2, area.y+1, Some(Style::default().bold()))?;
"Select sample:"
.blit(buf, area.x+2, area.y+2, Some(Style::default().bold()))?;
for (i, (is_dir, name)) in self.subdirs.iter()
.map(|path|(true, path))
.chain(self.files.iter().map(|path|(false, path)))
.enumerate()
.skip(self.offset)
{
let t = if is_dir { "" } else { "" };
format!("{t} {}", name.to_string_lossy())
.blit(buf, area.x + 2, area.y + 3 + i as u16, Some(if i == self.cursor {
Style::default().green()
} else {
Style::default().white()
}))?;
}
Lozenge(Style::default()).draw(buf, area)
});
handle!(AddSampleModal |self,e|{
if handle_keymap(self, e, KEYMAP_ADD_SAMPLE)? {
return Ok(true)
}
Ok(true)
});
impl AddSampleModal {
fn new (sample: &Arc<Sample>) -> Usually<Self> {
let dir = std::env::current_dir()?;
let (subdirs, files) = scan(&dir)?;
Ok(Self {
exited: false,
dir,
subdirs,
files,
cursor: 0,
offset: 0,
sample: sample.clone(),
search: None
})
}
}
fn scan (dir: &PathBuf) -> Usually<(Vec<OsString>, Vec<OsString>)> {
Ok(read_dir(dir)?.fold(
(vec!["..".into()], vec![]),
|(mut subdirs, mut files), entry|{
let entry = entry.expect("failed to read drectory entry");
let meta = entry.metadata().expect("failed to read entry metadata");
if meta.is_file() {
files.push(entry.file_name());
} else if meta.is_dir() {
subdirs.push(entry.file_name());
}
(subdirs, files)
}))
}
impl AddSampleModal {
fn rescan (&mut self) -> Usually<()> {
scan(&self.dir).map(|(subdirs, files)|{
self.subdirs = subdirs;
self.files = files;
})
}
fn prev (&mut self) {
self.cursor = self.cursor.saturating_sub(1);
}
fn next (&mut self) {
self.cursor = self.cursor + 1;
}
fn pick (&mut self) -> Usually<()> {
if self.cursor == 0 {
if let Some(parent) = self.dir.parent() {
self.dir = parent.into();
self.rescan()?;
}
} else if self.cursor < self.subdirs.len() {
self.dir = self.dir.join(&self.subdirs[self.cursor]);
self.rescan()?;
} else if (self.cursor - self.subdirs.len()) < self.files.len() {
} else {
}
Ok(())
}
}
pub const KEYMAP_ADD_SAMPLE: &'static [KeyBinding<AddSampleModal>] = keymap!(AddSampleModal {
[Esc, NONE, "add_sample_close", "close help dialog", |modal: &mut AddSampleModal|{
modal.exit();
Ok(true)
}],
[Up, NONE, "add_sample_prev", "select previous entry", |modal: &mut AddSampleModal|{
modal.prev();
Ok(true)
}],
[Down, NONE, "add_sample_next", "select next entry", |modal: &mut AddSampleModal|{
modal.next();
Ok(true)
}],
[Enter, NONE, "add_sample_enter", "activate selected entry", |modal: &mut AddSampleModal|{
modal.pick()?;
Ok(true)
}],
});