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
#[cfg(feature = "filesystem_watcher")]
use crate::{filesystem_watcher::FilesystemWatcher, AssetServer};
use crate::{AssetIo, AssetIoError, Metadata};
use anyhow::Result;
#[cfg(feature = "filesystem_watcher")]
use bevy_ecs::system::Res;
use bevy_utils::BoxedFuture;
#[cfg(feature = "filesystem_watcher")]
use bevy_utils::HashSet;
#[cfg(feature = "filesystem_watcher")]
use crossbeam_channel::TryRecvError;
use fs::File;
#[cfg(feature = "filesystem_watcher")]
use parking_lot::RwLock;
#[cfg(feature = "filesystem_watcher")]
use std::sync::Arc;
use std::{
    convert::TryFrom,
    env, fs,
    io::Read,
    path::{Path, PathBuf},
};

/// I/O implementation for the local filesystem.
///
/// This asset I/O is fully featured but it's not available on `android` and `wasm` targets.
pub struct FileAssetIo {
    root_path: PathBuf,
    #[cfg(feature = "filesystem_watcher")]
    filesystem_watcher: Arc<RwLock<Option<FilesystemWatcher>>>,
}

impl FileAssetIo {
    /// Creates a new `FileAssetIo` at a path relative to the executable's directory, optionally
    /// watching for changes.
    ///
    /// See `get_base_path` below.
    pub fn new<P: AsRef<Path>>(path: P, watch_for_changes: bool) -> Self {
        let file_asset_io = FileAssetIo {
            #[cfg(feature = "filesystem_watcher")]
            filesystem_watcher: Default::default(),
            root_path: Self::get_base_path().join(path.as_ref()),
        };
        if watch_for_changes {
            #[cfg(any(
                not(feature = "filesystem_watcher"),
                target_arch = "wasm32",
                target_os = "android"
            ))]
            panic!(
                "Watch for changes requires the filesystem_watcher feature and cannot be used on \
                wasm32 / android targets"
            );
            #[cfg(feature = "filesystem_watcher")]
            file_asset_io.watch_for_changes().unwrap();
        }
        file_asset_io
    }

    /// Returns the base path of the assets directory, which is normally the executable's parent
    /// directory.
    ///
    /// If the `CARGO_MANIFEST_DIR` environment variable is set, then its value will be used
    /// instead. It's set by cargo when running with `cargo run`.
    pub fn get_base_path() -> PathBuf {
        if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
            PathBuf::from(manifest_dir)
        } else {
            env::current_exe()
                .map(|path| {
                    path.parent()
                        .map(|exe_parent_path| exe_parent_path.to_owned())
                        .unwrap()
                })
                .unwrap()
        }
    }

    /// Returns the root directory where assets are loaded from.
    ///
    /// See `get_base_path`.
    pub fn root_path(&self) -> &PathBuf {
        &self.root_path
    }
}

impl AssetIo for FileAssetIo {
    fn load_path<'a>(&'a self, path: &'a Path) -> BoxedFuture<'a, Result<Vec<u8>, AssetIoError>> {
        Box::pin(async move {
            let mut bytes = Vec::new();
            let full_path = self.root_path.join(path);
            match File::open(&full_path) {
                Ok(mut file) => {
                    file.read_to_end(&mut bytes)?;
                }
                Err(e) => {
                    return if e.kind() == std::io::ErrorKind::NotFound {
                        Err(AssetIoError::NotFound(full_path))
                    } else {
                        Err(e.into())
                    }
                }
            }
            Ok(bytes)
        })
    }

    fn read_directory(
        &self,
        path: &Path,
    ) -> Result<Box<dyn Iterator<Item = PathBuf>>, AssetIoError> {
        let root_path = self.root_path.to_owned();
        Ok(Box::new(fs::read_dir(root_path.join(path))?.map(
            move |entry| {
                let path = entry.unwrap().path();
                path.strip_prefix(&root_path).unwrap().to_owned()
            },
        )))
    }

    fn watch_path_for_changes(&self, _path: &Path) -> Result<(), AssetIoError> {
        #[cfg(feature = "filesystem_watcher")]
        {
            let path = self.root_path.join(_path);
            let mut watcher = self.filesystem_watcher.write();
            if let Some(ref mut watcher) = *watcher {
                watcher
                    .watch(&path)
                    .map_err(|_error| AssetIoError::PathWatchError(path))?;
            }
        }

        Ok(())
    }

    fn watch_for_changes(&self) -> Result<(), AssetIoError> {
        #[cfg(feature = "filesystem_watcher")]
        {
            *self.filesystem_watcher.write() = Some(FilesystemWatcher::default());
        }
        #[cfg(not(feature = "filesystem_watcher"))]
        bevy_log::warn!("Watching for changes is not supported when the `filesystem_watcher` feature is disabled");

        Ok(())
    }

    fn get_metadata(&self, path: &Path) -> Result<Metadata, AssetIoError> {
        let full_path = self.root_path.join(path);
        full_path
            .metadata()
            .and_then(Metadata::try_from)
            .map_err(|e| {
                if e.kind() == std::io::ErrorKind::NotFound {
                    AssetIoError::NotFound(full_path)
                } else {
                    e.into()
                }
            })
    }
}

/// Watches for file changes in the local file system.
#[cfg(all(
    feature = "filesystem_watcher",
    all(not(target_arch = "wasm32"), not(target_os = "android"))
))]
pub fn filesystem_watcher_system(asset_server: Res<AssetServer>) {
    let mut changed = HashSet::default();
    let asset_io =
        if let Some(asset_io) = asset_server.server.asset_io.downcast_ref::<FileAssetIo>() {
            asset_io
        } else {
            return;
        };
    let watcher = asset_io.filesystem_watcher.read();
    if let Some(ref watcher) = *watcher {
        loop {
            let event = match watcher.receiver.try_recv() {
                Ok(result) => result.unwrap(),
                Err(TryRecvError::Empty) => break,
                Err(TryRecvError::Disconnected) => panic!("FilesystemWatcher disconnected."),
            };
            if let notify::event::Event {
                kind: notify::event::EventKind::Modify(_),
                paths,
                ..
            } = event
            {
                for path in &paths {
                    if !changed.contains(path) {
                        let relative_path = path.strip_prefix(&asset_io.root_path).unwrap();
                        let _ = asset_server.load_untracked(relative_path.into(), true);
                    }
                }
                changed.extend(paths);
            }
        }
    }
}