Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

14.1 KB
Raw Blame
//! Which folders a copy, a move or a deletion may have changed, so that the panes showing them can be read again where no change notice comes.
//!
//! WHY: a pane learns what changed in its folder from the system's change notices. A WSL distribution's folder sends none, and many
//! network drives don't either: after Cut and Paste the moved files stayed in the pane they were cut from, and deleted files stayed too.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use crate::navtree::norm;

/// The drive letters connected to a share (`Z:` for `\\nas\media`), so that a pane on the letter and an operation through the share's
/// own path (or the other way round) are known to be in the same folder.
#[derive(Debug, Clone, Default)]
pub struct Mapped(Vec<(char, String)>);

impl Mapped {
    /// From (letter, the share's path) pairs, as the system tells them.
    pub fn new(list: impl IntoIterator<Item = (char, String)>) -> Self {
        Self(list.into_iter().map(|(l, share)| (l.to_ascii_lowercase(), key(Path::new(&share)))).filter(|(_, k)| k.starts_with(r"\\")).collect())
    }

    /// [`key`], with a connected letter replaced by its share.
    fn key(&self, p: &Path) -> String {
        let k = key(p);
        let mut c = k.chars();
        if let (Some(l), Some(':')) = (c.next(), c.next())
            && let Some((_, share)) = self.0.iter().find(|(m, _)| *m == l)
        {
            return format!("{share}{}", c.as_str().trim_end_matches('\\'));
        }
        k
    }

    /// The paths on connected letters that are the folder of `key` (none, or one for each letter its share is connected to).
    fn on_letters(&self, key: &str) -> impl Iterator<Item = String> {
        self.0.iter().filter_map(move |(l, share)| match key.strip_prefix(share.as_str())? {
            "" => Some(format!("{l}:\\")),
            rest => rest.starts_with('\\').then(|| format!("{l}:{rest}")),
        })
    }
}

/// What one transfer or deletion may have changed. The folders are kept by the key they are compared by, each with whether it is on a drive whose
/// change notices can't be relied on.
#[derive(Debug, Clone, Default)]
pub struct Touched {
    /// Folders whose own list changed: the destination, and the folders items were moved out of or deleted from.
    dirs: HashMap<String, bool>,
    /// Folders everything in and under which may have changed: the items moved away or deleted, and what moved ones became in the destination (a
    /// folder of that name there may have been merged into).
    trees: HashMap<String, bool>,
    /// The letters as they were connected when the operation began.
    mapped: Mapped,
}

/// [`norm`], with the two names of a WSL distribution's server and the verbatim spelling of a share made one.
fn key(p: &Path) -> String {
    let k = norm(p);
    let k = match k.strip_prefix(r"\\?\unc\") {
        Some(rest) => format!(r"\\{rest}"),
        None => k,
    };
    match k.strip_prefix(r"\\wsl$\") {
        Some(rest) => format!(r"\\wsl.localhost\{rest}"),
        None => k,
    }
}

/// The folder a key is in, and the key's last name (by text: the keys use backslashes on every system).
fn split(key: &str) -> Option<(String, &str)> {
    let (dir, name) = key.rsplit_once('\\')?;
    if dir.is_empty() || name.is_empty() {
        return None;
    }
    Some((if dir.ends_with(':') { format!("{dir}\\") } else { dir.to_string() }, name))
}

impl Touched {
    /// What a transfer of `sources` into `dest` may change. `remote` says whether a path is on a drive whose change notices can't be
    /// relied on; it is asked once for each folder the items come from, and once for `dest`.
    pub fn by_transfer(moved: bool, sources: &[PathBuf], dest: &Path, mapped: Mapped, mut remote: impl FnMut(&Path) -> bool) -> Self {
        let mut t = Self { mapped, ..Self::default() };
        let (to, to_remote) = (t.mapped.key(dest), remote(dest));
        for s in sources {
            let from = t.mapped.key(s);
            let Some((dir, name)) = split(&from) else { continue };
            t.trees.insert(format!("{}\\{name}", to.trim_end_matches('\\')), to_remote);
            if moved {
                let remote = *t.dirs.entry(dir).or_insert_with(|| remote(s));
                t.trees.insert(from, remote);
            }
        }
        t.dirs.insert(to, to_remote);
        t
    }

