Skip to content

armgit / WacOS

Public Imported from GitHub
0

A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.

Rust
9.2 KB
Raw Blame
//! Porte de src\comum\idioma.h: o idioma da interface (`idioma=` no ajustes.txt) e o Tr().
//! Os dicionários são os mesmos idioma_<código>.inc do C++, convertidos pelo build.rs.

use std::collections::HashMap;

use windows::Win32::Foundation::SYSTEMTIME;
use windows::Win32::Globalization::*;

use crate::{pc, wz, Global};

mod gen {
    include!(concat!(env!("OUT_DIR"), "/idioma_gen.rs"));
}

pub const PT: usize = 0;
pub const EN: usize = 1;
pub const ES: usize = 2;
pub const FR: usize = 3;
pub const DE: usize = 4;
pub const IT: usize = 5;
pub const JA: usize = 6;
pub const ZH: usize = 7;
pub const KO: usize = 8;
pub const RU: usize = 9;
pub const PL: usize = 10;
pub const TR: usize = 11;
pub const VI: usize = 12; // vietnamita (tiếng Việt), PR #277
pub const COUNT: usize = 13;

pub struct Info {
    pub code: &'static str,
    pub locale: &'static str,
    pub native: &'static str,
}
pub const INFO: [Info; COUNT] = [
    Info { code: "pt", locale: "pt-BR", native: "Português (Brasil)" },
    Info { code: "en", locale: "en-US", native: "English" },
    Info { code: "es", locale: "es-ES", native: "Español" },
    Info { code: "fr", locale: "fr-FR", native: "Français" },
    Info { code: "de", locale: "de-DE", native: "Deutsch" },
    Info { code: "it", locale: "it-IT", native: "Italiano" },
    Info { code: "ja", locale: "ja-JP", native: "日本語" },
    Info { code: "zh", locale: "zh-CN", native: "简体中文" },
    Info { code: "ko", locale: "ko-KR", native: "한국어" },
    Info { code: "ru", locale: "ru-RU", native: "Русский" },
    Info { code: "pl", locale: "pl-PL", native: "Polski" },
    Info { code: "tr", locale: "tr-TR", native: "Türkçe" },
    Info { code: "vi", locale: "vi-VN", native: "Tiếng Việt" },
];
pub const MENU_ORDER: [usize; COUNT] = [EN, PT, ES, FR, DE, IT, PL, RU, TR, VI, JA, KO, ZH];

static LANG: Global<Option<usize>> = Global::new(None);
static DICTS: Global<[Option<HashMap<&'static str, &'static str>>; COUNT]> =
    Global::new([None, None, None, None, None, None, None, None, None, None, None, None, None]);

pub fn from_code(c: &str) -> usize {
    let c = c.to_lowercase();
    if c.len() < 2 {
        return EN;
    }
    INFO.iter().position(|i| c.starts_with(i.code)).unwrap_or(EN)
}

fn read_file() -> usize {
    match crate::ajustes::ler_padrao().get("idioma") {
        Some(v) => from_code(v),
        None => EN, // inglês é o padrão
    }
}

pub fn current() -> usize {
    *LANG.get().get_or_insert_with(read_file)
}
pub fn code() -> &'static str {
    INFO[current()].code
}
pub fn locale() -> &'static str {
    INFO[current()].locale
}
pub fn en() -> bool {
    current() == EN
}
pub fn pt() -> bool {
    current() == PT
}
pub fn set(l: usize) {
    *LANG.get() = Some(if l < COUNT { l } else { EN });
}
pub fn reload() {
    *LANG.get() = None;
}

fn tabela(l: usize) -> Option<&'static [(&'static str, &'static str)]> {
    Some(match l {
        EN => gen::T_EN,
        ES => gen::T_ES,
        FR => gen::T_FR,
        DE => gen::T_DE,
        IT => gen::T_IT,
        JA => gen::T_JA,
        ZH => gen::T_ZH,
        KO => gen::T_KO,
        RU => gen::T_RU,
        PL => gen::T_PL,
        TR => gen::T_TR,
        VI => gen::T_VI,
        _ => return None,
    })
}
pub fn map_for(l: usize) -> Option<&'static HashMap<&'static str, &'static str>> {
    let t = tabela(l)?;
    let d = &mut DICTS.get()[l];
    Some(d.get_or_insert_with(|| t.iter().copied().collect()))
}

