Skip to main content

crabshell_services/
folder.rs

1//! A folder's entries, followed as they change, as Qt's
2//! `FolderListModel` gives a wallpaper picker.
3
4#[cfg(test)]
5mod tests;
6
7use std::cell::{Cell, RefCell};
8use std::os::unix::fs::MetadataExt;
9use std::panic::{self, AssertUnwindSafe, Location};
10use std::path::PathBuf;
11use std::rc::Rc;
12use std::time::{Duration, Instant, SystemTime};
13
14use calloop::RegistrationToken;
15use calloop::timer::TimeoutAction;
16
17use crabshell_reactive::{ReadSignal, Signal, untrack};
18use crabshell_ui::{Cx, IntoProp};
19
20use crate::Shared;
21use crate::file::{FileError, FileErrorKind, Files, Follow, Keep, set};
22use crate::lines::panic_message;
23use crate::watch::{self, Watch};
24
25/// The most entries a folder view lists; the rest are dropped, logged.
26const MAX_ENTRIES: usize = 10_000;
27
28/// How long after a change the folder is read, so a burst of changes,
29/// or a program writing steadily, reads it at most 20 times a second.
30const SETTLE: Duration = Duration::from_millis(50);
31
32#[cfg(test)]
33thread_local! {
34  /// How many times this thread's folder views read their folder.
35  static READS: Cell<usize> = const { Cell::new(0) };
36}
37
38/// A folder's entries, from `cx.folder_view(path)`, read at the next flush
39/// and again when the folder changes. A `Copy` handle, like a signal.
40#[derive(Clone, Copy)]
41pub struct FolderView {
42  entries: Signal<Vec<FolderEntry>>,
43  error: Signal<Option<FileError>>,
44}
45
46/// A file, directory or link in a folder, from [`FolderView::entries`].
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub struct FolderEntry {
49  /// The folder's path joined with the name.
50  pub path: PathBuf,
51  /// The name in the folder, such as `beach.png`.
52  pub name: String,
53  /// Whether it is a directory or a link to one.
54  pub is_dir: bool,
55  /// Its size in bytes; for a link, its target's.
56  pub size: u64,
57  /// When it was last written, if the system says.
58  pub modified: Option<SystemTime>,
59}
60
61impl FolderView {
62  /// The folder's entries, one level, hidden ones too, sorted by name
63  /// regardless of case, then byte by byte. Empty while the folder can't
64  /// be read; [`error`](Self::error) says why.
65  pub fn entries(&self) -> ReadSignal<Vec<FolderEntry>> {
66    self.entries.read_only()
67  }
68
69  /// Why the last read failed, or `None` once one worked. A file at the
70  /// path is [`NotAFile`](FileErrorKind::NotAFile).
71  pub fn error(&self) -> ReadSignal<Option<FileError>> {
72    self.error.read_only()
73  }
74}
75
76/// `cx.folder_view(path)`.
77pub(crate) fn folder_view(
78  cx: &Cx,
79  path: impl IntoProp<PathBuf>,
80  at: &'static Location<'static>,
81) -> FolderView {
82  let view = FolderView {
83    entries: cx.signal(Vec::new()),
84    error: cx.signal(None),
85  };
86  let shared = cx.service::<Files>().map(|files| Rc::clone(&files.0));
87  let path = path.into_prop().shared();
88  // A memo, so a closure that reads other signals follows a new folder
89  // only when the path itself changes.
90  let path = cx.memo(move || {
91    panic::catch_unwind(AssertUnwindSafe(|| path()))
92      .inspect_err(|payload| {
93        let message = panic_message(payload.as_ref());
94        tracing::error!("cx.folder_view (called at {at}) panicked choosing its path: {message}");
95      })
96      .ok()
97  });
98  // Each run's scope holds the folder it follows, so a new path or the
99  // owner going stops following the old one.
100  cx.owner().effect_scoped(move |scope| match path.get() {
101    Some(path) => {
102      let folder = Folder::new(shared.clone(), path, view);
103      scope.signal(Keep(folder));
104    }
105    None => {
106      set(view.entries, Vec::new());
107      set(view.error, None);
108    }
109  });
110  view
111}
112
113/// One folder followed for a view.
114struct Folder {
115  /// `None` on a context the shell didn't set up: read once, never
116  /// followed.
117  shared: Option<Rc<Shared>>,
118  path: PathBuf,
119  view: FolderView,
120  /// Follows the path through its parents, for the folder made, removed
121  /// or replaced.
122  follow: RefCell<Option<Rc<Follow>>>,
123  /// The watch on the folder itself, with its device and inode.
124  own: RefCell<Option<(Watch, (u64, u64))>>,
125  /// The timer of a read waiting for [`SETTLE`] to pass.
126  waiting: Cell<Option<RegistrationToken>>,
127  logged_names: Cell<bool>,
128  logged_cap: Cell<bool>,
129}
130
131impl Folder {
132  fn new(shared: Option<Rc<Shared>>, path: PathBuf, view: FolderView) -> Rc<Folder> {
133    let folder = Rc::new(Folder {
134      shared,
135      path,
136      view,
137      follow: RefCell::new(None),
138      own: RefCell::new(None),
139      waiting: Cell::new(None),
140      logged_names: Cell::new(false),
141      logged_cap: Cell::new(false),
142    });
143    if let Some(shared) = &folder.shared {
144      let weak = Rc::downgrade(&folder);
145      let follow = Follow::new(shared, folder.path.clone(), move || {
146        if let Some(folder) = weak.upgrade() {
147          folder.queue();
148        }
149      });
150      folder.follow.replace(Some(follow));
151    }
152    folder.read();
153    folder
154  }
155
156  /// Reads the folder [`SETTLE`] from now, on a timer that exists only
157  /// while it waits, unless a read already waits.
158  fn queue(self: &Rc<Self>) {
159    if self.waiting.get().is_some() {
160      return;
161    }
162    let Some(event_loop) = self.shared.as_ref().and_then(|shared| shared.event_loop()) else {
163      return;
164    };
165    let weak = Rc::downgrade(self);
166    let tick = Box::new(move || {
167      if let Some(folder) = weak.upgrade() {
168        folder.waiting.set(None);
169        folder.read();
170      }
171      TimeoutAction::Drop
172    });
173    self
174      .waiting
175      .set(event_loop.insert_timer(Instant::now() + SETTLE, tick));
176  }
177
178  /// Reads the folder now and shows what it holds.
179  fn read(self: &Rc<Self>) {
180    #[cfg(test)]
181    READS.with(|reads| reads.set(reads.get() + 1));
182    let meta = std::fs::metadata(&self.path);
183    let dir = meta.as_ref().ok().filter(|meta| meta.is_dir());
184    // Watched before it is listed, so no change between is missed.
185    self.watch_own(dir.map(|meta| (meta.dev(), meta.ino())));
186    let listed = match meta {
187      Err(error) => Err(FileError::from(error)),
188      Ok(meta) if !meta.is_dir() => Err(FileError::new(
189        FileErrorKind::NotAFile,
190        "it isn't a directory",
191      )),
192      Ok(_) => self.list(),
193    };
194    let (entries, error) = match listed {
195      Ok(entries) => (entries, None),
196      Err(error) => {
197        // Once, while the same error stays.
198        let view = self.view;
199        if untrack(|| view.error.try_with(|old| old.as_ref() != Some(&error))) == Some(true) {
200          let path = self.path.display();
201          tracing::info!(%path, error = error.message, "can't read the folder");
202        }
203        (Vec::new(), Some(error))
204      }
205    };
206    set(self.view.entries, entries);
207    set(self.view.error, error);
208  }
209
210  /// Watches the folder at `id`, the device and inode of what is at the
211  /// path now, unless it is watched already; `None` drops the watch.
212  fn watch_own(self: &Rc<Self>, id: Option<(u64, u64)>) {
213    let Some(shared) = &self.shared else {
214      return;
215    };
216    if self.own.borrow().as_ref().map(|(_, watched)| *watched) == id {
217      return;
218    }
219    self.own.replace(None);
220    let Some(id) = id else {
221      return;
222    };
223    let weak = Rc::downgrade(self);
224    let listener = move |_: &watch::Change| {
225      if let Some(folder) = weak.upgrade() {
226        folder.queue();
227      }
228    };
229    // shortcut: a folder swapped in between the stat and the add is
230    // watched under the old one's id, and rewatched at the next change.
231    match watch::watch(shared, &self.path, watch::DIRECTORY, listener) {
232      Ok(watch) => {
233        self.own.replace(Some((watch, id)));
234      }
235      Err(error) => {
236        let path = self.path.display();
237        tracing::info!(%path, %error, "can't watch the folder, so changes in it aren't seen");
238      }
239    }
240  }
241
242  /// The folder's entries, sorted, the first [`MAX_ENTRIES`] of them.
243  fn list(&self) -> Result<Vec<FolderEntry>, FileError> {
244    let mut names = Vec::new();
245    for entry in std::fs::read_dir(&self.path)? {
246      let entry = match entry {
247        Ok(entry) => entry,
248        Err(error) => {
249          let path = self.path.display();
250          tracing::debug!(%path, %error, "can't read an entry in the folder");
251          continue;
252        }
253      };
254      let Ok(name) = entry.file_name().into_string() else {
255        if !self.logged_names.replace(true) {
256          let path = self.path.display();
257          tracing::info!(%path, "a name in the folder isn't UTF-8, so it is left out");
258        }
259        continue;
260      };
261      names.push(name);
262    }
263    names.sort_by_cached_key(|name| (name.to_lowercase(), name.clone()));
264    if names.len() > MAX_ENTRIES {
265      names.truncate(MAX_ENTRIES);
266      if !self.logged_cap.replace(true) {
267        let path = self.path.display();
268        tracing::info!(%path, "the folder holds over 10000 entries; the rest are left out");
269      }
270    }
271    let entries = names.into_iter().map(|name| {
272      let path = self.path.join(&name);
273      // A link counts as what it names, and as itself when that's gone.
274      let meta = std::fs::metadata(&path)
275        .or_else(|_| std::fs::symlink_metadata(&path))
276        .ok();
277      FolderEntry {
278        is_dir: meta.as_ref().is_some_and(std::fs::Metadata::is_dir),
279        size: meta.as_ref().map_or(0, std::fs::Metadata::len),
280        modified: meta.and_then(|meta| meta.modified().ok()),
281        path,
282        name,
283      }
284    });
285    Ok(entries.collect())
286  }
287}
288
289impl Drop for Folder {
290  fn drop(&mut self) {
291    let event_loop = self.shared.as_ref().and_then(|shared| shared.event_loop());
292    if let (Some(token), Some(event_loop)) = (self.waiting.take(), event_loop) {
293      event_loop.remove(token);
294    }
295  }
296}