wavegraph-remote 0.1.1

MIDI control and live graph discovery for WaveGraph
Documentation
//! Stateful command-line client for a running WaveGraph.
#![forbid(unsafe_code)]

#[path = "wr/commands.rs"]
mod commands;

#[cfg(test)]
#[path = "wr/tests.rs"]
mod tests;

use clap::{CommandFactory, Parser};
use commands::{Args, Command};
use core::time::Duration;
use miniline::{Config, DefaultEditor, error::ReadlineError};
use std::{
    io::{self, BufRead, IsTerminal as _, Write},
    process::ExitCode,
    thread,
};
use wavegraph_remote::{Channel, Client, Graph, MidiCommand, PortKind, Transport};

fn main() -> ExitCode {
    let args = Args::parse();
    #[cfg(feature = "fm1")]
    if let Err(error) = args.validate_transport() {
        error.exit();
    }
    match run(args) {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => {
            eprintln!("wr: {error}");
            ExitCode::FAILURE
        }
    }
}

fn run(args: Args) -> io::Result<()> {
    let stdout = io::stdout();
    let mut output = stdout.lock();
    if matches!(args.command, Some(Command::Help)) {
        return help(&mut output);
    }
    if matches!(args.command, Some(Command::Quit)) {
        return Ok(());
    }
    #[cfg(feature = "fm1")]
    if args.fm1 {
        let transport = wavegraph_remote::UsbTransport::connect(
            args.port.as_deref(),
            Duration::from_secs(args.timeout),
        )?;
        return run_session(args, transport, &mut output);
    }
    #[cfg(unix)]
    {
        let path = wavegraph_remote::socket_path(args.socket.as_deref())?;
        let transport =
            wavegraph_remote::UnixTransport::connect(path, Duration::from_secs(args.timeout))?;
        run_session(args, transport, &mut output)
    }
    #[cfg(not(unix))]
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "local DSP control requires Unix",
    ))
}

fn run_session(args: Args, transport: impl Transport, output: &mut impl Write) -> io::Result<()> {
    let mut session = Session {
        client: Client::new(transport),
        channel: Channel::new(args.channel)?,
        timeout: Duration::from_secs(args.timeout),
        held: Vec::new(),
    };
    match args.command {
        None | Some(Command::Repl) => {
            let result = session.repl(output);
            let cleanup = session.release_notes();
            match (result, cleanup) {
                (Ok(()), result) => result,
                (Err(error), Ok(())) => Err(error),
                (Err(error), Err(cleanup)) => Err(io::Error::other(format!(
                    "{error}; releasing held notes also failed: {cleanup}"
                ))),
            }
        }
        Some(command) => session.execute(command, output).map(|_| ()),
    }
}

struct Session<T: Transport> {
    client: Client<T>,
    channel: Channel,
    timeout: Duration,
    // Track the actual channel for every successful note-on, so changing the
    // selection does not strand a note during graceful REPL shutdown.
    held: Vec<(Channel, u8)>,
}

impl<T: Transport> Session<T> {
    fn repl(&mut self, output: &mut impl Write) -> io::Result<()> {
        let stdin = io::stdin();
        if !stdin.is_terminal() || !io::stdout().is_terminal() {
            return self.repl_stream(stdin.lock(), output);
        }

        let config = Config::builder().auto_add_history(true).build();
        let mut editor = DefaultEditor::with_config(config).map_err(io::Error::other)?;
        writeln!(
            output,
            "WaveGraph remote. Type help for commands, quit to leave."
        )?;
        loop {
            let prompt = format!("wr[ch{}]> ", self.channel.number());
            let line = match editor.readline(&prompt) {
                Ok(line) => line,
                Err(ReadlineError::Eof | ReadlineError::Interrupted) => return Ok(()),
                Err(error) => return Err(io::Error::other(error)),
            };
            if self.execute_line(&line, output)? {
                return Ok(());
            }
        }
    }

