Merge main into fix/launcher-text-field-edit (main.rs: keep main's background_error and the LineEdit field)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+63
-6
@@ -651,14 +651,17 @@ fn sounds_in(resources: &Path) -> bool {
|
||||
|
||||
/// What the Play page says of a version's resources.
|
||||
pub fn resources_summary(prepared: bool, sounds: bool, version: &str) -> String {
|
||||
use crate::i18n::trf;
|
||||
match (prepared, sounds) {
|
||||
(false, _) => {
|
||||
format!("Not prepared. Horizon needs the files of your own Minecraft {version}.")
|
||||
}
|
||||
(true, true) => format!("Prepared for Minecraft {version}"),
|
||||
(true, false) => format!(
|
||||
(false, _) => trf(
|
||||
"Not prepared. Horizon needs the files of your own Minecraft {version}.",
|
||||
&[("version", version)],
|
||||
),
|
||||
(true, true) => trf("Prepared for Minecraft {version}", &[("version", version)]),
|
||||
(true, false) => trf(
|
||||
"Prepared for Minecraft {version}, without its sounds: the game will be silent. \
|
||||
Prepare again to copy them from your Minecraft install."
|
||||
Prepare again to copy them from your Minecraft install.",
|
||||
&[("version", version)],
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -2604,6 +2607,16 @@ pub struct Settings {
|
||||
/// What the window does while the game runs. Stays by default.
|
||||
#[serde(default)]
|
||||
pub while_playing: WhilePlaying,
|
||||
/// The accent colour on top of the appearance (`themes::Accent`). Horizon's violet by default.
|
||||
#[serde(default)]
|
||||
pub accent: crate::themes::Accent,
|
||||
/// Home's background: a picture the player picked, kept in the data folder under this name
|
||||
/// (`themes::keep_background`). Unset shows Horizon's landscape.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub background: Option<String>,
|
||||
/// The window's language. Unset follows the system's (`i18n::Language::system`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub language: Option<crate::i18n::Language>,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
@@ -2628,6 +2641,17 @@ impl Settings {
|
||||
{
|
||||
fields.remove("while_playing");
|
||||
}
|
||||
if fields.get("accent").is_some_and(|a| {
|
||||
serde_json::from_value::<crate::themes::Accent>(a.clone()).is_err()
|
||||
}) {
|
||||
fields.remove("accent");
|
||||
}
|
||||
// A language this launcher doesn't have yet follows the system's.
|
||||
if fields.get("language").is_some_and(|l| {
|
||||
serde_json::from_value::<Option<crate::i18n::Language>>(l.clone()).is_err()
|
||||
}) {
|
||||
fields.remove("language");
|
||||
}
|
||||
}
|
||||
serde_json::from_value(value).unwrap_or_default()
|
||||
}
|
||||
@@ -2635,6 +2659,10 @@ impl Settings {
|
||||
pub fn desktop_entry(&self) -> bool {
|
||||
self.desktop_entry.unwrap_or(true)
|
||||
}
|
||||
/// The window's language: the one picked, else the system's.
|
||||
pub fn language(&self) -> crate::i18n::Language {
|
||||
self.language.unwrap_or_else(crate::i18n::Language::system)
|
||||
}
|
||||
/// Whether new Horizon versions are installed automatically.
|
||||
pub fn auto_install(&self) -> bool {
|
||||
self.install_new_versions.unwrap_or(true)
|
||||
@@ -2965,6 +2993,35 @@ mod tests {
|
||||
assert_eq!(here == WhilePlaying::Hide, cfg!(target_os = "macos"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_language_follows_the_system_unless_picked() {
|
||||
use crate::i18n::Language;
|
||||
assert_eq!(Settings::parse("{}").language, None);
|
||||
let fr = Settings::parse(r#"{"language": "fr"}"#);
|
||||
assert_eq!(fr.language(), Language::French);
|
||||
let future = Settings::parse(r#"{"language": "eo", "game_args": "--x"}"#);
|
||||
assert_eq!((future.language, future.game_args.as_str()), (None, "--x"));
|
||||
let saved = serde_json::to_value(Settings::default()).unwrap();
|
||||
assert!(saved.get("language").is_none(), "unset is left out");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_accent_is_violet_unless_picked_and_an_unknown_one_keeps_the_rest() {
|
||||
use crate::themes::Accent;
|
||||
assert_eq!(Settings::parse("{}").accent, Accent::Violet);
|
||||
let teal =
|
||||
Settings::parse(r#"{"accent": "teal", "background": "background-0123456789ab.png"}"#);
|
||||
assert_eq!(
|
||||
(teal.accent, teal.background.as_deref()),
|
||||
(Accent::Teal, Some("background-0123456789ab.png"))
|
||||
);
|
||||
let future = Settings::parse(r#"{"accent": "plaid", "game_args": "--x"}"#);
|
||||
assert_eq!(
|
||||
(future.accent, future.game_args.as_str()),
|
||||
(Accent::Violet, "--x")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_appearance_is_dark_unless_picked_and_an_unknown_one_keeps_the_rest() {
|
||||
assert_eq!(Settings::parse("{}").appearance, Appearance::Dark);
|
||||
|
||||
+37
-2
@@ -603,7 +603,10 @@ enum Cmd {
|
||||
/// Show the launcher's settings, or set one (the Settings page): selected-version TAG,
|
||||
/// minecraft-dir PATH, server-dir PATH ("default" resets a folder), install-new-versions
|
||||
/// on|off, opening-animation on|off, proxy http://host:port ("default" removes it),
|
||||
/// while-playing stay|minimize|hide (what the window does while the game runs)
|
||||
/// while-playing stay|minimize|hide (what the window does while the game runs), language
|
||||
/// system|en|fr|ru (the window's language; system follows the computer's), accent
|
||||
/// violet|blue|teal|green|amber|red|pink, background PATH (a picture behind Home; "default"
|
||||
/// shows Horizon's landscape)
|
||||
Settings {
|
||||
#[arg(value_parser = SETTING_KEYS)]
|
||||
key: Option<String>,
|
||||
@@ -740,7 +743,7 @@ pub fn command() -> clap::Command {
|
||||
pub const AI_COMMANDS: [&str; 2] = ["mcp", "agent-config"];
|
||||
|
||||
/// The keys `settings` sets.
|
||||
const SETTING_KEYS: [&str; 7] = [
|
||||
const SETTING_KEYS: [&str; 10] = [
|
||||
"selected-version",
|
||||
"minecraft-dir",
|
||||
"server-dir",
|
||||
@@ -748,6 +751,9 @@ const SETTING_KEYS: [&str; 7] = [
|
||||
"opening-animation",
|
||||
"proxy",
|
||||
"while-playing",
|
||||
"language",
|
||||
"accent",
|
||||
"background",
|
||||
];
|
||||
|
||||
fn on_off(value: &str) -> Result<bool, String> {
|
||||
@@ -770,6 +776,32 @@ fn set_setting(s: &mut backend::Settings, key: &str, value: &str) -> Result<(),
|
||||
s.while_playing = backend::WhilePlaying::parse(value)
|
||||
.ok_or_else(|| format!("{value}: say stay, minimize or hide"))?
|
||||
}
|
||||
"accent" => {
|
||||
use horizon_launcher::themes::Accent;
|
||||
s.accent = Accent::parse(value).ok_or_else(|| {
|
||||
let names: Vec<_> = Accent::ALL.iter().map(|a| a.name()).collect();
|
||||
format!("{value}: say {}", names.join(", "))
|
||||
})?
|
||||
}
|
||||
"background" => {
|
||||
s.background = match value.trim() {
|
||||
"default" | "" => None,
|
||||
file => Some(horizon_launcher::themes::keep_background(
|
||||
&backend::data_dir(),
|
||||
std::path::Path::new(file),
|
||||
)?),
|
||||
}
|
||||
}
|
||||
"language" => {
|
||||
use horizon_launcher::i18n::Language;
|
||||
s.language = match value.trim() {
|
||||
"system" | "default" => None,
|
||||
code => Some(
|
||||
Language::parse(code)
|
||||
.ok_or_else(|| format!("{value}: say system, en, fr or ru"))?,
|
||||
),
|
||||
}
|
||||
}
|
||||
"proxy" => {
|
||||
if value == "default" || value.is_empty() {
|
||||
s.proxy = None;
|
||||
@@ -796,6 +828,9 @@ fn settings_json(s: &backend::Settings) -> serde_json::Value {
|
||||
"proxy": s.proxy,
|
||||
"desktop_entry": s.desktop_entry.unwrap_or(true),
|
||||
"while_playing": s.while_playing.name(),
|
||||
"language": s.language.map_or("system", |l| l.code()),
|
||||
"accent": s.accent.name(),
|
||||
"background": horizon_launcher::themes::background(&backend::data_dir(), s.background.as_deref()),
|
||||
"no_ai": backend::no_ai(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
//! The launcher's languages: English (the strings in the code), French and Russian, the
|
||||
//! languages Horizon's own game menus have. A table per language (`launcher/lang/<code>.json`)
|
||||
//! maps each English string to its translation; a string the table lacks shows in English.
|
||||
//!
|
||||
//! The language follows the system's unless the player picks one in Settings
|
||||
//! (`Settings::language`). Translations are Horizon's own, written for this launcher.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicU8, Ordering};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Language {
|
||||
#[default]
|
||||
#[serde(rename = "en")]
|
||||
English,
|
||||
#[serde(rename = "fr")]
|
||||
French,
|
||||
#[serde(rename = "ru")]
|
||||
Russian,
|
||||
}
|
||||
|
||||
impl Language {
|
||||
pub const ALL: [Language; 3] = [Self::English, Self::French, Self::Russian];
|
||||
|
||||
/// Its code in `settings.json` and on the command line.
|
||||
pub fn code(self) -> &'static str {
|
||||
match self {
|
||||
Self::English => "en",
|
||||
Self::French => "fr",
|
||||
Self::Russian => "ru",
|
||||
}
|
||||
}
|
||||
|
||||
/// Its name in itself: what a player looks for in a list of languages.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::English => "English",
|
||||
Self::French => "Français",
|
||||
Self::Russian => "Русский",
|
||||
}
|
||||
}
|
||||
|
||||
/// A language code (`fr`, `fr-CH`, `fr_FR.UTF-8`), if the launcher has it.
|
||||
pub fn parse(code: &str) -> Option<Self> {
|
||||
let lower = code.trim().to_ascii_lowercase();
|
||||
let base = lower.split(['-', '_', '.', '@']).next().unwrap_or("");
|
||||
Self::ALL.into_iter().find(|l| l.code() == base)
|
||||
}
|
||||
|
||||
/// The first of the system's preferred languages the launcher has, else English.
|
||||
pub fn pick<'a>(preferred: impl IntoIterator<Item = &'a str>) -> Self {
|
||||
preferred
|
||||
.into_iter()
|
||||
.find_map(Self::parse)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The system's language, as far as the launcher has it.
|
||||
pub fn system() -> Self {
|
||||
let locales: Vec<String> = sys_locale::get_locales().collect();
|
||||
Self::pick(locales.iter().map(String::as_str))
|
||||
}
|
||||
|
||||
/// The table, as shipped: English text to this language's.
|
||||
fn source(self) -> &'static str {
|
||||
match self {
|
||||
Self::English => "{}",
|
||||
Self::French => include_str!("../lang/fr.json"),
|
||||
Self::Russian => include_str!("../lang/ru.json"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static CURRENT: AtomicU8 = AtomicU8::new(0);
|
||||
|
||||
/// Shows the launcher in `language` from now on.
|
||||
pub fn set(language: Language) {
|
||||
let i = Language::ALL
|
||||
.iter()
|
||||
.position(|l| *l == language)
|
||||
.unwrap_or(0);
|
||||
CURRENT.store(i as u8, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn current() -> Language {
|
||||
Language::ALL[CURRENT.load(Ordering::Relaxed) as usize % Language::ALL.len()]
|
||||
}
|
||||
|
||||
type Table = HashMap<String, &'static str>;
|
||||
|
||||
fn table(language: Language) -> &'static Table {
|
||||
static TABLES: OnceLock<Vec<Table>> = OnceLock::new();
|
||||
let tables = TABLES.get_or_init(|| {
|
||||
Language::ALL
|
||||
.iter()
|
||||
.map(|l| {
|
||||
serde_json::from_str::<HashMap<String, String>>(l.source())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|(en, said)| (en, &*Box::leak(said.into_boxed_str())))
|
||||
.collect()
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
let i = Language::ALL
|
||||
.iter()
|
||||
.position(|l| *l == language)
|
||||
.unwrap_or(0);
|
||||
&tables[i]
|
||||
}
|
||||
|
||||
/// `en` in `language`, or `en` itself where the table lacks it.
|
||||
pub fn tr_in(language: Language, en: &str) -> &str {
|
||||
table(language).get(en).copied().unwrap_or(en)
|
||||
}
|
||||
|
||||
/// `en` in the launcher's language.
|
||||
pub fn tr(en: &str) -> &str {
|
||||
tr_in(current(), en)
|
||||
}
|
||||
|
||||
/// `en` in the launcher's language with its `{name}` holes filled.
|
||||
pub fn trf(en: &str, args: &[(&str, &str)]) -> String {
|
||||
let mut out = tr(en).to_string();
|
||||
for (name, value) in args {
|
||||
out = out.replace(&format!("{{{name}}}"), value);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "i18n/tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,135 @@
|
||||
use super::*;
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::Path;
|
||||
|
||||
/// Every Rust file of the launcher's sources.
|
||||
fn sources(dir: &Path, out: &mut Vec<String>) {
|
||||
for entry in std::fs::read_dir(dir).unwrap().flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
sources(&path, out);
|
||||
} else if path.extension().is_some_and(|e| e == "rs") {
|
||||
// Comments left out: they quote strings too.
|
||||
let code = std::fs::read_to_string(path).unwrap();
|
||||
let lines = code
|
||||
.lines()
|
||||
.map(|l| match l.trim_start().starts_with("//") {
|
||||
true => "",
|
||||
false => l,
|
||||
});
|
||||
out.push(lines.collect::<Vec<_>>().join("\n"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The string literal at the start of `code` (just after its opening quote), unescaped the way
|
||||
/// Rust does: `\"`, `\\`, `\n`, and a backslash at a line's end that drops the next line's
|
||||
/// indent.
|
||||
fn literal(code: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut chars = code.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
'"' => break,
|
||||
'\\' => match chars.next() {
|
||||
Some('n') => out.push('\n'),
|
||||
Some('\n') => {
|
||||
while chars.peek().is_some_and(|c| c.is_whitespace()) {
|
||||
chars.next();
|
||||
}
|
||||
}
|
||||
Some(c) => out.push(c),
|
||||
None => break,
|
||||
},
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The English strings the code asks a translation for: `tr("…")` and `trf("…")`, and every
|
||||
/// other string literal (some reach `tr` through a widget).
|
||||
fn strings() -> (BTreeSet<String>, BTreeSet<String>) {
|
||||
let mut files = Vec::new();
|
||||
sources(
|
||||
&Path::new(env!("CARGO_MANIFEST_DIR")).join("src"),
|
||||
&mut files,
|
||||
);
|
||||
let (mut asked, mut all) = (BTreeSet::new(), BTreeSet::new());
|
||||
for file in &files {
|
||||
for (at, _) in file.match_indices('"') {
|
||||
let before = &file[..at];
|
||||
if before.ends_with('\\') || before.ends_with('\'') {
|
||||
continue;
|
||||
}
|
||||
let s = literal(&file[at + 1..]);
|
||||
let call = |name: &str| {
|
||||
before.ends_with(&format!("{name}(")) && {
|
||||
let head = &before[..before.len() - name.len() - 1];
|
||||
!head.ends_with(|c: char| c.is_alphanumeric() || c == '_')
|
||||
}
|
||||
};
|
||||
if call("tr") || call("trf") {
|
||||
asked.insert(s.clone());
|
||||
}
|
||||
all.insert(s);
|
||||
}
|
||||
}
|
||||
(asked, all)
|
||||
}
|
||||
|
||||
fn holes(s: &str) -> BTreeSet<&str> {
|
||||
s.split('{')
|
||||
.skip(1)
|
||||
.filter_map(|part| part.split_once('}').map(|(name, _)| name))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_language_has_every_string_the_code_asks_for() {
|
||||
let (asked, all) = strings();
|
||||
assert!(asked.contains("Language"), "the scan finds tr(\"…\")");
|
||||
for language in [Language::French, Language::Russian] {
|
||||
let table: HashMap<String, String> = serde_json::from_str(language.source())
|
||||
.unwrap_or_else(|e| panic!("lang/{}.json: {e}", language.code()));
|
||||
let missing: Vec<_> = asked.iter().filter(|s| !table.contains_key(*s)).collect();
|
||||
assert!(
|
||||
missing.is_empty(),
|
||||
"lang/{}.json lacks {missing:#?}",
|
||||
language.code()
|
||||
);
|
||||
let unused: Vec<_> = table.keys().filter(|s| !all.contains(*s)).collect();
|
||||
assert!(
|
||||
unused.is_empty(),
|
||||
"lang/{}.json has strings the code no longer has: {unused:#?}",
|
||||
language.code()
|
||||
);
|
||||
for (en, said) in &table {
|
||||
assert_eq!(holes(en), holes(said), "{}: {en:?}", language.code());
|
||||
assert!(
|
||||
!said.trim().is_empty(),
|
||||
"{}: {en:?} is empty",
|
||||
language.code()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_system_language_is_the_first_one_the_launcher_has() {
|
||||
assert_eq!(Language::pick(["fr-CH", "en-US"]), Language::French);
|
||||
assert_eq!(Language::pick(["de-CH", "ru_RU.UTF-8"]), Language::Russian);
|
||||
assert_eq!(Language::pick(["de-DE", "ja"]), Language::English);
|
||||
assert_eq!(Language::pick([]), Language::English);
|
||||
assert_eq!(Language::parse("FR"), Some(Language::French));
|
||||
assert_eq!(Language::parse("french"), None);
|
||||
assert_eq!(serde_json::to_string(&Language::Russian).unwrap(), "\"ru\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_string_shows_in_english() {
|
||||
assert_eq!(tr_in(Language::French, "Settings"), "Paramètres");
|
||||
assert_eq!(tr_in(Language::Russian, "Settings"), "Настройки");
|
||||
assert_eq!(tr_in(Language::English, "Settings"), "Settings");
|
||||
assert_eq!(tr_in(Language::French, "No such string"), "No such string");
|
||||
}
|
||||
@@ -448,7 +448,7 @@ fn record_play_in(
|
||||
pub fn play_time(played: Duration) -> String {
|
||||
let minutes = played.as_secs() / 60;
|
||||
match (minutes / 60, minutes % 60) {
|
||||
(0, 0) => "under a minute".into(),
|
||||
(0, 0) => crate::i18n::tr("under a minute").into(),
|
||||
(0, m) => format!("{m} min"),
|
||||
(h, m) if h < 100 => format!("{h} h {m:02} min"),
|
||||
(h, _) => format!("{h} h"),
|
||||
|
||||
@@ -190,11 +190,11 @@ impl Launcher {
|
||||
InstanceKind::Default | InstanceKind::Own => (
|
||||
self.page == Page::Play && selected.as_ref() == Some(&i.id),
|
||||
match (&tag, &i.version) {
|
||||
(None, Some(own)) => format!("{own} is not installed"),
|
||||
(None, None) => "No version installed".into(),
|
||||
(Some(_), _) if !prepared => "Needs preparing".into(),
|
||||
(Some(tag), Some(_)) => format!("Ready · {tag}"),
|
||||
(Some(_), None) => "Ready".into(),
|
||||
(None, Some(own)) => trf("{version} is not installed", &[("version", own)]),
|
||||
(None, None) => tr("No version installed").into(),
|
||||
(Some(_), _) if !prepared => tr("Needs preparing").into(),
|
||||
(Some(tag), Some(_)) => format!("{} · {tag}", tr("Ready")),
|
||||
(Some(_), None) => tr("Ready").into(),
|
||||
},
|
||||
),
|
||||
InstanceKind::Port => {
|
||||
@@ -202,10 +202,10 @@ impl Launcher {
|
||||
let summary = self.packs.iter().find(|p| p.slug == slug);
|
||||
(
|
||||
on_packs && self.pack_open.as_deref() == Some(slug),
|
||||
summary.map_or_else(|| "Modpack".into(), |p| p.summary()),
|
||||
summary.map_or_else(|| tr("Modpack").into(), |p| p.summary()),
|
||||
)
|
||||
}
|
||||
InstanceKind::Pack => (false, "From Horizon's registry".into()),
|
||||
InstanceKind::Pack => (false, tr("From Horizon's registry").into()),
|
||||
};
|
||||
let dot = matches!(i.kind, InstanceKind::Default | InstanceKind::Own).then(|| {
|
||||
div()
|
||||
@@ -621,7 +621,7 @@ impl Launcher {
|
||||
);
|
||||
Some(index_row(
|
||||
n,
|
||||
"Instance",
|
||||
tr("Instance"),
|
||||
Some(
|
||||
div()
|
||||
.flex()
|
||||
@@ -651,12 +651,14 @@ impl Launcher {
|
||||
/// "3 h 05 min in total · last played today", or "Not played yet".
|
||||
fn played_line(instance: &Instance) -> String {
|
||||
match instance.last_played {
|
||||
Some(when) => format!(
|
||||
"{} in total · last played {}",
|
||||
instances::play_time(instance.played),
|
||||
worlds_page::ago(when)
|
||||
Some(when) => trf(
|
||||
"{time} in total · last played {when}",
|
||||
&[
|
||||
("time", &instances::play_time(instance.played)),
|
||||
("when", &worlds_page::ago(when)),
|
||||
],
|
||||
),
|
||||
None => "Not played yet".into(),
|
||||
None => tr("Not played yet").into(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
//! Settings' Language row (`horizon_launcher::i18n`): the system's language, or one the player
|
||||
//! picks, each named in itself.
|
||||
use super::*;
|
||||
use horizon_launcher::i18n::Language;
|
||||
|
||||
impl Launcher {
|
||||
pub(super) fn language_row(&self, cx: &mut Context<Self>) -> Div {
|
||||
let t = self.theme;
|
||||
let mut options = vec![(None, "System")];
|
||||
options.extend(Language::ALL.map(|l| (Some(l), l.name())));
|
||||
let picker = segments("language", &options, self.settings.language, &t, {
|
||||
let this = cx.entity().downgrade();
|
||||
move |choice, _, cx| {
|
||||
let _ = this.update(cx, |this, cx| {
|
||||
this.settings.language = choice;
|
||||
this.settings.save();
|
||||
i18n::set(this.settings.language());
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
});
|
||||
let said = trf(
|
||||
"System follows your computer's language: {language} here. A string not translated \
|
||||
yet shows in English.",
|
||||
&[("language", Language::system().name())],
|
||||
);
|
||||
index_row(
|
||||
0,
|
||||
tr("Language"),
|
||||
Some(div().child(said).into_any_element()),
|
||||
Some(picker.into_any_element()),
|
||||
&t,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ pub mod export;
|
||||
pub mod game_app;
|
||||
pub mod game_log;
|
||||
pub mod heads;
|
||||
pub mod i18n;
|
||||
pub mod import;
|
||||
pub mod instances;
|
||||
pub mod launch;
|
||||
@@ -28,4 +29,5 @@ pub mod skins;
|
||||
pub mod sources;
|
||||
pub mod tailscale;
|
||||
pub mod telemetry;
|
||||
pub mod themes;
|
||||
pub mod worlds;
|
||||
|
||||
+115
-69
@@ -18,6 +18,7 @@ mod game_tools;
|
||||
mod import_page;
|
||||
mod instances_page;
|
||||
mod internet;
|
||||
mod language_page;
|
||||
mod launch_page;
|
||||
mod line_edit;
|
||||
mod markdown;
|
||||
@@ -36,6 +37,7 @@ mod shortcut_page;
|
||||
mod skin_page;
|
||||
mod switch_page;
|
||||
mod theme;
|
||||
mod themes_page;
|
||||
mod titlebar;
|
||||
mod while_playing;
|
||||
mod worlds_page;
|
||||
@@ -48,6 +50,7 @@ use gpui::{
|
||||
};
|
||||
use horizon_launcher::account::{self, Accounts, SignIn, SignInState};
|
||||
use horizon_launcher::backend::{self, Job, Msg, Release, Running, Settings, Updates};
|
||||
use horizon_launcher::i18n::{self, tr, trf};
|
||||
use horizon_launcher::instances;
|
||||
use horizon_launcher::telemetry;
|
||||
use scrollbar::Scrollbar;
|
||||
@@ -171,6 +174,8 @@ struct Launcher {
|
||||
account_menu: bool,
|
||||
/// Settings > Account's skin panel for an offline name (`skin_page.rs`).
|
||||
skin: Option<skin_page::SkinPanel>,
|
||||
/// Why the last picture for Home's background was refused.
|
||||
background_error: Option<String>,
|
||||
settings: Settings,
|
||||
/// The Discord, sponsor and website links: built in until links.json on main has been read.
|
||||
links: backend::Links,
|
||||
@@ -276,7 +281,7 @@ impl Launcher {
|
||||
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let (tx, rx) = channel();
|
||||
let appearance = cx.observe_window_appearance(window, |this, window, cx| {
|
||||
this.theme = Theme::for_appearance(this.settings.appearance, window.appearance());
|
||||
this.theme = this.settings_theme(window);
|
||||
cx.notify();
|
||||
});
|
||||
cx.spawn(async move |this, cx| loop {
|
||||
@@ -315,6 +320,7 @@ impl Launcher {
|
||||
})
|
||||
.detach();
|
||||
let mut settings = Settings::load();
|
||||
i18n::set(settings.language());
|
||||
if settings.minecraft_dir.is_none() {
|
||||
settings.minecraft_dir = backend::default_minecraft_dir();
|
||||
}
|
||||
@@ -342,7 +348,7 @@ impl Launcher {
|
||||
// `window.appearance()`, so both draw the same look.
|
||||
titlebar::apply_appearance(window, settings.appearance);
|
||||
let mut this = Self {
|
||||
theme: Theme::for_appearance(settings.appearance, window.appearance()),
|
||||
theme: Theme::for_appearance(settings.appearance, settings.accent, window.appearance()),
|
||||
page: Page::from_env(),
|
||||
switches: 0,
|
||||
content_scroll: Scrollbar::default(),
|
||||
@@ -371,6 +377,7 @@ impl Launcher {
|
||||
picker_open: false,
|
||||
account_menu: false,
|
||||
skin: None,
|
||||
background_error: None,
|
||||
args_input: line_edit::LineEdit::new(settings.game_args.clone(), 1024, 38),
|
||||
args_focused: false,
|
||||
args_focus: cx.focus_handle(),
|
||||
@@ -1192,6 +1199,8 @@ fn button(
|
||||
t: &Theme,
|
||||
) -> Stateful<Div> {
|
||||
let id: SharedString = id.into();
|
||||
let label: SharedString = label.into();
|
||||
let label = SharedString::from(tr(&label).to_string());
|
||||
let t = *t;
|
||||
let hover = match kind {
|
||||
Kind::Primary => t.on_face.opacity(0.10),
|
||||
@@ -1235,7 +1244,7 @@ fn button(
|
||||
.items_center()
|
||||
.gap(px(8.))
|
||||
.pb(px(if kind == Kind::Ghost { 0. } else { 2. }))
|
||||
.child(label.into()),
|
||||
.child(label),
|
||||
);
|
||||
keyboard(track_hover(base, id), &t).active(|s| s.opacity(theme::PRESSED).top(px(1.)))
|
||||
}
|
||||
@@ -1303,7 +1312,7 @@ fn section_title(label: &'static str, icon: &'static str, t: &Theme) -> Div {
|
||||
.child(
|
||||
blocks::pixel(18., FontWeight::SEMIBOLD)
|
||||
.text_color(t.ink)
|
||||
.child(label),
|
||||
.child(tr(label)),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1349,7 +1358,7 @@ fn segments<T: Copy + PartialEq + 'static>(
|
||||
.when(!active, |d| {
|
||||
d.text_color(t.muted).hover(move |s| s.text_color(t.ink))
|
||||
})
|
||||
.child(div().relative().child(label))
|
||||
.child(div().relative().child(tr(label)))
|
||||
.on_click(move |_: &ClickEvent, window, cx| pick(value, window, cx))
|
||||
}))
|
||||
}
|
||||
@@ -1375,13 +1384,13 @@ fn page_header(title: &str, description: &str, t: &Theme) -> Div {
|
||||
.child(
|
||||
blocks::pixel(36., FontWeight::SEMIBOLD)
|
||||
.text_color(t.ink)
|
||||
.child(title.to_string()),
|
||||
.child(tr(title).to_string()),
|
||||
)
|
||||
.child(
|
||||
text(theme::UI)
|
||||
.max_w(px(520.))
|
||||
.text_color(t.muted)
|
||||
.child(description.to_string()),
|
||||
.child(tr(description).to_string()),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1524,9 +1533,9 @@ fn megabytes(bytes: u64) -> String {
|
||||
// ----- Pages -------------------------------------------------------------------------------------
|
||||
|
||||
impl Launcher {
|
||||
/// The top bar: the mark and the name over the sidebar (in the title bar on Windows), the
|
||||
/// pages with their icons, then the account playing and the Settings button.
|
||||
fn topbar(&mut self, cx: &mut Context<Self>) -> Div {
|
||||
/// The top bar: the mark and name over the sidebar (in the title bar on Windows and Linux
|
||||
/// client-side decorations), the pages with their icons, then the account and Settings.
|
||||
fn topbar(&mut self, window: &Window, cx: &mut Context<Self>) -> Div {
|
||||
let t = self.theme;
|
||||
let mut nav = div().flex().flex_none().h_full().gap(px(2.));
|
||||
for (page, label, icon) in Page::ALL {
|
||||
@@ -1564,7 +1573,7 @@ impl Launcher {
|
||||
blocks::pixel(16., FontWeight::MEDIUM)
|
||||
.relative()
|
||||
.text_color(if active { t.ink } else { t.muted })
|
||||
.child(label),
|
||||
.child(tr(label)),
|
||||
)
|
||||
.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
|
||||
this.go(page);
|
||||
@@ -1662,8 +1671,8 @@ impl Launcher {
|
||||
.bg(t.side)
|
||||
.border_b_2()
|
||||
.border_color(t.outline)
|
||||
// Where the title bar is drawn here (Windows), it carries the mark and the name.
|
||||
.when(!titlebar::DRAWN, |bar| {
|
||||
// Custom title bars carry the mark and name above the sidebar.
|
||||
.when(!titlebar::draws_brand(window), |bar| {
|
||||
bar.child(
|
||||
div()
|
||||
.flex()
|
||||
@@ -1747,7 +1756,7 @@ impl Launcher {
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(px(4.))
|
||||
.child(heading("INSTANCES".into()).child(add))
|
||||
.child(heading(tr("INSTANCES").into()).child(add))
|
||||
.children(self.instance_items(heading, cx));
|
||||
let servers: Vec<_> = self
|
||||
.servers
|
||||
@@ -1756,7 +1765,7 @@ impl Launcher {
|
||||
.unwrap_or_else(|| self.side_servers.clone());
|
||||
let mut list = list;
|
||||
if !servers.is_empty() {
|
||||
list = list.child(heading("SERVERS".into()));
|
||||
list = list.child(heading(tr("SERVERS").into()));
|
||||
}
|
||||
for e in servers {
|
||||
let up = self.servers.is_up(&e.dir);
|
||||
@@ -1782,7 +1791,7 @@ impl Launcher {
|
||||
.flex_col()
|
||||
.min_w_0()
|
||||
.child(title(e.name.clone()))
|
||||
.child(sub(if up { "Running" } else { "Stopped" }.into())),
|
||||
.child(sub(tr(if up { "Running" } else { "Stopped" }).into())),
|
||||
)
|
||||
.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
|
||||
this.servers.open = Some(dir.clone());
|
||||
@@ -1866,7 +1875,7 @@ impl Launcher {
|
||||
text(theme::MICRO)
|
||||
.text_color(t.muted)
|
||||
.hover(move |s| s.text_color(t.ink))
|
||||
.child("HIDE"),
|
||||
.child(tr("HIDE")),
|
||||
)
|
||||
.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
|
||||
this.settings.partner_hidden = true;
|
||||
@@ -1888,7 +1897,7 @@ impl Launcher {
|
||||
if !self.links.website.is_empty() {
|
||||
foot = foot.child(link(
|
||||
"website",
|
||||
"Website",
|
||||
tr("Website"),
|
||||
"globe",
|
||||
self.links.website.clone(),
|
||||
));
|
||||
@@ -2053,7 +2062,7 @@ impl Launcher {
|
||||
"Start the game, or run a server for others to join.",
|
||||
&t,
|
||||
))
|
||||
.child(centered("No version installed yet.", &t).child(
|
||||
.child(centered(tr("No version installed yet."), &t).child(
|
||||
button("go-versions", "Choose a version", Kind::Secondary, &t).on_click(
|
||||
cx.listener(|this, _: &ClickEvent, _, cx| {
|
||||
this.go(Page::Versions);
|
||||
@@ -2069,10 +2078,12 @@ impl Launcher {
|
||||
let hero = self.hero(&tag, &version, prepared, cx);
|
||||
let running = self.client.is_some() || self.starting_client.is_some();
|
||||
let play_label = if running { "Running" } else { "Play" };
|
||||
// The label clears the icon in every language ("Играть" is wider than "Play").
|
||||
let mut play = button("play", play_label, Kind::Primary, &t)
|
||||
.min_w(px(200.))
|
||||
.h(px(60.))
|
||||
.px(px(28.))
|
||||
.pl(px(60.))
|
||||
.pr(px(28.))
|
||||
.text_size(px(28.))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.child(
|
||||
@@ -2113,7 +2124,7 @@ impl Launcher {
|
||||
);
|
||||
|
||||
let resources_value = if self.preparing {
|
||||
"Preparing…".to_string()
|
||||
tr("Preparing…").to_string()
|
||||
} else {
|
||||
backend::resources_summary(prepared, !silent, &version)
|
||||
};
|
||||
@@ -2138,7 +2149,9 @@ impl Launcher {
|
||||
let minecraft = self.settings.minecraft_dir.as_deref().map_or_else(
|
||||
|| {
|
||||
div()
|
||||
.child("Not found. Choose the folder where your launcher keeps Minecraft.")
|
||||
.child(tr(
|
||||
"Not found. Choose the folder where your launcher keeps Minecraft.",
|
||||
))
|
||||
.into_any_element()
|
||||
},
|
||||
|p| {
|
||||
@@ -2157,14 +2170,14 @@ impl Launcher {
|
||||
.children(self.launch_panel(cx))
|
||||
.child(index_row(
|
||||
2,
|
||||
"Resources",
|
||||
tr("Resources"),
|
||||
Some(div().child(resources_value).into_any_element()),
|
||||
Some(prepare.into_any_element()),
|
||||
&t,
|
||||
))
|
||||
.child(index_row(
|
||||
3,
|
||||
"Minecraft folder",
|
||||
tr("Minecraft folder"),
|
||||
Some(minecraft),
|
||||
Some(
|
||||
button("choose-mc", "Choose…", Kind::Ghost, &t)
|
||||
@@ -2180,10 +2193,10 @@ impl Launcher {
|
||||
if self.accounts.selected().is_none() && account::client_id().is_some() {
|
||||
rows = rows.child(index_row(
|
||||
5,
|
||||
"Playing offline",
|
||||
tr("Playing offline"),
|
||||
Some(
|
||||
div()
|
||||
.child("Online servers need a Microsoft account.")
|
||||
.child(tr("Online servers need a Microsoft account."))
|
||||
.into_any_element(),
|
||||
),
|
||||
Some(
|
||||
@@ -2214,6 +2227,21 @@ impl Launcher {
|
||||
gpui::linear_color_stop(t.page.opacity(to), at),
|
||||
))
|
||||
};
|
||||
let picture = self.home_background();
|
||||
let scene = match picture {
|
||||
Some(path) => gpui::img(path)
|
||||
.absolute()
|
||||
.top_0()
|
||||
.left_0()
|
||||
.size_full()
|
||||
.object_fit(gpui::ObjectFit::Cover),
|
||||
None => gpui::img(scene)
|
||||
.absolute()
|
||||
.bottom_0()
|
||||
.left_0()
|
||||
.w(px(scene_width))
|
||||
.h(px(art::SCENE_HEIGHT as f32 * art::SCENE_TEXEL)),
|
||||
};
|
||||
let banner = div()
|
||||
.relative()
|
||||
.flex()
|
||||
@@ -2228,14 +2256,7 @@ impl Launcher {
|
||||
.bg(gpui::rgb(art::sky_top(t.dark)))
|
||||
.border_b_2()
|
||||
.border_color(t.outline)
|
||||
.child(
|
||||
gpui::img(scene)
|
||||
.absolute()
|
||||
.bottom_0()
|
||||
.left_0()
|
||||
.w(px(scene_width))
|
||||
.h(px(art::SCENE_HEIGHT as f32 * art::SCENE_TEXEL)),
|
||||
)
|
||||
.child(scene)
|
||||
.child(veil(90., 0.82, 0., 0.62))
|
||||
.child(veil(180., 0., 0.75, 1.))
|
||||
.child(div().relative().child(hero))
|
||||
@@ -2260,7 +2281,7 @@ impl Launcher {
|
||||
.child(
|
||||
text(theme::CAPTION)
|
||||
.text_color(t.muted)
|
||||
.child("The first preparation takes a few minutes."),
|
||||
.child(tr("The first preparation takes a few minutes.")),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -2354,11 +2375,11 @@ impl Launcher {
|
||||
},
|
||||
)),
|
||||
);
|
||||
let help = if crash.report.is_some() {
|
||||
let help = tr(if crash.report.is_some() {
|
||||
"When you report it on Discord, attach the crash report file (or paste it with Copy report) and say what you were doing."
|
||||
} else {
|
||||
"The game ended without a crash report. When you report it on Discord, attach latest.log from the logs folder and say what you were doing."
|
||||
};
|
||||
});
|
||||
let mut body = div()
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
@@ -2368,7 +2389,7 @@ impl Launcher {
|
||||
.child(
|
||||
text(theme::HEADING)
|
||||
.text_color(t.ink)
|
||||
.child("Horizon crashed"),
|
||||
.child(tr("Horizon crashed")),
|
||||
);
|
||||
if !crash.summary.is_empty() {
|
||||
body = body.child(div().text_color(t.ink_soft).child(crash.summary));
|
||||
@@ -2444,7 +2465,7 @@ impl Launcher {
|
||||
.child(caps(format!("Minecraft {version}")).text_color(t.ink_soft))
|
||||
.child(div().size(px(4.)).bg(t.muted))
|
||||
.child(
|
||||
caps(if prepared { "Ready" } else { "Needs preparing" })
|
||||
caps(tr(if prepared { "Ready" } else { "Needs preparing" }))
|
||||
.text_color(if prepared { t.success } else { t.warn }),
|
||||
),
|
||||
)
|
||||
@@ -2582,10 +2603,10 @@ impl Launcher {
|
||||
}),
|
||||
);
|
||||
let horizon = match (&self.updates.horizon, &self.update_error) {
|
||||
(Some(r), _) => format!("{} available", r.tag),
|
||||
(Some(r), _) => trf("{version} available", &[("version", &r.tag)]),
|
||||
(None, Some(e)) => e.clone(),
|
||||
(None, None) if self.checked.is_some() => "Up to date".to_string(),
|
||||
_ => "Checking…".to_string(),
|
||||
(None, None) if self.checked.is_some() => tr("Up to date").to_string(),
|
||||
_ => tr("Checking…").to_string(),
|
||||
};
|
||||
let horizon_action = self
|
||||
.updates
|
||||
@@ -2602,18 +2623,36 @@ impl Launcher {
|
||||
});
|
||||
let launcher = match &self.self_update {
|
||||
SelfUpdate::Downloading(v, p) => {
|
||||
format!("{} · downloading {v}, {:.0}%", backend::VERSION, p * 100.)
|
||||
let done = format!("{:.0}", p * 100.);
|
||||
let said = trf(
|
||||
"downloading {version}, {percent}%",
|
||||
&[("version", v), ("percent", &done)],
|
||||
);
|
||||
format!("{} · {said}", backend::VERSION)
|
||||
}
|
||||
SelfUpdate::Ready(v) => format!("Updated to {v}. Restart the launcher to use it."),
|
||||
SelfUpdate::Failed(e) => format!("{} · the update failed: {e}", backend::VERSION),
|
||||
SelfUpdate::Ready(v) => trf(
|
||||
"Updated to {version}. Restart the launcher to use it.",
|
||||
&[("version", v)],
|
||||
),
|
||||
SelfUpdate::Failed(e) => format!(
|
||||
"{} · {}",
|
||||
backend::VERSION,
|
||||
trf("the update failed: {error}", &[("error", e)])
|
||||
),
|
||||
SelfUpdate::Idle => match &self.updates.launcher {
|
||||
Some(r) => format!(
|
||||
"{} · {} available",
|
||||
"{} · {}",
|
||||
backend::VERSION,
|
||||
backend::launcher_version(&r.tag).unwrap_or_default()
|
||||
trf(
|
||||
"{version} available",
|
||||
&[(
|
||||
"version",
|
||||
backend::launcher_version(&r.tag).unwrap_or_default()
|
||||
)]
|
||||
)
|
||||
),
|
||||
None if self.checked.is_some() && self.update_error.is_none() => {
|
||||
format!("{} · up to date", backend::VERSION)
|
||||
format!("{} · {}", backend::VERSION, tr("up to date"))
|
||||
}
|
||||
None => backend::VERSION.to_string(),
|
||||
},
|
||||
@@ -2638,7 +2677,7 @@ impl Launcher {
|
||||
),
|
||||
};
|
||||
let mono = |s: String| div().font_family(theme::MONO).child(s).into_any_element();
|
||||
let plain = |s: &str| div().child(s.to_string()).into_any_element();
|
||||
let plain = |s: &str| div().child(tr(s).to_string()).into_any_element();
|
||||
let (accounts, n) = self.account_rows(cx);
|
||||
let (offline, n) = self.offline_rows(n, cx);
|
||||
let appearance = segments(
|
||||
@@ -2657,7 +2696,7 @@ impl Launcher {
|
||||
this.settings.appearance = choice;
|
||||
this.settings.save();
|
||||
titlebar::apply_appearance(window, choice);
|
||||
this.theme = Theme::for_appearance(choice, window.appearance());
|
||||
this.theme = this.settings_theme(window);
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
@@ -2685,7 +2724,7 @@ impl Launcher {
|
||||
.child(group("Updates", "reload"))
|
||||
.child(index_row(
|
||||
n + 1,
|
||||
"Install new versions automatically",
|
||||
tr("Install new versions automatically"),
|
||||
Some(plain(
|
||||
"Your selected version only changes if you were playing the newest one.",
|
||||
)),
|
||||
@@ -2695,15 +2734,18 @@ impl Launcher {
|
||||
.child(group("Launcher", "monitor"))
|
||||
.child(index_row(
|
||||
n + 3,
|
||||
"Appearance",
|
||||
tr("Appearance"),
|
||||
Some(plain("Dark by default. System follows your computer's light or dark.")),
|
||||
Some(appearance.into_any_element()),
|
||||
&t,
|
||||
))
|
||||
.child(self.accent_row(cx))
|
||||
.child(self.home_background_row(cx))
|
||||
.child(self.language_row(cx))
|
||||
.child(self.while_playing_row(n + 3, cx))
|
||||
.child(index_row(
|
||||
n + 3,
|
||||
"Show the opening",
|
||||
tr("Show the opening"),
|
||||
Some(plain("The wordmark, while the release list loads.")),
|
||||
Some(opening.into_any_element()),
|
||||
&t,
|
||||
@@ -2718,24 +2760,25 @@ impl Launcher {
|
||||
.child(index_row(n + 7, "Horizon", Some(plain(&horizon)), horizon_action, &t))
|
||||
.child(index_row(
|
||||
n + 8,
|
||||
"Launcher",
|
||||
tr("Launcher"),
|
||||
Some(plain(&launcher)),
|
||||
launcher_action,
|
||||
&t,
|
||||
))
|
||||
.child(index_row(
|
||||
n + 9,
|
||||
"Data folder",
|
||||
tr("Data folder"),
|
||||
Some(mono(short(&backend::data_dir()))),
|
||||
None,
|
||||
&t,
|
||||
))
|
||||
.child(index_row(
|
||||
n + 10,
|
||||
"Logs",
|
||||
tr("Logs"),
|
||||
Some(mono(format!(
|
||||
"{} · crash reports beside it",
|
||||
short(&backend::logs_dir())
|
||||
"{} · {}",
|
||||
short(&backend::logs_dir()),
|
||||
tr("crash reports beside it")
|
||||
))),
|
||||
Some(
|
||||
button("open-logs", "Open", Kind::Secondary, &t)
|
||||
@@ -2751,7 +2794,7 @@ impl Launcher {
|
||||
.when(cfg!(target_os = "linux"), |d| {
|
||||
d.child(index_row(
|
||||
n + 11,
|
||||
"Applications menu",
|
||||
tr("Applications menu"),
|
||||
Some(plain(if self.settings.desktop_entry() {
|
||||
"Horizon and its icon are in your desktop's menu."
|
||||
} else {
|
||||
@@ -2963,11 +3006,11 @@ impl Launcher {
|
||||
a.name.clone(),
|
||||
Some(
|
||||
div()
|
||||
.child(if plays {
|
||||
.child(tr(if plays {
|
||||
"Microsoft account · plays"
|
||||
} else {
|
||||
"Microsoft account · signed in"
|
||||
})
|
||||
}))
|
||||
.into_any_element(),
|
||||
),
|
||||
Some(actions.into_any_element()),
|
||||
@@ -2980,8 +3023,8 @@ impl Launcher {
|
||||
Some(SignInState::Starting | SignInState::Code(_))
|
||||
);
|
||||
let detail = match &self.sign_in_state {
|
||||
_ if !configured => div().child(account::NOT_CONFIGURED),
|
||||
Some(SignInState::Starting) => div().child("Asking Microsoft…"),
|
||||
_ if !configured => div().child(tr(account::NOT_CONFIGURED)),
|
||||
Some(SignInState::Starting) => div().child(tr("Asking Microsoft…")),
|
||||
Some(SignInState::Code(code)) => div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
@@ -3001,7 +3044,7 @@ impl Launcher {
|
||||
None if self.accounts.accounts.is_empty() => div().child(
|
||||
"Sign in to play on online servers with your name and skin. Without an account the game plays offline.",
|
||||
),
|
||||
None => div().child("Add another account."),
|
||||
None => div().child(tr("Add another account.")),
|
||||
};
|
||||
let detail = if self.keychain || self.accounts.accounts.is_empty() {
|
||||
detail
|
||||
@@ -3072,7 +3115,7 @@ impl Launcher {
|
||||
};
|
||||
rows = rows.child(index_row(
|
||||
n,
|
||||
title,
|
||||
tr(title),
|
||||
Some(detail.into_any_element()),
|
||||
action,
|
||||
&t,
|
||||
@@ -3101,7 +3144,7 @@ impl Launcher {
|
||||
.text_size(px(12.))
|
||||
.cursor_text()
|
||||
.child(if self.friend_code.is_empty() && !focused {
|
||||
div().text_color(t.muted).child("Paste an invite code")
|
||||
div().text_color(t.muted).child(tr("Paste an invite code"))
|
||||
} else {
|
||||
// The end of a long code stays in view while typing.
|
||||
let shown: String = {
|
||||
@@ -3151,10 +3194,10 @@ impl Launcher {
|
||||
}
|
||||
index_row(
|
||||
4,
|
||||
"Join a friend",
|
||||
tr("Join a friend"),
|
||||
Some(
|
||||
div()
|
||||
.child("Paste the code a friend shows when they invite you.")
|
||||
.child(tr("Paste the code a friend shows when they invite you."))
|
||||
.into_any_element(),
|
||||
),
|
||||
Some(
|
||||
@@ -3602,7 +3645,7 @@ impl Render for Launcher {
|
||||
window.focus(&self.root_focus);
|
||||
}
|
||||
let stone = self.art.stone(t.page_rgb, t.dark, window.scale_factor());
|
||||
let topbar = self.topbar(cx);
|
||||
let topbar = self.topbar(window, cx);
|
||||
let sidebar = self.sidebar(cx);
|
||||
let mut root = div()
|
||||
.id("root")
|
||||
@@ -3757,6 +3800,7 @@ impl Render for Launcher {
|
||||
.bg(t.side)
|
||||
.children(titlebar::render(&t, window))
|
||||
.child(root.flex_1().min_h_0())
|
||||
.children(titlebar::resize_handles(window))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3886,6 +3930,8 @@ fn main() {
|
||||
window_bounds: Some(WindowBounds::Windowed(bounds)),
|
||||
window_min_size: Some(size(px(960.), px(600.))),
|
||||
titlebar: Some(titlebar::options()),
|
||||
#[cfg(target_os = "linux")]
|
||||
window_decorations: Some(gpui::WindowDecorations::Client),
|
||||
app_id: Some("horizon-launcher".into()),
|
||||
..Default::default()
|
||||
},
|
||||
|
||||
@@ -38,7 +38,7 @@ pub fn banner(id: &'static str, width: f32, t: &Theme) -> Stateful<Div> {
|
||||
crate::text(crate::theme::MICRO)
|
||||
.text_color(t.muted)
|
||||
.group_hover(id, move |s| s.text_color(t.ink))
|
||||
.child("PARTNER"),
|
||||
.child(horizon_launcher::i18n::tr("PARTNER")),
|
||||
)
|
||||
.child(
|
||||
div().relative().group_hover(id, |s| s.top(px(-2.))).child(
|
||||
|
||||
@@ -81,9 +81,12 @@ impl Launcher {
|
||||
true => l.cape = true,
|
||||
})
|
||||
});
|
||||
let what = if cape { "cape" } else { "skin" };
|
||||
if let Some(p) = &mut self.skin {
|
||||
p.note = Some(done.map(|()| format!("{name}'s {what} is kept.")));
|
||||
let said = match cape {
|
||||
false => trf("{name}'s skin is kept.", &[("name", &name)]),
|
||||
true => trf("{name}'s cape is kept.", &[("name", &name)]),
|
||||
};
|
||||
p.note = Some(done.map(|()| said));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,7 +139,7 @@ impl Launcher {
|
||||
Some(i) => gpui::img(i).w(px(w)).h(px(h)).into_any_element(),
|
||||
None => text(theme::CAPTION)
|
||||
.text_color(t.muted)
|
||||
.child(empty)
|
||||
.child(tr(empty))
|
||||
.into_any_element(),
|
||||
})
|
||||
};
|
||||
@@ -205,7 +208,7 @@ impl Launcher {
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.gap(px(12.))
|
||||
.child(caps(format!("{name}'s skin")).text_color(t.muted))
|
||||
.child(caps(trf("{name}'s skin", &[("name", &name)])).text_color(t.muted))
|
||||
.child(skin_buttons)
|
||||
.child(model)
|
||||
.child(cape_buttons)
|
||||
@@ -213,12 +216,12 @@ impl Launcher {
|
||||
Ok(said) => text(theme::CAPTION).text_color(t.muted).child(said),
|
||||
Err(e) => text(theme::CAPTION).text_color(t.danger).child(e),
|
||||
}))
|
||||
.child(text(theme::CAPTION).text_color(t.muted).child(
|
||||
.child(text(theme::CAPTION).text_color(t.muted).child(tr(
|
||||
"A 64×64 (or 64×32) skin PNG and a 64×32 cape PNG, kept by the \
|
||||
launcher and given to the game when this name plays. The game \
|
||||
draws the default skins for now; it uses these once it can. A \
|
||||
Microsoft account's skin and cape: coming soon.",
|
||||
)),
|
||||
))),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
+13
-13
@@ -12,12 +12,12 @@ impl Launcher {
|
||||
self.accounts
|
||||
.selected()
|
||||
.map_or_else(String::new, |a| a.name.clone()),
|
||||
"Microsoft account",
|
||||
tr("Microsoft account"),
|
||||
),
|
||||
Player::Offline(name) => (name, "Offline"),
|
||||
Player::Offline(name) => (name, tr("Offline")),
|
||||
Player::GameName => (
|
||||
self.offline_name.clone().unwrap_or_else(|| "Player".into()),
|
||||
"Offline",
|
||||
tr("Offline"),
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,7 @@ impl Launcher {
|
||||
(
|
||||
Player::Microsoft(a.uuid.clone()),
|
||||
a.name.clone(),
|
||||
"Microsoft",
|
||||
tr("Microsoft"),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
@@ -50,12 +50,12 @@ impl Launcher {
|
||||
self.accounts
|
||||
.offline
|
||||
.iter()
|
||||
.map(|n| (Player::Offline(n.clone()), n.clone(), "Offline")),
|
||||
.map(|n| (Player::Offline(n.clone()), n.clone(), tr("Offline"))),
|
||||
);
|
||||
out.push((
|
||||
Player::GameName,
|
||||
self.offline_name.clone().unwrap_or_else(|| "Player".into()),
|
||||
"Offline, the game's name",
|
||||
tr("Offline, the game's name"),
|
||||
));
|
||||
out
|
||||
}
|
||||
@@ -123,7 +123,7 @@ impl Launcher {
|
||||
.text_color(t.muted)
|
||||
.cursor_pointer()
|
||||
.hover(move |s| s.bg(t.plate_soft).text_color(t.ink))
|
||||
.child("Manage accounts")
|
||||
.child(tr("Manage accounts"))
|
||||
.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
|
||||
this.account_menu = false;
|
||||
this.go(Page::Settings);
|
||||
@@ -196,11 +196,11 @@ impl Launcher {
|
||||
name,
|
||||
Some(
|
||||
div()
|
||||
.child(if plays {
|
||||
.child(tr(if plays {
|
||||
"Offline name · plays"
|
||||
} else {
|
||||
"Offline name"
|
||||
})
|
||||
}))
|
||||
.into_any_element(),
|
||||
),
|
||||
Some(actions.into_any_element()),
|
||||
@@ -213,7 +213,7 @@ impl Launcher {
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(8.))
|
||||
.child(self.field(Field::OfflineName, "A name, 3 to 16 letters", 220., cx))
|
||||
.child(self.field(Field::OfflineName, tr("A name, 3 to 16 letters"), 220., cx))
|
||||
.child(
|
||||
button("offline-add", "Add", Kind::Secondary, &t).on_click(cx.listener(
|
||||
|this, _: &ClickEvent, _, cx| {
|
||||
@@ -224,13 +224,13 @@ impl Launcher {
|
||||
);
|
||||
rows = rows.child(index_row(
|
||||
n,
|
||||
"Offline name",
|
||||
tr("Offline name"),
|
||||
Some(
|
||||
div()
|
||||
.child(
|
||||
.child(tr(
|
||||
"Play offline under another name, and switch from the top bar. Online \
|
||||
servers don't take offline names.",
|
||||
)
|
||||
))
|
||||
.into_any_element(),
|
||||
),
|
||||
Some(add.into_any_element()),
|
||||
|
||||
+8
-14
@@ -4,6 +4,7 @@
|
||||
//! Mono for text (all bundled, SIL Open Font License).
|
||||
use gpui::{rgb, Hsla, WindowAppearance};
|
||||
use horizon_launcher::backend::Appearance;
|
||||
use horizon_launcher::themes::Accent;
|
||||
use horizon_theme as tokens;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -91,25 +92,18 @@ pub fn pinned_dark(choice: Appearance) -> Option<bool> {
|
||||
|
||||
impl Theme {
|
||||
/// The pinned look (`pinned_dark`: dark unless the player picked another), the system's when
|
||||
/// they asked to follow it.
|
||||
pub fn for_appearance(choice: Appearance, system: WindowAppearance) -> Self {
|
||||
/// they asked to follow it, in the player's accent.
|
||||
pub fn for_appearance(choice: Appearance, accent: Accent, system: WindowAppearance) -> Self {
|
||||
let system_dark = !matches!(
|
||||
system,
|
||||
WindowAppearance::Light | WindowAppearance::VibrantLight
|
||||
);
|
||||
if pinned_dark(choice).unwrap_or(system_dark) {
|
||||
Self::dark()
|
||||
let dark = pinned_dark(choice).unwrap_or(system_dark);
|
||||
Self::from(accent.apply(if dark {
|
||||
tokens::BLOCKS_DARK
|
||||
} else {
|
||||
Self::light()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dark() -> Self {
|
||||
Self::from(tokens::BLOCKS_DARK)
|
||||
}
|
||||
|
||||
pub fn light() -> Self {
|
||||
Self::from(tokens::BLOCKS_LIGHT)
|
||||
tokens::BLOCKS_LIGHT
|
||||
}))
|
||||
}
|
||||
|
||||
fn from(p: tokens::Blocks) -> Self {
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
//! The player's own look, on top of Dark, Light or System: an accent colour and a picture behind
|
||||
//! Home.
|
||||
//!
|
||||
//! An accent is a hue. Horizon's violet is the default; another hue turns the violet tokens
|
||||
//! (`horizon_theme::Blocks`' accent and the main action's face, bevel and lip) to it, keeping
|
||||
//! their saturation and lightness, then darkens or lightens each just enough to read as well as
|
||||
//! the violet does: white on the face at 4.5:1, the accent at 3:1 on every background.
|
||||
use horizon_theme::{contrast, Blocks};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Accent {
|
||||
#[default]
|
||||
Violet,
|
||||
Blue,
|
||||
Teal,
|
||||
Green,
|
||||
Amber,
|
||||
Red,
|
||||
Pink,
|
||||
}
|
||||
|
||||
impl Accent {
|
||||
pub const ALL: [Accent; 7] = [
|
||||
Self::Violet,
|
||||
Self::Blue,
|
||||
Self::Teal,
|
||||
Self::Green,
|
||||
Self::Amber,
|
||||
Self::Red,
|
||||
Self::Pink,
|
||||
];
|
||||
|
||||
/// Its name in `settings.json` and on the command line.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Violet => "violet",
|
||||
Self::Blue => "blue",
|
||||
Self::Teal => "teal",
|
||||
Self::Green => "green",
|
||||
Self::Amber => "amber",
|
||||
Self::Red => "red",
|
||||
Self::Pink => "pink",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(name: &str) -> Option<Self> {
|
||||
let name = name.trim().to_ascii_lowercase();
|
||||
let name = if name == "purple" || name == "default" {
|
||||
"violet"
|
||||
} else {
|
||||
&name
|
||||
};
|
||||
Self::ALL.into_iter().find(|a| a.name() == name)
|
||||
}
|
||||
|
||||
/// Its hue in degrees; None for the violet, whose tokens stay as they are.
|
||||
fn hue(self) -> Option<f32> {
|
||||
match self {
|
||||
Self::Violet => None,
|
||||
Self::Blue => Some(212.),
|
||||
Self::Teal => Some(176.),
|
||||
Self::Green => Some(140.),
|
||||
Self::Amber => Some(36.),
|
||||
Self::Red => Some(356.),
|
||||
Self::Pink => Some(322.),
|
||||
}
|
||||
}
|
||||
|
||||
/// `palette` with this accent.
|
||||
pub fn apply(self, mut p: Blocks) -> Blocks {
|
||||
let Some(hue) = self.hue() else {
|
||||
return p;
|
||||
};
|
||||
let turn = |c: u32| {
|
||||
let (_, s, l) = hsl(c);
|
||||
(hue, s, l)
|
||||
};
|
||||
// The face holds white text.
|
||||
let face = fit(turn(p.face), |c| contrast(p.on_face, c) >= 4.5, -1.);
|
||||
let (_, _, face_l) = hsl(face);
|
||||
let (h, s, l) = turn(p.face_bevel);
|
||||
p.face_bevel = from_hsl(h, s, l.max(face_l + 0.08).min(0.92));
|
||||
let (h, s, l) = turn(p.face_lip);
|
||||
p.face_lip = from_hsl(h, s, l.min(face_l - 0.12).max(0.05));
|
||||
p.face = face;
|
||||
// The accent marks things on every background: lighter on dark, darker on light.
|
||||
let grounds = [p.page, p.raised, p.button, p.panel, p.well];
|
||||
let reads = |c: u32| grounds.iter().all(|&g| contrast(c, g) >= 3.2);
|
||||
p.accent = fit(turn(p.accent), reads, if p.dark { 1. } else { -1. });
|
||||
p
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour's hue (degrees), saturation and lightness (0 to 1).
|
||||
fn hsl(c: u32) -> (f32, f32, f32) {
|
||||
let [r, g, b] = [16, 8, 0].map(|s| ((c >> s) & 255) as f32 / 255.);
|
||||
let (max, min) = (r.max(g).max(b), r.min(g).min(b));
|
||||
let l = (max + min) / 2.;
|
||||
if max == min {
|
||||
return (0., 0., l);
|
||||
}
|
||||
let d = max - min;
|
||||
let s = if l > 0.5 {
|
||||
d / (2. - max - min)
|
||||
} else {
|
||||
d / (max + min)
|
||||
};
|
||||
let h = if max == r {
|
||||
(g - b) / d + if g < b { 6. } else { 0. }
|
||||
} else if max == g {
|
||||
(b - r) / d + 2.
|
||||
} else {
|
||||
(r - g) / d + 4.
|
||||
};
|
||||
(h * 60., s, l)
|
||||
}
|
||||
|
||||
fn from_hsl(h: f32, s: f32, l: f32) -> u32 {
|
||||
let c = (1. - (2. * l - 1.).abs()) * s;
|
||||
let x = c * (1. - ((h / 60.) % 2. - 1.).abs());
|
||||
let m = l - c / 2.;
|
||||
let (r, g, b) = match (h.rem_euclid(360.) / 60.) as u32 {
|
||||
0 => (c, x, 0.),
|
||||
1 => (x, c, 0.),
|
||||
2 => (0., c, x),
|
||||
3 => (0., x, c),
|
||||
4 => (x, 0., c),
|
||||
_ => (c, 0., x),
|
||||
};
|
||||
let byte = |v: f32| ((v + m).clamp(0., 1.) * 255.).round() as u32;
|
||||
byte(r) << 16 | byte(g) << 8 | byte(b)
|
||||
}
|
||||
|
||||
/// The colour, made lighter (`step` 1) or darker (-1) a little at a time until `good` holds.
|
||||
fn fit((h, s, l): (f32, f32, f32), good: impl Fn(u32) -> bool, step: f32) -> u32 {
|
||||
let mut l = l;
|
||||
for _ in 0..100 {
|
||||
let c = from_hsl(h, s, l);
|
||||
if good(c) || !(0.0..=1.0).contains(&l) {
|
||||
return c;
|
||||
}
|
||||
l += step * 0.01;
|
||||
}
|
||||
from_hsl(h, s, l.clamp(0., 1.))
|
||||
}
|
||||
|
||||
/// The pictures Home can show: what the decoders read.
|
||||
const PICTURES: [&str; 4] = ["png", "jpg", "jpeg", "webp"];
|
||||
/// A picture above this is refused: a screen's worth is far less.
|
||||
const MAX_BYTES: u64 = 40 << 20;
|
||||
|
||||
/// Keeps `file` as Home's background in `dir` (`background-<hash>.<ext>`: a new picture gets a
|
||||
/// new name, so the window doesn't show the one it cached), after checking it is a picture, and
|
||||
/// returns the kept file's name. An older background goes.
|
||||
pub fn keep_background(dir: &Path, file: &Path) -> Result<String, String> {
|
||||
let shown = file.display();
|
||||
let ext = file
|
||||
.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.map(str::to_ascii_lowercase)
|
||||
.filter(|e| PICTURES.contains(&e.as_str()))
|
||||
.ok_or_else(|| format!("{shown}: a PNG, JPEG or WebP picture, please."))?;
|
||||
let size = std::fs::metadata(file)
|
||||
.map_err(|e| format!("{shown}: {e}"))?
|
||||
.len();
|
||||
if size > MAX_BYTES {
|
||||
return Err(format!("{shown} is over 40 MB."));
|
||||
}
|
||||
let bytes = std::fs::read(file).map_err(|e| format!("{shown}: {e}"))?;
|
||||
let (w, h) = image::ImageReader::new(std::io::Cursor::new(&bytes))
|
||||
.with_guessed_format()
|
||||
.ok()
|
||||
.and_then(|r| r.into_dimensions().ok())
|
||||
.ok_or_else(|| format!("{shown} isn't a picture the launcher can read."))?;
|
||||
if w < 64 || h < 64 {
|
||||
return Err(format!("{shown} is {w}×{h}: too small to fill Home."));
|
||||
}
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let hash = crate::sources::sha1_hex(&bytes);
|
||||
let name = format!("background-{}.{ext}", &hash[..12]);
|
||||
std::fs::write(dir.join(&name), &bytes).map_err(|e| format!("{name}: {e}"))?;
|
||||
for old in std::fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||
let other = old.file_name().to_string_lossy().into_owned();
|
||||
if other.starts_with("background-") && other != name {
|
||||
let _ = std::fs::remove_file(old.path());
|
||||
}
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// Home's background, if the player keeps one and it is still there.
|
||||
pub fn background(dir: &Path, name: Option<&str>) -> Option<PathBuf> {
|
||||
let name = name.filter(|n| n.starts_with("background-") && !n.contains(['/', '\\']))?;
|
||||
Some(dir.join(name)).filter(|p| p.is_file())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "themes/tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,107 @@
|
||||
use super::*;
|
||||
use horizon_theme::{BLOCKS_DARK, BLOCKS_LIGHT};
|
||||
|
||||
fn blend(top: u32, under: u32, alpha: f32) -> u32 {
|
||||
let channel = |shift: u32| {
|
||||
let (a, b) = ((top >> shift & 0xff) as f32, (under >> shift & 0xff) as f32);
|
||||
((a * alpha + b * (1. - alpha)).round() as u32) << shift
|
||||
};
|
||||
channel(16) | channel(8) | channel(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_accent_reads_as_well_as_the_violet() {
|
||||
for base in [BLOCKS_DARK, BLOCKS_LIGHT] {
|
||||
for accent in Accent::ALL {
|
||||
let p = accent.apply(base);
|
||||
let what = format!(
|
||||
"{} {}",
|
||||
accent.name(),
|
||||
if p.dark { "dark" } else { "light" }
|
||||
);
|
||||
let on_face = contrast(p.on_face, p.face);
|
||||
assert!(on_face >= 4.5, "{what}: text on the face {on_face:.2}");
|
||||
for g in [p.page, p.raised, p.button, p.panel, p.well] {
|
||||
let ring = contrast(p.accent, g);
|
||||
assert!(ring >= 3.0, "{what}: accent on {g:06x} {ring:.2}");
|
||||
}
|
||||
// Text over a selected suggestion (the launcher's theme::SELECTION).
|
||||
let selected = contrast(p.ink, blend(p.accent, p.panel, 0.22));
|
||||
assert!(selected >= 4.5, "{what}: text on a selection {selected:.2}");
|
||||
let (_, _, face) = hsl(p.face);
|
||||
assert!(
|
||||
hsl(p.face_bevel).2 > face && hsl(p.face_lip).2 < face,
|
||||
"{what}"
|
||||
);
|
||||
if accent != Accent::Violet {
|
||||
let (h, _, _) = hsl(p.face);
|
||||
let want = accent.hue().unwrap();
|
||||
let off = ((h - want).rem_euclid(360.)).min((want - h).rem_euclid(360.));
|
||||
assert!(off < 3., "{what}: face hue {h:.0}, not {want}");
|
||||
}
|
||||
}
|
||||
let violet = Accent::Violet.apply(base);
|
||||
assert_eq!((violet.accent, violet.face), (base.accent, base.face));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colours_go_to_hsl_and_back() {
|
||||
for c in [
|
||||
0x5b3fd6, 0x9a86ff, 0x000000, 0xffffff, 0x45c27a, 0xf0b84f, 0x123456,
|
||||
] {
|
||||
let (h, s, l) = hsl(c);
|
||||
assert_eq!(from_hsl(h, s, l), c, "{c:06x}");
|
||||
}
|
||||
assert_eq!(Accent::parse("Teal"), Some(Accent::Teal));
|
||||
assert_eq!(Accent::parse("purple"), Some(Accent::Violet));
|
||||
assert_eq!(Accent::parse("chartreuse"), None);
|
||||
assert_eq!(serde_json::to_string(&Accent::Amber).unwrap(), "\"amber\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_background_is_a_picture_kept_once() {
|
||||
let root = std::env::temp_dir().join(format!("horizon-background-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let picture = |name: &str, w: u32, h: u32| {
|
||||
let path = root.join(name);
|
||||
image::RgbImage::new(w, h).save(&path).unwrap();
|
||||
path
|
||||
};
|
||||
let dir = root.join("data");
|
||||
let png = picture("dusk.png", 160, 90);
|
||||
let first = keep_background(&dir, &png).unwrap();
|
||||
assert!(
|
||||
first.starts_with("background-") && first.ends_with(".png"),
|
||||
"{first}"
|
||||
);
|
||||
let jpg = picture("noon.jpg", 160, 90);
|
||||
let second = keep_background(&dir, &jpg).unwrap();
|
||||
assert!(second.ends_with(".jpg") && second != first, "{second}");
|
||||
assert!(!dir.join(&first).exists(), "the older one goes");
|
||||
assert_eq!(background(&dir, Some(&second)), Some(dir.join(&second)));
|
||||
assert_eq!(background(&dir, Some(&first)), None, "gone");
|
||||
assert_eq!(background(&dir, Some("../noon.jpg")), None);
|
||||
assert_eq!(background(&dir, None), None);
|
||||
|
||||
let tiny = picture("tiny.png", 16, 16);
|
||||
assert!(keep_background(&dir, &tiny)
|
||||
.unwrap_err()
|
||||
.contains("too small"));
|
||||
let text = root.join("notes.txt");
|
||||
std::fs::write(&text, "hi").unwrap();
|
||||
assert!(keep_background(&dir, &text)
|
||||
.unwrap_err()
|
||||
.contains("PNG, JPEG or WebP"));
|
||||
let fake = root.join("fake.png");
|
||||
std::fs::write(&fake, "not a picture").unwrap();
|
||||
assert!(keep_background(&dir, &fake)
|
||||
.unwrap_err()
|
||||
.contains("can read"));
|
||||
assert!(
|
||||
dir.join(&second).exists(),
|
||||
"a refused file keeps the old one"
|
||||
);
|
||||
std::fs::remove_dir_all(&root).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
//! Settings' accent colour and Home background rows (`horizon_launcher::themes`).
|
||||
use super::*;
|
||||
use horizon_launcher::themes::{self, Accent};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Each accent's swatch, in points.
|
||||
const SWATCH: f32 = 26.;
|
||||
|
||||
impl Launcher {
|
||||
/// The theme Settings ask for, under the window's own light or dark.
|
||||
pub(super) fn settings_theme(&self, window: &Window) -> Theme {
|
||||
Theme::for_appearance(
|
||||
self.settings.appearance,
|
||||
self.settings.accent,
|
||||
window.appearance(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The picture behind Home, if the player keeps one.
|
||||
pub(super) fn home_background(&self) -> Option<PathBuf> {
|
||||
themes::background(&backend::data_dir(), self.settings.background.as_deref())
|
||||
}
|
||||
|
||||
pub(super) fn accent_row(&self, cx: &mut Context<Self>) -> Div {
|
||||
let t = self.theme;
|
||||
let mut swatches = div().flex().gap(px(6.));
|
||||
for accent in Accent::ALL {
|
||||
let face = Theme::for_appearance(
|
||||
if t.dark {
|
||||
backend::Appearance::Dark
|
||||
} else {
|
||||
backend::Appearance::Light
|
||||
},
|
||||
accent,
|
||||
gpui::WindowAppearance::Dark,
|
||||
)
|
||||
.face;
|
||||
let chosen = self.settings.accent == accent;
|
||||
swatches = swatches.child(
|
||||
keyboard(
|
||||
div().id(SharedString::from(format!("accent-{}", accent.name()))),
|
||||
&t,
|
||||
)
|
||||
.size(px(SWATCH))
|
||||
.bg(face)
|
||||
.border_2()
|
||||
.border_color(if chosen { t.ink } else { t.outline })
|
||||
.cursor_pointer()
|
||||
.when(chosen, |d| {
|
||||
d.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.child(div().size(px(8.)).bg(t.on_face))
|
||||
})
|
||||
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
|
||||
this.settings.accent = accent;
|
||||
this.settings.save();
|
||||
this.theme = this.settings_theme(window);
|
||||
cx.notify();
|
||||
})),
|
||||
);
|
||||
}
|
||||
index_row(
|
||||
0,
|
||||
tr("Accent colour"),
|
||||
Some(
|
||||
div()
|
||||
.child(tr(
|
||||
"Horizon's violet by default. Every colour keeps text as easy to read.",
|
||||
))
|
||||
.into_any_element(),
|
||||
),
|
||||
Some(swatches.into_any_element()),
|
||||
&t,
|
||||
)
|
||||
}
|
||||
|
||||
fn choose_background(&mut self, cx: &mut Context<Self>) {
|
||||
let paths = cx.prompt_for_paths(PathPromptOptions {
|
||||
files: true,
|
||||
directories: false,
|
||||
multiple: false,
|
||||
prompt: Some(tr("Choose").to_string().into()),
|
||||
});
|
||||
cx.spawn(async move |this, cx| {
|
||||
let Ok(Ok(Some(mut paths))) = paths.await else {
|
||||
return;
|
||||
};
|
||||
let Some(path) = paths.pop() else {
|
||||
return;
|
||||
};
|
||||
let _ = this.update(cx, |this, cx| {
|
||||
this.take_background(&path);
|
||||
cx.notify();
|
||||
});
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn take_background(&mut self, path: &std::path::Path) {
|
||||
match themes::keep_background(&backend::data_dir(), path) {
|
||||
Ok(name) => {
|
||||
self.settings.background = Some(name);
|
||||
self.settings.save();
|
||||
self.background_error = None;
|
||||
}
|
||||
Err(e) => self.background_error = Some(e),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn home_background_row(&self, cx: &mut Context<Self>) -> Div {
|
||||
let t = self.theme;
|
||||
let custom = self.home_background().is_some();
|
||||
let mut actions = div().flex().gap(px(4.)).child(
|
||||
button(
|
||||
"background-choose",
|
||||
"Choose a picture…",
|
||||
Kind::Secondary,
|
||||
&t,
|
||||
)
|
||||
.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
|
||||
this.choose_background(cx);
|
||||
cx.notify();
|
||||
})),
|
||||
);
|
||||
if custom {
|
||||
actions = actions.child(
|
||||
button("background-reset", "Landscape", Kind::Ghost, &t).on_click(cx.listener(
|
||||
|this, _: &ClickEvent, _, cx| {
|
||||
this.settings.background = None;
|
||||
this.settings.save();
|
||||
cx.notify();
|
||||
},
|
||||
)),
|
||||
);
|
||||
}
|
||||
let said = if custom {
|
||||
tr("Your picture, behind Home, cropped to fill it.")
|
||||
} else {
|
||||
tr("Horizon's landscape. Pick a PNG, JPEG or WebP picture of your own.")
|
||||
};
|
||||
let detail = div().flex().flex_col().child(said.to_string()).children(
|
||||
self.background_error
|
||||
.clone()
|
||||
.map(|e| div().text_color(t.danger).child(e)),
|
||||
);
|
||||
index_row(
|
||||
0,
|
||||
tr("Home background"),
|
||||
Some(detail.into_any_element()),
|
||||
Some(actions.into_any_element()),
|
||||
&t,
|
||||
)
|
||||
}
|
||||
}
|
||||
+231
-5
@@ -1,12 +1,25 @@
|
||||
//! Custom Windows chrome. Other platforms keep their native window decorations; on macOS,
|
||||
//! `apply_appearance` repaints that chrome (the title bar) to match the chosen look.
|
||||
//! Window chrome: Windows and Linux client-side decorations are custom drawn; macOS and Linux
|
||||
//! server-side decorations use the platform's native chrome.
|
||||
use crate::theme::Theme;
|
||||
use gpui::{Div, TitlebarOptions, Window};
|
||||
use horizon_launcher::backend::Appearance;
|
||||
|
||||
/// Whether the launcher draws its own title bar (`render`) rather than the system.
|
||||
/// Whether Windows uses a transparent native title bar for the launcher's custom chrome.
|
||||
pub const DRAWN: bool = cfg!(target_os = "windows");
|
||||
|
||||
pub fn draws_brand(window: &Window) -> bool {
|
||||
#[cfg(target_os = "linux")]
|
||||
return matches!(
|
||||
window.window_decorations(),
|
||||
gpui::Decorations::Client { .. }
|
||||
);
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
let _ = window;
|
||||
DRAWN
|
||||
}
|
||||
}
|
||||
|
||||
pub fn options() -> TitlebarOptions {
|
||||
TitlebarOptions {
|
||||
title: Some("Horizon".into()),
|
||||
@@ -15,15 +28,228 @@ pub fn options() -> TitlebarOptions {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
#[cfg(all(not(target_os = "windows"), not(target_os = "linux")))]
|
||||
pub fn render(_theme: &Theme, _window: &Window) -> Option<Div> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Draw the launcher's Linux title bar when the platform uses client-side decorations.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn render(theme: &Theme, window: &Window) -> Option<Div> {
|
||||
use crate::{blocks, mark};
|
||||
use gpui::{div, prelude::*, px, Decorations, FontWeight, MouseButton};
|
||||
|
||||
if matches!(window.window_decorations(), Decorations::Server) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let controls = window.window_controls();
|
||||
let drag = div()
|
||||
.id("window-drag")
|
||||
.flex()
|
||||
.flex_1()
|
||||
.h_full()
|
||||
.items_center()
|
||||
.gap(px(8.))
|
||||
.px(px(12.))
|
||||
.on_mouse_down(MouseButton::Left, |_, window, _| window.start_window_move())
|
||||
.child(mark(16., theme))
|
||||
.child(blocks::pixel(13., FontWeight::MEDIUM).child("Horizon"));
|
||||
|
||||
let mut bar = div()
|
||||
.flex()
|
||||
.flex_none()
|
||||
.items_center()
|
||||
.h(px(32.))
|
||||
.bg(theme.side)
|
||||
.text_color(theme.muted)
|
||||
.border_b_1()
|
||||
.border_color(theme.outline)
|
||||
.child(drag);
|
||||
|
||||
if controls.minimize {
|
||||
let color = theme.ink_soft;
|
||||
let hover = theme.raised;
|
||||
bar = bar.child(
|
||||
div()
|
||||
.id("window-minimize")
|
||||
.flex()
|
||||
.flex_none()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.w(px(46.))
|
||||
.h_full()
|
||||
.cursor_pointer()
|
||||
.hover(move |style| style.bg(hover))
|
||||
.child(div().w(px(10.)).h(px(1.)).bg(color))
|
||||
.on_click(|_, window, _| window.minimize_window()),
|
||||
);
|
||||
}
|
||||
|
||||
if controls.maximize {
|
||||
let color = theme.ink_soft;
|
||||
let hover = theme.raised;
|
||||
let maximized = window.is_maximized();
|
||||
let square = || {
|
||||
div()
|
||||
.absolute()
|
||||
.size(px(10.))
|
||||
.border_1()
|
||||
.border_color(color)
|
||||
};
|
||||
let icon = div().relative().size(px(14.));
|
||||
let icon = if maximized {
|
||||
icon.child(
|
||||
div()
|
||||
.absolute()
|
||||
.left(px(4.))
|
||||
.top_0()
|
||||
.size(px(10.))
|
||||
.border_t_1()
|
||||
.border_r_1()
|
||||
.border_color(color),
|
||||
)
|
||||
.child(square().left(px(1.)).top(px(3.)))
|
||||
} else {
|
||||
icon.child(square().left(px(2.)).top(px(2.)))
|
||||
};
|
||||
bar = bar.child(
|
||||
div()
|
||||
.id("window-maximize")
|
||||
.flex()
|
||||
.flex_none()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.w(px(46.))
|
||||
.h_full()
|
||||
.cursor_pointer()
|
||||
.hover(move |style| style.bg(hover))
|
||||
.child(icon)
|
||||
.on_click(|_, window, _| window.zoom_window()),
|
||||
);
|
||||
}
|
||||
|
||||
let close_hover = theme.page;
|
||||
let close_bg = theme.danger;
|
||||
Some(
|
||||
bar.child(
|
||||
div()
|
||||
.id("window-close")
|
||||
.group("linux-window-close")
|
||||
.flex()
|
||||
.flex_none()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.w(px(46.))
|
||||
.h_full()
|
||||
.cursor_pointer()
|
||||
.hover(move |style| style.bg(close_bg).text_color(close_hover))
|
||||
.child(
|
||||
blocks::icon("close", 14., theme.ink_soft)
|
||||
.group_hover("linux-window-close", move |style| {
|
||||
style.text_color(close_hover)
|
||||
}),
|
||||
)
|
||||
.on_click(|_, window, _| window.remove_window()),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn resize_handles(window: &Window) -> Option<Div> {
|
||||
use gpui::{div, prelude::*, px, CursorStyle, Decorations, MouseButton, ResizeEdge};
|
||||
|
||||
if matches!(window.window_decorations(), Decorations::Server) || window.is_maximized() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let handle = |id, edge, cursor| {
|
||||
div()
|
||||
.id(id)
|
||||
.absolute()
|
||||
.cursor(cursor)
|
||||
.on_mouse_down(MouseButton::Left, move |_, window, _| {
|
||||
window.start_window_resize(edge)
|
||||
})
|
||||
};
|
||||
|
||||
Some(
|
||||
div()
|
||||
.absolute()
|
||||
.size_full()
|
||||
.child(
|
||||
handle("resize-left", ResizeEdge::Left, CursorStyle::ResizeLeft)
|
||||
.left_0()
|
||||
.top(px(8.))
|
||||
.bottom(px(8.))
|
||||
.w(px(5.)),
|
||||
)
|
||||
.child(
|
||||
handle("resize-right", ResizeEdge::Right, CursorStyle::ResizeRight)
|
||||
.right_0()
|
||||
.top(px(8.))
|
||||
.bottom(px(8.))
|
||||
.w(px(5.)),
|
||||
)
|
||||
.child(
|
||||
handle("resize-bottom", ResizeEdge::Bottom, CursorStyle::ResizeDown)
|
||||
.bottom_0()
|
||||
.left(px(8.))
|
||||
.right(px(8.))
|
||||
.h(px(5.)),
|
||||
)
|
||||
.child(
|
||||
handle(
|
||||
"resize-top-left",
|
||||
ResizeEdge::TopLeft,
|
||||
CursorStyle::ResizeUpLeftDownRight,
|
||||
)
|
||||
.left_0()
|
||||
.top_0()
|
||||
.size(px(8.)),
|
||||
)
|
||||
.child(
|
||||
handle(
|
||||
"resize-top-right",
|
||||
ResizeEdge::TopRight,
|
||||
CursorStyle::ResizeUpRightDownLeft,
|
||||
)
|
||||
.right_0()
|
||||
.top_0()
|
||||
.size(px(8.)),
|
||||
)
|
||||
.child(
|
||||
handle(
|
||||
"resize-bottom-left",
|
||||
ResizeEdge::BottomLeft,
|
||||
CursorStyle::ResizeUpRightDownLeft,
|
||||
)
|
||||
.left_0()
|
||||
.bottom_0()
|
||||
.size(px(8.)),
|
||||
)
|
||||
.child(
|
||||
handle(
|
||||
"resize-bottom-right",
|
||||
ResizeEdge::BottomRight,
|
||||
CursorStyle::ResizeUpLeftDownRight,
|
||||
)
|
||||
.right_0()
|
||||
.bottom_0()
|
||||
.size(px(8.)),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub fn resize_handles(_: &Window) -> Option<Div> {
|
||||
None
|
||||
}
|
||||
|
||||
/// macOS keeps the window's appearance on the system setting, so a launcher set to Dark still
|
||||
/// draws a light title bar on a light desktop. Pin the NSWindow's appearance to the choice
|
||||
/// instead (`theme::pinned_dark`: `System` clears the pin, handing the chrome back to the
|
||||
/// system). Elsewhere the chrome is ours (Windows) or the system's (Linux).
|
||||
/// system). Windows uses custom chrome; Linux draws it only when the compositor requests it.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn apply_appearance(window: &Window, choice: Appearance) {
|
||||
use objc2_app_kit::{
|
||||
|
||||
@@ -83,8 +83,8 @@ impl Launcher {
|
||||
};
|
||||
index_row(
|
||||
n,
|
||||
"While playing",
|
||||
Some(div().child(said).into_any_element()),
|
||||
tr("While playing"),
|
||||
Some(div().child(tr(said)).into_any_element()),
|
||||
Some(picker.into_any_element()),
|
||||
&t,
|
||||
)
|
||||
|
||||
@@ -32,9 +32,9 @@ pub(super) fn ago(when: std::time::SystemTime) -> String {
|
||||
let when: chrono::DateTime<chrono::Local> = when.into();
|
||||
let days = (chrono::Local::now().date_naive() - when.date_naive()).num_days();
|
||||
match days {
|
||||
..=0 => "today".into(),
|
||||
1 => "yesterday".into(),
|
||||
2..=13 => format!("{days} days ago"),
|
||||
..=0 => tr("today").into(),
|
||||
1 => tr("yesterday").into(),
|
||||
2..=13 => trf("{days} days ago", &[("days", &days.to_string())]),
|
||||
_ => when.format("%Y-%m-%d").to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user