/// pt -> idioma escolhido; sem tradução: inglês; sem inglês: None
pub fn lookup(pt_txt: &str) -> Option<&'static str> {
    let l = current();
    if l == PT {
        return None;
    }
    if let Some(m) = map_for(l) {
        if let Some(v) = m.get(pt_txt) {
            return Some(v);
        }
    }
    if l != EN {
        if let Some(v) = map_for(EN).and_then(|m| m.get(pt_txt)) {
            return Some(v);
        }
    }
    None
}

/// Tr(L"...")
pub fn tr(pt_txt: &str) -> String {
    if pt() {
        return pt_txt.to_string();
    }
    lookup(pt_txt).map(str::to_string).unwrap_or_else(|| pt_txt.to_string())
}

/// TrPick(pt, en)
pub fn tr_pick(pt_txt: &str, en_txt: &str) -> String {
    let l = current();
    if l == PT {
        return pt_txt.into();
    }
    if l == EN {
        return en_txt.into();
    }
    let Some(m) = map_for(l) else { return en_txt.into() };
    if let Some(v) = m.get(format!("{pt_txt}|{en_txt}").as_str()) {
        return v.to_string();
    }
    if let Some(e) = map_for(EN).and_then(|e| e.get(pt_txt)) {
        if *e == en_txt {
            if let Some(v) = m.get(pt_txt) {
                return v.to_string();
            }
        }
    }
    en_txt.into()
}

// ---- datas
pub const D_WEEKDAY_LONG: usize = 0;
pub const D_WEEKDAY_SHORT: usize = 1;
pub const D_LONG: usize = 2;
pub const D_MONTH_YEAR: usize = 3;
pub const D_SHORT: usize = 4;

const PADROES: [[&str; 5]; COUNT] = [
    ["dddd, d 'de' MMMM", "ddd d 'de' MMM", "d 'de' MMMM 'de' yyyy", "MMMM 'de' yyyy", "d 'de' MMM 'de' yyyy"],
    ["dddd, MMMM d", "ddd MMM d", "MMMM d, yyyy", "MMMM yyyy", "MMM d, yyyy"],
    ["dddd, d 'de' MMMM", "ddd d MMM", "d 'de' MMMM 'de' yyyy", "MMMM 'de' yyyy", "d MMM yyyy"],
    ["dddd d MMMM", "ddd d MMM", "d MMMM yyyy", "MMMM yyyy", "d MMM yyyy"],
    ["dddd, d. MMMM", "ddd d. MMM", "d. MMMM yyyy", "MMMM yyyy", "d. MMM yyyy"],
    ["dddd d MMMM", "ddd d MMM", "d MMMM yyyy", "MMMM yyyy", "d MMM yyyy"],
    ["M'月'd'日' dddd", "M'月'd'日'(ddd)", "yyyy'年'M'月'd'日'", "yyyy'年'M'月'", "yyyy/MM/dd"],
    ["M'月'd'日' dddd", "M'月'd'日' ddd", "yyyy'年'M'月'd'日'", "yyyy'年'M'月'", "yyyy'年'M'月'd'日'"],
    ["M'월' d'일' dddd", "M'월' d'일' (ddd)", "yyyy'년' M'월' d'일'", "yyyy'년' M'월'", "yyyy. M. d."],
    ["dddd, d MMMM", "ddd, d MMM", "d MMMM yyyy 'г.'", "MMMM yyyy", "d MMM yyyy 'г.'"],
    ["dddd, d MMMM", "ddd, d MMM", "d MMMM yyyy", "MMMM yyyy", "d MMM yyyy"],
    ["d MMMM dddd", "d MMM ddd", "d MMMM yyyy", "MMMM yyyy", "d MMM yyyy"],
    // vi: como o macOS em vietnamita ("Thứ Sáu, 20 tháng 11"): o mês em número, não o nome do Windows
    ["dddd, d 'tháng' M", "ddd d 'thg' M", "d 'tháng' M, yyyy", "'tháng' M 'năm' yyyy", "d 'thg' M, yyyy"],
];

