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
use crate::error::Error;
use crate::layouts::Entry;
use crate::CompiledShaders;
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use std::sync::mpsc::{Receiver, Sender};
use std::thread;
use std::time::Duration;

pub struct Watch {
    _handler: Handler,
    pub rx: Receiver<Result<Message, Error>>,
}

enum Loader {
    Graphics(GraphicsLoader),
    Compute(ComputeLoader),
}

enum SrcPath {
    Graphics(PathBuf, PathBuf),
    Compute(PathBuf),
}

struct GraphicsLoader {
    vertex: PathBuf,
    fragment: PathBuf,
    tx: Sender<Result<Message, Error>>,
}

struct ComputeLoader {
    compute: PathBuf,
    tx: Sender<Result<Message, Error>>,
}

pub struct Message {
    pub shaders: CompiledShaders,
    pub entry: Entry,
}

impl Watch {
    /// Paths to the vertex and fragment shaders.
    /// Frequency is how often the watcher will check the directory.
    pub fn create<T>(vertex: T, fragment: T, frequency: Duration) -> Result<Self, Error>
    where
        T: AsRef<Path>,
    {
        let src_path = SrcPath::Graphics(
            vertex.as_ref().to_path_buf(),
            fragment.as_ref().to_path_buf()
            );
        let (handler, rx) = create_watch(
            src_path,
            frequency,
        )?;
        Ok(Watch {
            _handler: handler,
            rx,
        })
    }

    pub fn create_compute<T>(compute: T, frequency: Duration) -> Result<Self, Error>
    where
        T: AsRef<Path>,
    {
        let src_path = SrcPath::Compute(
            compute.as_ref(). to_path_buf());
        let (handler, rx) = create_watch(
            src_path,
            frequency,
        )?;
        Ok(Watch {
            _handler: handler,
            rx,
        })
    }
}

impl GraphicsLoader {
    fn create(vertex: PathBuf, fragment: PathBuf) -> (Self, Receiver<Result<Message, Error>>) {
        let (tx, rx) = mpsc::channel();
        let loader = GraphicsLoader {
            vertex,
            fragment,
            tx,
        };
        loader.reload();
        (loader, rx)
    }

    fn reload(&self) {
        match crate::load(&self.vertex, &self.fragment) {
            Ok(shaders) => {
                let entry = crate::parse(&shaders);
                let msg = entry.map(|entry| Message { shaders, entry });
                self.tx.send(msg).ok()
            }
            Err(e) => self.tx.send(Err(e)).ok(),
        };
    }
}

impl ComputeLoader {
    fn create(compute: PathBuf) -> (Self, Receiver<Result<Message, Error>>) {
        let (tx, rx) = mpsc::channel();
        let loader = ComputeLoader {
            compute,
            tx,
        };
        loader.reload();
        (loader, rx)
    }

    fn reload(&self) {
        match crate::load_compute(&self.compute) {
            Ok(shaders) => {
                let entry = crate::parse_compute(&shaders);
                let msg = entry.map(|entry| Message { shaders, entry });
                self.tx.send(msg).ok()
            }
            Err(e) => self.tx.send(Err(e)).ok(),
        };
    }
}

impl Loader {
    fn reload(&self) {
        match self {
            Loader::Graphics(g) => g.reload(),
            Loader::Compute(g) => g.reload(),
        }
    }
}

struct Handler {
    thread_tx: mpsc::Sender<()>,
    handle: Option<thread::JoinHandle<()>>,
    _watcher: RecommendedWatcher,
}

impl Drop for Handler {
    fn drop(&mut self) {
        self.thread_tx.send(()).ok();
        if let Some(h) = self.handle.take() {
            h.join().ok();
        }
    }
}

fn create_watch(
    src_path: SrcPath,
    frequency: Duration
) -> Result<(Handler, mpsc::Receiver<Result<Message, Error>>), Error> {
    let (notify_tx, notify_rx) = mpsc::channel();
    let (thread_tx, thread_rx) = mpsc::channel();
    let mut watcher: RecommendedWatcher =
        Watcher::new(notify_tx, frequency).map_err(Error::FileWatch)?;

    let (loader, rx) = match src_path {
        SrcPath::Graphics(vert_path, frag_path) => {
            let mut vp = vert_path.clone();
            let mut fp = frag_path.clone();
            vp.pop();
            fp.pop();
            watcher
                .watch(&vp, RecursiveMode::NonRecursive)
                .map_err(Error::FileWatch)?;
            if vp != fp {
                watcher
                    .watch(&fp, RecursiveMode::NonRecursive)
                    .map_err(Error::FileWatch)?;
            }

            let (loader, rx) = GraphicsLoader::create(vert_path, frag_path);
            (Loader::Graphics(loader), rx)
        }
        SrcPath::Compute(compute_path) => {
            let mut cp = compute_path.clone();
            cp.pop();
            watcher
                .watch(&cp, RecursiveMode::NonRecursive)
                .map_err(Error::FileWatch)?;

            let (loader, rx) = ComputeLoader::create(compute_path);
            (Loader::Compute(loader), rx)
        }
    };


    let handle = thread::spawn(move || 'watch_loop: loop {
        if thread_rx.try_recv().is_ok() {
            break 'watch_loop;
        }
        if let Ok(notify::DebouncedEvent::Create(_)) | Ok(notify::DebouncedEvent::Write(_)) =
            notify_rx.recv_timeout(Duration::from_secs(1))
        {
            loader.reload();
        }
    });
    let handle = Some(handle);
    let handler = Handler {
        thread_tx,
        handle,
        _watcher: watcher,
    };
    Ok((handler, rx))
}