diff --git a/Cargo.lock b/Cargo.lock index 35bbe82..efd7253 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -959,6 +959,12 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" +[[package]] +name = "pico-args" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db8bcd96cb740d03149cbad5518db9fd87126a10ab519c011893b1754134c468" + [[package]] name = "pkg-config" version = "0.3.22" @@ -1389,6 +1395,7 @@ dependencies = [ "anyhow", "minifb", "notify", + "pico-args", "wasmtime", ] diff --git a/Cargo.toml b/Cargo.toml index b74e19f..be68e29 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,4 +9,5 @@ edition = "2021" wasmtime = "0.30" anyhow = "1" minifb = "0.19" -notify = "4" \ No newline at end of file +notify = "4" +pico-args = "0.4" \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 1ddedcf..84e60c3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,18 +1,48 @@ -use anyhow::{anyhow, Result}; +use std::path::PathBuf; +use std::sync::mpsc; +use std::time::Duration; + +use anyhow::{bail, Result}; use microw8::MicroW8; +use notify::{DebouncedEvent, Watcher}; +use pico_args::Arguments; mod microw8; fn main() -> Result<()> { - let filename = std::env::args() - .nth(1) - .ok_or_else(|| anyhow!("Missing .uw8 file path"))?; + let mut args = Arguments::from_env(); + + let watch_mode = args.contains(["-w", "--watch"]); + + let filename = args.free_from_os_str::(|s| Ok(s.into()))?; let mut uw8 = MicroW8::new()?; - uw8.load_from_file(filename)?; + let (tx, rx) = mpsc::channel(); + let mut watcher = notify::watcher(tx, Duration::from_millis(100))?; + + if watch_mode { + watcher.watch(&filename, notify::RecursiveMode::NonRecursive)?; + } + + if let Err(err) = uw8.load_from_file(&filename) { + if !watch_mode { + return Err(err); + } + eprintln!("Load error: {}", err); + } while uw8.is_open() { + match rx.try_recv() { + Ok(DebouncedEvent::Create(_) | DebouncedEvent::Write(_)) => { + if let Err(err) = uw8.load_from_file(&filename) { + eprintln!("Load error: {}", err) + } + } + Err(mpsc::TryRecvError::Disconnected) => bail!("File watcher disconnected"), + _ => (), + } + uw8.run_frame()?; }