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.7 KB
Raw Blame
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};

use chrono::{Local, TimeZone};

static ENGLISH: AtomicBool = AtomicBool::new(false);
static DECIMAL: AtomicBool = AtomicBool::new(false);
static IEC: AtomicBool = AtomicBool::new(false);
static DATE_STYLE: AtomicU8 = AtomicU8::new(0);
/// How the system writes a local date and time (Windows' short date and time, set by the app at start: `set_system_format`).
/// Unset (tests, other platforms): "05.11.2026 13:45".
static SYSTEM_FORMAT: std::sync::OnceLock<fn(&chrono::DateTime<Local>) -> Option<String>> = std::sync::OnceLock::new();
/// The same for the date alone ("17.11.2026"), for the places that show a day and no time: `set_system_date`.
/// Unset (tests, other platforms): "05.11.2026".
static SYSTEM_DATE: std::sync::OnceLock<fn(&chrono::DateTime<Local>) -> Option<String>> = std::sync::OnceLock::new();

/// Gives the date code the system's own way of writing a local date and time (issue 59: "Format of the creation date or last
/// modified date should adhere to the date/time format settings defined by the OS"). Set once.
pub fn set_system_format(f: fn(&chrono::DateTime<Local>) -> Option<String>) {
    let _ = SYSTEM_FORMAT.set(f);
}

/// Gives the date code the system's own way of writing a date with no time. Set once, beside `set_system_format`.
pub fn set_system_date(f: fn(&chrono::DateTime<Local>) -> Option<String>) {
    let _ = SYSTEM_DATE.set(f);
}

/// A local date and time as the system writes it, else "05.11.2026 13:45".
fn local(dt: &chrono::DateTime<Local>) -> String {
    SYSTEM_FORMAT.get().and_then(|f| f(dt)).unwrap_or_else(|| dt.format("%d.%m.%Y %H:%M").to_string())
}

/// A local date as the system writes it, else "05.11.2026".
fn local_date(dt: &chrono::DateTime<Local>) -> String {
    SYSTEM_DATE.get().and_then(|f| f(dt)).unwrap_or_else(|| dt.format("%d.%m.%Y").to_string())
}

/// How dates are shown (Settings → General → Date format).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DateStyle {
    /// Recent times as "5 dakika önce", older ones as a short date.
    Relative,
    /// The system's short date and time (Windows' regional format), "05.11.2026 13:45" where there is none.
    Local,
    /// ISO 8601 "2026-11-05 13:45"
    Universal,
}

pub fn set_date_style(s: DateStyle) {
    DATE_STYLE.store(s as u8, Ordering::Relaxed);
}

fn date_style() -> DateStyle {
    match DATE_STYLE.load(Ordering::Relaxed) {
        0 => DateStyle::Relative,
        1 => DateStyle::Local,
        _ => DateStyle::Universal,
    }
}

/// Sizes in powers of 1000 instead of 1024 (Settings → Files & folders → Size format).
pub fn set_decimal_sizes(on: bool) {
    DECIMAL.store(on, Ordering::Relaxed);
}

/// Powers of 1024 written as KiB, MiB, GiB (the IEC names) instead of Explorer's KB, MB, GB. Decimal sizes keep KB, MB, GB, which are
/// right for them.
pub fn set_binary_prefixes(on: bool) {
    IEC.store(on, Ordering::Relaxed);
}

/// UI language switch for the few words in number formats: English uses "bytes" and a decimal
/// point; the default (Turkish) uses "bayt" and a decimal comma.
pub fn set_english(on: bool) {
    ENGLISH.store(on, Ordering::Relaxed);
}

