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