EditorLocalization.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. using System;
  2. using System.Text.RegularExpressions;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using UnityEngine;
  6. namespace GoogleMobileAds.Editor
  7. {
  8. public class EditorLocalization
  9. {
  10. private const string LOCALIZATION_DATA_JSON_RELATIVE_PATH = "GoogleMobileAds/Editor";
  11. private const string LOCALIZATION_DATA_JSON_FILENAME =
  12. "gma_settings_editor_localization_data.json";
  13. private const string LOCALIZATIONS_JSON_KEY = "LocalizationsByKey";
  14. private const string LOCALIZATION_KEY_PREFIX = "KEY_";
  15. private readonly Lazy<EditorLocalizationData> _localizationData =
  16. new Lazy<EditorLocalizationData>(() => InitLocalizationDataOrThrow());
  17. private EditorLocalizationData GetLocalizationData() => _localizationData.Value;
  18. /**
  19. * Gets the default language for the settings editor.
  20. * We assume the default locale used belong to the list of supported cultures
  21. * (https://www.csharp-examples.net/culture-names/), and that each key has a default
  22. * localization provided.
  23. */
  24. public string GetDefaultLanguage()
  25. {
  26. return "en"; // English
  27. }
  28. /**
  29. * Checks that a localization key exists.
  30. */
  31. public bool HasKey(string key)
  32. {
  33. return GetLocalizationData().LocalizationsByKey.ContainsKey(key);
  34. }
  35. /**
  36. * Localizes a resource key based on a provided user language.
  37. * Returns the key name if the key could not be localized.
  38. */
  39. public string ForKey(string key)
  40. {
  41. key = key.ToUpper();
  42. // Accept both key syntaxes.
  43. if (key.StartsWith(LOCALIZATION_KEY_PREFIX))
  44. key = key.Replace(LOCALIZATION_KEY_PREFIX, "");
  45. if (GetLocalizationData().LocalizationsByKey.TryGetValue(key,
  46. out Dictionary<string, string> localizations))
  47. {
  48. // Key was found. Try to localize the key with the user language (e.g., "en" or "fr").
  49. // Else, use the default (fallback) language, if the localization key is missing for
  50. // the chosen language (or no language was selected).
  51. // The region is omitted purposely as we don't currently require this level of details.
  52. string userLanguage = GoogleMobileAdsSettings.LoadInstance().UserLanguage;
  53. if (localizations == null)
  54. {
  55. return null;
  56. }
  57. bool userLanguageExists = localizations.TryGetValue(userLanguage,
  58. out string userLocalization);
  59. bool userLocalizationIsValid = userLanguageExists &&
  60. !string.IsNullOrEmpty(userLocalization);
  61. return userLocalizationIsValid ? userLocalization: localizations[GetDefaultLanguage()];
  62. }
  63. // Error, key not found, no localization to return so let's fallback to the key name
  64. // to provide some sort of indication in the UI.
  65. Debug.LogError($"Localization key not found: {key}.");
  66. return key;
  67. }
  68. /**
  69. * Deserializes the localization data, encoded in json.
  70. * Returns the json deserialized to a EditorLocalizationData class instance.
  71. * Throws an ArgumentException if the json file cannot be deserialized.
  72. */
  73. private static EditorLocalizationData InitLocalizationDataOrThrow()
  74. {
  75. string localizationDataPath =
  76. Path.Combine(Application.dataPath, LOCALIZATION_DATA_JSON_RELATIVE_PATH,
  77. LOCALIZATION_DATA_JSON_FILENAME);
  78. // Handle importing the localization data file via Unity Package Manager.
  79. var pathUtils = ScriptableObject.CreateInstance<EditorPathUtils>();
  80. if (pathUtils.IsPackageRootPath())
  81. {
  82. localizationDataPath =
  83. Path.Combine(pathUtils.GetDirectoryAssetPath(), LOCALIZATION_DATA_JSON_FILENAME);
  84. }
  85. try
  86. {
  87. string json = File.ReadAllText(localizationDataPath);
  88. var data = DeserializeFromJson(json);
  89. if (data.LocalizationsByKey == null)
  90. {
  91. throw new ArgumentNullException("LocalizationsByKey");
  92. }
  93. return data;
  94. }
  95. catch (Exception)
  96. {
  97. throw new ArgumentException(
  98. $"Exception thrown while retrieving localization data from {localizationDataPath}:" +
  99. " {ex:full}");
  100. }
  101. }
  102. // We would like to handle the deserialization of the JSON file referenced above but without
  103. // leveraging any JSON library to avoid adding any dependency.
  104. private static EditorLocalizationData DeserializeFromJson(string json)
  105. {
  106. var data = new EditorLocalizationData();
  107. data.LocalizationsByKey = new Dictionary<string, Dictionary<string, string>>();
  108. // We match every field in the JSON. The order in which those matches are found is used to
  109. // deserialize the localization values.
  110. var regex = new Regex(@"""(?<val>[^""]+)""");
  111. var matches = regex.Matches(json);
  112. var currentKeys = new List<string>();
  113. var valueProcessed = false;
  114. foreach (Match match in matches)
  115. {
  116. var val = match.Groups["val"].Value;
  117. if (val.Equals(LOCALIZATIONS_JSON_KEY))
  118. {
  119. currentKeys.Clear();
  120. continue;
  121. }
  122. if (valueProcessed)
  123. {
  124. valueProcessed = false;
  125. if (val.StartsWith(LOCALIZATION_KEY_PREFIX))
  126. {
  127. // Start a new level.
  128. currentKeys.Clear();
  129. }
  130. else if (currentKeys.Count > 0)
  131. {
  132. // Go up one level by removing the latest key.
  133. currentKeys.RemoveAt(currentKeys.Count - 1);
  134. }
  135. }
  136. // The localization values are 2 levels deep.
  137. if (currentKeys.Count < 2)
  138. {
  139. currentKeys.Add(val);
  140. continue;
  141. }
  142. ProcessValue(data, currentKeys, val);
  143. valueProcessed = true;
  144. }
  145. return data;
  146. }
  147. private static void ProcessValue(EditorLocalizationData data, List<string> currentKeys,
  148. string val)
  149. {
  150. if (currentKeys.Count != 2)
  151. return;
  152. currentKeys[0] = currentKeys[0].Replace(LOCALIZATION_KEY_PREFIX, "");
  153. if (!data.LocalizationsByKey.ContainsKey(currentKeys[0]))
  154. data.LocalizationsByKey[currentKeys[0]] = new Dictionary<string, string>();
  155. data.LocalizationsByKey[currentKeys[0]][currentKeys[1]] = val;
  156. }
  157. }
  158. }