use std::io::{self, 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, FormatParser, grid_document, grid_path, read, read_grid_document, same_file,
song_format, with_end, write, write_bytes,
};
#[derive(Subcommand)]
pub enum DrumsCommand {
Render {
input: PathBuf,
output: PathBuf,
#[arg(long, value_parser = FormatParser)]
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_parser = FormatParser)]
from: Option<Format>,
},
Snap {
input: PathBuf,
output: PathBuf,
},
Lanes,
}
pub fn read_grid(path: &Path, what: &str) -> Result<DrumGrid> {
read_grid_document(path, what)
}
pub fn write_grid(grid: &DrumGrid, path: &Path, what: &str) -> Result<()> {
grid_path(path, what)?;
write_bytes(path, grid_document(grid)?.as_bytes())
}
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, 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 = if options.snap_levels {
drums.snapped_to_levels()
} else {
drums
};
report_left_out(&song, track, &drums);
Ok(drums)
}
pub fn levels_for(grid: DrumGrid, snap_levels: bool) -> Result<DrumGrid> {
if snap_levels {
return Ok(grid.snapped_to_levels());
}
if let Some((lane, bar, step, vel)) = grid.first_off_level() {
bail!(
"{lane}, bar {bar}, step {step}: velocity {vel} is not one of the grid view's \
levels; pass --snap-levels to show velocities snapped to the levels (apply --onto \
keeps each exact where its level is unchanged)"
);
}
Ok(grid)
}
pub 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 to = song_format(&output, to, "render writes")?;
write(
&read_grid(&input, "render reads")?.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, "read reads")?;
grid_path(&output, "read writes")?;
let options = ReadOptions {
grid,
track,
bars,
snap_levels,
};
let drums = grid_of_song(&read(&input, from, "read reads")?, &options, config)?;
write_grid(&drums, &output, "read writes")
}
DrumsCommand::Snap { input, output } => {
refuse_overwrite(&input, &output, "snap")?;
grid_path(&output, "snap writes")?;
let grid = read_grid(&input, "snap reads")?;
let snapped = grid.snapped_to_levels();
let moved = moved_velocities(&grid, &snapped);
eprintln!("duet: snapped {moved} velocities to the levels");
write_grid(&snapped, &output, "snap writes")
}
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")
}
}
}
pub fn moved_velocities(a: &DrumGrid, b: &DrumGrid) -> usize {
a.vel
.data()
.iter()
.zip(b.vel.data())
.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 std::path::{Path, PathBuf};
use duet_core::Song;
use duet_drums::DrumGrid;
use duet_schemas::Document;
use crate::io::{grid_document, read_grid_document, tool};
use crate::tests::run_hermetic;
fn temp(name: &str) -> 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)
}
fn grid_at(path: &Path) -> DrumGrid {
read_grid_document(path, "reads").expect("a drum-grid document")
}
#[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 want = DrumGrid::from_text(grid).expect("parse");
std::fs::write(
dir.join("beat.duet"),
grid_document(&want).expect("document"),
)
.expect("write");
let p = |name: &str| dir.join(name).to_str().expect("utf-8").to_owned();
duet(&["drums", "render", &p("beat.duet"), &p("beat.mid")]).expect("render");
duet(&[
"drums",
"read",
&p("beat.mid"),
&p("back.duet"),
"--grid",
"1/8",
])
.expect("read");
assert_eq!(grid_at(&dir.join("back.duet")), want);
std::fs::remove_dir_all(&dir).expect("clean up");
}
#[test]
fn off_level_velocities_are_refused_in_the_view_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";
let song = Song::from_text(song).expect("parse");
std::fs::write(
dir.join("take.duet"),
Document::new(tool(), song).write().expect("document"),
)
.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.duet"), 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 view = |of: &str, out: &str| duet(&["view", &p(of), "--as", "grid", "-o", &p(out)]);
read("exact.duet", false).expect("a document keeps 100");
let exact = grid_at(&dir.join("exact.duet"));
assert_eq!(exact.vel.data().iter().filter(|&&v| v == 100).count(), 1);
let err = view("exact.duet", "exact.drums").expect_err("100 is not a level");
assert!(err.to_string().contains("--snap-levels"), "{err}");
assert!(!dir.join("exact.drums").exists(), "nothing is written");
read("snapped.duet", true).expect("snapped as read");
duet(&["drums", "snap", &p("snapped.duet"), &p("snapped-2.duet")]).expect("snap");
let (a, b) = (
grid_at(&dir.join("snapped.duet")),
grid_at(&dir.join("snapped-2.duet")),
);
assert_eq!(a, b, "a snapped grid snaps to itself");
view("snapped.duet", "snapped.drums").expect("a snapped grid has a view");
let a = std::fs::read_to_string(dir.join("snapped.drums")).expect("a");
assert!(a.contains("kick | x"), "{a}");
assert!(a.contains("snare | . . . . g"), "{a}");
std::fs::remove_dir_all(&dir).expect("clean up");
}
}