/// A language's own names for sizes, where they are not the Latin "KB", "MB" (Windows writes "1,5 МБ" in Russian): the word for
/// bytes, the five unit names from KB up, the same with the IEC "i", and the decimal mark (issue 283).
#[derive(Clone, Debug, PartialEq)]
pub struct Units {
    pub bytes: &'static str,
    pub units: [&'static str; 5],
    pub iec: [&'static str; 5],
    pub mark: char,
}

static UNITS: std::sync::RwLock<Option<Units>> = std::sync::RwLock::new(None);

/// The language's own size names, or `None` for the usual ones. Set by the app with the language.
pub fn set_units(u: Option<Units>) {
    if let Ok(mut g) = UNITS.write() {
        *g = u;
    }
}

/// The size names of a language by its code, the Windows app's ("ru-RU") or the Mac's ("ru"), where it has its own: the Cyrillic
/// ones, and Polish "B" with a decimal comma ("1,50 MB", "512 B"; one word for bytes, "bajtów", would be wrong after 2, 3 and 4).
/// Pure.
pub fn units_for(code: &str) -> Option<Units> {
    const LATIN: [&str; 5] = ["KB", "MB", "GB", "TB", "PB"];
    const LATIN_IEC: [&str; 5] = ["KiB", "MiB", "GiB", "TiB", "PiB"];
    const CYR: [&str; 5] = ["КБ", "МБ", "ГБ", "ТБ", "ПБ"];
    const CYR_IEC: [&str; 5] = ["КиБ", "МиБ", "ГиБ", "ТиБ", "ПиБ"];
    // (exact codes: a Latin-script Serbian, "sr-Latn", must not get the Cyrillic names; the Mac's "sr" is Cyrillic)
    let (bytes, units, iec) = match code {
        "ru-RU" | "ru" | "uk-UA" | "uk" | "be-BY" | "be" => ("байт", CYR, CYR_IEC),
        "bg" => ("байта", CYR, CYR_IEC),
        "sr-Cyrl" | "sr" => ("бајтова", CYR, CYR_IEC),
        "pl-PL" | "pl" => ("B", LATIN, LATIN_IEC),
        _ => return None,
    };
    Some(Units { bytes, units, iec, mark: ',' })
}

/// The words of the relative times ("5 minutes ago"), in the UI language.
///
/// This crate has no translation table of its own (the texts live in `rf-app`), so the app hands the words over instead of a
/// flag: `set_english` alone made every language but Turkish say "3 h ago". The function is asked for a template ("{n} min ago",
/// "vor {n} Min.", "3 分钟前") and puts the number in where `{n}` stands.
pub type RelativeWords = fn(Relative) -> &'static str;

static RELATIVE_WORDS: std::sync::OnceLock<RelativeWords> = std::sync::OnceLock::new();

/// Gives the relative times their words. Set once (a second call changes nothing).
pub fn set_relative_words(f: RelativeWords) {
    let _ = RELATIVE_WORDS.set(f);
}

/// A span of the relative times: what a "… ago" text counts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Relative {
    /// "just now"
    Now,
    /// "5 minutes ago"
    Minute,
    /// "3 hours ago"
    Hour,
    /// "2 days ago"
    Day,
}

/// The words for a language nothing was handed over for: English, or Turkish when `set_english` was not called.
fn english_relative(kind: Relative) -> &'static str {
    match kind {
        Relative::Now => "just now",
        Relative::Minute => "{n} min ago",
        Relative::Hour => "{n} h ago",
        Relative::Day => "{n} d ago",
    }
}

/// Turkish, for the tests and the places that run before the app hands its words over.
fn turkish_relative(kind: Relative) -> &'static str {
    match kind {
        Relative::Now => "az önce",
        Relative::Minute => "{n} dakika önce",
        Relative::Hour => "{n} saat önce",
        Relative::Day => "{n} gün önce",
    }
}

/// A relative time with its number: "5 min ago", "az önce". The words come from [`set_relative_words`]; without it, English or
/// Turkish by `en` (the flag `set_english` sets).
fn relative(kind: Relative, n: i64, en: bool) -> String {
    let template = match RELATIVE_WORDS.get() {
        Some(f) => f(kind),
        None if en => english_relative(kind),
        None => turkish_relative(kind),
    };
    template.replace("{n}", &n.to_string())
}

/// "0 bayt", "512 bayt", "1,2 KB", "34,5 MB", "1,02 GB" (Turkish decimal comma).
pub fn size(bytes: u64) -> String {
    let decimal = DECIMAL.load(Ordering::Relaxed);
    size_with(bytes, ENGLISH.load(Ordering::Relaxed), decimal, !decimal && IEC.load(Ordering::Relaxed))
}

fn size_with(bytes: u64, en: bool, decimal: bool, iec: bool) -> String {
    let own = UNITS.read().ok().and_then(|g| g.clone());
    size_in(bytes, en, decimal, iec, own.as_ref())
}

