Skip to content

Visual Studio Code, rebuilt in Rust

Rust
7.4 KB
Raw Blame
//! The display language (mainImpl.ts, base/node/nls.ts): the locale from `--locale`, argv.json `locale` or the OS,
//! the language pack it resolves to, and the workbench strings that pack translates. Upstream looks each message up by
//! module and key. Command Palette items carry the `module#key` of the reference's call (port/tools/ref-commands), and
//! its `nlsKeys` give the keys of the menu bar's items and the views' titles; for a palette item without one, the index
//! of src/vs `localize` calls (build.rs) maps the English message to its module and key. The pack's `vscode`
//! translation file gives the text.

use std::borrow::Cow;
use std::collections::HashMap;
use std::path::Path;
use std::sync::OnceLock;

use config::json::{self, ParseOptions, Segment};
use config::json_edit::{FormattingOptions, apply_edits, set_property};
use exthost::language_packs::Nls;
use serde_json::Value;

const INDEX: &str = include_str!(concat!(env!("OUT_DIR"), "/nls_index.tsv"));

static TRANSLATIONS: OnceLock<HashMap<String, String>> = OnceLock::new();
static CONTENTS: OnceLock<Value> = OnceLock::new();

/// The window's translations: the language pack's main translation file read through the index.
pub fn init(nls: &Nls) {
    let main = nls.translations.get("vscode").and_then(Value::as_str);
    let Some(text) = main.and_then(|path| std::fs::read_to_string(path).ok()) else { return };
    let Ok(pack) = serde_json::from_str::<Value>(&text) else { return };
    let _ = TRANSLATIONS.set(translations_from(INDEX, &pack["contents"]));
    let _ = CONTENTS.set(pack["contents"].clone());
}

/// English message to translation; the first module translating a message wins.
// shortcut: a message two modules translate differently gets the first module's text; surfaces whose strings carry
// the reference's key use `localize_key` or `localize_in`.
fn translations_from(index: &str, contents: &Value) -> HashMap<String, String> {
    let mut translations = HashMap::new();
    for line in index.lines() {
        let mut fields = line.splitn(3, '\t');
        let (Some(module), Some(key), Some(message)) = (fields.next(), fields.next(), fields.next()) else { continue };
        let Some(translated) = contents[module][key].as_str().filter(|translated| !translated.is_empty()) else { continue };
        translations.entry(unescape(message)).or_insert_with(|| translated.to_owned());
    }
    translations
}

/// A TypeScript string literal's body as text.
fn unescape(literal: &str) -> String {
    let mut text = String::with_capacity(literal.len());
    let mut chars = literal.chars();
    while let Some(char) = chars.next() {
        if char != '\\' {
            text.push(char);
            continue;
        }
        match chars.next() {
            Some('n') => text.push('\n'),
            Some('t') => text.push('\t'),
            Some('r') => text.push('\r'),
            Some('u') => {
                let hex: String = chars.by_ref().take(4).collect();
                text.extend(u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32));
            }
            Some(other) => text.push(other),
            None => {}
        }
    }
    text
}

/// `localize` of the call `key` (`module#key`) names: the pack's text for it, else `english`; with no key, the
/// English message's text.
pub fn localize_key<'a>(key: Option<&str>, english: &'a str) -> Cow<'a, str> {
    match (key, CONTENTS.get()) {
        (None, _) => localize(english),
        (Some(key), Some(contents)) => keyed(contents, key, english),
        (Some(_), None) => Cow::Borrowed(english),
    }
}

/// `localize` of a menu bar item or a view title: the reference's key for `english` in `scope` (a menu bar menu, view
/// or view container id; port/tools/ref-commands `nlsKeys`), else `english`: a title the reference has no call for,
/// such as a folder's name or an extension's view, stays as it is.
pub fn localize_in<'a>(scope: &str, english: &'a str) -> Cow<'a, str> {
    match CONTENTS.get() {
        Some(contents) => scoped(contents, scope, english),
        None => Cow::Borrowed(english),
    }
}

