1
0

ContentLocalizationManager.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. using System.Globalization;
  2. using System.Linq;
  3. using System.Text.RegularExpressions;
  4. using Robust.Shared.Utility;
  5. namespace Content.Shared.Localizations
  6. {
  7. public sealed class ContentLocalizationManager
  8. {
  9. [Dependency] private readonly ILocalizationManager _loc = default!;
  10. // If you want to change your codebase's language, do it here.
  11. private const string Culture = "en-US";
  12. /// <summary>
  13. /// Custom format strings used for parsing and displaying minutes:seconds timespans.
  14. /// </summary>
  15. public static readonly string[] TimeSpanMinutesFormats = new[]
  16. {
  17. @"m\:ss",
  18. @"mm\:ss",
  19. @"%m",
  20. @"mm"
  21. };
  22. public void Initialize()
  23. {
  24. var culture = new CultureInfo(Culture);
  25. _loc.LoadCulture(culture);
  26. _loc.AddFunction(culture, "PRESSURE", FormatPressure);
  27. _loc.AddFunction(culture, "POWERWATTS", FormatPowerWatts);
  28. _loc.AddFunction(culture, "POWERJOULES", FormatPowerJoules);
  29. _loc.AddFunction(culture, "UNITS", FormatUnits);
  30. _loc.AddFunction(culture, "TOSTRING", args => FormatToString(culture, args));
  31. _loc.AddFunction(culture, "LOC", FormatLoc);
  32. _loc.AddFunction(culture, "NATURALFIXED", FormatNaturalFixed);
  33. _loc.AddFunction(culture, "NATURALPERCENT", FormatNaturalPercent);
  34. _loc.AddFunction(culture, "PLAYTIME", FormatPlaytime);
  35. /*
  36. * The following language functions are specific to the english localization. When working on your own
  37. * localization you should NOT modify these, instead add new functions specific to your language/culture.
  38. * This ensures the english translations continue to work as expected when fallbacks are needed.
  39. */
  40. var cultureEn = new CultureInfo("en-US");
  41. _loc.AddFunction(cultureEn, "MAKEPLURAL", FormatMakePlural);
  42. _loc.AddFunction(cultureEn, "MANY", FormatMany);
  43. }
  44. private ILocValue FormatMany(LocArgs args)
  45. {
  46. var count = ((LocValueNumber) args.Args[1]).Value;
  47. if (Math.Abs(count - 1) < 0.0001f)
  48. {
  49. return (LocValueString) args.Args[0];
  50. }
  51. else
  52. {
  53. return (LocValueString) FormatMakePlural(args);
  54. }
  55. }
  56. private ILocValue FormatNaturalPercent(LocArgs args)
  57. {
  58. var number = ((LocValueNumber) args.Args[0]).Value * 100;
  59. var maxDecimals = (int)Math.Floor(((LocValueNumber) args.Args[1]).Value);
  60. var formatter = (NumberFormatInfo)NumberFormatInfo.GetInstance(CultureInfo.GetCultureInfo(Culture)).Clone();
  61. formatter.NumberDecimalDigits = maxDecimals;
  62. return new LocValueString(string.Format(formatter, "{0:N}", number).TrimEnd('0').TrimEnd(char.Parse(formatter.NumberDecimalSeparator)) + "%");
  63. }
  64. private ILocValue FormatNaturalFixed(LocArgs args)
  65. {
  66. var number = ((LocValueNumber) args.Args[0]).Value;
  67. var maxDecimals = (int)Math.Floor(((LocValueNumber) args.Args[1]).Value);
  68. var formatter = (NumberFormatInfo)NumberFormatInfo.GetInstance(CultureInfo.GetCultureInfo(Culture)).Clone();
  69. formatter.NumberDecimalDigits = maxDecimals;
  70. return new LocValueString(string.Format(formatter, "{0:N}", number).TrimEnd('0').TrimEnd(char.Parse(formatter.NumberDecimalSeparator)));
  71. }
  72. private static readonly Regex PluralEsRule = new("^.*(s|sh|ch|x|z)$");
  73. private ILocValue FormatMakePlural(LocArgs args)
  74. {
  75. var text = ((LocValueString) args.Args[0]).Value;
  76. var split = text.Split(" ", 1);
  77. var firstWord = split[0];
  78. if (PluralEsRule.IsMatch(firstWord))
  79. {
  80. if (split.Length == 1)
  81. return new LocValueString($"{firstWord}es");
  82. else
  83. return new LocValueString($"{firstWord}es {split[1]}");
  84. }
  85. else
  86. {
  87. if (split.Length == 1)
  88. return new LocValueString($"{firstWord}s");
  89. else
  90. return new LocValueString($"{firstWord}s {split[1]}");
  91. }
  92. }
  93. // TODO: allow fluent to take in lists of strings so this can be a format function like it should be.
  94. /// <summary>
  95. /// Formats a list as per english grammar rules.
  96. /// </summary>
  97. public static string FormatList(List<string> list)
  98. {
  99. return list.Count switch
  100. {
  101. <= 0 => string.Empty,
  102. 1 => list[0],
  103. 2 => $"{list[0]} and {list[1]}",
  104. _ => $"{string.Join(", ", list.GetRange(0, list.Count - 1))}, and {list[^1]}"
  105. };
  106. }
  107. /// <summary>
  108. /// Formats a list as per english grammar rules, but uses or instead of and.
  109. /// </summary>
  110. public static string FormatListToOr(List<string> list)
  111. {
  112. return list.Count switch
  113. {
  114. <= 0 => string.Empty,
  115. 1 => list[0],
  116. 2 => $"{list[0]} or {list[1]}",
  117. _ => $"{string.Join(" or ", list)}"
  118. };
  119. }
  120. /// <summary>
  121. /// Formats a direction struct as a human-readable string.
  122. /// </summary>
  123. public static string FormatDirection(Direction dir)
  124. {
  125. return Loc.GetString($"zzzz-fmt-direction-{dir.ToString()}");
  126. }
  127. /// <summary>
  128. /// Formats playtime as hours and minutes.
  129. /// </summary>
  130. public static string FormatPlaytime(TimeSpan time)
  131. {
  132. time = TimeSpan.FromMinutes(Math.Ceiling(time.TotalMinutes));
  133. var hours = (int)time.TotalHours;
  134. var minutes = time.Minutes;
  135. return Loc.GetString($"zzzz-fmt-playtime", ("hours", hours), ("minutes", minutes));
  136. }
  137. private static ILocValue FormatLoc(LocArgs args)
  138. {
  139. var id = ((LocValueString) args.Args[0]).Value;
  140. return new LocValueString(Loc.GetString(id, args.Options.Select(x => (x.Key, x.Value.Value!)).ToArray()));
  141. }
  142. private static ILocValue FormatToString(CultureInfo culture, LocArgs args)
  143. {
  144. var arg = args.Args[0];
  145. var fmt = ((LocValueString) args.Args[1]).Value;
  146. var obj = arg.Value;
  147. if (obj is IFormattable formattable)
  148. return new LocValueString(formattable.ToString(fmt, culture));
  149. return new LocValueString(obj?.ToString() ?? "");
  150. }
  151. private static ILocValue FormatUnitsGeneric(LocArgs args, string mode)
  152. {
  153. const int maxPlaces = 5; // Matches amount in _lib.ftl
  154. var pressure = ((LocValueNumber) args.Args[0]).Value;
  155. var places = 0;
  156. while (pressure > 1000 && places < maxPlaces)
  157. {
  158. pressure /= 1000;
  159. places += 1;
  160. }
  161. return new LocValueString(Loc.GetString(mode, ("divided", pressure), ("places", places)));
  162. }
  163. private static ILocValue FormatPressure(LocArgs args)
  164. {
  165. return FormatUnitsGeneric(args, "zzzz-fmt-pressure");
  166. }
  167. private static ILocValue FormatPowerWatts(LocArgs args)
  168. {
  169. return FormatUnitsGeneric(args, "zzzz-fmt-power-watts");
  170. }
  171. private static ILocValue FormatPowerJoules(LocArgs args)
  172. {
  173. return FormatUnitsGeneric(args, "zzzz-fmt-power-joules");
  174. }
  175. private static ILocValue FormatUnits(LocArgs args)
  176. {
  177. if (!Units.Types.TryGetValue(((LocValueString) args.Args[0]).Value, out var ut))
  178. throw new ArgumentException($"Unknown unit type {((LocValueString) args.Args[0]).Value}");
  179. var fmtstr = ((LocValueString) args.Args[1]).Value;
  180. double max = Double.NegativeInfinity;
  181. var iargs = new double[args.Args.Count - 1];
  182. for (var i = 2; i < args.Args.Count; i++)
  183. {
  184. var n = ((LocValueNumber) args.Args[i]).Value;
  185. if (n > max)
  186. max = n;
  187. iargs[i - 2] = n;
  188. }
  189. if (!ut.TryGetUnit(max, out var mu))
  190. throw new ArgumentException("Unit out of range for type");
  191. var fargs = new object[iargs.Length];
  192. for (var i = 0; i < iargs.Length; i++)
  193. fargs[i] = iargs[i] * mu.Factor;
  194. fargs[^1] = Loc.GetString($"units-{mu.Unit.ToLower()}");
  195. // Before anyone complains about "{"+"${...}", at least it's better than MS's approach...
  196. // https://docs.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting#escaping-braces
  197. //
  198. // Note that the closing brace isn't replaced so that format specifiers can be applied.
  199. var res = String.Format(
  200. fmtstr.Replace("{UNIT", "{" + $"{fargs.Length - 1}"),
  201. fargs
  202. );
  203. return new LocValueString(res);
  204. }
  205. private static ILocValue FormatPlaytime(LocArgs args)
  206. {
  207. var time = TimeSpan.Zero;
  208. if (args.Args is { Count: > 0 } && args.Args[0].Value is TimeSpan timeArg)
  209. {
  210. time = timeArg;
  211. }
  212. return new LocValueString(FormatPlaytime(time));
  213. }
  214. }
  215. }