Skip to main content

egui_pop_api/files/
fs.rs

1//! Where the in-app picker reads: the system's file system ([`StdFs`],
2//! the default), or a folder held in memory ([`MemoryFs`]), for the web
3//! build, which has no file system, and for tests.
4//!
5//! The picker and the preview providers read through a [`SharedFs`]:
6//! listing a folder, the facts of a path, the first bytes of a file. The
7//! picker's New folder is the one thing it writes: [`StdFs`] makes the
8//! folder, and a [`MemoryFs`] refuses (it is read-only; the picker says
9//! so).
10//!
11//! ```
12//! use std::path::Path;
13//! use egui_pop_api::files::fs::{FileSystem, MemoryFs};
14//!
15//! let fs = MemoryFs::new()
16//!     .file("/demo/notes.txt", b"Hello".to_vec())
17//!     .dir("/demo/Photos");
18//! let names: Vec<String> = fs.read_dir(Path::new("/demo")).unwrap().into_iter().map(|e| e.name).collect();
19//! assert_eq!(names, ["Photos", "notes.txt"]);
20//! assert_eq!(fs.metadata(Path::new("/demo/notes.txt")).unwrap().len, 5);
21//! assert_eq!(fs.read(Path::new("/demo/notes.txt"), 2).unwrap(), b"He");
22//! ```
23
24use std::collections::{BTreeMap, BTreeSet};
25use std::fmt;
26use std::io::{self, Read as _};
27use std::path::{Component, Path, PathBuf};
28use std::sync::Arc;
29use std::time::SystemTime;
30
31/// One entry of a folder, as a file system lists it.
32#[derive(Clone, Debug, PartialEq, Eq)]
33pub struct DirItem {
34    pub name: String,
35    pub is_dir: bool,
36}
37
38/// The facts of a path.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub struct Meta {
41    pub is_dir: bool,
42    /// Its size in bytes (0 for a folder).
43    pub len: u64,
44    /// When it last changed, if the file system says.
45    pub modified: Option<SystemTime>,
46}
47
48/// What the picker and the preview providers read from.
49pub trait FileSystem: Send + Sync + fmt::Debug {
50    /// A folder's entries, in no particular order.
51    fn read_dir(&self, dir: &Path) -> io::Result<Vec<DirItem>>;
52
53    /// The facts of a path.
54    fn metadata(&self, path: &Path) -> io::Result<Meta>;
55
56    /// At most `limit` bytes from the start of a file.
57    fn read(&self, path: &Path, limit: usize) -> io::Result<Vec<u8>>;
58
59    /// Whether it can make folders ([`FileSystem::create_dir`]): the
60    /// picker's New folder is disabled, with the reason, when it cannot.
61    fn can_create_dirs(&self) -> bool {
62        false
63    }
64
65    /// Makes a folder, whose parent exists. By default it cannot.
66    fn create_dir(&self, _path: &Path) -> io::Result<()> {
67        Err(io::Error::new(
68            io::ErrorKind::Unsupported,
69            "this file system cannot make folders",
70        ))
71    }
72
73    /// Whether its paths are the system's own, so that other programs
74    /// (a system thumbnailer) can open them.
75    fn is_native(&self) -> bool {
76        false
77    }
78
79    fn is_dir(&self, path: &Path) -> bool {
80        self.metadata(path).is_ok_and(|m| m.is_dir)
81    }
82
83    fn is_file(&self, path: &Path) -> bool {
84        self.metadata(path).is_ok_and(|m| !m.is_dir)
85    }
86}
87
88/// A file system shared by the picker, its preview and the workers.
89pub type SharedFs = Arc<dyn FileSystem>;
90
91/// The system's file system.
92pub fn native() -> SharedFs {
93    Arc::new(StdFs)
94}
95
96/// The system's file system, through `std::fs`.
97#[derive(Clone, Copy, Debug, Default)]
98pub struct StdFs;
99
100impl FileSystem for StdFs {
101    fn read_dir(&self, dir: &Path) -> io::Result<Vec<DirItem>> {
102        Ok(std::fs::read_dir(dir)?
103            .filter_map(Result::ok)
104            .map(|e| DirItem {
105                name: e.file_name().to_string_lossy().into_owned(),
106                // Through links, as `Path::is_dir` does.
107                is_dir: e.path().is_dir(),
108            })
109            .collect())
110    }
111
112    fn metadata(&self, path: &Path) -> io::Result<Meta> {
113        let m = std::fs::metadata(path)?;
114        Ok(Meta {
115            is_dir: m.is_dir(),
116            len: if m.is_dir() { 0 } else { m.len() },
117            modified: m.modified().ok(),
118        })
119    }
120
121    fn read(&self, path: &Path, limit: usize) -> io::Result<Vec<u8>> {
122        let mut out = Vec::new();
123        std::fs::File::open(path)?
124            .take(limit as u64)
125            .read_to_end(&mut out)?;
126        Ok(out)
127    }
128
129    fn can_create_dirs(&self) -> bool {
130        // The web has no file system to write to.
131        !cfg!(target_arch = "wasm32")
132    }
133
134    fn create_dir(&self, path: &Path) -> io::Result<()> {
135        std::fs::create_dir(path)
136    }
137
138    fn is_native(&self) -> bool {
139        true
140    }
141}
142
143/// A folder tree held in memory: files with their bytes and their
144/// modification time, and folders (a file's folders exist with it).
145#[derive(Clone, Default)]
146pub struct MemoryFs {
147    files: BTreeMap<PathBuf, (Arc<[u8]>, Option<SystemTime>)>,
148    dirs: BTreeSet<PathBuf>,
149}
150
151impl fmt::Debug for MemoryFs {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        f.debug_struct("MemoryFs")
154            .field("files", &self.files.len())
155            .field("dirs", &self.dirs.len())
156            .finish()
157    }
158}
159
160/// A path without `.` and with `..` applied, so that `a/../b` is `b`.
161fn normal(path: &Path) -> PathBuf {
162    let mut out = PathBuf::new();
163    for c in path.components() {
164        match c {
165            Component::CurDir => {}
166            Component::ParentDir => {
167                out.pop();
168            }
169            c => out.push(c),
170        }
171    }
172    out
173}
174
175impl MemoryFs {
176    pub fn new() -> Self {
177        Self::default()
178    }
179
180    /// Adds a folder (and the folders above it).
181    pub fn dir(mut self, path: impl AsRef<Path>) -> Self {
182        self.add_dir(&normal(path.as_ref()));
183        self
184    }
185
186    /// Adds a file (and its folders), with no modification time.
187    pub fn file(self, path: impl AsRef<Path>, bytes: Vec<u8>) -> Self {
188        self.file_at(path, bytes, None)
189    }
190
191    /// Adds a file (and its folders) changed at `modified`.
192    pub fn file_at(
193        mut self,
194        path: impl AsRef<Path>,
195        bytes: Vec<u8>,
196        modified: Option<SystemTime>,
197    ) -> Self {
198        let path = normal(path.as_ref());
199        if let Some(parent) = path.parent() {
200            self.add_dir(parent);
201        }
202        self.files.insert(path, (bytes.into(), modified));
203        self
204    }
205
206    fn add_dir(&mut self, dir: &Path) {
207        for a in dir.ancestors() {
208            if a.as_os_str().is_empty() || !self.dirs.insert(a.to_path_buf()) {
209                break;
210            }
211        }
212    }
213}
214
215impl FileSystem for MemoryFs {
216    fn read_dir(&self, dir: &Path) -> io::Result<Vec<DirItem>> {
217        let dir = normal(dir);
218        if !self.dirs.contains(&dir) {
219            return Err(io::Error::new(io::ErrorKind::NotFound, "no such folder"));
220        }
221        let child = |p: &PathBuf| {
222            (p.parent() == Some(dir.as_path()))
223                .then(|| p.file_name().map(|n| n.to_string_lossy().into_owned()))
224                .flatten()
225        };
226        let dirs = self
227            .dirs
228            .iter()
229            .filter_map(|d| child(d).map(|name| DirItem { name, is_dir: true }));
230        let files = self.files.keys().filter_map(|f| {
231            child(f).map(|name| DirItem {
232                name,
233                is_dir: false,
234            })
235        });
236        Ok(dirs.chain(files).collect())
237    }
238
239    fn metadata(&self, path: &Path) -> io::Result<Meta> {
240        let path = normal(path);
241        if let Some((bytes, modified)) = self.files.get(&path) {
242            return Ok(Meta {
243                is_dir: false,
244                len: bytes.len() as u64,
245                modified: *modified,
246            });
247        }
248        if self.dirs.contains(&path) {
249            return Ok(Meta {
250                is_dir: true,
251                len: 0,
252                modified: None,
253            });
254        }
255        Err(io::Error::new(io::ErrorKind::NotFound, "no such file"))
256    }
257
258    fn read(&self, path: &Path, limit: usize) -> io::Result<Vec<u8>> {
259        let (bytes, _) = self
260            .files
261            .get(&normal(path))
262            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no such file"))?;
263        Ok(bytes[..bytes.len().min(limit)].to_vec())
264    }
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270
271    #[test]
272    fn a_memory_folder_lists_reads_and_resolves() {
273        let fs = MemoryFs::new()
274            .file("/r/a/x.txt", b"abc".to_vec())
275            .dir("/r/b/c");
276        let mut names: Vec<_> = fs
277            .read_dir(Path::new("/r"))
278            .unwrap()
279            .into_iter()
280            .map(|e| (e.name, e.is_dir))
281            .collect();
282        names.sort();
283        assert_eq!(names, [("a".into(), true), ("b".into(), true)]);
284        assert!(fs.is_dir(Path::new("/r/b/../a")));
285        assert!(fs.is_file(Path::new("/r/a/./x.txt")));
286        assert_eq!(fs.read(Path::new("/r/a/x.txt"), 99).unwrap(), b"abc");
287        assert!(fs.read_dir(Path::new("/r/a/x.txt")).is_err());
288        assert!(fs.metadata(Path::new("/nope")).is_err());
289        assert!(!fs.is_native());
290        // Read-only: the default of the trait.
291        assert!(!fs.can_create_dirs());
292        assert_eq!(
293            fs.create_dir(Path::new("/r/new")).unwrap_err().kind(),
294            io::ErrorKind::Unsupported
295        );
296        assert!(!fs.is_dir(Path::new("/r/new")));
297    }
298}