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.

21.6 KB
Raw Blame
use std::cmp::Ordering;
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
use std::sync::OnceLock;

use serde::{Deserialize, Serialize};

use crate::entry::Entry;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum SortKey {
    #[default]
    Name,
    Modified,
    Created,
    Size,
    Type,
    /// By tag (the order of the tags in Settings, untagged last). Needs one rank per entry:
    /// see `sortkeys`. Stored apart from the five above in the layout file.
    Tag,
    /// By the folder the item lies in, then its name (results from several folders).
    Path,
    /// By the sync column's state (online only, here, always here).
    Sync,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum SortDir {
    #[default]
    Asc,
    Desc,
}

impl SortDir {
    pub fn flip(self) -> Self {
        match self {
            SortDir::Asc => SortDir::Desc,
            SortDir::Desc => SortDir::Asc,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SortSpec {
    pub key: SortKey,
    pub dir: SortDir,
    pub dirs_first: bool,
    /// Files before folders (Files' "sort files first"); both false = mixed.
    pub files_first: bool,
}

impl Default for SortSpec {
    fn default() -> Self {
        Self { key: SortKey::Name, dir: SortDir::Asc, dirs_first: true, files_first: false }
    }
}

impl SortSpec {
    /// Clicking a column header: same key flips direction, new key starts ascending
    /// (except dates/size which feel more natural newest/biggest first).
    pub fn toggled(self, key: SortKey) -> Self {
        if self.key == key {
            Self { dir: self.dir.flip(), ..self }
        } else {
            let dir = match key {
                SortKey::Modified | SortKey::Created | SortKey::Size => SortDir::Desc,
                _ => SortDir::Asc,
            };
            Self { key, dir, ..self }
        }
    }

    /// Folders before files (or the reverse), when the spec asks; `None` = decided by the key.
    fn folder_order(&self, a: &Entry, b: &Entry) -> Option<Ordering> {
        if self.dirs_first && a.is_dir() != b.is_dir() {
            return Some(if a.is_dir() { Ordering::Less } else { Ordering::Greater });
        }
        if self.files_first && a.is_dir() != b.is_dir() {
            return Some(if a.is_dir() { Ordering::Greater } else { Ordering::Less });
        }
        None
    }

    fn directed(&self, ord: Ordering) -> Ordering {
        match self.dir {
            SortDir::Asc => ord,
            SortDir::Desc => ord.reverse(),
        }
    }

    /// Compares two entries by their own fields. The keys that need a value made beforehand
    /// (`Tag`, `Path`: see [`SortSpec::compare_ranked`]) fall back to the name here.
    pub fn compare(&self, a: &Entry, b: &Entry) -> Ordering {
        if let Some(o) = self.folder_order(a, b) {
            return o;
        }
        let primary = match self.key {
            SortKey::Name | SortKey::Tag | SortKey::Path => Ordering::Equal,
            SortKey::Modified => a.modified_ms.cmp(&b.modified_ms),
            SortKey::Created => a.created_ms.cmp(&b.created_ms),
            SortKey::Size => a.size.cmp(&b.size),
            SortKey::Type => a.ext.cmp(&b.ext),
            SortKey::Sync => crate::sortkeys::sync_rank(a).cmp(&crate::sortkeys::sync_rank(b)),
        };
        self.directed(primary.then_with(|| natural_cmp(a.shown(), b.shown())))
    }

    /// [`compare`](Self::compare) by the key alone, without breaking ties by name: entries the
    /// key cannot tell apart compare equal, so a second sort can order them (the items inside
    /// one group of a grouped list, sorted by the column the user picked).
    pub fn compare_key(&self, a: &Entry, b: &Entry) -> Ordering {
        if let Some(o) = self.folder_order(a, b) {
            return o;
        }
        let primary = match self.key {
            SortKey::Name | SortKey::Tag | SortKey::Path => natural_cmp(a.shown(), b.shown()),
            SortKey::Modified => a.modified_ms.cmp(&b.modified_ms),
            SortKey::Created => a.created_ms.cmp(&b.created_ms),
            SortKey::Size => a.size.cmp(&b.size),
            SortKey::Type => a.ext.cmp(&b.ext),
            SortKey::Sync => crate::sortkeys::sync_rank(a).cmp(&crate::sortkeys::sync_rank(b)),
        };
        self.directed(primary)
    }

    /// [`compare`](Self::compare) for the keys that sort by a rank made beforehand (one `u32` per
    /// entry: `ra`, `rb`). A tag sort keeps the entries without a tag ([`crate::sortkeys::NO_RANK`])
    /// last in both directions, the way folders stay first; ties are broken by name.
    pub fn compare_ranked(&self, a: &Entry, ra: u32, b: &Entry, rb: u32) -> Ordering {
        if !self.key.needs_ranks() {
            return self.compare(a, b);
        }
        if self.key == SortKey::Path {
            // The folder of the hit comes first, so every folder's hits stay one run. "Folders
            // first" then applies inside a folder (a directory leads its own folder's hits);
            // putting every directory before every file would split each folder's hits in two.
            let by_folder = self.directed(ra.cmp(&rb));
            if by_folder != Ordering::Equal {
                return by_folder;
            }
            return self.folder_order(a, b).unwrap_or_else(|| self.directed(natural_cmp(a.shown(), b.shown())));
        }
        if let Some(o) = self.folder_order(a, b) {
            return o;
        }
        if self.key == SortKey::Tag {
            use crate::sortkeys::NO_RANK;
            match (ra == NO_RANK, rb == NO_RANK) {
                (true, false) => return Ordering::Greater,
                (false, true) => return Ordering::Less,
                _ => {}
            }
        }
        self.directed(ra.cmp(&rb).then_with(|| natural_cmp(a.shown(), b.shown())))
    }

    /// Sorts indices into `entries` (we sort indices, not entries, so re-sorting is cheap).
    pub fn sort_indices(&self, entries: &[Entry], idx: &mut [u32]) {
        idx.sort_unstable_by(|&x, &y| self.compare(&entries[x as usize], &entries[y as usize]));
    }

    /// [`sort_indices`](Self::sort_indices) with one rank per entry (`ranks[i]` for `entries[i]`;
    /// a missing rank counts as none). Keys that need no rank sort as usual.
    pub fn sort_indices_ranked(&self, entries: &[Entry], ranks: &[u32], idx: &mut [u32]) {
        if !self.key.needs_ranks() {
            return self.sort_indices(entries, idx);
        }
        let rank = |i: u32| ranks.get(i as usize).copied().unwrap_or(crate::sortkeys::NO_RANK);
        idx.sort_unstable_by(|&x, &y| self.compare_ranked(&entries[x as usize], rank(x), &entries[y as usize], rank(y)));
    }
}

/// The platform's own order for two characters, once a platform crate has installed it (see
/// [`set_char_collator`]).
static COLLATOR: OnceLock<fn(char, char) -> Ordering> = OnceLock::new();

/// Gives name sorting the user's collation for the characters the weights below cannot place: on
/// a zh-CN Windows that is pinyin (白菜 before 苹果, as Explorer has it), on a Japanese one kana
/// among themselves. It orders those characters among themselves, never against a character the
/// weights already place: one source of order per pair, or three names can cycle and
/// `sort_unstable_by` may panic on a comparison that is not a total order. Installed once at
/// startup; where no platform installs one (tests, macOS for now) those characters keep code
/// point order.
pub fn set_char_collator(collate: fn(char, char) -> Ordering) {
    let _ = COLLATOR.set(collate);
}

/// Explorer-like "logical" comparison: case-insensitive, digit runs compared numerically
/// ("file2" < "file10"). Allocation-free on the ASCII path, which is the one a big folder takes
/// ~n·log n times; a character the weights cannot place pays a lookup (the platform's collator
/// caches its key).
pub fn natural_cmp(a: &str, b: &str) -> Ordering {
    natural_cmp_inner(COLLATOR.get().copied(), a, b)
}

/// [`natural_cmp`] with the collation handed in: a platform crate's tests sort through their own
/// without installing it for every other test in the process (see the Turkish note below).
pub fn natural_cmp_with(collate: fn(char, char) -> Ordering, a: &str, b: &str) -> Ordering {
    natural_cmp_inner(Some(collate), a, b)
}

fn natural_cmp_inner(collate: Option<fn(char, char) -> Ordering>, a: &str, b: &str) -> Ordering {
    if a.is_ascii() && b.is_ascii() {
        return natural_ascii(a.as_bytes(), b.as_bytes()).then_with(|| a.cmp(b));
    }
    let mut ai = a.char_indices().peekable();
    let mut bi = b.char_indices().peekable();
    loop {
        match (ai.peek().copied(), bi.peek().copied()) {
            (None, None) => return a.cmp(b), // stable tiebreak on exact bytes
            (None, Some(_)) => return Ordering::Less,
            (Some(_), None) => return Ordering::Greater,
            (Some((ia, ca)), Some((ib, cb))) => {
                if ca.is_ascii_digit() && cb.is_ascii_digit() {
                    let ea = digit_end(a.as_bytes(), ia);
                    let eb = digit_end(b.as_bytes(), ib);
                    let o = cmp_digits(&a.as_bytes()[ia..ea], &b.as_bytes()[ib..eb]);
                    if o != Ordering::Equal {
                        return o;
                    }
                    while ai.peek().is_some_and(|(i, _)| *i < ea) {
                        ai.next();
                    }
                    while bi.peek().is_some_and(|(i, _)| *i < eb) {
                        bi.next();
                    }
                } else {
                    let (la, lb) = (rank(ca), rank(cb));
                    if la != lb {
                        // One source of order for this pair: the weights decide every character
                        // they can place, and the collation only those they cannot, among
                        // themselves (issue 1071). Asking it about a pair the weights also have
                        // an opinion on lets the two disagree, and a < b < c < a is not a total
                        // order — `sort_unstable_by` may panic on one.
                        if la >= OTHER && lb >= OTHER {
                            if let Some(order) = locale_order(collate, ca, cb) {
                                return order;
                            }
                        }
                        return la.cmp(&lb);
                    }
                    ai.next();
                    bi.next();
                }
            }
        }
    }
}

/// The collation's answer for two characters, when it has one to give. Only characters the
/// weights cannot place reach it (see `rank`), so its order never has to agree with theirs.
fn locale_order(collate: Option<fn(char, char) -> Ordering>, a: char, b: char) -> Option<Ordering> {
    let order = collate?(a, b);
    (order != Ordering::Equal).then_some(order)
}

fn digit_end(s: &[u8], mut i: usize) -> usize {
    while i < s.len() && s[i].is_ascii_digit() {
        i += 1;
    }
    i
}

/// Numeric comparison of two digit runs of any length (no overflow), then shorter run first.
fn cmp_digits(x: &[u8], y: &[u8]) -> Ordering {
    let tx = &x[x.iter().take_while(|&&c| c == b'0').count()..];
    let ty = &y[y.iter().take_while(|&&c| c == b'0').count()..];
    tx.len().cmp(&ty.len()).then_with(|| tx.cmp(ty)).then_with(|| x.len().cmp(&y.len()))
}

fn natural_ascii(a: &[u8], b: &[u8]) -> Ordering {
    let (mut i, mut j) = (0, 0);
    while i < a.len() && j < b.len() {
        let (ca, cb) = (a[i], b[j]);
        if ca.is_ascii_digit() && cb.is_ascii_digit() {
            let (ea, eb) = (digit_end(a, i), digit_end(b, j));
            let o = cmp_digits(&a[i..ea], &b[j..eb]);
            if o != Ordering::Equal {
                return o;
            }
            i = ea;
            j = eb;
        } else {
            let (la, lb) = (rank(ca as char), rank(cb as char));
            if la != lb {
                return la.cmp(&lb);
            }
            i += 1;
            j += 1;
        }
    }
    (a.len() - i).cmp(&(b.len() - j))
}

static TURKISH: AtomicBool = AtomicBool::new(false);

/// First weight of a character the table above has no place for: every character it can place
/// sorts below this, so a pair above it is the collation's and a pair straddling it is the
/// weights' (see `natural_cmp_inner`).
const OTHER: u32 = 0x10000;

/// Turkish collation: capital `I` is the capital of dotless `ı` (as Explorer sorts on Turkish
/// Windows). Set once at startup from the user locale.
pub fn set_turkish_collation(on: bool) {
    TURKISH.store(on, AtomicOrdering::Relaxed);
}

pub(crate) fn turkish() -> bool {
    TURKISH.load(AtomicOrdering::Relaxed)
}

/// Uppercase. On a Turkish locale, words that are visibly Turkish (contain ç ğ ı ö ş ü or
/// their capitals, or İ) use Turkish rules (i → İ); other words — English file names such as
/// "windows", "readme" — use standard rules, so they don't turn into "WİNDOWS".
pub fn upper(s: &str) -> String {
    upper_with(s, turkish())
}

/// Lowercase; see `upper` for when Turkish rules (I → ı) apply. İ always becomes plain i.
pub fn lower(s: &str) -> String {
    lower_with(s, turkish())
}

fn is_turkish_word(w: &str) -> bool {
    w.chars().any(|c| matches!(c, 'ç' | 'ğ' | 'ı' | 'ö' | 'ş' | 'ü' | 'Ç' | 'Ğ' | 'İ' | 'Ö' | 'Ş' | 'Ü'))
}

/// Applies `f(word, turkish_rules)` to each alphanumeric run, keeping separators as they are.
fn map_words(s: &str, turkish: bool, f: impl Fn(&str, bool) -> String) -> String {
    let mut out = String::with_capacity(s.len());
    let mut word = String::new();
    let flush = |word: &mut String, out: &mut String| {
        if !word.is_empty() {
            out.push_str(&f(word, turkish && is_turkish_word(word)));
            word.clear();
        }
    };
    for c in s.chars() {
        if c.is_alphanumeric() {
            word.push(c);
        } else {
            flush(&mut word, &mut out);
            out.push(c);
        }
    }
    flush(&mut word, &mut out);
    out
}

fn upper_char(c: char, tr: bool) -> String {
    match c {
        'i' if tr => "İ".into(),
        'ı' => "I".into(),
        _ => c.to_uppercase().collect(),
    }
}

fn lower_char(c: char, tr: bool) -> String {
    match c {
        'I' if tr => "ı".into(),
        'İ' => "i".into(),
        _ => c.to_lowercase().collect(),
    }
}

fn upper_with(s: &str, turkish: bool) -> String {
    map_words(s, turkish, |w, tr| w.chars().map(|c| upper_char(c, tr)).collect())
}

fn lower_with(s: &str, turkish: bool) -> String {
    map_words(s, turkish, |w, tr| w.chars().map(|c| lower_char(c, tr)).collect())
}

/// "hELLO wORLD-foo" → "Hello World-Foo", with the same per-word Turkish rule.
pub fn title(s: &str) -> String {
    title_with(s, turkish())
}

fn title_with(s: &str, turkish: bool) -> String {
    map_words(s, turkish, |w, tr| {
        let mut cs = w.chars();
        match cs.next() {
            Some(first) => upper_char(first, tr) + &cs.map(|c| lower_char(c, tr)).collect::<String>(),
            None => String::new(),
        }
    })
}

/// Case-insensitive sort weight of a character (two digits are compared as numbers before this is asked).
/// - Punctuation and symbols (ASCII) before digits and letters, as in Explorer. WHY the digits have a weight of their own (issue
///   315): by code point `_` and the other signs after `9` (`: ; = @ [ ] ^ { } ~`) came after the digits, so "_test" stood below
///   "1_test" where Explorer has it on top.
/// - Digits, then letters.
/// - Latin letters in alphabet order, with the Turkish letters right after their base letter
///   (c ç d … g ğ h ı i … o ö p … s ş t u ü v) instead of after `z` by code point.
/// - Everything else after, by code point — or, where a collation is installed
///   ([`set_char_collator`]), in the collation's order among themselves. These are the characters
///   whose place in the alphabet a code point cannot name (Han, kana, accented Latin).
#[inline]
fn rank(c: char) -> u32 {
    const LETTERS: u32 = 0x1000;
    const DIGITS: u32 = 0x100;
    let r = |b: char| LETTERS + (b as u32 - 'a' as u32) * 4;
    let c = match c {
        'I' if TURKISH.load(AtomicOrdering::Relaxed) => 'ı',
        'İ' => 'i',
        _ => c,
    };
    let l = if c.is_ascii() { c.to_ascii_lowercase() } else { c.to_lowercase().next().unwrap_or(c) };
    match l {
        'a'..='z' => r(l),
        '0'..='9' => DIGITS + l as u32,
        'ç' => r('c') + 2,
        'ğ' => r('g') + 2,
        'ı' => r('i') - 2,
        'ö' => r('o') + 2,
        'ş' => r('s') + 2,
        'ü' => r('u') + 2,
        _ if l.is_ascii() => l as u32,
        _ => OTHER + l as u32,
    }
}

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

    #[test]
    fn natural_order() {
        let mut v = vec!["file10", "File2", "file1", "a", "B", "file02"];
        v.sort_by(|a, b| natural_cmp(a, b));
        assert_eq!(v, vec!["a", "B", "file1", "File2", "file02", "file10"]);
        // non-ASCII path agrees with the ASCII fast path
        let mut t = vec!["dosya10", "Çalışma2", "dosya2", "çalışma10", "Dosya1"];
        t.sort_by(|a, b| natural_cmp(a, b));
        assert_eq!(t, vec!["Çalışma2", "çalışma10", "Dosya1", "dosya2", "dosya10"]);
        assert_eq!(natural_cmp("x99999999999999999999999", "x100000000000000000000000"), Ordering::Less);
        // Turkish letters next to their base letter, not after z
        let mut tr = vec!["Zebra", "Çanta", "Dosya", "Ceket", "Şeker", "Su", "Tuz", "Ödev", "Ov", "Üzüm", "Uçak", "Vazo", "ılık", "iki", "hava", "ğ", "h"];
        tr.sort_by(|a, b| natural_cmp(a, b));
        assert_eq!(tr, vec!["Ceket", "Çanta", "Dosya", "ğ", "h", "hava", "ılık", "iki", "Ov", "Ödev", "Su", "Şeker", "Tuz", "Uçak", "Üzüm", "Vazo", "Zebra"]);
        // Turkish case rules only when enabled
        // (explicit flag: tests must not flip the global while others run in parallel)
        // Turkish words get Turkish rules, English-looking words standard ones
        assert_eq!(upper_with("işlem ılık windows", true), "İŞLEM ILIK WINDOWS");
        assert_eq!(lower_with("İZMİR WINDOWS README", true), "izmir windows readme");
        assert_eq!(upper_with("istanbul", false), "ISTANBUL");
        assert_eq!(title_with("şİMDİ readME", true), "Şimdi Readme");
        // consistent total order between the ASCII fast path and the general path
        let words = ["a", "B", "_x", "ç", "c", "I", "ı", "i", "İ", "z", "10", "9", "~", "é", "e"];
        for x in words {
            for y in words {
                assert_eq!(natural_cmp(x, y), natural_cmp(y, x).reverse(), "{x} {y}");
            }
        }
    }

    #[test]
    fn the_collation_orders_the_scripts_the_weights_only_know_by_code_point() {
        // a stand-in for Windows' CompareStringEx: the pinyin order of these four
        fn pinyin(a: char, b: char) -> Ordering {
            let weight = |c| match c {
                '白' => 0,
                '大' => 1,
                '电' => 2,
                '苹' => 3,
                _ => 4,
            };
            weight(a).cmp(&weight(b))
        }
        let mut v = vec!["苹果", "白菜", "大米", "电脑"];
        v.sort_by(|a, b| natural_cmp_with(pinyin, a, b));
        assert_eq!(v, vec!["白菜", "大米", "电脑", "苹果"]);
        // without one, the code point order is what it always was
        let mut w = vec!["苹果", "白菜", "大米", "电脑"];
        w.sort_by(|a, b| natural_cmp_inner(None, a, b));
        assert_eq!(w, vec!["大米", "电脑", "白菜", "苹果"]);
        // and ASCII names never reach it: the fast path answers first
        fn never(_: char, _: char) -> Ordering {
            panic!("an ASCII name must not ask the collation")
        }
        assert_eq!(natural_cmp_with(never, "file2", "file10"), Ordering::Less);
        assert_eq!(natural_cmp_with(never, "_test.txt", "1_test.txt"), Ordering::Less);
        // in a name that mixes the two, only the pairs the weights cannot place are handed over:
        // a character they place is never compared by the collation, even against one they cannot
        fn placed(_: char, _: char) -> Ordering {
            panic!("a character the weights place must not ask the collation")
        }
        assert_eq!(natural_cmp_with(placed, "苹.txt", "a.txt"), Ordering::Greater);
        assert_eq!(natural_cmp_with(placed, "苹.txt", "1.txt"), Ordering::Greater);
    }

    #[test]
    fn signs_stand_before_digits_and_digits_before_letters() {
        let mut v = vec!["2_test.txt", "a.txt", "1_test.txt", "_test.txt", "~x", "[x]", "9"];
        v.sort_by(|a, b| natural_cmp(a, b));
        assert_eq!(v, vec!["[x]", "_test.txt", "~x", "1_test.txt", "2_test.txt", "9", "a.txt"]);
        // the same with a letter that takes the other path
        let mut t = vec!["1_ç", "_ç", "ç"];
        t.sort_by(|a, b| natural_cmp(a, b));
        assert_eq!(t, vec!["_ç", "1_ç", "ç"]);
        // inside a name too: a sign against a digit
        assert_eq!(natural_cmp("a_1", "a1"), Ordering::Less);
    }

    #[test]
    fn dirs_first_and_toggle() {
        let es = vec![
            Entry::new("z.txt", EntryKind::File, 10, 5, 0, 0),
            Entry::new("adir", EntryKind::Dir, 0, 1, 0, 0),
            Entry::new("b.txt", EntryKind::File, 99, 9, 0, 0),
        ];
        let mut idx: Vec<u32> = (0..3).collect();
        SortSpec::default().sort_indices(&es, &mut idx);
        assert_eq!(idx, vec![1, 2, 0]);
        let s = SortSpec::default().toggled(SortKey::Size);
        assert_eq!(s.dir, SortDir::Desc);
        s.sort_indices(&es, &mut idx);
        assert_eq!(idx, vec![1, 2, 0]);
        let s = s.toggled(SortKey::Size);
        assert_eq!(s.dir, SortDir::Asc);
    }
}