pub fn date_pattern(kind: usize) -> &'static str {
    PADROES[current()][if kind < 5 { kind } else { D_LONG }]
}

/// Primeira letra maiúscula
pub fn cap(s: &str) -> String {
    let mut c = s.chars();
    match c.next() {
        Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
        None => String::new(),
    }
}

pub fn date(st: &SYSTEMTIME, kind: usize) -> String {
    let loc = wz(locale());
    let pat = wz(date_pattern(kind));
    let mut b = [0u16; 128];
    unsafe {
        GetDateFormatEx(pc(&loc), ENUM_DATE_FORMATS_FLAGS(0), Some(st), pc(&pat), Some(&mut b), None);
    }
    crate::from_w(&b)
}

pub fn date_time(st: &SYSTEMTIME, kind: usize) -> String {
    let mut sep = tr(" às ");
    if sep.is_empty() {
        sep = " ".into();
    }
    format!("{}{}{:02}:{:02}", date(st, kind), sep, st.wHour, st.wMinute)
}

pub fn locale_info(tipo: u32) -> String {
    let loc = wz(locale());
    let mut b = [0u16; 80];
    unsafe {
        GetLocaleInfoEx(pc(&loc), tipo, Some(&mut b));
    }
    crate::from_w(&b)
}

/// nome do mês (1..12); abrev = "nov."
pub fn month_name(m: i32, abrev: bool) -> String {
    let m = ((m - 1) % 12 + 12) % 12;
    let c = current();
    if c == ZH || c == JA {
        return format!("{}月", m + 1);
    }
    if c == KO {
        return format!("{}월", m + 1);
    }
    if c == VI {
        return format!("{}{}", if abrev { "thg " } else { "tháng " }, m + 1); // macOS: "tháng 11", não "Tháng Mười Một"
    }
    locale_info((if abrev { LOCALE_SABBREVMONTHNAME1 } else { LOCALE_SMONTHNAME1 }) + m as u32)
}

/// nome do dia (0 = domingo); forma: 0 inteiro, 1 abreviado, 2 o mais curto
pub fn day_name(d: i32, forma: i32) -> String {
    let d = ((d % 7) + 7) % 7;
    let i = ((d + 6) % 7) as u32;
    // vi: o mais curto do Windows é ambíguo ("C, H, B, T, N, S, B": duas "B"); o macOS usa "CN, T2...T7"
    let forma = if forma == 2 && current() == VI { 1 } else { forma };
    let base = match forma {
        0 => LOCALE_SDAYNAME1,
        1 => LOCALE_SABBREVDAYNAME1,
        _ => LOCALE_SSHORTESTDAYNAME1,
    };
    locale_info(base + i)
}

pub fn decimal_comma() -> bool {
    !matches!(current(), EN | JA | ZH | KO)
}

pub fn compass(k: usize) -> &'static str {
    const C: [[&str; 4]; COUNT] = [
        ["N", "L", "S", "O"],
        ["N", "E", "S", "W"],
        ["N", "E", "S", "O"],
        ["N", "E", "S", "O"],
        ["N", "O", "S", "W"],
        ["N", "E", "S", "O"],
        ["北", "東", "南", "西"],
        ["北", "东", "南", "西"],
        ["북", "동", "남", "서"],
        ["С", "В", "Ю", "З"],
        ["N", "E", "S", "W"],
        ["K", "D", "G", "B"],
        ["B", "Đ", "N", "T"],
    ];
    C[current()][k & 3]
}

#[cfg(test)]
mod testes {
    use super::*;
    #[test]
    fn dicionarios_carregam() {
        assert!(gen::T_EN.len() > 1500, "en tem {}", gen::T_EN.len());
        set(EN);
        assert_eq!(tr("Cancelar"), "Cancel");
        assert_eq!(tr("texto que não existe"), "texto que não existe");
        set(FR);
        assert_ne!(tr("Cancelar"), "Cancelar");
        set(PT);
        assert_eq!(tr("Cancelar"), "Cancelar");
    }
}