Client LuaCsForBarotrauma
ReplaceLString.cs
1 #nullable enable
2 using System;
3 using System.Collections.Generic;
4 using System.Collections.Immutable;
5 using System.Linq;
7 
8 namespace Barotrauma
9 {
11  {
12  private readonly LocalizedString nestedStr;
13  private readonly ImmutableDictionary<LocalizedString, (LocalizedString Value, FormatCapitals FormatCapitals)> replacements;
14  private readonly StringComparison stringComparison;
15 
17  {
18  nestedStr = nStr;
19  replacements = r.Select(kvf => (kvf.Key, (kvf.Value, kvf.FormatCapitals))).ToImmutableDictionary();
20  stringComparison = sc;
21  }
22 
23  public ReplaceLString(LocalizedString nStr, StringComparison sc, params (LocalizedString Key, LocalizedString Value)[] r)
24  : this(nStr, sc, r.Select(kv => (kv.Key, kv.Value, FormatCapitals.No))) { }
25 
26  public ReplaceLString(LocalizedString nStr, StringComparison sc, IEnumerable<(Identifier Key, LocalizedString Value, FormatCapitals FormatCapitals)> r)
27  : this(nStr, sc, r.Select(p => ((LocalizedString)p.Key.Value, p.Value, p.FormatCapitals))) { }
28 
29  public ReplaceLString(LocalizedString nStr, StringComparison sc, params (Identifier Key, LocalizedString Value)[] r)
30  : this(nStr, sc, r.Select(kv => ((LocalizedString)kv.Key.Value, kv.Value, FormatCapitals.No))) { }
31 
32  private static string HandleVariableCapitalization(string text, string variableTag, string variableValue)
33  {
34  int index = text.IndexOf(variableTag, StringComparison.InvariantCulture) - 1;
35  if (index == -1)
36  {
37  return variableValue;
38  }
39 
40  for (int i = index; i >= 0; i--)
41  {
42  if (char.IsWhiteSpace(text[i])) { continue; }
43 
44  if (text[i] != '.')
45  {
46  variableValue = variableValue.ToLowerInvariant();
47  }
48  else
49  {
50  variableValue = TextManager.Capitalize(variableValue).Value;
51  break;
52  }
53  }
54 
55  return variableValue;
56  }
57 
58  public override bool Loaded => nestedStr.Loaded;
59  public override void RetrieveValue()
60  {
61  cachedValue = nestedStr.Value;
62  foreach (var varName in replacements.Keys)
63  {
64  string key = varName.Value;
65  string value = replacements[varName].Value.Value;
66  if (replacements[varName].FormatCapitals == FormatCapitals.Yes)
67  {
68  value = HandleVariableCapitalization(cachedValue, key, value);
69  }
70  cachedValue = cachedValue.Replace(key, value, stringComparison);
71  }
73  }
74  }
75 }
ReplaceLString(LocalizedString nStr, StringComparison sc, params(LocalizedString Key, LocalizedString Value)[] r)
ReplaceLString(LocalizedString nStr, StringComparison sc, IEnumerable<(Identifier Key, LocalizedString Value, FormatCapitals FormatCapitals)> r)
ReplaceLString(LocalizedString nStr, StringComparison sc, IEnumerable<(LocalizedString Key, LocalizedString Value, FormatCapitals FormatCapitals)> r)
ReplaceLString(LocalizedString nStr, StringComparison sc, params(Identifier Key, LocalizedString Value)[] r)
override void RetrieveValue()