    fn repl_stream(&mut self, mut input: impl BufRead, output: &mut impl Write) -> io::Result<()> {
        let mut line = String::new();
        while input.read_line(&mut line)? != 0 {
            if self.execute_line(&line, output)? {
                break;
            }
            line.clear();
        }
        Ok(())
    }

    fn execute_line(&mut self, line: &str, output: &mut impl Write) -> io::Result<bool> {
        match commands::parse_line(line) {
            Ok(None) => (),
            Ok(Some(Ok(command))) => match self.execute(command, output) {
                Ok(quit) => return Ok(quit),
                Err(error) => writeln!(output, "wr: {error}")?,
            },
            Ok(Some(Err(error))) => write!(output, "{error}")?,
            Err(error) => writeln!(output, "wr: {error}")?,
        }
        Ok(false)
    }

    // A true result means that the user requested a graceful exit.
    fn execute(&mut self, command: Command, output: &mut impl Write) -> io::Result<bool> {
        match command {
            Command::Repl => {
                writeln!(output, "Already in an interactive session.")?;
            }
            Command::Graph => {
                let graph = self.client.graph(self.timeout)?;
                writeln!(
                    output,
                    "Session {}  revision {}  frame {}",
                    graph.session, graph.revision, graph.first_frame,
                )?;
                nodes(&graph, output)?;
                writeln!(output, "\nConnections:")?;
                let connections = graph.connections()?;
                if connections.is_empty() {
                    writeln!(output, "  (none)")?;
                }
                for connection in connections {
                    writeln!(
                        output,
                        "  {} -> {}",
                        label(&connection.source),
                        label(&connection.destination),
                    )?;
                }
                write!(output, "Outputs:")?;
                for bus in graph.outputs {
                    write!(output, " bus{bus}")?;
                }
                writeln!(output)?;
            }
            Command::Nodes => nodes(&self.client.graph(self.timeout)?, output)?,
            Command::Inspect { alias } => self.inspect(&alias, output)?,
            Command::Select { target } => self.select(&target, output)?,
            Command::Channel { number } => {
                if let Some(number) = number {
                    self.channel = Channel::new(number)?;
                }
                writeln!(output, "Channel {}", self.channel.number())?;
            }
            Command::Play => {
                self.client.send(MidiCommand::Play)?;
                writeln!(output, "Sent MIDI Start.")?;
            }
            Command::Stop => {
                self.client.send(MidiCommand::Stop)?;
                writeln!(output, "Sent MIDI Stop.")?;
            }
            Command::Note {
                number,
                velocity,
                duration_ms,
            } => {
                self.note_on(number, velocity)?;
                thread::sleep(Duration::from_millis(duration_ms));
                self.note_off(number)?;
                writeln!(
                    output,
                    "Sent note {number} on channel {} ({duration_ms} ms).",
                    self.channel.number(),
                )?;
            }
            Command::On { number, velocity } => self.note_on(number, velocity)?,
            Command::Off { number } => self.note_off(number)?,
            Command::Cc { controller, value } => {
                self.client.send(MidiCommand::ControlChange {
                    channel: self.channel,
                    controller,
                    value,
                })?;
            }
            Command::Panic => {
                self.client.send(MidiCommand::AllNotesOff {
                    channel: self.channel,
                })?;
                self.held.retain(|(channel, _)| *channel != self.channel);
                writeln!(
                    output,
                    "Sent All Notes Off on channel {}.",
                    self.channel.number()
                )?;
            }
            Command::Help => help(output)?,
            Command::Quit => return Ok(true),
        }
        Ok(false)
    }

