use std::fs;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use clap::Subcommand;
use duet_core::{Grid, Song};
use duet_drums::DrumGrid;
use crate::config::Config;
use crate::io::{Format, grid_form, read, same_file, song_format, with_end, write};
#[derive(Subcommand)]
pub enum DrumsCommand {
Render {
input: PathBuf,
output: PathBuf,
#[arg(long, value_enum)]
to: Option<Format>,
},
Read {
input: PathBuf,
output: PathBuf,
#[arg(long)]
grid: Grid,
#[arg(long)]
track: Option<String>,
#[arg(long)]
bars: Option<u32>,
#[arg(long)]
snap_levels: bool,
#[arg(long, value_enum)]
from: Option<Format>,
},
Snap {
input: PathBuf,
output: PathBuf,
},
Lanes,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum GridForm {
Text,
Json,
Toml,
}
pub fn read_grid(path: &Path, form: GridForm, config: &Config) -> Result<DrumGrid> {
let text = if path == Path::new("-") {
let mut buf = String::new();
io::stdin()
.read_to_string(&mut buf)
.context("reading standard input")?;
buf
} else {
fs::read_to_string(path).with_context(|| path.display().to_string())?
};
let grid = match form {
GridForm::Text => {
for notice in &config.text_notices {
eprintln!("duet: {notice}");
}
DrumGrid::from_text_in(&text, &config.text_lanes)?
}
GridForm::Json => normalized(serde_json::from_str(&text)?)?,
GridForm::Toml => normalized(toml::from_str(&text)?)?,
};
Ok(grid)
}
fn normalized(mut grid: DrumGrid) -> duet_drums::Result<DrumGrid> {
grid.normalize()?;
Ok(grid)
}
pub fn write_grid(grid: &DrumGrid, path: &Path, form: GridForm) -> Result<()> {
let bytes = match form {
GridForm::Text => grid.to_text()?.into_bytes(),
GridForm::Json => {
let mut s = serde_json::to_string_pretty(grid)?;
s.push('\n');
s.into_bytes()
}
GridForm::Toml => toml::to_string(grid)?.into_bytes(),
};
if path == Path::new("-") {
io::stdout()
.write_all(&bytes)
.context("writing standard output")?;
} else {
fs::write(path, bytes).with_context(|| path.display().to_string())?;
}
Ok(())
}
pub struct ReadOptions {
pub grid: Grid,
pub track: Option<String>,
pub bars: Option<u32>,
pub snap_levels: bool,
}
pub fn grid_of_song(
song: &Song,
options: &ReadOptions,
form: GridForm,
config: &Config,
) -> Result<DrumGrid> {
let song = with_end(song, config.end)?;
let track = options.track.as_deref();
let drums = DrumGrid::from_song(&song, options.grid, &config.lanes, track, options.bars)?;
let drums = levels_for(drums, options.snap_levels, form)?;
report_left_out(&song, track, &drums);
Ok(drums)
}
pub fn levels_for(grid: DrumGrid, snap_levels: bool, form: GridForm) -> Result<DrumGrid> {
if snap_levels {
return Ok(grid.snapped_to_levels());
}
if form == GridForm::Text
&& let Some((lane, bar, step, vel)) = grid.first_off_level()
{
bail!(
"{lane}, bar {bar}, step {step}: velocity {vel} is not one of the .drums \
text levels; pass --snap-levels to snap velocities to the levels, or \
write the exact form (.drums.json or .drums.toml)"
);
}
Ok(grid)
}
fn refuse_overwrite(input: &Path, output: &Path, what: &str) -> Result<()> {
if input != Path::new("-") && same_file(input, output) {
bail!(
"{} is the input; {what} writes a new file and never changes its input",
output.display()
);
}
Ok(())
}
pub fn run(command: DrumsCommand, config: &Config) -> Result<()> {
match command {
DrumsCommand::Render { input, output, to } => {
refuse_overwrite(&input, &output, "render")?;
let form = grid_form(&input, "render reads")?;
let to = song_format(&output, to, Format::Text, "render writes")?;
write(
&read_grid(&input, form, config)?.to_song()?,
&output,
to,
config.end,
)
}
DrumsCommand::Read {
input,
output,
grid,
track,
bars,
snap_levels,
from,
} => {
refuse_overwrite(&input, &output, "read")?;
let from = song_format(&input, from, Format::Midi, "read reads")?;
let form = grid_form(&output, "read writes")?;
let options = ReadOptions {
grid,
track,
bars,
snap_levels,
};
let drums = grid_of_song(&read(&input, from)?, &options, form, config)?;
write_grid(&drums, &output, form)
}
DrumsCommand::Snap { input, output } => {
refuse_overwrite(&input, &output, "snap")?;
let (from, to) = (
grid_form(&input, "snap reads")?,
grid_form(&output, "snap writes")?,
);
let grid = read_grid(&input, from, config)?;
let snapped = grid.snapped_to_levels();
let moved = moved_velocities(&grid, &snapped);
eprintln!("duet: snapped {moved} velocities to the levels");
write_grid(&snapped, &output, to)
}
DrumsCommand::Lanes => {
let map = &config.lanes;
let mut out = format!("# lane map {}, channel {}\n", map.name(), map.channel());
let width = map.lanes().map(|l| l.name.len()).max().unwrap_or(1);
let groups = map.lanes().map(|l| l.group.len()).max().unwrap_or(1);
for lane in map.lanes() {
let line = format!(
"{:<width$} {:>3} {:<groups$}",
lane.name, lane.key, lane.group
);
if lane.aliases.is_empty() {
out.push_str(line.trim_end());
} else {
out.push_str(&format!("{line} also {}", lane.aliases.join(", ")));
}
out.push('\n');
}
io::stdout()
.write_all(out.as_bytes())
.context("writing standard output")
}
}
}
fn moved_velocities(a: &DrumGrid, b: &DrumGrid) -> usize {
a.bars
.iter()
.zip(&b.bars)
.flat_map(|(x, y)| x.vel.iter().flatten().zip(y.vel.iter().flatten()))
.filter(|(x, y)| x != y)
.count()
}
fn report_left_out(song: &Song, track: Option<&str>, grid: &DrumGrid) {
let drums = match track {
Some(name) => song.tracks.iter().find(|t| t.name == name),
None => song.tracks.iter().find(|t| t.channel == grid.channel),
};
let others = song.tracks.len().saturating_sub(1);
let controls = drums.map_or(0, |t| t.controls.len());
if others > 0 || controls > 0 {
eprintln!(
"duet: read the drum track; left out {others} other track(s), and {controls} \
control(s) on the drum track"
);
}
}
#[cfg(test)]
mod tests {
use crate::tests::run_hermetic;
fn temp(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("duet-drums-{name}-{}", std::process::id()));
std::fs::create_dir_all(&dir).expect("temp dir");
dir
}
fn duet(args: &[&str]) -> anyhow::Result<()> {
run_hermetic(args)
}
#[test]
fn a_grid_renders_to_midi_and_reads_back_the_same() {
let dir = temp("render");
let grid = "grid 1/8\n\n[bars 1-2]\nhh | x x x x x x x x | x x x x x x X . |\nsnare | . . X . . . X g | . . X . . . X . |\nkick | X . . . X X . . | X . . . X . . . |\n";
let input = dir.join("beat.drums");
std::fs::write(&input, grid).expect("write");
let p = |name: &str| dir.join(name).to_str().expect("utf-8").to_owned();
duet(&["drums", "render", &p("beat.drums"), &p("beat.mid")]).expect("render");
duet(&[
"drums",
"read",
&p("beat.mid"),
&p("back.drums"),
"--grid",
"1/8",
])
.expect("read");
let back = std::fs::read_to_string(dir.join("back.drums")).expect("read back");
let want = duet_drums::DrumGrid::from_text(grid).expect("parse");
assert_eq!(
duet_drums::DrumGrid::from_text(&back).expect("parse back"),
want
);
std::fs::remove_dir_all(&dir).expect("clean up");
}
#[test]
fn off_level_velocities_are_refused_as_text_until_snapped() {
let dir = temp("snap");
let song = "[track \"Kit\" ch10]\n1.1.0 C2 0.25 100\n1.2.0 D2 0.25 64\n";
std::fs::write(dir.join("take.notes"), song).expect("write");
let p = |name: &str| dir.join(name).to_str().expect("utf-8").to_owned();
let read = |out: &str, snap: bool| {
let (take, out) = (p("take.notes"), p(out));
let mut args = vec![
"drums",
"read",
take.as_str(),
out.as_str(),
"--grid",
"1/16",
];
if snap {
args.push("--snap-levels");
}
duet(&args)
};
let err = read("take.drums", false).expect_err("100 is not a level");
assert!(err.to_string().contains("--snap-levels"), "{err}");
read("take.drums.json", false).expect("the exact form keeps any velocity");
let exact = std::fs::read_to_string(dir.join("take.drums.json")).expect("json");
assert!(exact.contains("100") && exact.contains("64"), "{exact}");
read("snapped.drums", true).expect("snapped as read");
duet(&[
"drums",
"snap",
&p("take.drums.json"),
&p("snapped-2.drums"),
])
.expect("snap");
let a = std::fs::read_to_string(dir.join("snapped.drums")).expect("a");
let b = std::fs::read_to_string(dir.join("snapped-2.drums")).expect("b");
assert_eq!(a, b, "--snap-levels and drums snap agree");
assert!(a.contains("kick | x"), "{a}");
assert!(a.contains("snare | . . . . g"), "{a}");
std::fs::remove_dir_all(&dir).expect("clean up");
}
}