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
use std::{path::Path, sync::mpsc::Receiver};

use crate::*;
use notify::{event::AccessKind, Event, EventKind, RecursiveMode, Watcher};

pub struct HotReload {
    rx: Receiver<Result<Event, notify::Error>>,
    watcher: notify::RecommendedWatcher,
}

impl HotReload {
    pub fn new() -> Self {
        println!("SHADER HOT RELOADING ENABLED!");

        let (tx, rx) = std::sync::mpsc::channel();

        let watcher =
            notify::RecommendedWatcher::new(tx, Default::default()).unwrap();


        let mut x = Self { rx, watcher };

        x.watch_path(Path::new(&concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../assets/shaders"
        )))
        .unwrap();

        x
    }

    pub fn watch_path(&mut self, path: &Path) -> Result<()> {
        self.watcher.watch(path, RecursiveMode::Recursive)?;
        Ok(())
    }

    pub fn maybe_reload_shaders(&self) -> bool {
        let mut reload = false;

        if let Ok(maybe_event) = self.rx.try_recv() {
            match maybe_event {
                Ok(event) => {
                    let is_close_write = matches!(
                        event.kind,
                        EventKind::Access(AccessKind::Close(
                            notify::event::AccessMode::Write
                        ))
                    );

                    let is_temp = event
                        .paths
                        .iter()
                        .all(|p| p.to_string_lossy().ends_with('~'));

                    if is_close_write && !is_temp {
                        reload = true;
                        // println!("Got watch {:?}", event);
                    }
                }

                Err(err) => eprintln!("Error: {:?}", err),
            }
        }

        reload
    }
}