1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
mod dto;
mod est;
mod live;
mod midi;
mod mos;
mod mts;
mod scala;
mod scale;

use std::{
    fmt::{self, Debug, Display},
    fs::File,
    io::{self, Write},
    path::PathBuf,
};

use est::EstOptions;
use io::Read;
use live::LiveOptions;
use mos::MosCommand;
use mts::MtsOptions;
use scala::{KbmCommand, SclOptions};
use scale::{DiffOptions, DumpOptions, ScaleCommand};
use structopt::StructOpt;
use tune::scala::{KbmBuildError, SclBuildError};

#[doc(hidden)]
pub mod shared;

#[derive(StructOpt)]
struct MainOptions {
    /// Write output to a file instead of stdout
    #[structopt(long = "--of")]
    output_file: Option<PathBuf>,

    #[structopt(subcommand)]
    command: MainCommand,
}

#[derive(StructOpt)]
enum MainCommand {
    /// Create a scale file
    #[structopt(name = "scl")]
    Scl(SclOptions),

    /// Create a keyboard mapping file
    #[structopt(name = "kbm")]
    Kbm(KbmCommand),

    /// Analyze equal-step tunings
    #[structopt(name = "est")]
    Est(EstOptions),

    /// Find MOS scales from generators or vice versa
    #[structopt(name = "mos")]
    Mos(MosCommand),

    /// Print a scale to stdout
    #[structopt(name = "scale")]
    Scale(ScaleCommand),

    /// Display details of a scale
    #[structopt(name = "dump")]
    Dump(DumpOptions),

    /// Display differences between a source scale and a target scale
    #[structopt(name = "diff")]
    Diff(DiffOptions),

    /// Print MIDI Tuning Standard messages and/or send them to MIDI devices
    #[structopt(name = "mts")]
    Mts(MtsOptions),

    /// Enable synthesizers with limited tuning support to be played in any tuning.
    /// This is achieved by reading MIDI data from a sequencer/keyboard and sending modified MIDI data to a synthesizer.
    /// The sequencer/keyboard and synthesizer can be the same device. In this case, remember to disable local keyboard playback.
    #[structopt(name = "live")]
    Live(LiveOptions),

    /// List MIDI devices
    #[structopt(name = "devices")]
    Devices,
}

impl MainOptions {
    fn run(self) -> Result<(), CliError> {
        let stdin = io::stdin();
        let input = Box::new(stdin.lock());

        let stdout = io::stdout();
        let output: Box<dyn Write> = match self.output_file {
            Some(output_file) => Box::new(File::create(output_file)?),
            None => Box::new(stdout.lock()),
        };

        let stderr = io::stderr();
        let error = Box::new(stderr.lock());

        let mut app = App {
            input,
            output,
            error,
        };

        self.command.run(&mut app)
    }
}

impl MainCommand {
    fn run(self, app: &mut App) -> CliResult<()> {
        match self {
            MainCommand::Scl(options) => options.run(app)?,
            MainCommand::Kbm(options) => options.run(app)?,
            MainCommand::Est(options) => options.run(app)?,
            MainCommand::Mos(options) => options.run(app)?,
            MainCommand::Scale(options) => options.run(app)?,
            MainCommand::Dump(options) => options.run(app)?,
            MainCommand::Diff(options) => options.run(app)?,
            MainCommand::Mts(options) => options.run(app)?,
            MainCommand::Live(options) => options.run(app)?,
            MainCommand::Devices => shared::print_midi_devices(&mut app.output, "tune-cli")?,
        }
        Ok(())
    }
}

pub fn run_in_shell_env(args: impl IntoIterator<Item = String>) -> CliResult<()> {
    let options = match MainOptions::from_iter_safe(args) {
        Err(err) => {
            return if err.use_stderr() {
                Err(CliError::CommandError(err.message))
            } else {
                println!("{}", err);
                Ok(())
            };
        }
        Ok(options) => options,
    };

    options.run()
}

pub fn run_in_wasm_env(
    args: impl IntoIterator<Item = String>,
    input: impl Read,
    mut output: impl Write,
    error: impl Write,
) -> CliResult<()> {
    let command = match MainCommand::from_iter_safe(args) {
        Err(err) => {
            return if err.use_stderr() {
                Err(CliError::CommandError(err.message))
            } else {
                output.write_all(err.message.as_bytes())?;
                Ok(())
            }
        }
        Ok(command) => command,
    };

    let mut app = App {
        input: Box::new(input),
        output: Box::new(output),
        error: Box::new(error),
    };

    command.run(&mut app)
}

struct App<'a> {
    input: Box<dyn 'a + Read>,
    output: Box<dyn 'a + Write>,
    error: Box<dyn 'a + Write>,
}

impl App<'_> {
    pub fn write(&mut self, message: impl Display) -> io::Result<()> {
        write!(&mut self.output, "{}", message)
    }

    pub fn writeln(&mut self, message: impl Display) -> io::Result<()> {
        writeln!(&mut self.output, "{}", message)
    }

    pub fn errln(&mut self, message: impl Display) -> io::Result<()> {
        writeln!(&mut self.error, "{}", message)
    }

    pub fn read(&mut self) -> &mut dyn Read {
        &mut self.input
    }
}

pub type CliResult<T> = Result<T, CliError>;

pub enum CliError {
    IoError(io::Error),
    CommandError(String),
}

impl Debug for CliError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CliError::IoError(err) => write!(f, "IO error / {}", err),
            CliError::CommandError(err) => write!(f, "The command failed / {}", err),
        }
    }
}

impl From<String> for CliError {
    fn from(v: String) -> Self {
        CliError::CommandError(v)
    }
}

impl From<SclBuildError> for CliError {
    fn from(v: SclBuildError) -> Self {
        CliError::CommandError(format!("Could not create scale ({:?})", v))
    }
}

impl From<KbmBuildError> for CliError {
    fn from(v: KbmBuildError) -> Self {
        CliError::CommandError(format!("Could not create keybord mapping ({:?})", v))
    }
}

impl From<io::Error> for CliError {
    fn from(v: io::Error) -> Self {
        CliError::IoError(v)
    }
}