Localization mod for Gamecraft.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
3.0KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using GamecraftModdingAPI;
  5. using GamecraftModdingAPI.Commands;
  6. using GamecraftModdingAPI.Utility;
  7. using HarmonyLib;
  8. using IllusionPlugin;
  9. using Newtonsoft.Json;
  10. using Newtonsoft.Json.Linq;
  11. using ServiceLayer;
  12. namespace Localization
  13. {
  14. public class LocalizationMod : IEnhancedPlugin
  15. {
  16. private readonly DirectoryInfo _pluginFolder = new DirectoryInfo(Path.Combine("Plugins", "Localization"));
  17. public override void OnApplicationStart()
  18. {
  19. Main.Init();
  20. if (!_pluginFolder.Exists)
  21. _pluginFolder.Create();
  22. string settingsPath = Path.Combine(_pluginFolder.FullName, "settings.json");
  23. JObject settings;
  24. if (File.Exists(settingsPath))
  25. {
  26. try
  27. {
  28. using (var stream = new JsonTextReader(File.OpenText(settingsPath)))
  29. settings = JObject.Load(stream);
  30. string lang = (string) (settings["lang"] ?? (settings["lang"] = "en-us"));
  31. LoadTranslation(lang);
  32. }
  33. catch (Exception e)
  34. {
  35. Logging.LogError(e);
  36. settings = new JObject();
  37. }
  38. }
  39. else
  40. settings = new JObject();
  41. CommandBuilder.Builder("SetLanguage", "Sets the game's language")
  42. .Action<string>(lang =>
  43. {
  44. settings["lang"] = lang;
  45. using (var stream = new JsonTextWriter(new StreamWriter(File.OpenWrite(settingsPath))))
  46. settings.WriteTo(stream);
  47. LoadTranslation(lang);
  48. }).Build();
  49. }
  50. public override void OnApplicationQuit()
  51. {
  52. Main.Shutdown();
  53. }
  54. private void LoadTranslation(string lang)
  55. {
  56. Logging.CommandLog("Loading translation for " + lang + "...");
  57. string langPath = Path.Combine(_pluginFolder.FullName, lang + ".json");
  58. if (!File.Exists(langPath))
  59. {
  60. Logging.CommandLogError("Could not find json file!");
  61. return;
  62. }
  63. var strings = JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(langPath));
  64. var origStrings =
  65. (Dictionary<string, string>) AccessTools.Field(typeof(LocalizationService), "LocalizedStrings")
  66. .GetValue(null);
  67. foreach (var kv in strings)
  68. {
  69. if (!origStrings.Remove(kv.Key))
  70. Logging.CommandLogWarning(kv.Key + " wasn't in the original file.");
  71. origStrings.Add(kv.Key, kv.Value);
  72. }
  73. Logging.CommandLog("Updated " + strings.Count + " strings (" + origStrings.Count + " strings in total)");
  74. }
  75. public override string Name { get; } = "LocalizationMod";
  76. public override string Version { get; } = "1.0.0";
  77. }
  78. }