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.

6.8 KB
Raw Blame
//! The user's own order for characters, from the system's collation tables.
//!
//! Explorer sorts names with the shell's `StrCmpLogicalW`, whose text half is the locale's
//! collation: pinyin on a zh-CN Windows (白菜 above 苹果), kana in gojūon, and so on.
//! `rf_core::sort` compares names itself — digit runs as numbers, weights for the ASCII signs —
//! and a code point says nothing about the order of Han or kana, so the app installs
//! [`compare_chars`] there at startup (issue 1071). It is asked only about two characters the
//! weights cannot place: both sources must not have a say in one pair, or three names can form a
//! cycle and the sort may panic on it.

use std::cell::RefCell;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::rc::Rc;

use windows::core::PCWSTR;
use windows::Win32::Foundation::LPARAM;
use windows::Win32::Globalization::{LCMapStringEx, LCMAP_SORTKEY};

thread_local! {
    /// Each character's sort key, made once: a sort asks after the same few hundred characters
    /// again and again (a folder of Chinese names), and one key is a trip through NLS.
    static KEYS: RefCell<HashMap<char, Rc<[u8]>>> = RefCell::new(HashMap::new());
}

/// Orders two characters the way the user's Windows does, which is how Explorer orders them.
pub fn compare_chars(a: char, b: char) -> Ordering {
    if a == b {
        return Ordering::Equal;
    }
    let (ka, kb) = (key(a), key(b));
    ka.cmp(&kb)
}

fn key(c: char) -> Rc<[u8]> {
    if let Some(key) = KEYS.with(|keys| keys.borrow().get(&c).cloned()) {
        return key;
    }
    let key: Rc<[u8]> = sort_key(PCWSTR::null(), c).into();
    KEYS.with(|keys| keys.borrow_mut().insert(c, Rc::clone(&key)));
    key
}

/// The character's NLS sort key: the bytes whose memcmp order is the collation's order. The
/// locale is a parameter so a test can ask for one (zh-CN's pinyin) whatever Windows this runs on.
fn sort_key(locale: PCWSTR, c: char) -> Vec<u8> {
    let mut unit = [0u16; 2];
    let src = c.encode_utf16(&mut unit);
    // (a sort key is counted in bytes, the binding counts the slice it is handed: a u16 buffer as
    // long as the key is big holds twice the bytes, and the count it passes is the one NLS wants)
    let need = unsafe { LCMapStringEx(locale, LCMAP_SORTKEY, src, None, None, None, LPARAM(0)) };
    if need <= 0 {
        return (c as u32).to_be_bytes().to_vec();
    }
    let mut buf = vec![0u16; need as usize];
    let written = unsafe { LCMapStringEx(locale, LCMAP_SORTKEY, src, Some(&mut buf), None, None, LPARAM(0)) };
    if written <= 0 || written > need {
        // (no key: the code point, so the order stays total and this shows up as itself)
        return (c as u32).to_be_bytes().to_vec();
    }
    // SAFETY: the buffer holds `need` u16s, so `written` (at most `need`) bytes of it are there.
    unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::<u8>(), written as usize) }.to_vec()
}

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

    /// zh-CN's order, asked for by name: Windows carries every locale's tables, so the test says
    /// what it is about (pinyin) on whatever locale the machine running it has.
    fn zh(a: char, b: char) -> Ordering {
        sort_key(w!("zh-CN"), a).cmp(&sort_key(w!("zh-CN"), b))
    }

    /// A name order, as the app sorts with this collator installed.
    fn cmp(a: &str, b: &str) -> Ordering {
        rf_core::sort::natural_cmp_with(zh, a, b)
    }

    #[test]
    fn the_scripts_a_code_point_cannot_order() {
        // pinyin, as Explorer has it on a zh-CN Windows (issue 1071): bai, da, dian, huo, ping
        assert_eq!(cmp("白", "大"), Ordering::Less);
        assert_eq!(cmp("大", "电"), Ordering::Less);
        assert_eq!(cmp("火", "苹"), Ordering::Less);
        // the code point order is another one (苹 U+82F9 is above 白 U+767D)
        assert_eq!(cmp("苹", "白"), Ordering::Greater);
        // Han after the Latin letters and the digits, as Explorer has them: a pair that straddles
        // the two blocks is the weights' to decide, the collation only hears about Han on both
        // sides
        assert_eq!(cmp("苹", "Z"), Ordering::Greater);
        assert_eq!(cmp("苹", "9"), Ordering::Greater);
    }

    #[test]
    fn a_pair_the_weights_place_is_never_asked_of_the_collation() {
        // Explorer puts a sign before a digit (`会议:` above `会议3`), the weights put the digit
        // first: one source of order per pair, so the weights win here. The sign's own follow-up,
        // not something to mix in (it would let three names form a cycle).
        assert_eq!(cmp(":", "3"), Ordering::Greater);
        // accented letters keep the weights' place as well: after z, not beside e
        assert_eq!(cmp("é", "f"), Ordering::Greater);
        assert_eq!(cmp("é", "e"), Ordering::Greater);
    }

    /// The order has to be total: `sort_unstable_by` is allowed to panic on one that is not, and
    /// three names are enough to show it. One source of order per pair is what keeps it so; this
    /// walks every triple of an alphabet the two sources disagree about, prefixes and digit runs
    /// included.
    #[test]
    fn the_order_is_total_over_every_triple_of_a_mixed_alphabet() {
        const ALPHABET: [&str; 22] = [
            "-", "'", "_", "=", ":", "0", "3", "9", "a", "Z", "é", "ö", "白", "大", "苹", "あ", "。", "a1", "a01", "白1",
            "白-", "a-",
        ];
        for x in ALPHABET {
            for y in ALPHABET {
                let xy = rf_core::sort::natural_cmp_with(compare_chars, x, y);
                assert_eq!(
                    xy,
                    rf_core::sort::natural_cmp_with(compare_chars, y, x).reverse(),
                    "{x} vs {y} disagrees with {y} vs {x}"
                );
                for z in ALPHABET {
                    if xy == Ordering::Greater {
                        continue;
                    }
                    let yz = rf_core::sort::natural_cmp_with(compare_chars, y, z);
                    if yz == Ordering::Greater {
                        continue;
                    }
                    let xz = rf_core::sort::natural_cmp_with(compare_chars, x, z);
                    assert_ne!(xz, Ordering::Greater, "{x} <= {y} <= {z}, but {x} > {z}");
                }
            }
        }
    }

    #[test]
    fn whole_names_in_explorer_order() {
        let mut names =
            vec!["苹果.txt", "Zebra.txt", "电脑10.txt", "大米10.txt", "白菜.txt", "火车.txt", "大米9.txt", "电脑2.txt"];
        names.sort_by(|a, b| rf_core::sort::natural_cmp_with(zh, a, b));
        assert_eq!(
            names,
            vec![
                "Zebra.txt",
                "白菜.txt",
                "大米9.txt",
                "大米10.txt",
                "电脑2.txt",
                "电脑10.txt",
                "火车.txt",
                "苹果.txt",
            ]
        );
    }
}