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
4 changes: 4 additions & 0 deletions apps/projectcraft/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ impl eframe::App for Shell {
if let Some(on) = self.app.take_autosave_changed() {
settings::save_autosave(on);
}
if let Some(lang) = self.app.take_language_changed() {
settings::save_language(lang);
}
}

/// Runs before `ui`, and also while the window is minimized or hidden, when `ui` does not:
Expand Down Expand Up @@ -68,6 +71,7 @@ fn main() -> eframe::Result {
},
_ => Session::new(projectcraft_engine::model::Project::new("New project", today())),
};
projectcraft_ui_egui::i18n::set_current(settings::load_language());
let mut app = App::new(session, if sample { None } else { path.clone() });
app.recent = settings::load_recent();
// `--sample` keeps nothing: no autosave, no recovery copy.
Expand Down
101 changes: 99 additions & 2 deletions apps/projectcraft/src/settings.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
//! The app's settings folder and what's kept in it: the recent-files list (`recent-files.txt`, one
//! path a line), the autosave switch (`autosave.txt`, `off` when turned off) and an untitled
//! project's recovery copy (`recovery/`).
//! path a line), the autosave switch (`autosave.txt`, `off` when turned off), the interface
//! language (`language.txt`, BCP 47 tag), and an untitled project's recovery copy (`recovery/`).

use std::path::PathBuf;

use projectcraft_ui_egui::i18n::Lang;

/// The settings folder: macOS `~/Library/Application Support/ProjectCraft`, Windows
/// `%APPDATA%\ProjectCraft`, otherwise `$XDG_CONFIG_HOME/projectcraft` or `~/.config/projectcraft`.
/// `PROJECTCRAFT_PROFILE_DIR` overrides the whole folder for isolated runs.
Expand Down Expand Up @@ -84,3 +86,98 @@ pub fn save_autosave(on: bool) {
eprintln!("couldn't save the autosave setting to {}: {e}", file.display());
}
}

fn language_file() -> Option<PathBuf> {
settings_dir().map(|d| d.join("language.txt"))
}

fn resolve_language_from_str(saved: Option<&str>, env_tags: &[Option<String>]) -> Lang {
if let Some(tag) = saved.and_then(Lang::from_tag) {
return tag;
}
if let Some(lang) = env_tags.first().and_then(|v| v.as_deref()).and_then(Lang::from_tag) {
return lang;
}
let effective_posix = env_tags.get(1..).unwrap_or(&[]).iter().flatten().map(|s| s.trim()).find(|s| !s.is_empty());
effective_posix.and_then(Lang::from_tag).unwrap_or(Lang::English)
}

/// The interface language: `language.txt` if valid, otherwise `PROJECTCRAFT_LANG` / locale env vars.
pub fn load_language() -> Lang {
let env_tags = ["PROJECTCRAFT_LANG", "LC_ALL", "LC_MESSAGES", "LANG"].map(|k| std::env::var(k).ok());
load_language_from(language_file().as_deref(), &env_tags)
}

fn load_language_from(file: Option<&std::path::Path>, env_tags: &[Option<String>]) -> Lang {
let mut bytes = Vec::new();
let saved = if let Some(Ok(f)) = file.map(std::fs::File::open) {
let _ = std::io::Read::read_to_end(&mut std::io::Read::take(f, 64), &mut bytes);
Some(String::from_utf8_lossy(&bytes).into_owned())
} else {
None
};
resolve_language_from_str(saved.as_deref(), env_tags)
}

/// Writes the interface language tag. A failure only loses the setting, so it's reported and otherwise ignored.
pub fn save_language(lang: Lang) {
let Some(file) = language_file() else {
return;
};
save_language_to(&file, lang);
}

fn save_language_to(file: &std::path::Path, lang: Lang) {
if lang == Lang::Pseudo {
return;
}
let body = format!("{}\n", lang.code());
let result = file
.parent()
.map_or(Ok(()), projectcraft_engine::create_private_dir_all)
.and_then(|()| projectcraft_engine::write_private(file, body.as_bytes()));
if let Err(e) = result {
eprintln!("couldn't save the language setting to {}: {e}", file.display());
}
}

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

#[test]
fn language_resolution_normalizes_hebrew_and_legacy_iw_tags() {
assert_eq!(resolve_language_from_str(Some("he\n"), &[]), Lang::Hebrew);
assert_eq!(resolve_language_from_str(Some("iw_IL.UTF-8"), &[]), Lang::Hebrew);
assert_eq!(resolve_language_from_str(None, &[None, Some("he_IL.UTF-8".to_owned())]), Lang::Hebrew);
assert_eq!(resolve_language_from_str(Some("xx"), &[Some("iw".to_owned())]), Lang::Hebrew);
assert_eq!(resolve_language_from_str(None, &[None, Some("fr_FR.UTF-8".to_owned())]), Lang::English);
// Non-empty LC_ALL overrides lower-priority LANG even when unsupported.
assert_eq!(resolve_language_from_str(None, &[None, Some("C".to_owned()), None, Some("he_IL.UTF-8".to_owned())]), Lang::English);
// Empty LC_ALL / LC_MESSAGES fall through to LANG.
assert_eq!(
resolve_language_from_str(None, &[None, Some(String::new()), Some(" ".to_owned()), Some("he_IL.UTF-8".to_owned())]),
Lang::Hebrew
);
// PROJECTCRAFT_LANG keeps precedence over POSIX locale vars.
assert_eq!(
resolve_language_from_str(None, &[Some("iw".to_owned()), Some("C".to_owned()), None, Some("en_US.UTF-8".to_owned())]),
Lang::Hebrew
);
}

