From f9e304f45ee4b469565e190d376c5a26403f87d5 Mon Sep 17 00:00:00 2001 From: Connor Slade Date: Sat, 25 Nov 2023 23:49:26 -0500 Subject: [PATCH] Default config --- README.md | 1 + src/main.rs | 30 +++++++++++++++++++++++------- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 0b5820a..aaefa88 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,7 @@ makey-midi --debug connect "Microsoft GS Wavetable Synth" ## Config Below is an example `config.toml` file. +If no config file is found when running, makey-midi will fall back to the default config shown below. The `channel` defined what channel the midi events are sent on. The `keymap` is the main part where you map keyboard keys to midi notes. A list of all possible key values is in the dropdown below, and a table of midi notes can be found [here](https://www.inspiredacoustics.com/en/MIDI_note_numbers_and_center_frequencies). diff --git a/src/main.rs b/src/main.rs index b654f1d..f7a799e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,6 +10,8 @@ use crate::{args::Args, config::Config}; mod args; mod config; +const DEFAULT_CONFIG: &str = include_str!("../config.toml"); + struct MakeyMidi { debug: bool, config: Config, @@ -19,25 +21,24 @@ struct MakeyMidi { fn main() -> Result<()> { let args = Args::parse(); - - let raw_config = - fs::read_to_string(args.config.unwrap_or_else(|| PathBuf::from("config.toml")))?; - let config = toml::from_str::(&raw_config)?; + let config = load_config(args.config.unwrap_or_else(|| PathBuf::from("config.toml")))?; + let output = args.midi.midi_device()?; let mut app = MakeyMidi { debug: args.debug, config, - output: args.midi.midi_device()?, + output, pressed: HashSet::new(), }; - if let Err(error) = listen(move |x| callback(&mut app, x)) { + + if let Err(error) = listen(move |x| key_handler(&mut app, x)) { println!("[E] Rdev error: {:?}", error) } Ok(()) } -fn callback(app: &mut MakeyMidi, event: Event) { +fn key_handler(app: &mut MakeyMidi, event: Event) { let event = match event.event_type { EventType::KeyPress(e) => { if !app.pressed.insert(e) { @@ -77,3 +78,18 @@ fn callback(app: &mut MakeyMidi, event: Event) { let _ = app.output.send(&buf); } } + +fn load_config(path: PathBuf) -> Result { + let raw_config = match fs::read_to_string(path) { + Ok(x) => x, + Err(error) => { + println!("[E] Failed to read config file: {:?}", error); + println!("[I] Using default config and writing to disk"); + if let Err(e) = fs::write("config.toml", DEFAULT_CONFIG) { + println!("[E] Failed to write default config: {:?}", e); + } + DEFAULT_CONFIG.to_owned() + } + }; + Ok(toml::from_str(&raw_config)?) +}