Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,19 @@ disktree ~/src # or any directory
disktree --help # options: apparent size, follow links, skip hidden, …
```

### Interface language

Click **Language / 语言** in the top bar or source chooser, or press `F2`,
then choose **English** or **简体中文**. The window changes immediately; the
current scan, navigation and marked paths stay in place. The choice is saved
for the next launch in the user configuration directory, beside the Power
Efficiency setting. English is the default and fallback.

The language setting covers the window and macOS application menus. Command
line help, exported prompts/scripts and technical filesystem/SSH diagnostics
retain their original wording. See [Adding a language](docs/translations.md)
to contribute another translation.

### Servers over SSH (read-only)

```sh
Expand Down
42 changes: 29 additions & 13 deletions crates/disktree-app/src/app_menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
//! draws no menu bar on Linux or Windows, so there the same actions get the
//! shortcuts their users expect, with ctrl, and nothing else.

use crate::i18n::t;

use gpui_kit::{App, KeyBinding, Menu, MenuItem, SystemMenuType};

pub use menu_actions::*;
Expand Down Expand Up @@ -39,6 +41,8 @@ mod menu_actions {
GoBack,
/// Forward again, after going back.
GoForward,
/// Choose the interface language.
ChooseLanguage,
]
);
}
Expand Down Expand Up @@ -90,27 +94,39 @@ pub fn install(cx: &mut App) {
KeyBinding::new("cmd-[", GoBack, None),
KeyBinding::new("cmd-]", GoForward, None),
]);
update_language(cx);
}

