using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using UnityEngine;
namespace GrassCutter
{
///
/// Interface languages. Every player-facing string is written in English in the code and looked up here by that
/// English text: Loc.T("PLAY"), or Loc.F("{0} sectors clean", n) for text with values in it. A missing
/// translation shows the English. Tables are Resources/Loc/<code>.txt, one "english TAB translation" per line
/// (Tools/loc/extract.py lists every key the code uses). Text kept in data tables (tool names, perk descriptions…)
/// is marked Loc.N("…") where it is written and translated with Loc.T where it is shown.
///
public static class Loc
{
public class Lang
{
public string code, steam, native;
/// Numbers are written the way this culture writes them.
public string culture;
/// Chinese, Japanese, Korean: drawn with the Noto CJK cut, not LilitaOne/Nunito.
public string cjkFont;
/// LilitaOne has no Cyrillic, nor Polish or Turkish letters: these draw headings in Nunito Black.
public bool latinDisplayOnly;
}
/// The twelve ticked as "Interface" on the Steam page, English first. steam is what Steam's
/// GetCurrentGameLanguage() answers.
public static readonly Lang[] All =
{
new Lang { code = "en", steam = "english", native = "English", culture = "en-US" },
new Lang { code = "fr", steam = "french", native = "Français", culture = "fr-FR" },
new Lang { code = "it", steam = "italian", native = "Italiano", culture = "it-IT" },
new Lang { code = "de", steam = "german", native = "Deutsch", culture = "de-DE" },
new Lang { code = "es", steam = "spanish", native = "Español", culture = "es-ES" },
new Lang { code = "pt-BR", steam = "brazilian", native = "Português (Brasil)", culture = "pt-BR" },
new Lang { code = "pl", steam = "polish", native = "Polski", culture = "pl-PL", latinDisplayOnly = true },
new Lang { code = "tr", steam = "turkish", native = "Türkçe", culture = "tr-TR", latinDisplayOnly = true },
new Lang { code = "ru", steam = "russian", native = "Русский", culture = "ru-RU", latinDisplayOnly = true },
new Lang { code = "zh-Hans", steam = "schinese", native = "简体中文", culture = "zh-CN", cjkFont = "GcCjkSC" },
new Lang { code = "ja", steam = "japanese", native = "日本語", culture = "ja-JP", cjkFont = "GcCjkJP" },
new Lang { code = "ko", steam = "koreana", native = "한국어", culture = "ko-KR", cjkFont = "GcCjkKR" },
};
public static Lang Current { get; private set; } = All[0];
public static string Code => Current.code;
public static bool IsEnglish => Current == All[0];
/// For numbers on screen (thousands, decimals). Never for saves or the network: those stay invariant.
public static CultureInfo Culture { get; private set; } = CultureInfo.GetCultureInfo("en-US");
/// After the language changes: screens rebuild themselves.
public static event Action Changed;
static Dictionary _table;
static bool _ready;
/// The English text in the current language, or the English if it has no translation.
public static string T(string en)
{
if (!_ready) Init();
if (string.IsNullOrEmpty(en) || _table == null) return en;
return _table.TryGetValue(en, out var s) && !string.IsNullOrEmpty(s) ? s : en;
}
/// T, then string.Format with this language's culture: "{0:N0} sectors" etc.
public static string F(string en, params object[] args)
{
var fmt = T(en);
try { return string.Format(Culture, fmt, args); }
catch (FormatException)
{
// a broken translation must never take the UI down: fall back to the English pattern
try { return string.Format(Culture, en, args); } catch (FormatException) { return en; }
}
}
/// Marks English kept in a data table for the extractor; the table hands it to T where it is shown.
public static string N(string en) => en;
/// A number the way the language writes it ("1,234.5", "1 234,5", "1.234,5").
public static string Num(double v, string format = "N0") => v.ToString(format, Culture);
public static string Num(float v, string format) => v.ToString(format, Culture);
// ───────────────────────── text sent over the network ─────────────────────────
const char PackMark = '\u0001', ArgMark = '\u0002', KeyMark = '\u0003';
/// Server text (announcements) goes out as the English pattern and its values, and every client reads it
/// in its own language. Arguments that are themselves English keys go through .
public static string Pack(string en, params string[] args)
{
var sb = new StringBuilder();
sb.Append(PackMark).Append(en);
foreach (var a in args) sb.Append(ArgMark).Append(a ?? "");
return sb.ToString();
}
/// An argument of that the reader translates too (a tool or machine name).
public static string Key(string en) => KeyMark + en;
/// The reader's side of ; plain text goes through T.
public static string Unpack(string text)
{
if (string.IsNullOrEmpty(text)) return text;
if (text[0] != PackMark) return text[0] == KeyMark ? Arg(text) : T(text);
var parts = text.Substring(1).Split(ArgMark);
var args = new object[parts.Length - 1];
for (int i = 1; i < parts.Length; i++) args[i - 1] = Arg(parts[i]);
return F(parts[0], args);
}
/// A translated name with something after it, like "Sickle" + " III".
public static string Key(string en, string suffix) => KeyMark + en + SuffixMark + suffix;
const char SuffixMark = '\u0004';
static string Arg(string a)
{
if (a.Length == 0 || a[0] != KeyMark) return a;
a = a.Substring(1);
int s = a.IndexOf(SuffixMark);
return s < 0 ? T(a) : T(a.Substring(0, s)) + " " + a.Substring(s + 1);
}
// ───────────────────────── choosing ─────────────────────────
const string Pref = "s_lang";
/// Saved choice, else Steam's language for this game, else the system's, else English.
public static void Init()
{
if (_ready) return;
_ready = true;
string code = CommandLine.Get("-demolang") ?? CommandLine.Get("-lang");
if (Find(code) == null) code = PlayerPrefs.GetString(Pref, "");
if (Find(code) == null) code = FromSteam();
if (Find(code) == null) code = FromSystem();
Load(Find(code) ?? All[0]);
}
public static Lang Find(string code)
{
if (string.IsNullOrEmpty(code)) return null;
foreach (var l in All) if (string.Equals(l.code, code, StringComparison.OrdinalIgnoreCase) || l.steam == code) return l;
return null;
}
/// The settings screen's choice: remembered, and the screens rebuild. The language shots switch without remembering.
public static void Set(string code, bool remember = true)
{
var l = Find(code) ?? All[0];
if (remember)
{
PlayerPrefs.SetString(Pref, l.code);
PlayerPrefs.Save();
}
_ready = true;
if (l == Current && _table != null) return;
Load(l);
Changed?.Invoke();
}
static string FromSteam()
{
try { return SteamManager.Initialized ? Steamworks.SteamApps.GetCurrentGameLanguage() : null; }
catch (Exception) { return null; }
}
static string FromSystem()
{
switch (Application.systemLanguage)
{
case SystemLanguage.French: return "fr";
case SystemLanguage.Italian: return "it";
case SystemLanguage.German: return "de";
case SystemLanguage.Spanish: return "es";
case SystemLanguage.Portuguese: return "pt-BR";
case SystemLanguage.Polish: return "pl";
case SystemLanguage.Turkish: return "tr";
case SystemLanguage.Russian: case SystemLanguage.Ukrainian: case SystemLanguage.Belarusian: return "ru";
case SystemLanguage.Chinese: case SystemLanguage.ChineseSimplified: return "zh-Hans";
case SystemLanguage.Japanese: return "ja";
case SystemLanguage.Korean: return "ko";
default: return "en";
}
}
static void Load(Lang l)
{
Current = l;
try { Culture = CultureInfo.GetCultureInfo(l.culture); }
catch (CultureNotFoundException) { Culture = CultureInfo.InvariantCulture; }
_table = null;
if (l == All[0]) return;
var asset = Resources.Load("Loc/" + l.code);
if (!asset) { Debug.LogWarning($"[Loc] no table for {l.code}"); return; }
_table = Parse(asset.text);
Resources.UnloadAsset(asset);
Debug.Log($"[Loc] {l.code}: {_table.Count} strings");
}
/// "english TAB translation" per line; # starts a comment; \n \t \\ are escapes on both sides.
public static Dictionary Parse(string text)
{
var d = new Dictionary(4096);
foreach (var raw in text.Split('\n'))
{
var line = raw.TrimEnd('\r');
if (line.Length == 0 || line[0] == '#') continue;
int tab = line.IndexOf('\t');
if (tab <= 0) continue;
var key = Unescape(line.Substring(0, tab));
var val = Unescape(line.Substring(tab + 1));
d[key] = val;
}
return d;
}
static string Unescape(string s)
{
if (s.IndexOf('\\') < 0) return s;
var sb = new StringBuilder(s.Length);
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (c == '\\' && i + 1 < s.Length)
{
char n = s[++i];
sb.Append(n == 'n' ? '\n' : n == 't' ? '\t' : n);
}
else sb.Append(c);
}
return sb.ToString();
}
// ───────────────────────── fonts ─────────────────────────
/// The heading and body fonts for the current language.
public static void Fonts(AssetBank bank, out Font display, out Font body)
{
var lilita = Named(bank, "LilitaOne");
var nunito = Named(bank, "Nunito-Black") ?? Named(bank, "Nunito");
display = lilita;
body = nunito;
if (Current.cjkFont != null)
{
var cjk = Named(bank, Current.cjkFont);
if (cjk) { display = cjk; body = cjk; }
else Debug.LogWarning($"[Loc] font {Current.cjkFont} missing: {Current.code} will show boxes");
}
else if (Current.latinDisplayOnly && nunito) display = nunito;
if (!display) display = body;
}
static Font Named(AssetBank bank, string name)
{
if (bank == null) return null;
foreach (var f in bank.fonts) if (f && f.name.Contains(name)) return f;
return null;
}
}
}