Skip to main content

qframe/widgets/file_manager/
state.rs

1//! What a [`FileManager`](super::FileManager) knows about the folder it shows, and what happens to
2//! it.
3//!
4//! Reading a folder is I/O, so it never happens while drawing: the state asks for a folder when it
5//! is opened and keeps the answer, and the view is built from what is already known.
6
7use std::collections::{BTreeMap, BTreeSet};
8use std::path::{Path, PathBuf};
9use std::sync::Arc;
10
11use crate::runtime::{Command, Confirm, Task, TaskEvent, TaskId, TaskOutcome};
12use crate::widgets::{Toast, TreeDrop};
13
14use super::details::{FileDetails, PAGE};
15use super::ops::{self, FileChange, FileError, NameProblem, is_within, name_of, parent_key};
16use super::watch::Live;
17
18/// The key of the folder the manager is rooted at. Keys below it are paths relative to the root,
19/// written with `/` whatever the platform, because they are identities rather than paths.
20pub const ROOT: &str = "";
21
22/// The key of the entry `name` inside the folder `parent`.
23#[must_use]
24pub fn child_key(parent: &str, name: &str) -> String {
25    if parent.is_empty() { name.to_owned() } else { format!("{parent}/{name}") }
26}
27
28/// One entry of a folder, as a file manager reads it: a name and whether it can be opened.
29///
30/// A tree row shows nothing else, so nothing else is read. Size, date and permissions each mean
31/// another call to the system for every entry, which a folder of ten thousand entries cannot
32/// afford, so they belong to the views that show them.
33#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
34pub struct FolderEntry {
35    /// Its name, without any folder before it.
36    pub name: String,
37    /// Whether it is a folder, and so can be opened. A symbolic link is never a folder: opening
38    /// one would leave the tree it is drawn in.
39    pub folder: bool,
40}
41
42impl FolderEntry {
43    /// Reads one folder the way [`read_folder`](Self::read_folder) does, keeping why it could not
44    /// be read rather than what the system said about it, so the words are chosen where the
45    /// person's language is known.
46    pub(super) fn list(path: &Path) -> Result<Vec<Self>, FileError> {
47        let mut entries = Vec::new();
48        for entry in std::fs::read_dir(path).map_err(ops::read_error)? {
49            let entry = entry.map_err(ops::read_error)?;
50            let name = entry.file_name().to_string_lossy().into_owned();
51            let folder = entry.file_type().is_ok_and(|kind| kind.is_dir());
52            entries.push(Self { name, folder });
53        }
54        entries.sort_by(|a, b| b.folder.cmp(&a.folder).then_with(|| a.name.cmp(&b.name)));
55        Ok(entries)
56    }
57
58    /// Whether the entry is one the platform hides: on every system the framework runs on, a name
59    /// that starts with a dot.
60    #[must_use]
61    pub fn is_hidden(&self) -> bool {
62        self.name.starts_with('.')
63    }
64
65    /// Reads one folder, folders first and then files, each group in name order.
66    ///
67    /// This touches the disk, so it belongs on a background thread; [`FileManagerState`] asks for
68    /// it with [`Command::perform`] and never while drawing.
69    ///
70    /// # Errors
71    ///
72    /// What the operating system said, when the folder cannot be read. The manager's own reads say
73    /// it in the person's language instead; see [`FileManagerMsg::Listed`].
74    pub fn read_folder(path: &Path) -> Result<Vec<Self>, String> {
75        let mut entries = Vec::new();
76        for entry in std::fs::read_dir(path).map_err(|error| error.to_string())? {
77            let entry = entry.map_err(|error| error.to_string())?;
78            // A name the platform does not spell as text is still an entry; showing it lossily is
79            // better than pretending the folder holds less than it does.
80            let name = entry.file_name().to_string_lossy().into_owned();
81            // `file_type` does not follow a link, so a link to a folder is an entry and not a way
82            // out of the tree.
83            let folder = entry.file_type().is_ok_and(|kind| kind.is_dir());
84            entries.push(Self { name, folder });
85        }
86        entries.sort_by(|a, b| b.folder.cmp(&a.folder).then_with(|| a.name.cmp(&b.name)));
87        Ok(entries)
88    }
89}
90
91/// What the name the dialog asks for is for.
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub enum NameFor {
94    /// A new, empty file.
95    File,
96    /// A new, empty folder.
97    Folder,
98    /// The entry of this key, which keeps its place and takes the new name.
99    Rename(String),
100}
101
102/// The dialog that asks for a name, while it is open.
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub struct Naming {
105    /// What the name is for.
106    pub purpose: NameFor,
107    /// The key of the folder the name is to be used in.
108    pub folder: String,
109    /// What has been typed.
110    pub value: String,
111    /// Whether the person tried to confirm; an empty name is only pointed out after that, so a
112    /// dialog that has just opened does not start by scolding.
113    pub tried: bool,
114}
115
116/// Something that happened in a [`FileManager`](super::FileManager).
117///
118/// Hand every one of these to [`FileManagerState::update`]; the application's own messages come
119/// from [`FileManager::on_open`](super::FileManager::on_open) and the items it adds to the menu,
120/// never from here.
121///
122/// More things may happen as the manager grows, so match with a `_` arm; an application normally
123/// hands every one of these straight over without looking.
124#[derive(Debug, Clone)]
125#[non_exhaustive]
126pub enum FileManagerMsg {
127    /// The cursor moved to this key.
128    Select(String),
129    /// The entries of these keys became the selection.
130    Choose(Vec<String>),
131    /// The folder of this key was opened, or closed when `false`.
132    Expand(String, bool),
133    /// The folder of this key was read in the background, or could not be, by the application's
134    /// own reading. The text is the system's own; hand it over as it comes.
135    Read(String, Result<Vec<FolderEntry>, String>),
136    /// The folder of this key was read by the manager itself.
137    ///
138    /// Why a read failed is kept as a [`FileError`] rather than as words, because the thread that
139    /// read the folder does not know the person's language; the words are chosen here.
140    Listed(String, Result<Vec<FolderEntry>, FileError>),
141    /// A new file was asked for in the folder of this key.
142    NewFile(String),
143    /// A new folder was asked for in the folder of this key.
144    NewFolder(String),
145    /// The entry of this key was asked to take another name.
146    Rename(String),
147    /// The entry of this key was cut, with the rest of the selection when it is part of it, to be
148    /// pasted into another folder.
149    Cut(String),
150    /// The entry of this key was copied, with the rest of the selection when it is part of it, to
151    /// be pasted into another folder. What was copied stays where it is.
152    Copy(String),
153    /// What was cut was asked to go into the folder of this key.
154    Paste(String),
155    /// What was cut is to stay where it is after all.
156    DropCut,
157    /// Entries were dragged onto a folder, or onto the free space that stands for the root.
158    Drop(TreeDrop),
159    /// The entry of this key was asked to be deleted, with the rest of the selection when it is
160    /// part of it; the person is asked first.
161    Delete(String),
162    /// The person said yes to deleting the entries of these keys.
163    DeleteConfirmed(Vec<String>),
164    /// The entry of this key was asked to go to the trash, with the rest of the selection when it
165    /// is part of it. Nothing is asked: the trash can be looked in again.
166    Trash(String),
167    /// Hidden entries are shown from now on, or hidden again when `false`.
168    ShowHidden(bool),
169    /// The long operation running now started, came further along or ended.
170    Work(TaskEvent),
171    /// The long operation running now was asked to stop.
172    Stop,
173    /// Every open folder was asked to be read again.
174    Refresh,
175    /// The name in the dialog changed.
176    Name(String),
177    /// The name in the dialog was confirmed.
178    Submit,
179    /// The dialog was closed without a name.
180    CloseNaming,
181    /// Operations finished or were refused: for each entry its key and what came of it.
182    Done(Vec<(String, Result<FileChange, FileError>)>),
183    /// A batch of outside changes of the watch `u64` arrived; empty once that watch was let go.
184    Changed(u64, Vec<crate::storage::FolderChange>),
185    /// A [bounded](FileManagerState::following_within) wait of the watch `u64` ended with nothing
186    /// changed; the watch waits again.
187    Quiet(u64),
188    /// The details of the entries of these keys were asked for: their size, when they changed and
189    /// their permissions. Keys that are already known, or already on their way, cost nothing.
190    Detail(Vec<String>),
191    /// The details of these keys were read, `None` for an entry the system said nothing about.
192    Detailed(Vec<(String, Option<FileDetails>)>),
193    /// A flat view stepped into the folder of this key; it is read if it has not been.
194    Enter(String),
195    /// A flat view stepped out of the folder it shows, into the one above it.
196    Leave,
197}
198
199/// A long operation the manager is running in the background right now.
200///
201/// Copying is the one operation that can take a while: a rename is instant whatever it moves, but
202/// a folder of photographs is read and written byte by byte. So a copy runs as a
203/// [`Task`](crate::runtime::Task), tells how far it has come and can be stopped; everything else
204/// still runs straight through.
205#[derive(Debug, Clone)]
206pub struct FileWork {
207    id: TaskId,
208    entries: usize,
209    done: f32,
210    note: String,
211}
212
213impl FileWork {
214    /// The task doing the work, so an application can show it in a
215    /// [`Tasks`](crate::runtime::Tasks) model of its own beside its other background work, or stop
216    /// it without going through the manager's own button.
217    #[must_use]
218    pub fn id(&self) -> TaskId {
219        self.id
220    }
221
222    /// The share done, from 0 to 1.
223    #[must_use]
224    pub fn done(&self) -> f32 {
225        self.done
226    }
227
228    /// The name of the entry being copied right now, empty before the first one starts.
229    #[must_use]
230    pub fn note(&self) -> &str {
231        &self.note
232    }
233
234    /// How many entries the operation was given.
235    #[must_use]
236    pub fn entries(&self) -> usize {
237        self.entries
238    }
239}
240
241/// Where a deleted entry goes.
242#[derive(Debug, Default)]
243enum Trash {
244    /// Nowhere: deleting takes an entry away for good, which is all a manager did before.
245    #[default]
246    Off,
247    /// The person's own trash, where the freedesktop specification puts it.
248    Home,
249    /// This folder, for an application with a trash of its own.
250    In(PathBuf),
251}
252
253impl Trash {
254    /// The folder entries go to, when there is one.
255    fn folder(&self) -> Option<PathBuf> {
256        match self {
257            Self::Off => None,
258            Self::Home => super::trash::home_trash(),
259            Self::In(folder) => Some(folder.clone()),
260        }
261    }
262}
263
264/// Turns a manager's messages into the application's own.
265pub(super) type Wrap<Msg> = Arc<dyn Fn(FileManagerMsg) -> Msg + Send + Sync>;
266
267/// What a file manager has read of its root folder, what is open in it, and what is selected.
268///
269/// The application owns one of these per manager on screen, hands it every [`FileManagerMsg`] and
270/// draws it with [`FileManager`](super::FileManager). It reads folders in the background, keeps no
271/// settings and writes nothing of its own to disk.
272///
273/// ```
274/// use qframe::prelude::*;
275/// use qframe::widgets::{FileManager, FileManagerMsg, FileManagerState};
276///
277/// struct Files {
278///     manager: FileManagerState,
279///     opened: Option<std::path::PathBuf>,
280/// }
281///
282/// #[derive(Clone)]
283/// enum Msg {
284///     Manager(FileManagerMsg),
285///     Open(std::path::PathBuf),
286/// }
287///
288/// impl App for Files {
289///     type Msg = Msg;
290///     fn init(&mut self) -> Command<Msg> {
291///         self.manager.load(Msg::Manager)
292///     }
293///     fn update(&mut self, msg: Msg) -> Command<Msg> {
294///         match msg {
295///             Msg::Manager(message) => self.manager.update(message, Msg::Manager),
296///             Msg::Open(path) => {
297///                 self.opened = Some(path);
298///                 Command::none()
299///             }
300///         }
301///     }
302///     fn view(&self, ui: &mut View<'_, Msg>) {
303///         FileManager::new(&self.manager, Msg::Manager)
304///             .on_open(|path| Msg::Open(path.to_path_buf()))
305///             .show(ui)
306///             .fill();
307///     }
308/// }
309/// ```
310#[derive(Debug)]
311pub struct FileManagerState {
312    root: PathBuf,
313    confined: bool,
314    following: bool,
315    /// The folder a flat view shows; the root until one is stepped into.
316    shown: String,
317    children: BTreeMap<String, Vec<FolderEntry>>,
318    /// What is known about an entry besides its name, for the entries it was asked for. Never a
319    /// whole folder: a folder of ten thousand entries must not become ten thousand calls.
320    details: BTreeMap<String, Option<FileDetails>>,
321    /// The keys whose details were asked for and have not come back yet, so one ask is not made
322    /// twice.
323    reading: BTreeSet<String>,
324    open: BTreeSet<String>,
325    loading: BTreeSet<String>,
326    selected: Option<String>,
327    chosen: Vec<String>,
328    /// Why a folder could not be read, by key, for every folder whose last read failed. The root
329    /// is in here like any other: one place holds the reason, so a folder that failed can never
330    /// be drawn as one that is simply empty.
331    errors: BTreeMap<String, String>,
332    cut: Vec<String>,
333    /// Whether what waits to be pasted is to be copied rather than moved.
334    copying: bool,
335    trash: Trash,
336    hidden: bool,
337    work: Option<FileWork>,
338    naming: Option<Naming>,
339    pub(super) live: Live,
340    /// Counts the watches started, so a batch of one that was let go is recognised.
341    pub(super) runs: u64,
342    /// How long one wait for outside changes may last; `None` waits until something changes.
343    pub(super) patience: Option<std::time::Duration>,
344}
345
346impl FileManagerState {
347    /// The key of the root folder: the manager's top row, and the folder every other key is
348    /// written relative to.
349    pub const ROOT: &'static str = ROOT;
350
351    /// A manager of the folder at `root`, with nothing read yet.
352    ///
353    /// The root is the manager's top row and starts open: its entries are what the manager is for.
354    #[must_use]
355    pub fn new(root: impl Into<PathBuf>) -> Self {
356        Self {
357            root: root.into(),
358            confined: false,
359            following: false,
360            shown: ROOT.to_owned(),
361            children: BTreeMap::new(),
362            details: BTreeMap::new(),
363            reading: BTreeSet::new(),
364            open: BTreeSet::from([ROOT.to_owned()]),
365            loading: BTreeSet::new(),
366            selected: None,
367            chosen: Vec::new(),
368            errors: BTreeMap::new(),
369            cut: Vec::new(),
370            copying: false,
371            trash: Trash::Off,
372            hidden: false,
373            work: None,
374            naming: None,
375            live: Live::Off,
376            runs: 0,
377            patience: None,
378        }
379    }
380
381    /// Keeps every operation inside the root: a key that climbs out of it is refused, and so is
382    /// one that goes through a symbolic link, because a link can point anywhere.
383    ///
384    /// An application that shows a folder the person must not leave (a project, a sandbox) asks
385    /// for this; one that shows the whole file system does not. It is a rule about what may be
386    /// changed on disk, so it belongs to the state the operations run from and not to the view,
387    /// which is built afresh every frame.
388    #[must_use]
389    pub fn confined(mut self) -> Self {
390        self.confined = true;
391        self
392    }
393
394    /// Whether operations are kept inside the root.
395    #[must_use]
396    pub fn is_confined(&self) -> bool {
397        self.confined
398    }
399
400    /// Deleting puts an entry in the person's own trash instead of taking it away for good, the
401    /// way the freedesktop trash specification says: `$XDG_DATA_HOME/Trash`, or
402    /// `~/.local/share/Trash` when that variable says nothing.
403    ///
404    /// An entry that cannot be renamed into that folder — one on another file system, or a run with
405    /// no home folder at all — is not deleted quietly instead: the manager says there is no trash
406    /// for it and asks whether to delete it for good, in the danger colour, as its own question.
407    ///
408    /// Windows and macOS have a trash of their own that this specification does not describe, so
409    /// there this asks the same question rather than inventing a folder.
410    #[must_use]
411    pub fn trashing(mut self) -> Self {
412        self.trash = Trash::Home;
413        self
414    }
415
416    /// Deleting puts an entry in the trash folder `folder` instead of the person's own, for an
417    /// application that keeps a trash of its own and for a test, which must never touch the
418    /// person's.
419    ///
420    /// The folder is made when the first entry goes into it, with the `files` and `info` folders
421    /// the specification asks for.
422    #[must_use]
423    pub fn trashing_in(mut self, folder: impl Into<PathBuf>) -> Self {
424        self.trash = Trash::In(folder.into());
425        self
426    }
427
428    /// Whether deleting puts entries in a trash.
429    #[must_use]
430    pub fn is_trashing(&self) -> bool {
431        !matches!(self.trash, Trash::Off)
432    }
433
434    /// Shows the entries the platform hides: the ones whose name starts with a dot.
435    ///
436    /// Off by default, the way a folder is usually looked at. The entries are read either way —
437    /// one read of a folder is one read — so turning this on shows them without going to the disk,
438    /// and a new entry's name is checked against a hidden one that is already there whether they
439    /// are shown or not.
440    #[must_use]
441    pub fn showing_hidden(mut self, showing: bool) -> Self {
442        self.hidden = showing;
443        self
444    }
445
446    /// Shows or hides the hidden entries; see [`showing_hidden`](Self::showing_hidden).
447    pub fn set_showing_hidden(&mut self, showing: bool) {
448        self.hidden = showing;
449    }
450
451    /// Whether the entries the platform hides are shown.
452    #[must_use]
453    pub fn shows_hidden(&self) -> bool {
454        self.hidden
455    }
456
457    /// Follows the folders on screen with a [`FolderWatch`](crate::storage::FolderWatch), so what
458    /// another program changes in them is read again without being asked.
459    ///
460    /// Off by default: the watch waits on a background thread, which a screen that is not shown
461    /// has no reason to keep, and a test drives the batches itself. Turn it on for a manager the
462    /// person is looking at and off again when it leaves the screen.
463    #[must_use]
464    pub fn following(mut self, following: bool) -> Self {
465        self.following = following;
466        self
467    }
468
469    /// Follows outside changes like [`following(true)`](Self::following), with each wait for them
470    /// lasting at most `bound`; a wait that ends with nothing changed simply waits again.
471    ///
472    /// Made for screen tests: a [`Harness`](crate::runtime::Harness) runs the wait on the spot, and
473    /// an unbounded one would never come back, so a test that wants to see another program's
474    /// change arrive gives a short bound and steps the harness. A running application keeps
475    /// `following(true)`.
476    #[must_use]
477    pub fn following_within(mut self, bound: std::time::Duration) -> Self {
478        self.following = true;
479        self.patience = Some(bound);
480        self
481    }
482
483    /// Turns following outside changes on or off; see [`following`](Self::following).
484    pub fn set_following(&mut self, following: bool) {
485        self.following = following;
486        if !following {
487            self.live = Live::Off;
488        }
489    }
490
491    /// Whether outside changes are followed.
492    #[must_use]
493    pub fn follows_changes(&self) -> bool {
494        self.following
495    }
496
497    /// The folder the manager shows.
498    #[must_use]
499    pub fn root(&self) -> &Path {
500        &self.root
501    }
502
503    /// The entries of the folder `key`, when they have been read.
504    #[must_use]
505    pub fn children(&self, key: &str) -> Option<&[FolderEntry]> {
506        self.children.get(key).map(Vec::as_slice)
507    }
508
509    /// The folder a flat view shows, the root until one is stepped into.
510    ///
511    /// The tree shows the whole root and takes no notice of this; the list and the icons show this
512    /// one folder, and [`FileManagerMsg::Enter`] and [`FileManagerMsg::Leave`] move through it.
513    #[must_use]
514    pub fn folder(&self) -> &str {
515        &self.shown
516    }
517
518    /// What is known about the entry `key` besides its name: its size, when it changed last and
519    /// its permissions.
520    ///
521    /// `None` while nothing has been asked for that entry, and `Some(None)` for one the system
522    /// said nothing about — it went away, or may not be looked at. Ask for details with
523    /// [`detail`](Self::detail) or [`FileManagerMsg::Detail`]; a tree row never asks.
524    #[must_use]
525    pub fn details(&self, key: &str) -> Option<Option<&FileDetails>> {
526        self.details.get(key).map(Option::as_ref)
527    }
528
529    /// Whether the details of `key` have been asked for, whether or not the answer has come.
530    #[must_use]
531    pub fn has_details(&self, key: &str) -> bool {
532        self.details.contains_key(key) || self.reading.contains(key)
533    }
534
535    /// Whether the folder `key` is open.
536    #[must_use]
537    pub fn is_open(&self, key: &str) -> bool {
538        self.open.contains(key)
539    }
540
541    /// Whether the folder `key` is being read right now.
542    #[must_use]
543    pub fn is_loading(&self, key: &str) -> bool {
544        self.loading.contains(key)
545    }
546
547    /// The key of the entry the cursor is on: the row with the pillar, which the keys move from.
548    #[must_use]
549    pub fn selected(&self) -> Option<&str> {
550        self.selected.as_deref()
551    }
552
553    /// The keys of every selected entry, the cursor's among them unless it was taken out.
554    #[must_use]
555    pub fn chosen(&self) -> &[String] {
556        &self.chosen
557    }
558
559    /// Why the root folder could not be read, when it could not be.
560    #[must_use]
561    pub fn error(&self) -> Option<&str> {
562        self.folder_error(ROOT)
563    }
564
565    /// Why the folder `key` could not be read, when its last read failed.
566    ///
567    /// A folder the system refused keeps its row and says so; before this the manager kept only
568    /// the root's reason and drew every other refused folder as an empty one, which told the
569    /// person a folder they may not look into holds nothing. `key` may be
570    /// [`ROOT`](Self::ROOT), which is what [`error`](Self::error) asks for.
571    #[must_use]
572    pub fn folder_error(&self, key: &str) -> Option<&str> {
573        self.errors.get(key).map(String::as_str)
574    }
575
576    /// The keys of the entries that were cut and wait to be pasted; empty while what waits is to
577    /// be copied instead.
578    #[must_use]
579    pub fn cut(&self) -> &[String] {
580        if self.copying { &[] } else { &self.cut }
581    }
582
583    /// The keys of the entries that were copied and wait to be pasted.
584    #[must_use]
585    pub fn copied(&self) -> &[String] {
586        if self.copying { &self.cut } else { &[] }
587    }
588
589    /// The keys of the entries that wait to be pasted, whether pasting will move or copy them.
590    /// Only one of the two waits at a time: copying something lets go of what was cut.
591    #[must_use]
592    pub fn pending(&self) -> &[String] {
593        &self.cut
594    }
595
596    /// Whether pasting what waits will copy it rather than move it.
597    #[must_use]
598    pub fn is_copying(&self) -> bool {
599        self.copying
600    }
601
602    /// Whether the entry `key` was cut, or is inside a folder that was. A copied entry is not: it
603    /// stays where it is, so nothing about it is faint.
604    #[must_use]
605    pub fn is_cut(&self, key: &str) -> bool {
606        !self.copying && self.cut.iter().any(|cut| is_within(key, cut))
607    }
608
609    /// The entries of the folder `key` that are drawn: all of them, or the ones the platform does
610    /// not hide while [`shows_hidden`](Self::shows_hidden) is off.
611    #[must_use]
612    pub fn shown_children(&self, key: &str) -> Option<Vec<&FolderEntry>> {
613        let entries = self.children(key)?;
614        Some(entries.iter().filter(|entry| self.hidden || !entry.is_hidden()).collect())
615    }
616
617    /// The long operation running in the background, while one is running. See [`FileWork`].
618    #[must_use]
619    pub fn work(&self) -> Option<&FileWork> {
620        self.work.as_ref()
621    }
622
623    /// The dialog asking for a name, while it is open.
624    #[must_use]
625    pub fn naming(&self) -> Option<&Naming> {
626        self.naming.as_ref()
627    }
628
629    /// Whether the entry `key` is a folder, as far as the manager has read.
630    #[must_use]
631    pub fn is_folder(&self, key: &str) -> bool {
632        let name = name_of(key);
633        self.children(parent_key(key)).is_some_and(|entries| entries.iter().any(|e| e.folder && e.name == name))
634    }
635
636    /// The keys of every folder the manager has read so far, the root excepted.
637    #[must_use]
638    pub fn folder_keys(&self) -> BTreeSet<String> {
639        self.children
640            .iter()
641            .flat_map(|(parent, entries)| {
642                entries.iter().filter(|entry| entry.folder).map(move |entry| child_key(parent, &entry.name))
643            })
644            .collect()
645    }
646
647    /// The path on disk of the entry `key`, the root itself for [`Self::ROOT`].
648    #[must_use]
649    pub fn path(&self, key: &str) -> PathBuf {
650        key.split('/').filter(|part| !part.is_empty()).fold(self.root.clone(), |path, part| path.join(part))
651    }
652
653    /// Makes `key` the one selected entry, with the cursor on it.
654    pub fn select(&mut self, key: &str) {
655        self.selected = Some(key.to_owned());
656        self.chosen = vec![key.to_owned()];
657    }
658
659    /// What an action asked for on the row `key` acts on: the whole selection when the row is one
660    /// of several selected, and the row alone otherwise, the way a right click on a row is meant.
661    ///
662    /// An entry inside a folder that is also taken is left out, because it goes wherever the
663    /// folder goes; the root itself is never taken.
664    #[must_use]
665    pub fn targets(&self, key: &str) -> Vec<String> {
666        targets_of(&self.chosen, key)
667    }
668
669    /// What is wrong with the name typed so far, if anything; an empty name only once the person
670    /// has tried to confirm it.
671    #[must_use]
672    pub fn naming_problem(&self) -> Option<NameProblem> {
673        let naming = self.naming.as_ref()?;
674        let siblings = self.children(&naming.folder).unwrap_or_default().iter().map(|entry| entry.name.as_str());
675        let current = match &naming.purpose {
676            NameFor::Rename(key) => Some(name_of(key)),
677            NameFor::File | NameFor::Folder => None,
678        };
679        let problem = ops::check_name(&naming.value, siblings, current).err()?;
680        (problem != NameProblem::Empty || naming.tried).then_some(problem)
681    }
682
683    /// The folders whose rows are on screen: every open folder whose folders above it are all open
684    /// too, the root first when it is. A folder left open inside a closed one is remembered, not
685    /// shown.
686    #[must_use]
687    pub fn visible_folders(&self) -> Vec<String> {
688        self.open
689            .iter()
690            .filter(|key| {
691                let mut above = key.as_str();
692                while above != ROOT {
693                    above = parent_key(above);
694                    if !self.open.contains(above) {
695                        return false;
696                    }
697                }
698                true
699            })
700            .cloned()
701            .collect()
702    }
703
704    /// The folders whose entries are shown: the root and every open folder that has been read.
705    fn shown_folders(&self) -> Vec<String> {
706        std::iter::once(ROOT.to_owned())
707            .chain(self.open.iter().filter(|key| *key != ROOT && self.children.contains_key(*key)).cloned())
708            .collect()
709    }
710
711    /// Opens or closes the folder `key`, and answers whether its entries still have to be read.
712    ///
713    /// A folder is read once; opening it again shows what is already known and reads nothing, so
714    /// clicking a chevron twice does not go to the disk twice.
715    fn expand(&mut self, key: &str, open: bool) -> bool {
716        if !open {
717            self.open.remove(key);
718            return false;
719        }
720        self.open.insert(key.to_owned());
721        if self.children.contains_key(key) || self.loading.contains(key) {
722            return false;
723        }
724        self.loading.insert(key.to_owned());
725        true
726    }
727
728    /// Takes the answer for the folder `key`.
729    ///
730    /// A folder that could not be read keeps its place and the root says what happened, so the
731    /// person sees the reason rather than a gap.
732    fn take_read(&mut self, key: &str, entries: Result<Vec<FolderEntry>, String>) {
733        self.loading.remove(key);
734        // A folder closed or gone while it was being read keeps nothing of the answer, so opening
735        // it again, or a new folder of its name, reads afresh.
736        if key != ROOT && !self.open.contains(key) {
737            return;
738        }
739        match entries {
740            Ok(entries) => {
741                self.errors.remove(key);
742                self.children.insert(key.to_owned(), entries);
743                // A folder read again may hold entries that changed since, so what was known about
744                // them is let go and asked for afresh rather than shown out of date.
745                self.details.retain(|entry, _| parent_key(entry) != key);
746                self.reading.retain(|entry| parent_key(entry) != key);
747                self.prune(key);
748            }
749            Err(problem) => {
750                // The reason is kept whichever folder it was. The root draws it in place of the
751                // tree; any other folder keeps its row, holds no entries and says on the row that
752                // it could not be read, so an empty folder and a refused one never look alike.
753                self.errors.insert(key.to_owned(), problem);
754                if key != ROOT {
755                    self.children.insert(key.to_owned(), Vec::new());
756                }
757            }
758        }
759    }
760
761    /// Forgets what the manager held below the folder `key` that its entries, just read, no longer
762    /// have: an entry removed or moved away by another program leaves no open folder, cut or
763    /// selection behind that would act on a name that is not there.
764    fn prune(&mut self, key: &str) {
765        let Some(entries) = self.children.get(key) else { return };
766        let names: BTreeSet<&str> = entries.iter().map(|entry| entry.name.as_str()).collect();
767        let held = self
768            .open
769            .iter()
770            .chain(self.children.keys())
771            .chain(&self.loading)
772            .chain(&self.cut)
773            .chain(&self.chosen)
774            .chain(&self.selected);
775        let gone: BTreeSet<String> = held
776            .filter(|held| *held != key && (key == ROOT || is_within(held, key)))
777            .map(|held| {
778                let below = if key == ROOT { held.as_str() } else { &held[key.len() + 1..] };
779                below.split('/').next().unwrap_or(below)
780            })
781            .filter(|name| !names.contains(name))
782            .map(|name| child_key(key, name))
783            .collect();
784        for child in gone {
785            self.forget(&child);
786        }
787    }
788
789    /// Gives every key at or below `from` the place `to` instead, after a rename or a move, so an
790    /// open folder stays open and the selection stays on what moved.
791    fn rekey(&mut self, from: &str, to: &str) {
792        let moved = |key: &str| is_within(key, from).then(|| format!("{to}{}", &key[from.len()..]));
793        self.open = self.open.iter().map(|key| moved(key).unwrap_or_else(|| key.clone())).collect();
794        self.loading.retain(|key| !is_within(key, from));
795        self.children = std::mem::take(&mut self.children)
796            .into_iter()
797            .map(|(key, entries)| (moved(&key).unwrap_or(key), entries))
798            .collect();
799        self.details = std::mem::take(&mut self.details)
800            .into_iter()
801            .map(|(key, details)| (moved(&key).unwrap_or(key), details))
802            .collect();
803        self.errors = std::mem::take(&mut self.errors)
804            .into_iter()
805            .map(|(key, problem)| (moved(&key).unwrap_or(key), problem))
806            .collect();
807        self.reading.retain(|key| !is_within(key, from));
808        if let Some(new) = moved(&self.shown) {
809            self.shown = new;
810        }
811        for key in self.selected.iter_mut().chain(&mut self.cut).chain(&mut self.chosen) {
812            if let Some(new) = moved(key) {
813                *key = new;
814            }
815        }
816    }
817
818    /// Forgets everything at or below `key`, after it was deleted. The cursor goes to the folder it
819    /// was in, the nearest thing still there.
820    fn forget(&mut self, key: &str) {
821        // A folder a flat view shows that is taken away leaves the view in the one above it.
822        if is_within(&self.shown, key) {
823            self.shown = parent_key(key).to_owned();
824        }
825        self.details.retain(|entry, _| !is_within(entry, key));
826        self.reading.retain(|entry| !is_within(entry, key));
827        self.open.retain(|open| !is_within(open, key));
828        self.loading.retain(|loading| !is_within(loading, key));
829        self.children.retain(|folder, _| !is_within(folder, key));
830        self.errors.retain(|folder, _| !is_within(folder, key));
831        self.cut.retain(|cut| !is_within(cut, key));
832        self.chosen.retain(|chosen| !is_within(chosen, key));
833        if self.selected.as_deref().is_some_and(|selected| is_within(selected, key)) {
834            let parent = parent_key(key);
835            self.selected = (parent != ROOT).then(|| parent.to_owned());
836        }
837    }
838}
839
840/// What an action on the row `key` acts on while `chosen` is selected; see
841/// [`FileManagerState::targets`]. The menu is built after the view, without the state, so it takes
842/// the selection along.
843pub(super) fn targets_of(chosen: &[String], key: &str) -> Vec<String> {
844    let keys = if chosen.len() > 1 && chosen.iter().any(|selected| selected == key) {
845        chosen.to_vec()
846    } else {
847        vec![key.to_owned()]
848    };
849    outermost(keys)
850}
851
852/// `keys` without any key inside a folder that is also among them, and without the root, in their
853/// order.
854pub(super) fn outermost(keys: Vec<String>) -> Vec<String> {
855    let all = keys.clone();
856    keys.into_iter()
857        .filter(|key| key != ROOT && !all.iter().any(|other| other != key && is_within(key, other)))
858        .collect()
859}
860
861/// How many names a question lists before it only counts the rest.
862const NAMES_SHOWN: usize = 5;
863
864impl FileManagerState {
865    /// Reads the root the first time, and every folder on screen again after that: the files may
866    /// have changed while the manager was away.
867    ///
868    /// Call it when the manager comes on screen. `wrap` turns the manager's messages into the
869    /// application's own, as in [`update`](Self::update).
870    pub fn load<Msg: Clone + Send + 'static>(
871        &mut self,
872        wrap: impl Fn(FileManagerMsg) -> Msg + Send + Sync + 'static,
873    ) -> Command<Msg> {
874        let wrap: Wrap<Msg> = Arc::new(wrap);
875        self.with_wrap(&wrap, Self::load_with)
876    }
877
878    /// Applies `message` and answers with the work it asks for: folders are read and file
879    /// operations run on background threads, never while drawing.
880    ///
881    /// `wrap` is a function such as `Msg::Manager`, or a closure that captures what it needs, such
882    /// as a screen's own conversion. It is used for every message the work sends back, so it must
883    /// be safe to move to another thread.
884    pub fn update<Msg: Clone + Send + 'static>(
885        &mut self,
886        message: FileManagerMsg,
887        wrap: impl Fn(FileManagerMsg) -> Msg + Send + Sync + 'static,
888    ) -> Command<Msg> {
889        let wrap: Wrap<Msg> = Arc::new(wrap);
890        self.with_wrap(&wrap, |state, wrap| state.apply(message, wrap))
891    }
892
893    /// Runs `work` and then keeps the watch on exactly the folders on screen, whatever the work
894    /// changed about them.
895    fn with_wrap<Msg: Clone + Send + 'static>(
896        &mut self,
897        wrap: &Wrap<Msg>,
898        work: impl FnOnce(&mut Self, &Wrap<Msg>) -> Command<Msg>,
899    ) -> Command<Msg> {
900        let command = work(self, wrap);
901        let followed = super::watch::follow(self, wrap);
902        Command::batch([command, followed])
903    }
904
905    fn load_with<Msg: Clone + Send + 'static>(&mut self, wrap: &Wrap<Msg>) -> Command<Msg> {
906        if self.children.contains_key(ROOT) {
907            let shown = self.shown_folders();
908            return self.reread(shown, wrap);
909        }
910        if !self.loading.insert(ROOT.to_owned()) {
911            return Command::none();
912        }
913        self.read_folder(ROOT, wrap)
914    }
915
916    /// Asks for the details of the entries `keys`: their size, when they changed last and their
917    /// permissions.
918    ///
919    /// Only the keys nothing is known about yet are read, so asking for the same page twice costs
920    /// nothing. Use this when the application knows exactly which rows it draws; a view that shows
921    /// details asks for a page around the cursor by itself. Never hand it a whole folder: every
922    /// key is one more call to the system, which over a remote file system is what a large folder
923    /// cannot afford.
924    ///
925    /// The answers come back as [`FileManagerMsg::Detailed`] and are read with
926    /// [`details`](Self::details).
927    pub fn detail<Msg: Clone + Send + 'static>(
928        &mut self,
929        keys: Vec<String>,
930        wrap: impl Fn(FileManagerMsg) -> Msg + Send + Sync + 'static,
931    ) -> Command<Msg> {
932        let wrap: Wrap<Msg> = Arc::new(wrap);
933        self.read_details(keys, &wrap)
934    }
935
936    /// Asks for the details of a page of entries of the folder `folder`, around the cursor.
937    ///
938    /// A page of two hundred entries is always more than a screen holds and far less than a large
939    /// folder, so a person scrolling rarely waits and a folder of ten thousand entries never turns
940    /// into ten thousand calls to the system. The cursor decides where the page sits; a cursor
941    /// somewhere else, or nowhere, starts it at the top of the folder.
942    ///
943    /// The views that show details use this by themselves; an application that knows exactly which
944    /// rows it draws asks for those with [`detail`](Self::detail) instead.
945    pub fn detail_page<Msg: Clone + Send + 'static>(
946        &mut self,
947        folder: &str,
948        wrap: impl Fn(FileManagerMsg) -> Msg + Send + Sync + 'static,
949    ) -> Command<Msg> {
950        let wrap: Wrap<Msg> = Arc::new(wrap);
951        self.read_page(folder, &wrap)
952    }
953
954    /// Shows the folder `key` in the flat views, reading it if it has not been read.
955    ///
956    /// The cursor starts at the folder's own row, so the keys go on from the top of what is now
957    /// shown rather than from a row of the folder that was left.
958    fn enter<Msg: Clone + Send + 'static>(&mut self, key: &str, wrap: &Wrap<Msg>) -> Command<Msg> {
959        if key != ROOT && !self.is_folder(key) {
960            return Command::none();
961        }
962        self.shown = key.to_owned();
963        self.selected = None;
964        self.chosen.clear();
965        // The folder is opened as well as shown, so the tree and the flat views agree about where
966        // the person is when the shape is changed.
967        let read = self.expand(key, true);
968        if read { self.read_folder(key, wrap) } else { Command::none() }
969    }
970
971    /// The entries of a page around the cursor in the folder `folder` that nothing is known about
972    /// yet and that nothing is on its way for.
973    ///
974    /// This is what a view showing details asks for while it draws: it is empty once the page is
975    /// known or already being read, so the view asks once and then stops asking.
976    #[must_use]
977    pub fn detail_gaps(&self, folder: &str) -> Vec<String> {
978        let Some(entries) = self.shown_children(folder) else { return Vec::new() };
979        let keys: Vec<String> = entries.iter().map(|entry| child_key(folder, &entry.name)).collect();
980        let at = self.selected.as_deref().and_then(|cursor| keys.iter().position(|key| key == cursor)).unwrap_or(0);
981        // The page is put around the cursor, so moving on in either direction stays inside it.
982        let start = at.saturating_sub(PAGE / 2);
983        keys.into_iter().skip(start).take(PAGE).filter(|key| !self.has_details(key)).collect()
984    }
985
986    /// The page of [`detail_page`](Self::detail_page), for the manager's own asking.
987    pub(super) fn read_page<Msg: Clone + Send + 'static>(&mut self, folder: &str, wrap: &Wrap<Msg>) -> Command<Msg> {
988        let page = self.detail_gaps(folder);
989        self.read_details(page, wrap)
990    }
991
992    /// Reads the details of `keys` on a background thread, leaving out what is known or on its way.
993    pub(super) fn read_details<Msg: Clone + Send + 'static>(
994        &mut self,
995        keys: Vec<String>,
996        wrap: &Wrap<Msg>,
997    ) -> Command<Msg> {
998        let wanted: Vec<String> = keys.into_iter().filter(|key| key != ROOT && !self.has_details(key)).collect();
999        if wanted.is_empty() {
1000            return Command::none();
1001        }
1002        for key in &wanted {
1003            self.reading.insert(key.clone());
1004        }
1005        let (root, wrap) = (self.root.clone(), Arc::clone(wrap));
1006        Command::perform(move || {
1007            let read = wanted
1008                .iter()
1009                .map(|key| {
1010                    let path =
1011                        key.split('/').filter(|part| !part.is_empty()).fold(root.clone(), |at, part| at.join(part));
1012                    (key.clone(), FileDetails::read(&path))
1013                })
1014                .collect();
1015            wrap(FileManagerMsg::Detailed(read))
1016        })
1017    }
1018
1019    /// Reads one folder on a background thread.
1020    fn read_folder<Msg: Clone + Send + 'static>(&self, key: &str, wrap: &Wrap<Msg>) -> Command<Msg> {
1021        let (key, path, wrap) = (key.to_owned(), self.path(key), Arc::clone(wrap));
1022        Command::perform(move || wrap(FileManagerMsg::Listed(key.clone(), FolderEntry::list(&path))))
1023    }
1024
1025    /// Reads the folders `keys` again, each while it is still shown.
1026    pub(super) fn reread<Msg: Clone + Send + 'static>(&mut self, keys: Vec<String>, wrap: &Wrap<Msg>) -> Command<Msg> {
1027        let keys: Vec<String> = keys.into_iter().filter(|key| key == ROOT || self.is_open(key)).collect();
1028        let commands: Vec<Command<Msg>> = keys
1029            .into_iter()
1030            .map(|key| {
1031                self.loading.insert(key.clone());
1032                self.read_folder(&key, wrap)
1033            })
1034            .collect();
1035        Command::batch(commands)
1036    }
1037
1038    /// Reads again every folder on screen: when the person asks, when the manager is returned to,
1039    /// and when a watch says anything may have changed.
1040    pub(super) fn refresh<Msg: Clone + Send + 'static>(&mut self, wrap: &Wrap<Msg>) -> Command<Msg> {
1041        let shown = self.shown_folders();
1042        self.reread(shown, wrap)
1043    }
1044
1045    fn apply<Msg: Clone + Send + 'static>(&mut self, message: FileManagerMsg, wrap: &Wrap<Msg>) -> Command<Msg> {
1046        match message {
1047            FileManagerMsg::Select(key) => {
1048                self.selected = Some(key);
1049                Command::none()
1050            }
1051            FileManagerMsg::Choose(keys) => {
1052                self.chosen = keys;
1053                Command::none()
1054            }
1055            FileManagerMsg::Expand(key, open) => {
1056                if !self.expand(&key, open) {
1057                    return Command::none();
1058                }
1059                self.read_folder(&key, wrap)
1060            }
1061            FileManagerMsg::Read(key, entries) => {
1062                self.take_read(&key, entries);
1063                Command::none()
1064            }
1065            FileManagerMsg::Listed(key, entries) => {
1066                self.take_read(&key, entries.map_err(|problem| problem.message()));
1067                Command::none()
1068            }
1069            FileManagerMsg::NewFile(folder) => self.ask_name(NameFor::File, folder, String::new(), wrap),
1070            FileManagerMsg::NewFolder(folder) => self.ask_name(NameFor::Folder, folder, String::new(), wrap),
1071            FileManagerMsg::Rename(key) => {
1072                let (folder, name) = (parent_key(&key).to_owned(), name_of(&key).to_owned());
1073                self.ask_name(NameFor::Rename(key), folder, name, wrap)
1074            }
1075            FileManagerMsg::Cut(key) => {
1076                self.cut = self.targets(&key);
1077                self.copying = false;
1078                Command::none()
1079            }
1080            FileManagerMsg::Copy(key) => {
1081                self.cut = self.targets(&key);
1082                self.copying = true;
1083                Command::none()
1084            }
1085            FileManagerMsg::DropCut => {
1086                self.cut.clear();
1087                self.copying = false;
1088                Command::none()
1089            }
1090            FileManagerMsg::Paste(into) => {
1091                let keys = self.cut.clone();
1092                if self.copying {
1093                    return self.copy_all(keys, into, wrap);
1094                }
1095                self.move_all(keys, into, wrap)
1096            }
1097            FileManagerMsg::Drop(TreeDrop { keys, into }) => {
1098                self.move_all(outermost(keys), into.unwrap_or_default(), wrap)
1099            }
1100            FileManagerMsg::Delete(key) => self.ask_delete(self.targets(&key), wrap),
1101            FileManagerMsg::DeleteConfirmed(keys) => {
1102                let confined = self.confined;
1103                self.run_each(keys, wrap, move |root, key| (key.to_owned(), ops::delete(root, key, confined)))
1104            }
1105            FileManagerMsg::Trash(key) => {
1106                let keys = self.targets(&key);
1107                self.trash_all(keys, wrap)
1108            }
1109            FileManagerMsg::ShowHidden(showing) => {
1110                self.hidden = showing;
1111                Command::none()
1112            }
1113            FileManagerMsg::Work(event) => self.took_event(event, wrap),
1114            FileManagerMsg::Stop => match &self.work {
1115                Some(work) => Command::cancel_task(work.id),
1116                None => Command::none(),
1117            },
1118            FileManagerMsg::Refresh => self.refresh(wrap),
1119            FileManagerMsg::Name(value) => {
1120                if let Some(naming) = &mut self.naming {
1121                    naming.value = value;
1122                }
1123                Command::none()
1124            }
1125            FileManagerMsg::Submit => self.submit(wrap),
1126            FileManagerMsg::CloseNaming => {
1127                self.naming = None;
1128                Command::none()
1129            }
1130            FileManagerMsg::Done(results) => self.done(results, wrap),
1131            FileManagerMsg::Changed(run, batch) => super::watch::changed(self, run, batch, wrap),
1132            FileManagerMsg::Quiet(run) => super::watch::quiet(self, run, wrap),
1133            FileManagerMsg::Enter(key) => self.enter(&key, wrap),
1134            FileManagerMsg::Leave => {
1135                if self.shown == ROOT {
1136                    return Command::none();
1137                }
1138                let left = self.shown.clone();
1139                let up = parent_key(&left).to_owned();
1140                let command = self.enter(&up, wrap);
1141                // The cursor lands on the folder that was left, which is where the eye already is.
1142                self.selected = Some(left);
1143                command
1144            }
1145            FileManagerMsg::Detail(keys) => self.read_details(keys, wrap),
1146            FileManagerMsg::Detailed(read) => {
1147                for (key, details) in read {
1148                    self.reading.remove(&key);
1149                    self.details.insert(key, details);
1150                }
1151                Command::none()
1152            }
1153        }
1154    }
1155
1156    /// Opens the dialog asking for a name in `folder`, opening the folder too: the new entry will
1157    /// be shown there, and the names already in it are what the name is checked against.
1158    fn ask_name<Msg: Clone + Send + 'static>(
1159        &mut self,
1160        purpose: NameFor,
1161        folder: String,
1162        value: String,
1163        wrap: &Wrap<Msg>,
1164    ) -> Command<Msg> {
1165        let read = folder != ROOT && self.expand(&folder, true);
1166        let command = if read { self.read_folder(&folder, wrap) } else { Command::none() };
1167        self.naming = Some(Naming { purpose, folder, value, tried: false });
1168        command
1169    }
1170
1171    /// Takes the name in the dialog, or points out what is wrong with it.
1172    fn submit<Msg: Clone + Send + 'static>(&mut self, wrap: &Wrap<Msg>) -> Command<Msg> {
1173        let Some(naming) = self.naming.as_mut() else { return Command::none() };
1174        naming.tried = true;
1175        if self.naming_problem().is_some() {
1176            return Command::none();
1177        }
1178        let Some(Naming { purpose, folder, value: name, .. }) = self.naming.take() else { return Command::none() };
1179        let confined = self.confined;
1180        match purpose {
1181            NameFor::File => self.run_each(vec![folder], wrap, move |root, folder| {
1182                (child_key(folder, &name), ops::create_file(root, folder, &name, confined))
1183            }),
1184            NameFor::Folder => self.run_each(vec![folder], wrap, move |root, folder| {
1185                (child_key(folder, &name), ops::create_folder(root, folder, &name, confined))
1186            }),
1187            // The same name again is nothing to do, not a clash with itself.
1188            NameFor::Rename(key) if name_of(&key) == name => Command::none(),
1189            NameFor::Rename(key) => self
1190                .run_each(vec![key], wrap, move |root, key| (key.to_owned(), ops::rename(root, key, &name, confined))),
1191        }
1192    }
1193
1194    /// Moves the entries `keys` into the folder `into`, each on its own: one that cannot go does
1195    /// not keep the others from going, and the answer says which stayed and why.
1196    fn move_all<Msg: Clone + Send + 'static>(
1197        &mut self,
1198        keys: Vec<String>,
1199        into: String,
1200        wrap: &Wrap<Msg>,
1201    ) -> Command<Msg> {
1202        if keys.is_empty() {
1203            return Command::none();
1204        }
1205        let confined = self.confined;
1206        self.run_each(keys, wrap, move |root, key| (key.to_owned(), ops::move_into(root, key, &into, confined)))
1207    }
1208
1209    /// Copies the entries `keys` into the folder `into`, each on its own, as a background task
1210    /// that says how far it has come and can be stopped.
1211    ///
1212    /// A copy is the one operation with no upper bound: a rename is instant whatever it moves,
1213    /// while a folder of photographs is read and written byte by byte. So this does not hold a
1214    /// thread until it is over and hope it is quick; it is a task like a build or a download, with
1215    /// a share done and a way to say stop.
1216    ///
1217    /// One copy runs at a time: starting another while one is going would make two progress bars
1218    /// for one row of the manager, so a copy asked for while one runs is refused by doing nothing.
1219    fn copy_all<Msg: Clone + Send + 'static>(
1220        &mut self,
1221        keys: Vec<String>,
1222        into: String,
1223        wrap: &Wrap<Msg>,
1224    ) -> Command<Msg> {
1225        if keys.is_empty() || self.work.is_some() {
1226            return Command::none();
1227        }
1228        let (confined, root, count) = (self.confined, self.root.clone(), keys.len());
1229        let label = crate::t!("quvyta.file-manager.copying", n = count);
1230        let finish = Arc::clone(wrap);
1231        let events = Arc::clone(wrap);
1232        let task = Task::new(label, move |cx| {
1233            let mut results = Vec::new();
1234            let step = 1.0 / count as f32;
1235            for (index, key) in keys.iter().enumerate() {
1236                cx.note(name_of(key).to_owned());
1237                let base = index as f32 * step;
1238                let progress = |done: u64, total: u64| {
1239                    let share = if total == 0 { 1.0 } else { done as f32 / total as f32 };
1240                    cx.progress(base + share * step);
1241                };
1242                let stopped = || cx.is_cancelled();
1243                let watch = ops::Watch { progress: &progress, stopped: &stopped };
1244                results.push((key.clone(), ops::copy_watched(&root, key, &into, confined, &watch)));
1245                if cx.is_cancelled() {
1246                    // What was copied before the person said stop stays; the half-written one was
1247                    // taken away again by the copy itself.
1248                    break;
1249                }
1250            }
1251            Ok(finish(FileManagerMsg::Done(results)))
1252        })
1253        .on_event(move |event| events(FileManagerMsg::Work(event)));
1254        self.work = Some(FileWork { id: task.id(), entries: count, done: 0.0, note: String::new() });
1255        Command::task(task)
1256    }
1257
1258    /// Takes what the running operation said about itself.
1259    ///
1260    /// A task that was stopped never delivers its result, so the folders it touched are read again
1261    /// here: what it had already copied is on disk and belongs on the screen.
1262    fn took_event<Msg: Clone + Send + 'static>(&mut self, event: TaskEvent, wrap: &Wrap<Msg>) -> Command<Msg> {
1263        let Some(work) = &mut self.work else { return Command::none() };
1264        if event.id() != work.id {
1265            return Command::none();
1266        }
1267        match event {
1268            TaskEvent::Started { .. } => Command::none(),
1269            TaskEvent::Progress { fraction, note, .. } => {
1270                if let Some(fraction) = fraction {
1271                    work.done = fraction;
1272                }
1273                if let Some(note) = note {
1274                    work.note = note;
1275                }
1276                Command::none()
1277            }
1278            TaskEvent::Finished { outcome, .. } => {
1279                self.work = None;
1280                match outcome {
1281                    TaskOutcome::Cancelled => self.refresh(wrap),
1282                    // A task that ended by itself delivered its `Done` first, which read the
1283                    // folders it touched already.
1284                    TaskOutcome::Done | TaskOutcome::Failed(_) => Command::none(),
1285                }
1286            }
1287        }
1288    }
1289
1290    /// Puts the entries `keys` in the trash, each on its own.
1291    ///
1292    /// Nothing is asked first: the trash can be looked in again, and a question about something
1293    /// that can be undone is a question not worth asking. An entry the trash cannot take is not
1294    /// deleted quietly: [`done`](Self::done) asks about that one on its own.
1295    fn trash_all<Msg: Clone + Send + 'static>(&mut self, keys: Vec<String>, wrap: &Wrap<Msg>) -> Command<Msg> {
1296        let Some(trash) = self.trash.folder() else {
1297            // No trash at all is the same answer for every entry, and the question comes at once.
1298            return self.ask_delete_forever(keys, wrap);
1299        };
1300        if keys.is_empty() {
1301            return Command::none();
1302        }
1303        let confined = self.confined;
1304        self.run_each(keys, wrap, move |root, key| (key.to_owned(), ops::to_trash(&trash, root, key, confined)))
1305    }
1306
1307    /// Asks before deleting, which cannot be undone; a folder says it takes everything in it along.
1308    fn ask_delete<Msg: Clone + Send + 'static>(&self, keys: Vec<String>, wrap: &Wrap<Msg>) -> Command<Msg> {
1309        let folders = keys.iter().any(|key| self.is_folder(key));
1310        let (title, message) = match keys.as_slice() {
1311            [] => return Command::none(),
1312            [key] => {
1313                let name = name_of(key);
1314                let text = if folders {
1315                    "quvyta.file-manager.delete-folder-text"
1316                } else {
1317                    "quvyta.file-manager.delete-file-text"
1318                };
1319                (crate::t!("quvyta.file-manager.delete-title", name = name), crate::t!(text, name = name))
1320            }
1321            many => {
1322                let mut names = many.iter().take(NAMES_SHOWN).map(|key| name_of(key)).collect::<Vec<_>>().join(", ");
1323                if many.len() > NAMES_SHOWN {
1324                    names =
1325                        format!("{names} {}", crate::t!("quvyta.file-manager.and-more", n = many.len() - NAMES_SHOWN));
1326                }
1327                let text = if folders {
1328                    "quvyta.file-manager.delete-many-folders-text"
1329                } else {
1330                    "quvyta.file-manager.delete-many-text"
1331                };
1332                (
1333                    crate::t!("quvyta.file-manager.delete-many-title", n = many.len()),
1334                    crate::t!(text, names = names.as_str()),
1335                )
1336            }
1337        };
1338        let label = if keys.len() > 1 {
1339            crate::t!("quvyta.file-manager.delete-many", n = keys.len())
1340        } else {
1341            crate::t!("quvyta.file-manager.delete")
1342        };
1343        let confirmed = wrap(FileManagerMsg::DeleteConfirmed(keys));
1344        Command::confirm(Confirm::new(title, confirmed).message(message).confirm_label(label).danger())
1345    }
1346
1347    /// Asks whether to delete for good what the trash could not take, saying why the trash was no
1348    /// use: on another file system, or there is none.
1349    fn ask_delete_forever<Msg: Clone + Send + 'static>(&self, keys: Vec<String>, wrap: &Wrap<Msg>) -> Command<Msg> {
1350        let (title, message) = match keys.as_slice() {
1351            [] => return Command::none(),
1352            [key] => {
1353                let name = name_of(key);
1354                (
1355                    crate::t!("quvyta.file-manager.no-trash-title", name = name),
1356                    crate::t!("quvyta.file-manager.no-trash-text", name = name),
1357                )
1358            }
1359            many => (
1360                crate::t!("quvyta.file-manager.no-trash-many-title", n = many.len()),
1361                crate::t!("quvyta.file-manager.no-trash-many-text"),
1362            ),
1363        };
1364        let confirmed = wrap(FileManagerMsg::DeleteConfirmed(keys));
1365        let label = crate::t!("quvyta.file-manager.delete-forever");
1366        Command::confirm(Confirm::new(title, confirmed).message(message).confirm_label(label).danger())
1367    }
1368
1369    /// Runs a file operation for each of `items` on a background thread, one after the other: a
1370    /// move of several entries is done in the order they were given, so a clash between two of
1371    /// them is decided the same way every time.
1372    fn run_each<Msg: Clone + Send + 'static>(
1373        &self,
1374        items: Vec<String>,
1375        wrap: &Wrap<Msg>,
1376        work: impl Fn(&Path, &str) -> (String, Result<FileChange, FileError>) + Send + 'static,
1377    ) -> Command<Msg> {
1378        let (root, wrap) = (self.root.clone(), Arc::clone(wrap));
1379        Command::perform(move || wrap(FileManagerMsg::Done(items.iter().map(|item| work(&root, item)).collect())))
1380    }
1381
1382    /// Takes what the operations changed: the manager follows it, the folders they touched are
1383    /// read again and the selection goes to what was made or moved. What was refused is said,
1384    /// entry by entry when there were several.
1385    fn done<Msg: Clone + Send + 'static>(
1386        &mut self,
1387        results: Vec<(String, Result<FileChange, FileError>)>,
1388        wrap: &Wrap<Msg>,
1389    ) -> Command<Msg> {
1390        let total = results.len();
1391        let mut touched = Vec::new();
1392        let mut arrived = Vec::new();
1393        let mut refused = Vec::new();
1394        let mut without_trash = Vec::new();
1395        for (key, result) in results {
1396            match result {
1397                // The trash could not take it, so the person is asked about that one entry instead
1398                // of being told off: it is a limit of the trash, not a mistake of theirs.
1399                Err(FileError::NoTrash) => without_trash.push(key),
1400                Err(error) => refused.push((key, error)),
1401                Ok(FileChange::Copied(key)) => {
1402                    touched.push(parent_key(&key).to_owned());
1403                    arrived.push(key);
1404                }
1405                Ok(FileChange::Trashed(key)) => {
1406                    self.forget(&key);
1407                    touched.push(parent_key(&key).to_owned());
1408                }
1409                Ok(FileChange::Created(key)) => {
1410                    touched.push(parent_key(&key).to_owned());
1411                    arrived.push(key);
1412                }
1413                Ok(FileChange::Moved(from, to)) => {
1414                    // A cut entry that went somewhere is used up; one that was refused stays cut,
1415                    // to be tried elsewhere.
1416                    self.cut.retain(|cut| *cut != from);
1417                    if from == to {
1418                        continue;
1419                    }
1420                    self.rekey(&from, &to);
1421                    let parent = parent_key(&to).to_owned();
1422                    if parent != ROOT {
1423                        self.open.insert(parent.clone());
1424                    }
1425                    touched.extend([parent_key(&from).to_owned(), parent]);
1426                    arrived.push(to);
1427                }
1428                Ok(FileChange::Deleted(key)) => {
1429                    self.forget(&key);
1430                    touched.push(parent_key(&key).to_owned());
1431                }
1432            }
1433        }
1434        if let Some(first) = arrived.first() {
1435            self.selected = Some(first.clone());
1436            self.chosen = arrived;
1437        }
1438        touched.sort();
1439        touched.dedup();
1440        // An entry the trash could not take is asked about, not counted among the refusals.
1441        let total = total - without_trash.len();
1442        let asked = self.ask_delete_forever(without_trash, wrap);
1443        Command::batch([refusal(total, &refused), asked, self.reread(touched, wrap)])
1444    }
1445}
1446
1447/// Says what was refused: the reason alone when there was one entry, and which entries stayed with
1448/// each one's reason when there were several.
1449fn refusal<Msg: Clone + Send + 'static>(total: usize, refused: &[(String, FileError)]) -> Command<Msg> {
1450    match refused {
1451        [] => Command::none(),
1452        [(_, error)] if total == 1 => {
1453            Command::toast(Toast::danger(crate::t!("quvyta.file-manager.failed")).body(error.message()))
1454        }
1455        _ => {
1456            let lines: Vec<String> =
1457                refused.iter().map(|(key, error)| format!("{}: {}", name_of(key), error.message())).collect();
1458            let title = crate::t!("quvyta.file-manager.failed-some", failed = refused.len(), total = total);
1459            Command::toast(Toast::danger(title).body(lines.join("\n")))
1460        }
1461    }
1462}