fn size_in(bytes: u64, en: bool, decimal: bool, iec: bool, own: Option<&Units>) -> String {
    let base: f64 = if decimal { 1000.0 } else { 1024.0 };
    let mut units: [&str; 6] = if iec {
        [if en { "bytes" } else { "bayt" }, "KiB", "MiB", "GiB", "TiB", "PiB"]
    } else {
        [if en { "bytes" } else { "bayt" }, "KB", "MB", "GB", "TB", "PB"]
    };
    if let Some(o) = own {
        let names = if iec { &o.iec } else { &o.units };
        units = [o.bytes, names[0], names[1], names[2], names[3], names[4]];
    }
    if (bytes as f64) < base {
        // ("1 byte", not "1 bytes")
        let word = if bytes == 1 && units[0] == "bytes" { "byte" } else { units[0] };
        return format!("{bytes} {word}");
    }
    let mut v = bytes as f64;
    let mut u = 0;
    while v >= base && u < units.len() - 1 {
        v /= base;
        u += 1;
    }
    let s = if v >= 100.0 {
        format!("{v:.0}")
    } else if v >= 10.0 {
        format!("{v:.1}")
    } else {
        format!("{v:.2}")
    };
    let s = match own {
        Some(o) if o.mark != '.' => s.replace('.', &o.mark.to_string()),
        Some(_) => s,
        None if en => s,
        None => s.replace('.', ","),
    };
    format!("{s} {}", units[u])
}

#[cfg(test)]
mod units_tests {
    use super::{size_in, units_for};

    #[test]
    fn a_cyrillic_language_has_its_own_size_names_and_comma() {
        let ru = units_for("ru-RU").unwrap();
        assert_eq!(size_in(1536 * 1024, true, false, false, Some(&ru)), "1,50 МБ");
        assert_eq!(size_in(14, true, false, false, Some(&ru)), "14 байт");
        assert_eq!(size_in(1536, true, false, true, Some(&ru)), "1,50 КиБ");
        assert!(units_for("de-DE").is_none(), "the others keep KB, MB");
        assert_eq!(size_in(1536, true, false, false, None), "1.50 KB");
    }

    #[test]
    fn polish_writes_a_decimal_comma_and_b_and_the_mac_codes_count() {
        let pl = units_for("pl-PL").unwrap();
        assert_eq!(size_in(1536 * 1024, true, false, false, Some(&pl)), "1,50 MB");
        assert_eq!(size_in(0, true, false, false, Some(&pl)), "0 B");
        assert_eq!(size_in(1536, true, false, true, Some(&pl)), "1,50 KiB");
        assert_eq!(units_for("pl"), Some(pl));
        assert_eq!(units_for("ru"), units_for("ru-RU"));
        assert_eq!(units_for("sr"), units_for("sr-Cyrl"));
        assert!(units_for("zh-Hans").is_none());
        assert!(units_for("sr-Latn").is_none(), "Latin-script Serbian keeps KB, MB");
    }
}

/// A file time in the chosen [`DateStyle`].
pub fn datetime(ms: i64) -> String {
    let now = chrono::Local::now().timestamp_millis();
    datetime_with(ms, date_style(), now, ENGLISH.load(Ordering::Relaxed))
}

/// Always the full local date-time "05.11.2026 03:51" (details, tooltips).
pub fn datetime_full(ms: i64) -> String {
    datetime_with(ms, DateStyle::Local, 0, false)
}

/// The date alone, "05.11.2026", in the system's own short date: a day heading, a "last modified on" line.
pub fn date(ms: i64) -> String {
    if ms <= 0 {
        return String::new();
    }
    let chrono::LocalResult::Single(dt) = Local.timestamp_millis_opt(ms) else { return String::new() };
    local_date(&dt)
}

