Repository navigation
Expand file tree
/
Copy pathLanguageEngine.cs
More file actions
295 lines (253 loc) · 9.44 KB
/
Copy pathLanguageEngine.cs
File metadata and controls
295 lines (253 loc) · 9.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Text.Json;
using Jeffijoe.MessageFormat;
using UniGetUI.Core.Data;
using UniGetUI.Core.Logging;
using UniGetUI.Core.SettingsEngine;
namespace UniGetUI.Core.Language
{
public class LanguageEngine
{
private static readonly Dictionary<string, string> LocaleAliases = new(StringComparer.OrdinalIgnoreCase)
{
{ "es_MX", "es-MX" },
{ "tg", "tl" },
{ "ua", "uk" },
};
private Dictionary<string, string> MainLangDict = [];
public static string SelectedLocale = "??";
[NotNull]
public string? Locale { get; private set; }
private MessageFormatter? Formatter;
public LanguageEngine(string ForceLanguage = "")
{
string LangName = Settings.GetValue(Settings.K.PreferredLanguage);
if (LangName is "default" or "")
{
LangName = CultureInfo.CurrentUICulture.ToString().Replace("-", "_");
if (string.IsNullOrWhiteSpace(LangName))
{
LangName = "en";
}
}
LoadLanguage((ForceLanguage != "") ? ForceLanguage : LangName);
}
/// <summary>
/// Loads the specified language into the current instance
/// </summary>
/// <param name="lang">the language code</param>
public void LoadLanguage(string lang)
{
try
{
lang = (lang ?? string.Empty).Trim();
Locale = "en";
Locale = ResolveLocale(lang);
MainLangDict = LoadLanguageFile(Locale);
Formatter = CreateFormatter(Locale);
SelectedLocale = Locale;
Logger.Info("Loaded language locale: " + Locale);
}
catch (Exception ex)
{
Logger.Error($"Could not load language file \"{lang}\"");
Logger.Error(ex);
// Keep the app functional even if locale resolution fails.
Locale = "en";
MainLangDict = LoadLanguageFile(Locale);
Formatter = CreateFormatter(Locale);
SelectedLocale = Locale;
}
}
private static MessageFormatter CreateFormatter(string locale)
{
string formatterLocale = locale.Replace('_', '-');
try
{
CultureInfo.GetCultureInfo(formatterLocale);
}
catch (CultureNotFoundException)
{
Logger.Warn(
$"Culture \"{formatterLocale}\" is not available, formatting translated strings with the invariant culture"
);
formatterLocale = CultureInfo.InvariantCulture.Name;
}
return new() { Locale = formatterLocale };
}
private static string ResolveLocale(string lang)
{
foreach (string candidate in GetLocaleCandidates(lang))
{
if (LanguageData.LanguageReference.ContainsKey(candidate))
{
return candidate;
}
}
return "en";
}
private static IEnumerable<string> GetLocaleCandidates(string lang)
{
HashSet<string> candidates = new(StringComparer.OrdinalIgnoreCase);
void AddCandidate(string? candidate)
{
if (!string.IsNullOrWhiteSpace(candidate))
{
candidates.Add(candidate.Trim());
}
}
string requested = (lang ?? string.Empty).Trim();
string underscored = requested.Replace('-', '_');
string hyphenated = requested.Replace('_', '-');
AddCandidate(requested);
AddCandidate(underscored);
AddCandidate(hyphenated);
if (LocaleAliases.TryGetValue(requested, out string? requestedAlias))
{
AddCandidate(requestedAlias);
}
if (LocaleAliases.TryGetValue(underscored, out string? underscoredAlias))
{
AddCandidate(underscoredAlias);
}
string[] localeSegments = underscored.Split('_', StringSplitOptions.RemoveEmptyEntries);
if (localeSegments.Length > 0)
{
string baseLanguage = localeSegments[0];
AddCandidate(baseLanguage);
if (LocaleAliases.TryGetValue(baseLanguage, out string? baseLanguageAlias))
{
AddCandidate(baseLanguageAlias);
}
}
return candidates;
}
public Dictionary<string, string> LoadLanguageFile(string LangKey)
{
try
{
string BundledLangAsset = "Languages/lang_" + LangKey + ".json";
string BundledLangFileToLoad = BundledAssets.DiskPath(BundledLangAsset);
Dictionary<string, string> LangDict = [];
if (!BundledAssets.Exists(BundledLangAsset))
{
Logger.Error(
$"Tried to access a non-existing bundled language file! file={BundledLangFileToLoad}"
);
}
else
{
try
{
LangDict = ParseLanguageEntries(
BundledAssets.ReadAllText(BundledLangAsset),
BundledLangFileToLoad
);
}
catch (Exception ex)
{
Logger.Warn(
$"Something went wrong when parsing language file {BundledLangFileToLoad}"
);
Logger.Warn(ex);
}
}
return LangDict;
}
catch (Exception e)
{
Logger.Error($"LoadLanguageFile Failed for LangKey={LangKey}");
Logger.Error(e);
return [];
}
}
private static Dictionary<string, string> ParseLanguageEntries(
string fileContents,
string filePath
)
{
Dictionary<string, string> entries = [];
HashSet<string> duplicateKeys = [];
Utf8JsonReader reader = new(
Encoding.UTF8.GetBytes(fileContents),
new JsonReaderOptions
{
AllowTrailingCommas = true,
CommentHandling = JsonCommentHandling.Skip,
}
);
if (!reader.Read() || reader.TokenType != JsonTokenType.StartObject)
{
throw new JsonException($"Language file {filePath} does not contain a JSON object");
}
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndObject)
{
break;
}
if (reader.TokenType != JsonTokenType.PropertyName)
{
throw new JsonException(
$"Unexpected token {reader.TokenType} in language file {filePath}"
);
}
string key = reader.GetString() ?? throw new JsonException("Translation key is null");
if (!reader.Read())
{
throw new JsonException($"Missing translation value for key {key}");
}
using JsonDocument value = JsonDocument.ParseValue(ref reader);
string parsedValue = value.RootElement.ValueKind == JsonValueKind.Null
? ""
: value.RootElement.ToString();
if (!entries.TryAdd(key, parsedValue))
{
duplicateKeys.Add(key);
entries[key] = parsedValue;
}
}
if (duplicateKeys.Count > 0)
{
Logger.Warn(
$"Language file {filePath} contains duplicate keys. Keeping the last value for: {string.Join(", ", duplicateKeys)}"
);
}
return entries;
}
public string Translate(string key)
{
if (key == "WingetUI")
{
if (
MainLangDict.TryGetValue("formerly WingetUI", out var formerly)
&& formerly != ""
)
{
return "UniGetUI (" + formerly + ")";
}
return "UniGetUI (formerly WingetUI)";
}
if (key == "Formerly known as WingetUI")
{
return MainLangDict.GetValueOrDefault(key, key);
}
if (key is null or "")
{
return "";
}
if (MainLangDict.TryGetValue(key, out var value) && value != "")
{
return value.Replace("WingetUI", "UniGetUI");
}
return key.Replace("WingetUI", "UniGetUI");
}
public string Translate(string key, Dictionary<string, object?> dict)
{
Formatter ??= CreateFormatter(Locale ?? "en");
return Formatter.FormatMessage(Translate(key), dict);
}
}
}