Survivalcraft API 1.8.2.3 v1.8.2.3
Survivalcraft 2.4
载入中...
搜索中...
未找到
LanguageControl.cs
浏览该文件的文档.
1using System.Globalization;
2using System.Text.Json;
3using System.Text.Json.Nodes;
4using Engine;
6
7namespace Game {
8 public static class LanguageControl {
9 public static JsonNode jsonNode;
10 public static JsonNode englishJsonNode;
11 public static string Ok;
12 public static string Cancel;
13 public static string None;
14 public static string Nothing;
15 public static string Error;
16 public static string On;
17 public static string Off;
18 public static string Disable;
19 public static string Enable;
20 public static string Warning;
21 public static string Back;
22 public static string Allowed;
23 public static string NAllowed;
24 public static string Unknown;
25 public static string Yes;
26 public static string No;
27 public static string Unavailable;
28 public static string Exists;
29 public static string Success;
30 public static string Delete;
34#if BROWSER
35 public static HashSet<string> LanguageTypes = [];
36#else
37 public static Dictionary<string, CultureInfo> LanguageTypes = [];
38
39 public static CultureInfo CurrentLanguageCultureInfo { get; set; } = new("en-US", false);
40#endif
41
42 public static string CurrentLanguageName { get; set; } = "en-US";
43
44 public static void Initialize(string languageType) {
45#if BROWSER
46 if (!LanguageTypes.Contains(languageType)) {
47#else
48 if (!LanguageTypes.TryGetValue(languageType, out CultureInfo cultureInfo)) {
49#endif
50 throw new Exception($"Language {languageType} not supported.");
51 }
52 Ok = null;
53 Cancel = null;
54 None = null;
55 Nothing = null;
56 Error = null;
57 On = null;
58 Off = null;
59 Disable = null;
60 Enable = null;
61 Warning = null;
62 Back = null;
63 Allowed = null;
64 NAllowed = null;
65 Unknown = null;
66 Yes = null;
67 No = null;
68 Unavailable = null;
69 Exists = null;
70 Success = null;
71 Delete = null;
72 jsonNode = null;
73 ModsManager.SetConfig("Language", languageType);
74 CurrentLanguageName = languageType;
75#if BROWSER
77#else
78 CurrentLanguageCultureInfo = cultureInfo;
79#endif
80 }
81
82 public static void loadJson(Stream stream) {
83 string txt = new StreamReader(stream).ReadToEnd();
84 if (txt.Length > 0) { //加载原版语言包
85 JsonNode newJsonNode;
86 try {
87 newJsonNode = JsonNode.Parse(txt, null, JsonDocumentReader.DefaultJsonOptions);
88 }
89 catch (Exception e) {
90 Log.Error($"Invalid json file, reason: {e}");
91 return;
92 }
93 if (jsonNode == null) {
94 jsonNode = newJsonNode;
95 }
96 else {
97 MergeJsonNode(jsonNode, newJsonNode);
98 }
99 }
100 }
101
102 public static void LoadEnglishJson(Stream stream) {
103 string txt = new StreamReader(stream).ReadToEnd();
104 if (txt.Length > 0) {
105 JsonNode newJsonNode;
106 try {
107 newJsonNode = JsonNode.Parse(txt, null, JsonDocumentReader.DefaultJsonOptions);
108 }
109 catch (Exception e) {
110 Log.Error($"Invalid json file, reason: {e}");
111 return;
112 }
113 if (englishJsonNode == null) {
114 englishJsonNode = newJsonNode;
115 }
116 else {
117 MergeJsonNode(englishJsonNode, newJsonNode);
118 }
119 }
120 }
121
122 public static void SetUsual(bool force = false) {
123 if (force) {
124 Ok = Get("Usual", "ok");
125 Cancel = Get("Usual", "cancel");
126 None = Get("Usual", "none");
127 Nothing = Get("Usual", "nothing");
128 Error = Get("Usual", "error");
129 On = Get("Usual", "on");
130 Off = Get("Usual", "off");
131 Disable = Get("Usual", "disable");
132 Enable = Get("Usual", "enable");
133 Warning = Get("Usual", "warning");
134 Back = Get("Usual", "back");
135 Allowed = Get("Usual", "allowed");
136 NAllowed = Get("Usual", "not allowed");
137 Unknown = Get("Usual", "unknown");
138 Yes = Get("Usual", "yes");
139 No = Get("Usual", "no");
140 Unavailable = Get("Usual", "Unavailable");
141 Exists = Get("Usual", "exist");
142 Success = Get("Usual", "success");
143 Delete = Get("Usual", "delete");
144 }
145 else {
146 Ok ??= Get("Usual", "ok");
147 Cancel ??= Get("Usual", "cancel");
148 None ??= Get("Usual", "none");
149 Nothing ??= Get("Usual", "nothing");
150 Error ??= Get("Usual", "error");
151 On ??= Get("Usual", "on");
152 Off ??= Get("Usual", "off");
153 Disable ??= Get("Usual", "disable");
154 Enable ??= Get("Usual", "enable");
155 Warning ??= Get("Usual", "warning");
156 Back ??= Get("Usual", "back");
157 Allowed ??= Get("Usual", "allowed");
158 NAllowed ??= Get("Usual", "not allowed");
159 Unknown ??= Get("Usual", "unknown");
160 Yes ??= Get("Usual", "yes");
161 No ??= Get("Usual", "no");
162 Unavailable ??= Get("Usual", "Unavailable");
163 Exists ??= Get("Usual", "exist");
164 Success ??= Get("Usual", "success");
165 Delete ??= Get("Usual", "delete");
166 }
167 }
168
169 public static void MergeJsonNode(JsonNode oldNode, JsonNode newNode) {
170 if (oldNode == null
171 || newNode == null) {
172 return;
173 }
174 switch (newNode.GetValueKind()) {
175 case JsonValueKind.Object: {
176 if (oldNode.GetValueKind() == JsonValueKind.Object) {
177 JsonObject oldObject = oldNode.AsObject();
178 JsonObject newObject = newNode.AsObject();
179 foreach (KeyValuePair<string, JsonNode> newChild in newObject) {
180 if (newChild.Value == null) {
181 continue;
182 }
183 if (oldObject.TryGetPropertyValue(newChild.Key, out JsonNode oldChild)) {
184 MergeJsonNode(oldChild, newChild.Value);
185 }
186 else {
187 oldObject.Add(newChild.Key, newChild.Value.DeepClone());
188 }
189 }
190 }
191 else {
192 ReplaceJsonNode(oldNode, newNode.DeepClone());
193 }
194 break;
195 }
196 case JsonValueKind.Array: {
197 if (oldNode.GetValueKind() == JsonValueKind.Array) {
198 JsonArray oldArray = oldNode.AsArray();
199 JsonArray newArray = newNode.AsArray();
200 if (newArray.Count > oldArray.Count) {
201 for (int i = 0; i < oldArray.Count; i++) {
202 MergeJsonNode(oldArray[i], newArray[i]);
203 }
204 for (int i = oldArray.Count; i < newArray.Count; i++) {
205 oldArray.Add(newArray[i]?.DeepClone());
206 }
207 }
208 else {
209 for (int i = 0; i < newArray.Count; i++) {
210 MergeJsonNode(oldArray[i], newArray[i]);
211 }
212 }
213 }
214 else {
215 ReplaceJsonNode(oldNode, newNode.DeepClone());
216 }
217 break;
218 }
219 case JsonValueKind.String:
220 case JsonValueKind.Number:
221 case JsonValueKind.True:
222 case JsonValueKind.False: {
223 ReplaceJsonNode(oldNode, newNode.DeepClone());
224 break;
225 }
226 }
227 }
228
229 public static void ReplaceJsonNode(JsonNode oldNode, JsonNode newNode) {
230 switch (oldNode.Parent) {
231 case JsonObject parentObject:
232 parentObject[oldNode.GetPropertyName()] = newNode;
233 return;
234 case JsonArray parentArray: parentArray[oldNode.GetElementIndex()] = newNode; break;
235 }
236 }
237
239 public static string LName() => ModsManager.Configs["Language"];
240
247 public static string Get(string className, int key) =>
248 //获得键值
249 Get(className, key.ToString());
250
251 public static string GetWorldPalette(int index) => Get("WorldPalette", "Colors", index.ToString());
252
253 public static string Get(params string[] key) => Get(out bool _, key);
254
255 public static string Get(out bool r, params string[] keys) { //获得键值
256 if (jsonNode == null) {
257 if (englishJsonNode == null) {
258 r = false;
259 return string.Join(':', keys);
260 }
262 }
263 string result = Get(out r, jsonNode, keys);
264 if (r) {
265 return result;
266 }
267 if (CurrentLanguageName != "en-US") {
268 result = Get(out r, englishJsonNode, keys);
269 }
270 return result;
271 }
272
273 public static string Get(out bool r, JsonNode node, params string[] keys) {
274 r = false;
275 JsonNode nowNode = node;
276 bool flag = false;
277 foreach (string key in keys) {
278 if (string.IsNullOrEmpty(key)
279 || nowNode == null) {
280 break;
281 }
282 if (nowNode.GetValueKind() == JsonValueKind.Object) {
283 nowNode = nowNode[key];
284 if (nowNode == null) {
285 break;
286 }
287 flag = true;
288 }
289 else if (nowNode.GetValueKind() == JsonValueKind.Array
290 && int.TryParse(key, out int num)
291 && num >= 0) {
292 JsonArray array = nowNode.AsArray();
293 if (num < array.Count) {
294 nowNode = array[num];
295 flag = true;
296 }
297 else {
298 break;
299 }
300 }
301 else {
302 break;
303 }
304 }
305 if (nowNode != null) {
306 switch (nowNode.GetValueKind()) {
307 case JsonValueKind.String:
308 r = true;
309 return nowNode.GetValue<string>();
310 case JsonValueKind.Number:
311 r = true;
312 return nowNode.GetValue<decimal>().ToString(CultureInfo.InvariantCulture);
313 }
314 }
315 return flag ? keys.Last() : string.Join(':', keys);
316 }
317
318 public static bool TryGet(out string result, params string[] keys) {
319 result = Get(out bool r, keys);
320 return r;
321 }
322
323 public static bool TryGet(out string result, JsonNode node, params string[] keys) {
324 result = Get(out bool r, node, keys);
325 return r;
326 }
327
328 public static string GetWithoutFallback(out bool r, params string[] keys) => Get(out r, jsonNode, keys);
329
330 public static string GetBlock(string blockName, string prop) {
331 TryGetBlock(blockName, prop, out string result);
332 return result;
333 }
334
335 public static bool TryGetBlock(string blockName, string prop, out string result) {
336 if (blockName.Length == 0) {
337 result = string.Empty;
338 return false;
339 }
340 string[] nm = blockName.Split(':'); //这里不要改成集合表达式,在不同的编译器上会导致bug或者编译失败
341 result = Get(out bool r, "Blocks", nm.Length < 2 ? $"{blockName}:0" : blockName, prop);
342 if (!r) {
343 result = Get(out r, "Blocks", $"{nm[0]}:0", prop);
344 }
345 return r;
346 }
347
348 public static string GetContentWidgets(string name, string prop) => Get("ContentWidgets", name, prop);
349
350 public static string GetContentWidgets(string name, int pos) => Get("ContentWidgets", name, pos.ToString());
351
352 public static string GetDatabase(string name, string prop) => Get("Database", name, prop);
353
354 public static string GetFireworks(string name, string prop) => Get("FireworksBlock", name, prop);
355
356 public static void ChangeLanguage(string languageType) {
357 Initialize(languageType);
359 if (languageType == "en-US"
360 && englishJsonNode != null) {
362 SetUsual(true);
363 }
364 else {
365 foreach (ModEntity c in ModsManager.ModList) {
366 c.LoadLauguage();
367 }
368 SetUsual(true);
369 }
370#if !ANDROID
371 string title = $"{(SettingsManager.SafeMode ? $"[{LanguageControl.Get("Usual", "safeMode")}]" : "")}{Get("Usual", "gameName")} {ModsManager.ShortGameVersion} - API {ModsManager.APIVersionString}";
372#if DEBUG
373 title = $"[{Get("Usual", "debug")}]{title}";
374#endif
375 Window.TitlePrefix = title;
376#endif
377 Dictionary<string, object> objs = [];
378 foreach (KeyValuePair<string, Screen> c in ScreensManager.m_screens) {
379 Type type = c.Value.GetType();
380#pragma warning disable IL2072
381 object obj = Activator.CreateInstance(type);
382#pragma warning restore IL2072
383 objs.Add(c.Key, obj);
384 }
385 foreach (KeyValuePair<string, object> c in objs) {
386 ScreensManager.m_screens[c.Key] = c.Value as Screen;
387 }
392 ScreensManager.SwitchScreen("MainMenu");
393 }
394
395 public static Dictionary<string, string> CachedLanguageFullNames = [];
396
397 public static void CreateLanguageSelectionDialog(Widget parent) {
398 if (CachedLanguageFullNames.Count == 0) {
399#if BROWSER
400 foreach (string name in LanguageTypes) {
402 name,
403 name switch {
404 "en-US" => "English (United States)",
405 "zh-CN" => "中文 (中国)",
406 "ro-RO" => "română (România)",
407 "ru-RU" => "русский (Россия)",
408 "es-419" => "español (Latinoamérica)",
409 "vi-VN" => "Tiếng Việt (Việt Nam)",
410 "zh-CN-old" => "[旧] 中文 (中国)",
411 _ => $"{name}"
412 }
413 );
414 }
415#else
416 CultureInfo oldUICulture = Thread.CurrentThread.CurrentUICulture;
417 try {
418 Thread.CurrentThread.CurrentUICulture = CurrentLanguageCultureInfo;
419 foreach ((string name, CultureInfo cultureInfo) in LanguageTypes) {
420 string nativeName = cultureInfo.NativeName;
421 string displayName = cultureInfo.DisplayName;
422 if (name == "zh-CN-old") {
423 CachedLanguageFullNames.Add(name, $"[旧] {nativeName} - {displayName}");
424 }
425 else {
426 CachedLanguageFullNames.Add(name, nativeName == displayName ? nativeName : $"{nativeName} - {displayName}");
427 }
428 }
429 }
430 finally {
431 Thread.CurrentThread.CurrentUICulture = oldUICulture;
432 }
433#endif
434 }
435 IOrderedEnumerable<KeyValuePair<string, string>> sorted = CachedLanguageFullNames.OrderBy(item => item.Key switch {
436 "en-US" => 0,
437 "zh-CN" => 1,
438 "zh-CN-old" => 1000,
439 _ => 2
440 }
441 );
443 null,
445 null,
446 sorted,
447 70f,
448 item => item is KeyValuePair<string, string> pair
449 ? new LabelWidget {
450 Text = pair.Value,
451 Color = pair.Key == CurrentLanguageName ? new Color(50, 150, 35) : Color.White,
452 Margin = new Vector2(20f, 0f),
453 HorizontalAlignment = WidgetAlignment.Near,
454 VerticalAlignment = WidgetAlignment.Center
455 }
456 : null,
457 item => {
458 if (item is KeyValuePair<string, string> pair && pair.Key != CurrentLanguageName) {
459 ChangeLanguage(pair.Key);
460 }
461 }
462 )
463 );
464 }
465 }
466}
Engine.Color Color
static partial void SetDocumentLang(string lang)
static void Error(object message)
定义 Log.cs:80
static string TitlePrefix
virtual void Initialize()
static void Initialize()
static void ShowDialog(ContainerWidget parentWidget, Dialog dialog)
static int Index
static readonly JsonDocumentOptions DefaultJsonOptions
static void ReplaceJsonNode(JsonNode oldNode, JsonNode newNode)
static string GetWorldPalette(int index)
static string GetBlock(string blockName, string prop)
static CultureInfo CurrentLanguageCultureInfo
static void ChangeLanguage(string languageType)
static string GetWithoutFallback(out bool r, params string[] keys)
static void Initialize(string languageType)
static string GetContentWidgets(string name, string prop)
static void loadJson(Stream stream)
static string Get(out bool r, params string[] keys)
static string Get(out bool r, JsonNode node, params string[] keys)
static Dictionary< string, string > CachedLanguageFullNames
static string GetFireworks(string name, string prop)
static void LoadEnglishJson(Stream stream)
static Dictionary< string, CultureInfo > LanguageTypes
语言标识符、与相应的CultureInfo
static void SetUsual(bool force=false)
static void CreateLanguageSelectionDialog(Widget parent)
static bool TryGetBlock(string blockName, string prop, out string result)
static string GetDatabase(string name, string prop)
static JsonNode englishJsonNode
static string GetContentWidgets(string name, int pos)
static bool TryGet(out string result, params string[] keys)
static bool TryGet(out string result, JsonNode node, params string[] keys)
static string LName()
当前设置中的语言的标识符,如果是在加载完成后获取语言,建议改用CurrentLanguageName
static string Get(params string[] key)
static string Get(string className, int key)
获取在当前语言类名键对应的字符串
static void MergeJsonNode(JsonNode oldNode, JsonNode newNode)
virtual void LoadLauguage()
初始化语言包
static void SwitchScreen(string name, params object[] parameters)
static Dictionary< string, Screen > m_screens
static void SetConfig(string key, string value)
static List< ModEntity > ModList
所有已启用的模组
static Dictionary< string, string > Configs
static Color White