fn datetime_with(ms: i64, style: DateStyle, now: i64, en: bool) -> String {
    if ms <= 0 {
        return String::new();
    }
    let chrono::LocalResult::Single(dt) = Local.timestamp_millis_opt(ms) else { return String::new() };
    match style {
        DateStyle::Universal => dt.format("%Y-%m-%d %H:%M").to_string(),
        DateStyle::Local => local(&dt),
        DateStyle::Relative => {
            let secs = (now - ms) / 1000;
            let (kind, n) = match secs {
                s if s < 0 => return local(&dt),
                s if s < 45 => return relative(Relative::Now, 0, en),
                s if s < 3600 => (Relative::Minute, ((s + 30) / 60).max(1)),
                s if s < 86_400 => (Relative::Hour, s / 3600),
                s if s < 7 * 86_400 => (Relative::Day, s / 86_400),
                _ => return local(&dt),
            };
            relative(kind, n, en)
        }
    }
}

/// Windows FILETIME (100ns since 1601) → Unix ms.
pub fn filetime_to_unix_ms(ft: u64) -> i64 {
    if ft == 0 {
        return 0;
    }
    (ft / 10_000) as i64 - 11_644_473_600_000
}

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

    #[test]
    fn sizes() {
        assert_eq!(size(0), "0 bayt");
        assert_eq!(size(1023), "1023 bayt");
        assert_eq!(size(1024), "1,00 KB");
        assert_eq!(size(1536), "1,50 KB");
        assert_eq!(size(10 * 1024 * 1024 + 1), "10,0 MB");
        assert_eq!(size(500 * 1024 * 1024 * 1024), "500 GB");
    }

    #[test]
    fn relative_and_formats() {
        let now = 1_800_000_000_000i64;
        // nothing handed over yet: the words follow the `en` flag, as they did before `set_relative_words`
        assert_eq!(datetime_with(now - 10_000, DateStyle::Relative, now, false), "az önce");
        assert_eq!(datetime_with(now - 5 * 60_000, DateStyle::Relative, now, false), "5 dakika önce");
        assert_eq!(datetime_with(now - 3 * 3_600_000, DateStyle::Relative, now, true), "3 h ago");
        assert_eq!(datetime_with(now - 2 * 86_400_000, DateStyle::Relative, now, false), "2 gün önce");
        assert!(datetime_with(now - 30 * 86_400_000, DateStyle::Relative, now, false).contains('.'));
        assert_eq!(datetime_with(now, DateStyle::Universal, now, false).len(), 16);
        // and once the UI language hands its words over, they are the ones every relative time says, whatever `en` holds.
        // (one value for the whole process, so the fallback above is asked for first, in this same test)
        fn german(kind: Relative) -> &'static str {
            match kind {
                Relative::Now => "gerade eben",
                Relative::Minute => "vor {n} Min.",
                Relative::Hour => "vor {n} Std.",
                Relative::Day => "vor {n} Tagen",
            }
        }
        set_relative_words(german);
        for en in [false, true] {
            assert_eq!(datetime_with(now - 10_000, DateStyle::Relative, now, en), "gerade eben");
            assert_eq!(datetime_with(now - 5 * 60_000, DateStyle::Relative, now, en), "vor 5 Min.");
            assert_eq!(datetime_with(now - 3 * 3_600_000, DateStyle::Relative, now, en), "vor 3 Std.");
            assert_eq!(datetime_with(now - 2 * 86_400_000, DateStyle::Relative, now, en), "vor 2 Tagen");
        }
        assert_eq!(size_with(1500, false, true, false), "1,50 KB");
        assert_eq!(size_with(1500, false, false, false), "1,46 KB");
        assert_eq!(size_with(1500, true, false, true), "1.46 KiB");
        assert_eq!(size_with(3 * 1024 * 1024 * 1024, true, false, true), "3.00 GiB");
        assert_eq!(size_with(512, true, false, true), "512 bytes");
    }

    #[test]
    fn filetime() {
        // 2000-01-01T00:00:00Z
        assert_eq!(filetime_to_unix_ms(125_911_584_000_000_000), 946_684_800_000);
        assert_eq!(filetime_to_unix_ms(0), 0);
    }

    /// The date alone is the system's own short date, with no time after it.
    #[test]
    fn a_date_has_no_time() {
        let ms = 1_800_000_000_000i64;
        let day = date(ms);
        assert!(!day.is_empty());
        assert!(!day.contains(':'), "no time: {day}");
        assert!(day.contains("2027") || day.contains("27"), "the year is there: {day}");
        assert_eq!(date(0), "");
        assert_eq!(date(-1), "");
    }
}