From c2dbbf36c078533705458c28dd5c2f138a830474 Mon Sep 17 00:00:00 2001 From: Hanno Braun Date: Fri, 18 Mar 2022 15:03:26 +0100 Subject: [PATCH] Add `model::Watcher` --- fj-app/src/main.rs | 22 +++++----------------- fj-app/src/model.rs | 32 +++++++++++++++++++++++++++++--- 2 files changed, 34 insertions(+), 20 deletions(-) diff --git a/fj-app/src/main.rs b/fj-app/src/main.rs index 95afd60ad..b3cbbeda0 100644 --- a/fj-app/src/main.rs +++ b/fj-app/src/main.rs @@ -8,7 +8,7 @@ mod model; mod window; use std::path::PathBuf; -use std::{collections::HashMap, sync::mpsc, time::Instant}; +use std::{collections::HashMap, time::Instant}; use fj_debug::DebugInfo; use fj_math::{Aabb, Scalar, Triangle}; @@ -130,8 +130,7 @@ fn main() -> anyhow::Result<()> { return Ok(()); } - let (watcher_tx, watcher_rx) = mpsc::sync_channel(0); - let _watcher = model.watch(watcher_tx, parameters)?; + let watcher = model.watch(parameters)?; let event_loop = EventLoop::new(); let window = Window::new(&event_loop); @@ -154,20 +153,9 @@ fn main() -> anyhow::Result<()> { let now = Instant::now(); - match watcher_rx.try_recv() { - Ok(shape) => { - processed_shape = shape_processor.process(&shape); - processed_shape.update_geometry(&mut renderer); - } - Err(mpsc::TryRecvError::Empty) => { - // Nothing to receive from the channel. We don't care. - } - Err(mpsc::TryRecvError::Disconnected) => { - // The other end has disconnected. This is probably the result - // of a panic on the other thread, or a program shutdown in - // progress. In any case, not much we can do here. - panic!(); - } + if let Some(shape) = watcher.receive() { + processed_shape = shape_processor.process(&shape); + processed_shape.update_geometry(&mut renderer); } match event { diff --git a/fj-app/src/model.rs b/fj-app/src/model.rs index c426d59d7..89b5dcd68 100644 --- a/fj-app/src/model.rs +++ b/fj-app/src/model.rs @@ -97,9 +97,9 @@ impl Model { pub fn watch( self, - tx: mpsc::SyncSender, parameters: HashMap, - ) -> Result { + ) -> Result { + let (tx, rx) = mpsc::sync_channel(0); let watch_path = self.src_path.clone(); let mut watcher = notify::recommended_watcher( @@ -169,7 +169,33 @@ impl Model { watcher.watch(&watch_path, notify::RecursiveMode::Recursive)?; - Ok(watcher) + Ok(Watcher { + _watcher: Box::new(watcher), + channel: rx, + }) + } +} + +pub struct Watcher { + _watcher: Box, + channel: mpsc::Receiver, +} + +impl Watcher { + pub fn receive(&self) -> Option { + match self.channel.try_recv() { + Ok(shape) => Some(shape), + Err(mpsc::TryRecvError::Empty) => { + // Nothing to receive from the channel. + None + } + Err(mpsc::TryRecvError::Disconnected) => { + // The other end has disconnected. This is probably the result + // of a panic on the other thread, or a program shutdown in + // progress. In any case, not much we can do here. + panic!(); + } + } } }