-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoc.cs
More file actions
382 lines (328 loc) · 12.6 KB
/
Loc.cs
File metadata and controls
382 lines (328 loc) · 12.6 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using MelonLoader;
using UnityEngine;
namespace MelatoninAccess
{
/// <summary>
/// Centralized localization for all mod-generated screen reader strings.
/// Language follows the in-game language index from SaveManager.GetLang().
/// </summary>
public static class Loc
{
private const int LanguageCount = 10;
private const int EnglishLang = 0;
private const int LocalizationSchemaVersion = 1;
private const string LocalizationFolderName = "localization";
private const string HandlerName = "Loc";
private static readonly string[] LanguageCodes =
{
"en",
"zh-Hans",
"zh-Hant",
"ja",
"ko",
"vi",
"fr",
"de",
"es",
"pt"
};
private static readonly Dictionary<string, string>[] _translations = new Dictionary<string, string>[LanguageCount];
private static bool _initialized;
private static int _currentLang = EnglishLang;
[Serializable]
private sealed class LocalizationFile
{
public int schemaVersion = LocalizationSchemaVersion;
public string language = "";
public LocalizationEntry[] entries = new LocalizationEntry[0];
}
[Serializable]
private sealed class LocalizationEntry
{
public string key = "";
public string value = "";
}
/// <summary>
/// Initializes translation dictionaries.
/// </summary>
public static void Initialize()
{
if (_initialized) return;
for (int i = 0; i < LanguageCount; i++)
{
_translations[i] = new Dictionary<string, string>();
}
LoadFromJsonFiles();
RefreshLanguage();
_initialized = true;
}
/// <summary>
/// Refreshes the current language from game settings.
/// </summary>
public static void RefreshLanguage()
{
_currentLang = NormalizeLanguageIndex(GetGameLanguageIndex());
}
/// <summary>
/// Gets a localized string by key.
/// </summary>
public static string Get(string key)
{
if (!_initialized) Initialize();
int latestLang = NormalizeLanguageIndex(GetGameLanguageIndex());
if (latestLang != _currentLang)
{
_currentLang = latestLang;
}
if (_translations[_currentLang].TryGetValue(key, out string value))
{
return value;
}
if (_translations[EnglishLang].TryGetValue(key, out string english))
{
return english;
}
return key;
}
/// <summary>
/// Gets a localized string by key and formats it with placeholders.
/// </summary>
public static string Get(string key, params object[] args)
{
string template = Get(key);
try
{
return string.Format(template, args);
}
catch
{
return template;
}
}
/// <summary>
/// Gets a localized level/dream name from the internal dream key.
/// </summary>
public static string GetDreamName(string rawName)
{
if (string.IsNullOrWhiteSpace(rawName)) return Get("unknown_level");
string normalized = rawName.Trim().ToLowerInvariant();
string key = "dream_name_" + normalized;
string localized = Get(key);
if (localized != key) return localized;
if (normalized.Length == 1) return normalized.ToUpperInvariant();
return char.ToUpperInvariant(normalized[0]) + normalized.Substring(1);
}
private static void LoadFromJsonFiles()
{
string localizationDir = ResolveLocalizationDirectory();
if (string.IsNullOrWhiteSpace(localizationDir))
{
MelonLogger.Warning($"[{HandlerName}] Localization directory not found.");
return;
}
int totalLoaded = 0;
var fallbackLanguages = new List<string>();
for (int langIndex = 0; langIndex < LanguageCodes.Length; langIndex++)
{
string languageCode = LanguageCodes[langIndex];
string filePath = Path.Combine(localizationDir, $"loc.{languageCode}.json");
int loadedForLanguage = LoadLanguageFile(langIndex, languageCode, filePath, out bool usedFallbackParser);
totalLoaded += loadedForLanguage;
if (usedFallbackParser)
{
fallbackLanguages.Add(languageCode);
}
}
MelonLogger.Msg($"[{HandlerName}] Loaded {totalLoaded} localization entries from JSON.");
if (fallbackLanguages.Count > 0)
{
MelonLogger.Msg($"[{HandlerName}] Localization JSON fallback parser active for {fallbackLanguages.Count} language file(s).");
DebugLogger.Log(
LogCategory.Handler,
HandlerName,
$"Fallback parser languages: {string.Join(", ", fallbackLanguages)}");
}
}
private static int LoadLanguageFile(int langIndex, string languageCode, string filePath, out bool usedFallbackParser)
{
usedFallbackParser = false;
if (!File.Exists(filePath))
{
MelonLogger.Warning($"[{HandlerName}] Missing localization file for {languageCode}: {filePath}");
return 0;
}
try
{
string json = File.ReadAllText(filePath);
if (!string.IsNullOrEmpty(json) && json[0] == '\uFEFF')
{
json = json.Substring(1);
}
LocalizationFile file = JsonUtility.FromJson<LocalizationFile>(json);
if (file == null || file.entries == null || file.entries.Length == 0)
{
if (!TryParseLocalizationFallback(json, out LocalizationFile fallbackFile, out string fallbackError))
{
if (file == null)
{
MelonLogger.Warning(
$"[{HandlerName}] Failed to parse localization JSON: {filePath}. Fallback parser error: {fallbackError}");
}
else
{
MelonLogger.Warning(
$"[{HandlerName}] No localization entries found in {filePath}. Fallback parser error: {fallbackError}");
}
return 0;
}
file = fallbackFile;
usedFallbackParser = true;
}
if (file.schemaVersion != LocalizationSchemaVersion)
{
MelonLogger.Warning(
$"[{HandlerName}] Unexpected schema version in {filePath}: {file.schemaVersion} (expected {LocalizationSchemaVersion}).");
}
int loaded = 0;
Dictionary<string, string> dictionary = _translations[langIndex];
foreach (LocalizationEntry entry in file.entries)
{
if (entry == null || string.IsNullOrWhiteSpace(entry.key))
{
continue;
}
dictionary[entry.key] = entry.value ?? "";
loaded++;
}
return loaded;
}
catch (Exception ex)
{
MelonLogger.Warning($"[{HandlerName}] Failed to load localization file {filePath}: {ex.Message}");
return 0;
}
}
private static bool TryParseLocalizationFallback(string json, out LocalizationFile file, out string error)
{
file = null;
error = "";
if (string.IsNullOrWhiteSpace(json))
{
error = "Localization JSON is empty.";
return false;
}
MatchCollection matches = Regex.Matches(
json,
"\\{\\s*\"key\"\\s*:\\s*\"(?<key>(?:\\\\.|[^\"\\\\])*)\"\\s*,\\s*\"value\"\\s*:\\s*\"(?<value>(?:\\\\.|[^\"\\\\])*)\"\\s*\\}",
RegexOptions.Singleline);
if (matches.Count == 0)
{
error = "No localization key/value entries were found.";
return false;
}
var entries = new LocalizationEntry[matches.Count];
for (int i = 0; i < matches.Count; i++)
{
string key = DecodeJsonString(matches[i].Groups["key"].Value);
string value = DecodeJsonString(matches[i].Groups["value"].Value);
entries[i] = new LocalizationEntry
{
key = key,
value = value
};
}
file = new LocalizationFile
{
schemaVersion = LocalizationSchemaVersion,
language = "",
entries = entries
};
return true;
}
private static string DecodeJsonString(string text)
{
if (string.IsNullOrEmpty(text))
{
return "";
}
try
{
return Regex.Unescape(text);
}
catch
{
return text;
}
}
private static string ResolveLocalizationDirectory()
{
string assemblyDir = Path.GetDirectoryName(typeof(Loc).Assembly.Location) ?? "";
string assemblyParent = "";
if (!string.IsNullOrWhiteSpace(assemblyDir))
{
DirectoryInfo parent = Directory.GetParent(assemblyDir);
assemblyParent = parent != null ? parent.FullName : "";
}
string gameRoot = ResolveGameRootDirectory();
string cwd = Directory.GetCurrentDirectory();
string appBaseDir = AppDomain.CurrentDomain.BaseDirectory ?? "";
string englishFileName = $"loc.{LanguageCodes[EnglishLang]}.json";
string[] candidates =
{
Path.Combine(assemblyDir, LocalizationFolderName),
Path.Combine(assemblyParent, LocalizationFolderName),
Path.Combine(gameRoot, "Mods", LocalizationFolderName),
Path.Combine(gameRoot, LocalizationFolderName),
Path.Combine(appBaseDir, "Mods", LocalizationFolderName),
Path.Combine(appBaseDir, LocalizationFolderName),
Path.Combine(cwd, "Mods", LocalizationFolderName),
Path.Combine(cwd, LocalizationFolderName)
};
foreach (string candidate in candidates)
{
if (string.IsNullOrWhiteSpace(candidate)) continue;
if (!Directory.Exists(candidate)) continue;
string englishPath = Path.Combine(candidate, englishFileName);
if (File.Exists(englishPath))
{
return candidate;
}
}
return "";
}
private static string ResolveGameRootDirectory()
{
string dataPath = Application.dataPath ?? "";
if (string.IsNullOrWhiteSpace(dataPath))
{
return "";
}
string normalizedDataPath = dataPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
if (!normalizedDataPath.EndsWith("_Data", StringComparison.OrdinalIgnoreCase))
{
return "";
}
DirectoryInfo parent = Directory.GetParent(normalizedDataPath);
return parent != null ? parent.FullName : "";
}
private static int GetGameLanguageIndex()
{
try
{
return SaveManager.GetLang();
}
catch
{
return EnglishLang;
}
}
private static int NormalizeLanguageIndex(int lang)
{
return (lang >= 0 && lang < LanguageCount) ? lang : EnglishLang;
}
}
}