    /// What deleting `paths` may change. `remote` as in [`Self::by_transfer`], asked once for each folder the items are in.
    pub fn by_delete(paths: &[PathBuf], mapped: Mapped, mut remote: impl FnMut(&Path) -> bool) -> Self {
        let mut t = Self { mapped, ..Self::default() };
        for p in paths {
            let item = t.mapped.key(p);
            let Some((dir, _)) = split(&item) else { continue };
            let remote = *t.dirs.entry(dir).or_insert_with(|| remote(p));
            t.trees.insert(item, remote);
        }
        t
    }

    /// Whether the list of `dir` may have changed: `Some(true)` on a drive whose change notices can't be relied on, `Some(false)` on
    /// any other, `None` when the transfer had nothing to do with it.
    pub fn changed(&self, dir: &Path) -> Option<bool> {
        let mut at = self.mapped.key(dir);
        if let Some(&remote) = self.dirs.get(&at) {
            return Some(remote);
        }
        // up its own path, not through the items: there can be a great many of them, and the UI thread asks
        loop {
            if let Some(&remote) = self.trees.get(&at) {
                return Some(remote);
            }
            at = split(&at)?.0;
        }
    }

    /// Whether anything in or under `dir` may have changed: its own list, or a folder anywhere inside it. That is what a size measured
    /// for `dir` covers (issue 965: a folder's size in its parent's list stayed as it was after files were deleted inside it, since
    /// the parent's change notices say nothing of what happens inside a subfolder).
    pub fn inside(&self, dir: &Path) -> bool {
        let at = self.mapped.key(dir);
        let below = format!("{}\\", at.trim_end_matches('\\'));
        self.dirs.keys().chain(self.trees.keys()).any(|k| *k == at || k.starts_with(&below))
    }

    /// The folders with a changed list that are on a drive whose change notices can't be relied on, in every spelling they may be
    /// open under.
    /// Every folder whose list or contents changed (the folders listed and the items' own paths), in every spelling they may be open
    /// under. A size measured for any of them or for a folder above them is out of date (issue 965).
    pub fn all_dirs(&self) -> Vec<PathBuf> {
        let mut out = Vec::new();
        for key in self.dirs.keys().chain(self.trees.keys()) {
            out.push(PathBuf::from(key));
            out.extend(self.mapped.on_letters(key).map(PathBuf::from));
        }
        out
    }

