wavegraph-remote 0.1.0

MIDI control and live graph discovery for WaveGraph
Documentation
//! Argument parsing shared by one-shot commands and the interactive prompt.

use clap::{Parser, Subcommand};
use std::io;

/// Connect to a running WaveGraph over USB MIDI.
#[derive(Debug, Parser)]
#[command(name = "wr", version, disable_help_subcommand = true)]
pub(super) struct Args {
    /// USB MIDI port name or substring. Ambiguous matches are rejected.
    #[arg(long, global = true)]
    pub port: Option<String>,

    /// Initial MIDI channel, numbered 1 through 16.
    #[arg(long, short, global = true, default_value_t = 1, value_parser = clap::value_parser!(u8).range(1..=16))]
    pub channel: u8,

    /// Seconds to wait for a graph response.
    #[arg(long, global = true, default_value_t = 2, value_parser = clap::value_parser!(u64).range(1..=60))]
    pub timeout: u64,

    /// Omit the command to open an interactive session.
    #[command(subcommand)]
    pub command: Option<Command>,
}

#[derive(Debug, Parser)]
#[command(name = "wr", no_binary_name = true, disable_help_subcommand = true)]
struct Line {
    #[command(subcommand)]
    command: Command,
}

/// Commands operate on the selected channel unless they take an explicit alias.
#[derive(Debug, Subcommand)]
pub(super) enum Command {
    /// Open an interactive session (also the default).
    Repl,
    /// Show the running graph's nodes, connections and outputs.
    Graph,
    /// List live process instances and their MIDI channels.
    #[command(alias = "instruments")]
    Nodes,
    /// Describe a live process instance and its ports.
    Inspect {
        /// Exact alias from `nodes`.
        alias: String,
    },
    /// Select an instance's current MIDI channel, or a channel number.
    Select {
        /// Exact alias from `nodes`, or a channel numbered 1 through 16.
        target: String,
    },
    /// Show or change the session's selected MIDI channel.
    Channel {
        /// MIDI channel, numbered 1 through 16.
        #[arg(value_parser = clap::value_parser!(u8).range(1..=16))]
        number: Option<u8>,
    },
    /// Start playback from the beginning using MIDI Start.
    Play,
    /// Stop playback using MIDI Stop.
    Stop,
    /// Audition a note, then send its note-off.
    Note {
        /// MIDI note number; middle C is 60.
        #[arg(value_parser = clap::value_parser!(u8).range(0..=127))]
        number: u8,
        /// Strike velocity.
        #[arg(default_value_t = 100, value_parser = clap::value_parser!(u8).range(1..=127))]
        velocity: u8,
        /// Duration in milliseconds, timed by the host.
        #[arg(default_value_t = 250, value_parser = clap::value_parser!(u64).range(1..=60_000))]
        duration_ms: u64,
    },
    /// Send a note-on; use `off` to release it.
    On {
        /// MIDI note number.
        #[arg(value_parser = clap::value_parser!(u8).range(0..=127))]
        number: u8,
        /// Strike velocity.
        #[arg(default_value_t = 100, value_parser = clap::value_parser!(u8).range(1..=127))]
        velocity: u8,
    },
    /// Send a note-off.
    Off {
        /// MIDI note number.
        #[arg(value_parser = clap::value_parser!(u8).range(0..=127))]
        number: u8,
    },
    /// Send a MIDI control change.
    Cc {
        /// Controller number.
        #[arg(value_parser = clap::value_parser!(u8).range(0..=127))]
        controller: u8,
        /// Controller value.
        #[arg(value_parser = clap::value_parser!(u8).range(0..=127))]
        value: u8,
    },
    /// Send All Notes Off (CC 123) on the selected channel.
    Panic,
    /// Show the command reference.
    Help,
    /// Leave the session, releasing notes started by this REPL.
    #[command(alias = "exit")]
    Quit,
}

pub(super) fn parse_line(line: &str) -> io::Result<Option<Result<Command, clap::Error>>> {
    let words = words(line)?;
    if words.is_empty() {
        Ok(None)
    } else {
        Ok(Some(Line::try_parse_from(words).map(|line| line.command)))
    }
}

// A small tokenizer, not a shell: quotes group aliases and backslashes quote
// the next character. There is no expansion, command substitution or execution.
fn words(line: &str) -> io::Result<Vec<String>> {
    let mut result = Vec::new();
    let mut word = String::new();
    let mut quote = None;
    let mut escaped = false;
    let mut started = false;
    for ch in line.chars() {
        if escaped {
            word.push(ch);
            escaped = false;
            continue;
        }
        match (quote, ch) {
            (Some('\''), '\'') | (Some('"'), '"') => quote = None,
            (Some('\''), _) => word.push(ch),
            (_, '\\') => {
                escaped = true;
                started = true;
            }
            (Some(_), _) => word.push(ch),
            (None, '\'' | '"') => {
                quote = Some(ch);
                started = true;
            }
            (None, '#') if !started => break,
            (None, ch) if ch.is_whitespace() => {
                if started {
                    result.push(core::mem::take(&mut word));
                    started = false;
                }
            }
            (None, _) => {
                word.push(ch);
                started = true;
            }
        }
    }
    if quote.is_some() || escaped {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "unfinished quote or escape",
        ));
    }
    if started {
        result.push(word);
    }
    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rejects_out_of_range_midi_before_connecting() {
        for args in [
            vec!["wr", "--channel", "0", "on", "60"],
            vec!["wr", "--channel", "17", "on", "60"],
            vec!["wr", "on", "128"],
            vec!["wr", "on", "60", "0"],
            vec!["wr", "off", "128"],
            vec!["wr", "cc", "128", "0"],
            vec!["wr", "cc", "74", "128"],
        ] {
            assert!(Args::try_parse_from(args).is_err());
        }
        assert!(Args::try_parse_from(["wr", "--channel", "16", "cc", "127", "127"]).is_ok());
    }

    #[test]
    fn defaults_to_a_repl_and_bounded_audition() -> io::Result<()> {
        let args = Args::try_parse_from(["wr"]).map_err(io::Error::other)?;
        assert!(args.command.is_none());
        assert_eq!(args.channel, 1);
        assert!(matches!(
            parse_line("note 60")?,
            Some(Ok(Command::Note {
                number: 60,
                velocity: 100,
                duration_ms: 250,
            }))
        ));
        Ok(())
    }

    #[test]
    fn repl_handles_aliases_comments_and_parse_errors() -> io::Result<()> {
        assert_eq!(
            words("select 'bass voice' # comment")?,
            ["select", "bass voice"]
        );
        assert_eq!(words("select bass\\ voice")?, ["select", "bass voice"]);
        assert!(parse_line("  # comment")?.is_none());
        assert!(matches!(parse_line("cc 74 128")?, Some(Err(_))));
        assert!(matches!(parse_line("on 60 100 extra")?, Some(Err(_))));
        assert!(words("select 'unfinished").is_err());
        assert!(words("select trailing\\").is_err());
        Ok(())
    }
}