#[test]
fn language_file_round_trips_hebrew_and_back_to_english() {
let dir = std::env::temp_dir().join(format!("projectcraft-lang-test-{}", std::process::id()));
let file = dir.join("language.txt");
let _ = std::fs::remove_dir_all(&dir);

save_language_to(&file, Lang::Hebrew);
assert_eq!(load_language_from(Some(&file), &[]), Lang::Hebrew);

save_language_to(&file, Lang::English);
assert_eq!(load_language_from(Some(&file), &[]), Lang::English);

let _ = std::fs::remove_dir_all(&dir);
}
}
12 changes: 7 additions & 5 deletions crates/ui-egui/src/assign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,14 +272,16 @@ impl App {
ui.add_space(6.0);
let decimal = p.options.units_format == UnitsFormat::Decimal;
let hint = match (p.resources.iter().any(|r| r.kind == ResourceType::Material), decimal) {
(true, false) => tl!("Units: a percentage for people and equipment (50%); for materials a quantity (5 tons) or a rate (2 tons/d)."),
(true, false) => {
tl_logical!("Units: a percentage for people and equipment (50%); for materials a quantity (5 tons) or a rate (2 tons/d).")
}
(true, true) => {
tl!("Units: a decimal for people and equipment (0.5, or 50%); for materials a quantity (5 tons) or a rate (2 tons/d).")
tl_logical!("Units: a decimal for people and equipment (0.5, or 50%); for materials a quantity (5 tons) or a rate (2 tons/d).")
}
(false, false) => tl!("Units: the share of each resource's working time (50% is half its day)."),
(false, true) => tl!("Units: the share of each resource's working time (0.5 is half its day; 50% works too)."),
(false, false) => tl_logical!("Units: the share of each resource's working time (50% is half its day)."),
(false, true) => tl_logical!("Units: the share of each resource's working time (0.5 is half its day; 50% works too)."),
};
ui.label(RichText::new(hint).color(t.text_dim));
crate::i18n::wrapped_label(ui, hint, |r| r.color(t.text_dim));
if !error.is_empty() {
ui.add_space(6.0);
ui.label(RichText::new(error.as_str()).color(t.warning));
Expand Down
19 changes: 10 additions & 9 deletions crates/ui-egui/src/browser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,11 +289,12 @@ fn body(ui: &mut Ui, b: &mut FileBrowser, t: &Tokens) -> Option<Option<PathBuf>>
FileRequest::Export(f) => i18n::fmt(tl!("Export as {format}"), &[("format", f.name())]),
});
if b.unavailable {
ui.label(
RichText::new(tl!(
crate::i18n::wrapped_label(
ui,
tl_logical!(
"The system file dialog isn't available, so ProjectCraft shows its own. To get the system dialog, install a file chooser portal (such as xdg-desktop-portal-gtk) or zenity."
))
.color(t.text_dim),
),
|r| r.color(t.text_dim),
);
}
ui.add_space(6.0);
Expand Down Expand Up @@ -392,13 +393,13 @@ fn body(ui: &mut Ui, b: &mut FileBrowser, t: &Tokens) -> Option<Option<PathBuf>>
});
let kinds = match b.request {
FileRequest::Open => {
tl!("ProjectCraft projects (*.projectcraft), and Microsoft Project XML (*.xml) and CSV (*.csv), imported as a new project")
tl_logical!("ProjectCraft projects (*.projectcraft), and Microsoft Project XML (*.xml) and CSV (*.csv), imported as a new project")
}
FileRequest::SaveAs => tl!("ProjectCraft projects (*.projectcraft)"),
FileRequest::Export(Format::Mspdi) => tl!("Microsoft Project XML (*.xml): a copy; the project stays as it is"),
FileRequest::Export(Format::Csv) => tl!("CSV (*.csv): a copy; the project stays as it is"),
FileRequest::SaveAs => tl_logical!("ProjectCraft projects (*.projectcraft)"),
FileRequest::Export(Format::Mspdi) => tl_logical!("Microsoft Project XML (*.xml): a copy; the project stays as it is"),
FileRequest::Export(Format::Csv) => tl_logical!("CSV (*.csv): a copy; the project stays as it is"),
};
ui.label(RichText::new(kinds).color(t.text_dim));
crate::i18n::wrapped_label(ui, kinds, |r| r.color(t.text_dim));
ui.add_space(8.0);
let mut cancel = ui.input(|i| i.key_pressed(egui::Key::Escape));
let enter = !location_done && ui.input(|i| i.key_pressed(egui::Key::Enter));
Expand Down
Loading