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.

Sort names by the locale's collation, not by code point

DeepSky Loong99538a7e4d64
diff --git a/crates/rf-app/src/lib.rs b/crates/rf-app/src/lib.rs
index 90a5eb59..54339562 100644
--- a/crates/rf-app/src/lib.rs
+++ b/crates/rf-app/src/lib.rs
@@ -1030,6 +1030,9 @@ pub fn main() {
app_icon::reapply(cx.global::<settings::Settings>().app_icon.clone());
}
rf_core::sort::set_turkish_collation(rf_win::encoding::user_locale_is_turkish());
+ // (names the way Explorer orders them: pinyin on a Chinese Windows, accents beside their
+ // base letter, issue 1071)
+ rf_core::sort::set_char_collator(rf_win::collate::compare_chars);
// eski kod sayfalı metinlerin tahmini: Türkçe olmayan sistemde Türkçe ipucu verilmez
if !rf_win::encoding::user_locale_is_turkish() {
rf_core::textload::set_locale_hint(None);
diff --git a/crates/rf-core/src/sort.rs b/crates/rf-core/src/sort.rs
index 48d6f939..25129df4 100644
--- a/crates/rf-core/src/sort.rs
+++ b/crates/rf-core/src/sort.rs
@@ -1,5 +1,6 @@
use std::cmp::Ordering;
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
+use std::sync::OnceLock;
use serde::{Deserialize, Serialize};
@@ -168,9 +169,32 @@ impl SortSpec {
}
}
+/// 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 any Windows the
+/// locale's letters with their accents next to the plain ones. 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 (it runs ~n·log n times when sorting big folders).
+/// ("file2" < "file10"). Allocation-free on the ASCII path, which is the one a big folder takes
+/// ~n·log n times; a non-ASCII character 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));
}
@@ -198,6 +222,11 @@ pub fn natural_cmp(a: &str, b: &str) -> Ordering {
} else {
let (la, lb) = (rank(ca), rank(cb));
if la != lb {
+ // (in the scripts these weights only know by code point — Han, kana,
+ // accented Latin — the locale decides, issue 1071)
+ if let Some(order) = locale_order(collate, ca, cb) {
+ return order;
+ }
return la.cmp(&lb);
}
ai.next();
@@ -208,6 +237,16 @@ pub fn natural_cmp(a: &str, b: &str) -> Ordering {
}
}
+/// The collation's answer for two characters, when it has one to give: the ASCII weights are
+/// already the user's alphabet, everything above them is not.
+fn locale_order(collate: Option<fn(char, char) -> Ordering>, a: char, b: char) -> Option<Ordering> {
+ if a.is_ascii() && b.is_ascii() {
+ return None;
+ }
+ 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;
@@ -342,7 +381,8 @@ fn title_with(s: &str, turkish: bool) -> String {
/// - 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.
+/// - Everything else after, by code point, unless a collation is installed
+/// ([`set_char_collator`]): it decides these, the scripts whose order is not code point.
#[inline]
fn rank(c: char) -> u32 {
const LETTERS: u32 = 0x1000;
@@ -403,6 +443,34 @@ mod tests {
}
}
+ #[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);
+ }
+
#[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"];
diff --git a/crates/rf-win/src/collate.rs b/crates/rf-win/src/collate.rs
new file mode 100644
index 00000000..11e2f34d
--- /dev/null
+++ b/crates/rf-win/src/collate.rs
@@ -0,0 +1,110 @@
+//! 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 苹果), letters with their accents beside the
+//! plain ones, 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 that order, so the app installs
+//! [`compare_chars`] there at startup (issue 1071).
+
+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))
+ }
+
+ #[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!(zh('白', '大'), Ordering::Less);
+ assert_eq!(zh('大', '电'), Ordering::Less);
+ assert_eq!(zh('火', '苹'), Ordering::Less);
+ // the code point order is another one (苹 U+82F9 is above 白 U+767D)
+ assert_eq!(zh('苹', '白'), Ordering::Greater);
+ // Han after the Latin letters and the digits, as Explorer has them
+ assert_eq!(zh('苹', 'Z'), Ordering::Greater);
+ assert_eq!(zh('苹', '9'), Ordering::Greater);
+ // a sign before a digit
+ assert_eq!(zh(':', '3'), Ordering::Less);
+ // accented letters beside their base letter, not after z
+ assert_eq!(zh('é', 'f'), Ordering::Less);
+ }
+
+ #[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",
+ ]
+ );
+ }
+}
diff --git a/crates/rf-win/src/lib.rs b/crates/rf-win/src/lib.rs
index 071a864f..a6ed20d4 100644
--- a/crates/rf-win/src/lib.rs
+++ b/crates/rf-win/src/lib.rs
@@ -13,6 +13,7 @@ pub mod apps_direct;
pub mod bench;
pub mod cert;
pub mod clipboard;
+pub mod collate;
pub mod vfiles;
pub mod complete;
pub mod ctxmenu;