/// Rebuild localized menus without registering handlers or bindings twice.
pub fn update_language(cx: &App) {
if !cfg!(target_os = "macos") {
return;
}
cx.set_menus([
Menu::new("disktree").items([
MenuItem::os_submenu("Services", SystemMenuType::Services),
MenuItem::os_submenu(t!(cx, "Services"), SystemMenuType::Services),
MenuItem::separator(),
MenuItem::action("Hide disktree", Hide),
MenuItem::action("Hide Others", HideOthers),
MenuItem::action("Show All", ShowAll),
MenuItem::action(t!(cx, "Hide disktree"), Hide),
MenuItem::action(t!(cx, "Hide Others"), HideOthers),
MenuItem::action(t!(cx, "Show All"), ShowAll),
MenuItem::separator(),
MenuItem::action("Quit disktree", Quit),
MenuItem::action(t!(cx, "Quit disktree"), Quit),
]),
Menu::new("File").items([
MenuItem::action("Open Folder\u{2026}", OpenFolder),
MenuItem::action("Show in Finder", ShowInFinder),
Menu::new(t!(cx, "File")).items([
MenuItem::action(t!(cx, "Open Folder\u{2026}"), OpenFolder),
MenuItem::action(t!(cx, "Show in Finder"), ShowInFinder),
MenuItem::separator(),
MenuItem::action("Rescan", Rescan),
MenuItem::action(t!(cx, "Rescan"), Rescan),
MenuItem::separator(),
MenuItem::action("Close Window", CloseWindow),
MenuItem::action(t!(cx, "Close Window"), CloseWindow),
]),
Menu::new("Go").items([
MenuItem::action("Back", GoBack),
MenuItem::action("Forward", GoForward),
Menu::new("Language / 语言").items([MenuItem::action(
t!(cx, "Choose interface language"),
ChooseLanguage,
)]),
Menu::new(t!(cx, "Go")).items([
MenuItem::action(t!(cx, "Back"), GoBack),
MenuItem::action(t!(cx, "Forward"), GoForward),
]),
]);
}
47 changes: 34 additions & 13 deletions crates/disktree-app/src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,31 @@ impl GitState {
}

/// One short line: `clean, no stash`, `3 changed, 1 stash, 2 unpushed`.
pub fn summary(&self) -> String {
pub fn summary(&self, language: crate::i18n::Language) -> String {
let mut parts = Vec::new();
parts.push(match self.changed {
Some(0) => "clean".to_string(),
Some(count) => format!("{count} changed"),
None => "changes unknown".to_string(),
Some(0) => language.text("clean").to_string(),
Some(count) => crate::i18n::format(
language.text("{0} changed"),
&[count.to_string()],
),
None => language.text("changes unknown").to_string(),
});
parts.push(match self.stashes {
0 => "no stash".to_string(),
1 => "1 stash".to_string(),
count => format!("{count} stashes"),
0 => language.text("no stash").to_string(),
1 => language.text("1 stash").to_string(),
count => crate::i18n::format(
language.text("{0} stashes"),
&[count.to_string()],
),
});
match self.unpushed {
Some(0) => {}
Some(count) => parts.push(format!("{count} unpushed")),
None => parts.push("no upstream".to_string()),
Some(count) => parts.push(crate::i18n::format(
language.text("{0} unpushed"),
&[count.to_string()],
)),
None => parts.push(language.text("no upstream").to_string()),
}
parts.join(", ")
}
Expand Down Expand Up @@ -218,25 +227,37 @@ mod tests {
..GitState::default()
};
assert!(clean.is_clean());
assert_eq!(clean.summary(), "clean, no stash");
assert_eq!(
clean.summary(crate::i18n::Language::English),
"clean, no stash"
);
let busy = GitState {
changed: Some(3),
stashes: 1,
unpushed: Some(2),
};
assert!(!busy.is_clean());
assert_eq!(busy.summary(), "3 changed, 1 stash, 2 unpushed");
assert_eq!(
busy.summary(crate::i18n::Language::English),
"3 changed, 1 stash, 2 unpushed"
);
let local = GitState {
changed: Some(0),
..GitState::default()
};
assert_eq!(local.summary(), "clean, no stash, no upstream");
assert_eq!(
local.summary(crate::i18n::Language::English),
"clean, no stash, no upstream"
);
assert!(!local.is_clean(), "unpushed history could be lost");
let guarded = GitState {
unpushed: Some(0),
..GitState::default()
};
assert_eq!(guarded.summary(), "changes unknown, no stash");
assert_eq!(
guarded.summary(crate::i18n::Language::English),
"changes unknown, no stash"
);
assert!(!guarded.is_clean(), "unknown is not clean");
}

Expand Down
191 changes: 191 additions & 0 deletions crates/disktree-app/src/i18n.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
//! Window language and a small, dependency-free message catalog.

use std::io::{self, Write as _};
use std::path::{Path, PathBuf};

use gpui_kit::{App, Global};

#[path = "locales/zh_cn.rs"]
mod zh_cn;

/// Languages offered by the window, using stable keys in the saved setting.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Language {
#[default]
English,
SimplifiedChinese,
}

impl Global for Language {}

impl Language {
/// Display order of the built-in languages.
pub const ALL: [Self; 2] = [Self::English, Self::SimplifiedChinese];

/// Stable locale identifier; independent of the translated display name.
pub const fn key(self) -> &'static str {
match self {
Self::English => "en",
Self::SimplifiedChinese => "zh-CN",
}
}

/// Autonyms keep the language control usable after an accidental switch.
pub const fn name(self) -> &'static str {
match self {
Self::English => "English",
Self::SimplifiedChinese => "简体中文",
}
}

/// Unknown or newer keys safely retain the original English interface.
pub fn parse(key: &str) -> Self {
Self::ALL
.into_iter()
.find(|lang| lang.key() == key)
.unwrap_or_default()
}

/// English is also the fallback for a message not yet translated.
pub fn text(self, key: &str) -> &str {
if self == Self::SimplifiedChinese
&& let Ok(index) =
zh_cn::MESSAGES.binary_search_by_key(&key, |&(en, _)| en)
{
return zh_cn::MESSAGES[index].1;
}
key
}
}

/// Read the language from this GPUI app, keeping window tests isolated.
pub fn language(cx: &App) -> Language {
cx.try_global::<Language>().copied().unwrap_or_default()
}

/// Translate presentation text; never use this for paths or protocol values.
pub fn text<'a>(cx: &App, key: &'a str) -> &'a str {
language(cx).text(key)
}

