TranslationHelper.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. using System.Diagnostics;
  2. using System.Globalization;
  3. using System.Text.Json;
  4. using System.Text.Json.Serialization;
  5. namespace PicView.Core.Localization;
  6. [JsonSourceGenerationOptions(AllowTrailingCommas = true)]
  7. [JsonSerializable(typeof(LanguageModel))]
  8. internal partial class LanguageSourceGenerationContext : JsonSerializerContext;
  9. /// <summary>
  10. /// Helper class for managing language-related tasks, including loading and switching languages.
  11. /// </summary>
  12. public static class TranslationHelper
  13. {
  14. /// <summary>
  15. /// The current language model containing translations.
  16. /// </summary>
  17. public static LanguageModel? Translation { get; private set; }
  18. /// <summary>
  19. /// Initializes the language model by setting all strings to empty.
  20. /// </summary>
  21. /// <remarks>
  22. /// This is used to defer loading translations until explicitly needed.
  23. /// </remarks>
  24. public static void Init()
  25. {
  26. Translation = new LanguageModel();
  27. }
  28. /// <summary>
  29. /// Retrieves the translated string for the given key.
  30. /// </summary>
  31. /// <param name="key">The key representing the translation string.</param>
  32. /// <returns>The translated string, or the key itself if no translation is found.</returns>
  33. public static string GetTranslation(string key)
  34. {
  35. if (Translation == null)
  36. {
  37. return key;
  38. }
  39. var propertyInfo = typeof(LanguageModel).GetProperty(key);
  40. return propertyInfo?.GetValue(Translation) as string ?? key;
  41. }
  42. /// <summary>
  43. /// Loads the language file based on the provided ISO language code.
  44. /// </summary>
  45. /// <param name="isoLanguageCode">The ISO language code (e.g., 'en', 'da').</param>
  46. /// <returns>Returns true if the language file was successfully loaded; false if an error occurred.</returns>
  47. public static async Task<bool> LoadLanguage(string isoLanguageCode)
  48. {
  49. var jsonLanguageFile = DetermineLanguageFilePath(isoLanguageCode);
  50. try
  51. {
  52. await LoadLanguageFromFileAsync(jsonLanguageFile).ConfigureAwait(false);
  53. return true;
  54. }
  55. catch (FileNotFoundException fnfEx)
  56. {
  57. #if DEBUG
  58. Trace.WriteLine($"Language file not found: {fnfEx.Message}");
  59. #endif
  60. return false;
  61. }
  62. catch (Exception ex)
  63. {
  64. #if DEBUG
  65. Trace.WriteLine($"{nameof(LoadLanguage)} exception:\n{ex.Message}");
  66. #endif
  67. return false;
  68. }
  69. }
  70. /// <summary>
  71. /// Determines the correct language based on the system's current culture and loads the corresponding language file.
  72. /// </summary>
  73. public static async Task DetermineAndLoadLanguage()
  74. {
  75. var isoLanguageCode = DetermineCorrectLanguage();
  76. Settings.UIProperties.UserLanguage = isoLanguageCode;
  77. await LoadLanguage(isoLanguageCode).ConfigureAwait(false);
  78. }
  79. /// <summary>
  80. /// Retrieves a list of available language files in the language directory.
  81. /// </summary>
  82. /// <returns>An enumerable collection of paths to available language JSON files.</returns>
  83. public static IEnumerable<string> GetLanguages()
  84. {
  85. var languagesDirectory = GetLanguagesDirectory();
  86. return Directory.EnumerateFiles(languagesDirectory, "*.json", SearchOption.TopDirectoryOnly);
  87. }
  88. /// <summary>
  89. /// Changes the application's language by loading the corresponding language file.
  90. /// </summary>
  91. /// <param name="language">The index of the language to be changed.</param>
  92. public static async Task ChangeLanguage(int language)
  93. {
  94. var choice = (Languages)language;
  95. var languageCode = choice.ToString().Replace('_', '-');
  96. Settings.UIProperties.UserLanguage = languageCode;
  97. await LoadLanguage(languageCode).ConfigureAwait(false);
  98. await SaveSettingsAsync().ConfigureAwait(false);
  99. }
  100. /// <summary>
  101. /// Determines the file path for the specified ISO language code.
  102. /// </summary>
  103. /// <param name="isoLanguageCode">The ISO language code representing the desired language.</param>
  104. /// <returns>The file path of the matching language file, or the English language file as a fallback.</returns>
  105. private static string DetermineLanguageFilePath(string isoLanguageCode)
  106. {
  107. var languagesDirectory = GetLanguagesDirectory();
  108. var matchingFiles = Directory.GetFiles(languagesDirectory, "*.json")
  109. .Where(file => Path.GetFileNameWithoutExtension(file)?.Equals(isoLanguageCode, StringComparison.OrdinalIgnoreCase) == true)
  110. .ToList();
  111. return matchingFiles.FirstOrDefault() ?? Path.Combine(languagesDirectory, "en.json");
  112. }
  113. /// <summary>
  114. /// Loads a language from the specified file path.
  115. /// </summary>
  116. /// <param name="filePath">The path to the language JSON file.</param>
  117. /// <returns>A task that completes once the language is loaded.</returns>
  118. /// <exception cref="FileNotFoundException">Thrown when the language file is not found.</exception>
  119. private static async Task LoadLanguageFromFileAsync(string filePath)
  120. {
  121. if (!File.Exists(filePath))
  122. {
  123. throw new FileNotFoundException($"Language file not found: {filePath}");
  124. }
  125. var jsonString = await File.ReadAllTextAsync(filePath).ConfigureAwait(false);
  126. var language = JsonSerializer.Deserialize(jsonString, typeof(LanguageModel), LanguageSourceGenerationContext.Default) as LanguageModel;
  127. Translation = language;
  128. }
  129. /// <summary>
  130. /// Retrieves the directory path where language files are stored.
  131. /// </summary>
  132. /// <returns>The path to the language files directory.</returns>
  133. private static string GetLanguagesDirectory()
  134. {
  135. return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config/Languages/");
  136. }
  137. /// <summary>
  138. /// Determines the correct language code based on the system's current UI culture.
  139. /// </summary>
  140. /// <returns>The ISO language code to use for translations.</returns>
  141. public static string DetermineCorrectLanguage()
  142. {
  143. var userCulture = CultureInfo.CurrentUICulture;
  144. var baseLanguageCode = userCulture.TwoLetterISOLanguageName; // Gets 'da' from 'da-DK'
  145. // Handle special cases, e.g., Chinese or different regions.
  146. switch (baseLanguageCode)
  147. {
  148. case "zh":
  149. // Simplified Chinese vs Traditional Chinese
  150. return userCulture.Name switch
  151. {
  152. "zh-TW" => "zh-TW", // Traditional Chinese
  153. "zh-HK" => "zh-TW", // Treat Hong Kong as Traditional Chinese
  154. _ => "zh-CN" // Default to Simplified Chinese
  155. };
  156. case "de":
  157. // Handle German-speaking regions (Austria, Germany, Switzerland)
  158. return "de"; // Map all 'de-*' to 'de'
  159. default:
  160. // Fall back to the base language if it's available in the translation files
  161. return GetLanguages()
  162. .Any(lang => Path.GetFileNameWithoutExtension(lang) == baseLanguageCode)
  163. ? baseLanguageCode
  164. : "en"; // Default to English if not found
  165. }
  166. }
  167. }