    fn select(&mut self, target: &str, output: &mut impl Write) -> io::Result<()> {
        if !target.is_empty() && target.bytes().all(|byte| byte.is_ascii_digit()) {
            let number = target.parse().map_err(|_| {
                io::Error::new(io::ErrorKind::InvalidInput, "channel must be in 1..=16")
            })?;
            self.channel = Channel::new(number)?;
            return writeln!(output, "Selected channel {}.", self.channel.number());
        }
        let graph = self.client.graph(self.timeout)?;
        let node = graph.node(target).ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::NotFound,
                format!(
                    "unknown instance {}; use nodes to list aliases",
                    label(target)
                ),
            )
        })?;
        let channel = node.midi_channel.ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("{} has no MIDI channel", label(target)),
            )
        })?;
        self.channel = channel;
        writeln!(
            output,
            "Selected {} on channel {}. Selection follows the channel if its instrument changes.",
            label(&node.alias),
            channel.number(),
        )
    }

    fn inspect(&mut self, alias: &str, output: &mut impl Write) -> io::Result<()> {
        let graph = self.client.graph(self.timeout)?;
        let node = graph.node(alias).ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::NotFound,
                format!(
                    "unknown instance {}; use nodes to list aliases",
                    label(alias)
                ),
            )
        })?;
        writeln!(
            output,
            "{}: {} (node {}, generation {})",
            label(&node.alias),
            label(&node.kind),
            node.id,
            node.generation,
        )?;
        match node.midi_channel {
            Some(channel) => writeln!(output, "MIDI channel: {}", channel.number())?,
            None => writeln!(output, "MIDI channel: none")?,
        }
        for (index, kind) in node.inlets.iter().enumerate() {
            writeln!(output, "  in{index}: {}", port_kind(*kind))?;
        }
        for (index, kind) in node.outlets.iter().enumerate() {
            writeln!(output, "  out{index}: {}", port_kind(*kind))?;
        }
        Ok(())
    }

    fn note_on(&mut self, note: u8, velocity: u8) -> io::Result<()> {
        self.client.send(MidiCommand::NoteOn {
            channel: self.channel,
            note,
            velocity,
        })?;
        self.held.push((self.channel, note));
        Ok(())
    }

    fn note_off(&mut self, note: u8) -> io::Result<()> {
        self.client.send(MidiCommand::NoteOff {
            channel: self.channel,
            note,
        })?;
        if let Some(index) = self
            .held
            .iter()
            .position(|held| *held == (self.channel, note))
        {
            self.held.remove(index);
        }
        Ok(())
    }

    fn release_notes(&mut self) -> io::Result<()> {
        let mut first_error = None;
        while let Some((channel, note)) = self.held.pop() {
            if let Err(error) = self.client.send(MidiCommand::NoteOff { channel, note }) {
                first_error.get_or_insert(error);
            }
        }
        first_error.map_or(Ok(()), Err)
    }
}

fn nodes(graph: &Graph, output: &mut impl Write) -> io::Result<()> {
    writeln!(
        output,
        " ID  ALIAS             KIND              MIDI  IN  OUT"
    )?;
    for node in &graph.nodes {
        let channel = node
            .midi_channel
            .map_or_else(|| "-".into(), |channel| channel.number().to_string());
        writeln!(
            output,
            "{:>3}  {:<16}  {:<16}  {:>4}  {:>2}  {:>3}",
            node.id,
            label(&node.alias),
            label(&node.kind),
            channel,
            node.inlets.len(),
            node.outlets.len(),
        )?;
    }
    Ok(())
}

const fn port_kind(kind: PortKind) -> &'static str {
    match kind {
        PortKind::Signal => "signal",
        PortKind::Message => "message",
    }
}

// Device-provided labels must not become terminal control sequences.
fn label(value: &str) -> String {
    let mut result = String::new();
    for ch in value.chars() {
        if ch.is_control() {
            result.extend(ch.escape_default());
        } else {
            result.push(ch);
        }
    }
    result
}

fn help(output: &mut impl Write) -> io::Result<()> {
    Args::command().write_long_help(output)?;
    writeln!(
        output,
        "\n\nREPL selection is local to wr. MIDI channels are numbered 1 through 16.\n\
         select chooses a channel; it does not reassign the instrument on the device.\n\
         note durations use the host clock. on holds a note until off or REPL exit.\n\
         Graceful REPL exit releases only notes started by that session.\n\
         Aliases containing spaces can be quoted; # starts a comment between words.",
    )
}