Client LuaCsForBarotrauma
ServerLanguageOptions.cs
1 using System;
2 using System.Collections.Immutable;
3 using System.Linq;
4 using System.Xml.Linq;
5 
6 namespace Barotrauma;
7 
8 static class ServerLanguageOptions
9 {
10  public readonly record struct LanguageOption(
11  string Label,
12  LanguageIdentifier Identifier,
13  ImmutableArray<LanguageIdentifier> MapsFrom)
14  {
15  public static LanguageOption FromXElement(XElement element)
16  => new LanguageOption(
17  Label:
18  element.GetAttributeString("label", ""),
19  Identifier:
20  element.GetAttributeIdentifier("identifier", LanguageIdentifier.None.Value)
21  .ToLanguageIdentifier(),
22  MapsFrom:
23  element.GetAttributeIdentifierArray("mapsFrom", Array.Empty<Identifier>())
24  .Select(id => id.ToLanguageIdentifier()).ToImmutableArray());
25  }
26 
27  public static readonly ImmutableArray<LanguageOption> Options;
28 
29  static ServerLanguageOptions()
30  {
31  var languageOptionElements
32  = XMLExtensions.TryLoadXml("Data/languageoptions.xml")?.Root?.Elements()
33  ?? Enumerable.Empty<XElement>();
34  Options = languageOptionElements
35  // Convert the XElements into LanguageOptions immediately since they can be worked with more directly
36  .Select(LanguageOption.FromXElement)
37  // Remove options with duplicate identifiers
38  .DistinctBy(p => p.Identifier)
39  // Remove options where the label is empty or the identifier is missing
40  .Where(p => !p.Label.IsNullOrWhiteSpace() && p.Identifier != LanguageIdentifier.None)
41  // Sort the options based on the lexicographical order of the labels
42  .OrderBy(p => p.Label)
43  .ToImmutableArray();
44  }
45 
46  public static LanguageIdentifier PickLanguage(LanguageIdentifier id)
47  {
48  if (id == LanguageIdentifier.None)
49  {
50  id = GameSettings.CurrentConfig.Language;
51  }
52 
53  foreach (var (_, identifier, mapsFrom) in Options)
54  {
55  if (id == identifier || mapsFrom.Contains(id))
56  {
57  return identifier;
58  }
59  }
60 
61  return TextManager.DefaultLanguage;
62  }
63 }