    pub fn remote_dirs(&self) -> Vec<PathBuf> {
        let mut out = Vec::new();
        for (key, _) in self.dirs.iter().filter(|&(_, &remote)| remote) {
            out.push(PathBuf::from(key));
            out.extend(self.mapped.on_letters(key).map(PathBuf::from));
            if let Some(rest) = key.strip_prefix(r"\\wsl.localhost\") {
                out.push(PathBuf::from(format!(r"\\wsl$\{rest}")));
            }
        }
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn paths(list: &[&str]) -> Vec<PathBuf> {
        list.iter().map(PathBuf::from).collect()
    }

    fn unc(p: &Path) -> bool {
        p.to_string_lossy().starts_with(r"\\")
    }

    #[test]
    fn a_move_changes_the_folder_it_takes_from_and_the_one_it_goes_to() {
        let t = Touched::by_transfer(true, &paths(&[r"\\wsl.localhost\Ubuntu\home\me\a.txt"]), Path::new(r"C:\in"), Mapped::default(), unc);
        assert_eq!(t.changed(Path::new(r"\\wsl.localhost\Ubuntu\home\me")), Some(true));
        assert_eq!(t.changed(Path::new(r"\\WSL.LOCALHOST\ubuntu\home\me\")), Some(true), "case and a closing separator");
        assert_eq!(t.changed(Path::new(r"C:\in")), Some(false), "a local folder has its watcher");
        assert_eq!(t.changed(Path::new(r"\\wsl.localhost\Ubuntu\home")), None);
        assert_eq!(t.changed(Path::new(r"\\wsl.localhost\Ubuntu\home\me\other")), None);
        assert_eq!(t.remote_dirs(), paths(&[r"\\wsl.localhost\ubuntu\home\me", r"\\wsl$\ubuntu\home\me"]));
    }

    #[test]
    fn a_change_anywhere_inside_a_folder_is_inside_it_and_nowhere_else() {
        let t = Touched::by_delete(&paths(&[r"C:\top\data\sub\g.bin"]), Mapped::default(), unc);
        assert!(t.inside(Path::new(r"C:\top\data\sub")), "the folder the item was deleted from");
        assert!(t.inside(Path::new(r"C:\top\data")), "a folder above it");
        assert!(t.inside(Path::new(r"C:\")), "the drive");
        assert!(t.inside(Path::new(r"c:\TOP\")), "case and a closing separator");
        assert!(!t.inside(Path::new(r"C:\top\database")), "a name that only begins the same");
        assert!(!t.inside(Path::new(r"C:\top\data\other")), "a folder beside it");
        let m = Touched::by_transfer(false, &paths(&[r"D:\a.txt"]), Path::new(r"C:\top\in"), Mapped::default(), unc);
        assert!(m.inside(Path::new(r"C:\top")), "a paste into a folder inside it");
        assert!(!m.inside(Path::new(r"D:\")), "a copy changes nothing where it takes from");
    }

    #[test]
    fn a_copy_leaves_the_folder_it_takes_from_alone() {
        let t = Touched::by_transfer(false, &paths(&[r"\\nas\share\a.txt"]), Path::new(r"\\nas\in"), Mapped::default(), unc);
        assert_eq!(t.changed(Path::new(r"\\nas\share")), None);
        assert_eq!(t.changed(Path::new(r"\\nas\in")), Some(true));
    }

    #[test]
    fn the_spellings_of_one_wsl_folder_are_the_same_folder() {
        let t = Touched::by_transfer(true, &paths(&[r"\\wsl$\Ubuntu\tmp\a.txt"]), Path::new(r"C:\in"), Mapped::default(), unc);
        assert_eq!(t.changed(Path::new(r"\\wsl.localhost\Ubuntu\tmp")), Some(true));
        assert_eq!(t.changed(Path::new(r"\\?\UNC\wsl$\Ubuntu\tmp")), Some(true));
    }

    #[test]
    fn a_pane_in_a_moved_folder_or_in_one_that_was_merged_into_is_reached() {
        let t = Touched::by_transfer(true, &paths(&[r"\\nas\share\album"]), Path::new(r"Z:\"), Mapped::default(), |p| unc(p) || p.starts_with(r"Z:\"));
        assert_eq!(t.changed(Path::new(r"\\nas\share\album\2024")), Some(true));
        assert_eq!(t.changed(Path::new(r"\\nas\share\albums")), None, "a name that only begins the same");
        assert_eq!(t.changed(Path::new(r"Z:\album\2024")), Some(true));
        assert_eq!(t.changed(Path::new(r"Z:\")), Some(true), "a drive's root");
        assert_eq!(t.changed(Path::new(r"Z:\other")), None);
    }

    #[test]
    fn a_move_out_of_a_drives_root_names_that_root() {
        let t = Touched::by_transfer(true, &paths(&[r"Z:\a.txt", r"Z:\b.txt"]), Path::new(r"C:\in"), Mapped::default(), |p| p.to_string_lossy().starts_with("Z:"));
        assert_eq!(t.changed(Path::new(r"Z:\")), Some(true));
        assert_eq!(t.remote_dirs(), paths(&[r"z:\"]));
    }

    #[test]
    fn a_connected_letter_and_its_share_are_the_same_folder() {
        let mapped = || Mapped::new([('Z', r"\\NAS\Media".to_string()), ('W', r"\\wsl$\Ubuntu".to_string()), ('Y', r"\\nas\media\deep".to_string())]);
        let net = |p: &Path| unc(p) || !p.to_string_lossy().starts_with("C:");
        // cut through the share, shown on the letter
        let t = Touched::by_transfer(true, &paths(&[r"\\nas\media\new\a.txt"]), Path::new(r"C:\in"), mapped(), net);
        assert_eq!(t.changed(Path::new(r"Z:\new")), Some(true));
        assert_eq!(t.changed(Path::new(r"\\?\Z:\New\")), Some(true));
        assert_eq!(t.changed(Path::new(r"Z:\")), None);
        assert_eq!(t.remote_dirs(), paths(&[r"\\nas\media\new", r"z:\new"]));
        // cut on the letter, shown through the share and through another letter
        let t = Touched::by_transfer(true, &paths(&[r"Z:\deep\a.txt"]), Path::new(r"C:\in"), mapped(), net);
        assert_eq!(t.changed(Path::new(r"\\nas\media\deep")), Some(true));
        assert_eq!(t.changed(Path::new(r"Y:\")), Some(true), "a letter connected to a folder inside the share");
        assert_eq!(t.remote_dirs(), paths(&[r"\\nas\media\deep", r"z:\deep", r"y:\"]));
        // a letter's root, and a share whose name only begins the same
        let t = Touched::by_delete(&paths(&[r"Z:\a.txt", r"\\nas\media2\b.txt"]), mapped(), net);
        assert_eq!(t.changed(Path::new(r"\\nas\media")), Some(true));
        let dirs = t.remote_dirs();
        assert_eq!(dirs.len(), 3, "{dirs:?}");
        assert!(dirs.contains(&PathBuf::from(r"z:\")) && dirs.contains(&PathBuf::from(r"\\nas\media2")));
        // a WSL distribution on a letter, under either name of its server
        let t = Touched::by_delete(&paths(&[r"\\wsl.localhost\Ubuntu\tmp\a.txt"]), mapped(), net);
        assert_eq!(t.changed(Path::new(r"W:\tmp")), Some(true));
    }

    #[test]
    fn a_letter_that_is_not_connected_stays_itself() {
        let mapped = Mapped::new([('Z', r"\\nas\media".to_string()), ('X', "not a share".to_string())]);
        let t = Touched::by_delete(&paths(&[r"X:\d\a.txt", r"C:\d\b.txt"]), mapped, |_| false);
        assert_eq!(t.changed(Path::new(r"X:\d")), Some(false));
        assert_eq!(t.changed(Path::new(r"C:\d")), Some(false));
        assert_eq!(t.changed(Path::new(r"Z:\d")), None);
    }

    #[test]
    fn a_deletion_changes_the_folders_the_items_were_in_and_what_was_in_them() {
        let t = Touched::by_delete(&paths(&[r"\\nas\share\album", r"\\wsl$\Ubuntu\tmp\a.txt", r"C:\x\b.txt"]), Mapped::default(), unc);
        assert_eq!(t.changed(Path::new(r"\\nas\share")), Some(true));
        assert_eq!(t.changed(Path::new(r"\\nas\share\album\2024")), Some(true), "a pane in the deleted folder");
        assert_eq!(t.changed(Path::new(r"\\nas\share\other")), None);
        assert_eq!(t.changed(Path::new(r"\\wsl.localhost\Ubuntu\tmp")), Some(true));
        assert_eq!(t.changed(Path::new(r"C:\x")), Some(false), "a local folder has its watcher");
    }

    #[test]
    fn each_folder_is_asked_about_once() {
        let mut asked = 0;
        let sources: Vec<PathBuf> = (0..1000).map(|i| PathBuf::from(format!(r"Z:\from\{i}.txt"))).collect();
        Touched::by_transfer(true, &sources, Path::new(r"C:\in"), Mapped::default(), |_| {
            asked += 1;
            true
        });
        assert_eq!(asked, 2);
    }
}