/// Substitute numbered slots in one pass. Inserted paths are never parsed
/// again, even when they contain braces or look like another slot.
pub fn format(template: &str, values: &[String]) -> String {
let mut result = String::new();
let mut rest = template;
while let Some(start) = rest.find('{') {
result.push_str(&rest[..start]);
rest = &rest[start..];
if let Some(end) = rest.find('}')
&& let Ok(index) = rest[1..end].parse::<usize>()
&& let Some(value) = values.get(index)
{
result.push_str(value);
rest = &rest[end + 1..];
} else {
result.push('{');
rest = &rest[1..];
}
}
result.push_str(rest);
result
}

/// Save beside the existing per-user power preference, never in a scan root.
pub fn settings_path() -> Option<PathBuf> {
crate::power::settings_path().map(|path| path.with_file_name("language"))
}

/// Missing preferences use English; filesystem failures remain visible.
pub fn load(path: &Path) -> io::Result<Language> {
match std::fs::read_to_string(path) {
Ok(value) => Ok(Language::parse(value.trim())),
Err(error) if error.kind() == io::ErrorKind::NotFound => {
Ok(Language::default())
}
Err(error) => Err(error),
}
}

/// Atomic replacement preserves the previous setting after a failed write.
pub fn save(path: &Path, language: Language) -> io::Result<()> {
let parent = path.parent().ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidInput, "no settings directory")
})?;
std::fs::create_dir_all(parent)?;
let mut file = tempfile::NamedTempFile::new_in(parent)?;
writeln!(file, "{}", language.key())?;
file.persist(path).map_err(|error| error.error)?;
Ok(())
}

/// Static messages borrow the catalog; numbered messages format their values.
macro_rules! t {
($cx:expr, $key:expr) => { crate::i18n::text($cx, $key) };
($cx:expr, $key:expr, $($value:expr),+ $(,)?) => {
crate::i18n::format(crate::i18n::text($cx, $key), &[$(format!("{}", $value)),+])
};
}
pub(crate) use t;

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

fn slots(template: &str) -> Vec<usize> {
let mut slots = template
.split('{')
.skip(1)
.map(|part| {
part.split_once('}')
.expect("closed slot")
.0
.parse()
.expect("numbered slot")
})
.collect::<Vec<_>>();
slots.sort_unstable();
slots
}

#[test]
fn catalog_is_sorted_complete_and_preserves_every_slot() {
let mut previous = "";
for &(english, chinese) in zh_cn::MESSAGES {
assert!(english > previous, "duplicate or unsorted: {english}");
assert!(!chinese.is_empty(), "missing: {english}");
assert_eq!(slots(english), slots(chinese), "slots: {english}");
assert_eq!(Language::English.text(english), english);
assert_eq!(Language::SimplifiedChinese.text(english), chinese);
previous = english;
}
assert_eq!(
Language::SimplifiedChinese.text("untranslated diagnostic"),
"untranslated diagnostic"
);
}

#[test]
fn numbered_slots_can_reorder_without_interpreting_inserted_paths() {
assert_eq!(
format("{1}: {0} / {1}", &["folder/{1}/中文".into(), "3".into()]),
"3: folder/{1}/中文 / 3"
);
assert_eq!(format("{9} {bad} {", &[]), "{9} {bad} {");
}

#[test]
fn saved_language_survives_replacement_and_unknown_values_fall_back() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("config/language");
assert_eq!(load(&path).expect("missing"), Language::English);
for language in Language::ALL {
save(&path, language).expect("save");
assert_eq!(load(&path).expect("load"), language);
}
std::fs::write(&path, "future-language").expect("write");
assert_eq!(load(&path).expect("fallback"), Language::English);
assert!(save(dir.path(), Language::English).is_err());
assert!(load(dir.path()).is_err());
}
}
Loading