fn scoped<'a>(contents: &Value, scope: &str, english: &'a str) -> Cow<'a, str> {
    match crate::command_palette::REFERENCE["nlsKeys"][scope][english].as_str() {
        Some(key) => keyed(contents, key, english),
        None => Cow::Borrowed(english),
    }
}

fn keyed<'a>(contents: &Value, key: &str, english: &'a str) -> Cow<'a, str> {
    let (module, key) = key.split_once('#').expect("a module#key");
    match contents[module][key].as_str().filter(|translated| !translated.is_empty()) {
        Some(translated) => Cow::Owned(translated.to_owned()),
        None => Cow::Borrowed(english),
    }
}

/// `localize`: the active language pack's text for an English workbench message.
fn localize(english: &str) -> Cow<'_, str> {
    match TRANSLATIONS.get().and_then(|translations| translations.get(english)) {
        Some(translated) => Cow::Owned(translated.clone()),
        None => Cow::Borrowed(english),
    }
}

/// `getUserDefinedLocale` then `app.getLocale()`: `--locale`, argv.json `locale`, else the OS's first preferred
/// language, lowercased; Chinese becomes zh-cn or zh-tw (`processZhLocale`).
pub fn user_locale(locale_flag: Option<&str>, argv_file: &Path) -> String {
    let argv_locale = || {
        let content = std::fs::read_to_string(argv_file).ok()?;
        let argv = json::parse(&content, &mut Vec::new(), ParseOptions::default())?;
        argv["locale"].as_str().map(str::to_owned)
    };
    match locale_flag.map(str::to_owned).or_else(argv_locale) {
        Some(locale) => locale.to_lowercase(),
        None => process_zh_locale(&os_locale().to_lowercase()),
    }
}

#[cfg(target_os = "macos")]
fn os_locale() -> String {
    let languages = objc2_foundation::NSLocale::preferredLanguages();
    languages.firstObject().map_or_else(|| "en".to_owned(), |language| language.to_string())
}

/// Chromium's locale on Linux: the first of `LC_ALL`, `LC_MESSAGES` and `LANG` that is set, `C` and `POSIX` as en-US.
#[cfg(target_os = "linux")]
fn os_locale() -> String {
    let variable = ["LC_ALL", "LC_MESSAGES", "LANG"].into_iter().find_map(|key| std::env::var(key).ok().filter(|value| !value.is_empty()));
    let locale = variable.as_deref().unwrap_or("C").split(['.', '@']).next().unwrap_or_default();
    match locale {
        "" | "C" | "POSIX" => "en-US".to_owned(),
        locale => locale.replace('_', "-"),
    }
}

// shortcut: en-US until the Windows UI language is read; port/ledger.md M24 row app/src/nls.rs:146 (GetUserPreferredUILanguages).
#[cfg(target_os = "windows")]
fn os_locale() -> String {
    "en-US".to_owned()
}

pub fn process_zh_locale(locale: &str) -> String {
    if !locale.starts_with("zh") {
        return locale.to_owned();
    }
    match locale.split('-').nth(1) {
        Some("hans" | "cn" | "sg" | "my") => "zh-cn".into(),
        _ => "zh-tw".into(),
    }
}

/// localeService.ts `writeLocaleValue`: argv.json `locale` set, or removed for `None`.
pub fn write_argv_locale(argv_file: &Path, locale: Option<&str>, options: impl FnOnce(&str) -> FormattingOptions) -> std::io::Result<()> {
    let content = std::fs::read_to_string(argv_file).unwrap_or_default();
    let value = locale.map(Value::from);
    let edits = set_property(&content, &[Segment::Key("locale".into())], value.as_ref(), &options(&content));
    if let Some(folder) = argv_file.parent() {
        std::fs::create_dir_all(folder)?;
    }
    std::fs::write(argv_file, apply_edits(&content, &edits))
}

#[cfg(test)]
mod tests;