-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLocalizationManager.cs
203 lines (180 loc) · 6.66 KB
/
LocalizationManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using JetBrains.Annotations;
using YamlDotNet.Serialization;
namespace LocalizationManager;
[PublicAPI]
public class Localizer
{
private static readonly Dictionary<string, Dictionary<string, Func<string>>> PlaceholderProcessors = new();
private static readonly Dictionary<string, Dictionary<string, string>> loadedTexts = new();
private static readonly ConditionalWeakTable<Localization, string> localizationLanguage = new();
private static readonly List<WeakReference<Localization>> localizationObjects = new();
private static BaseUnityPlugin? _plugin;
private static BaseUnityPlugin plugin
{
get
{
if (_plugin is null)
{
IEnumerable<TypeInfo> types;
try
{
types = Assembly.GetExecutingAssembly().DefinedTypes.ToList();
}
catch (ReflectionTypeLoadException e)
{
types = e.Types.Where(t => t != null).Select(t => t.GetTypeInfo());
}
_plugin = (BaseUnityPlugin)BepInEx.Bootstrap.Chainloader.ManagerObject.GetComponent(types.First(t => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t)));
}
return _plugin;
}
}
private static readonly List<string> fileExtensions = new() { ".json", ".yml" };
private static void UpdatePlaceholderText(Localization localization, string key)
{
localizationLanguage.TryGetValue(localization, out string language);
string text = loadedTexts[language][key];
if (PlaceholderProcessors.TryGetValue(key, out Dictionary<string, Func<string>> textProcessors))
{
text = textProcessors.Aggregate(text, (current, kv) => current.Replace("{" + kv.Key + "}", kv.Value()));
}
localization.AddWord(key, text);
}
public static void AddPlaceholder<T>(string key, string placeholder, ConfigEntry<T> config, Func<T, string>? convertConfigValue = null) where T : notnull
{
convertConfigValue ??= val => val.ToString();
if (!PlaceholderProcessors.ContainsKey(key))
{
PlaceholderProcessors[key] = new Dictionary<string, Func<string>>();
}
void UpdatePlaceholder()
{
PlaceholderProcessors[key][placeholder] = () => convertConfigValue(config.Value);
UpdatePlaceholderText(Localization.instance, key);
}
config.SettingChanged += (_, _) => UpdatePlaceholder();
if (loadedTexts.ContainsKey(Localization.instance.GetSelectedLanguage()))
{
UpdatePlaceholder();
}
}
public static void AddText(string key, string text)
{
List<WeakReference<Localization>> remove = new();
foreach (WeakReference<Localization> reference in localizationObjects)
{
if (reference.TryGetTarget(out Localization localization))
{
Dictionary<string, string> texts = loadedTexts[localizationLanguage.GetOrCreateValue(localization)];
if (!localization.m_translations.ContainsKey(key))
{
texts[key] = text;
localization.AddWord(key, text);
}
}
else
{
remove.Add(reference);
}
}
foreach (WeakReference<Localization> reference in remove)
{
localizationObjects.Remove(reference);
}
}
public static void Load() => LoadLocalization(Localization.instance, Localization.instance.GetSelectedLanguage());
private static void LoadLocalization(Localization __instance, string language)
{
if (!localizationLanguage.Remove(__instance))
{
localizationObjects.Add(new WeakReference<Localization>(__instance));
}
localizationLanguage.Add(__instance, language);
Dictionary<string, string> localizationFiles = new();
foreach (string file in Directory.GetFiles(Path.GetDirectoryName(Paths.PluginPath)!, $"{plugin.Info.Metadata.Name}.*", SearchOption.AllDirectories).Where(f => fileExtensions.IndexOf(Path.GetExtension(f)) >= 0))
{
string key = Path.GetFileNameWithoutExtension(file).Split('.')[1];
if (localizationFiles.ContainsKey(key))
{
// Handle duplicate key
UnityEngine.Debug.LogWarning($"Duplicate key {key} found for {plugin.Info.Metadata.Name}. The duplicate file found at {file} will be skipped.");
}
else
{
localizationFiles[key] = file;
}
}
if (LoadTranslationFromAssembly("English") is not { } englishAssemblyData)
{
throw new Exception($"Found no English localizations in mod {plugin.Info.Metadata.Name}. Expected an embedded resource translations/English.json or translations/English.yml.");
}
Dictionary<string, string>? localizationTexts = new DeserializerBuilder().IgnoreFields().Build().Deserialize<Dictionary<string, string>?>(System.Text.Encoding.UTF8.GetString(englishAssemblyData));
if (localizationTexts is null)
{
throw new Exception($"Localization for mod {plugin.Info.Metadata.Name} failed: Localization file was empty.");
}
string? localizationData = null;
if (language != "English")
{
if (localizationFiles.ContainsKey(language))
{
localizationData = File.ReadAllText(localizationFiles[language]);
}
else if (LoadTranslationFromAssembly(language) is { } languageAssemblyData)
{
localizationData = System.Text.Encoding.UTF8.GetString(languageAssemblyData);
}
}
if (localizationData is null && localizationFiles.ContainsKey("English"))
{
localizationData = File.ReadAllText(localizationFiles["English"]);
}
if (localizationData is not null)
{
foreach (KeyValuePair<string, string> kv in new DeserializerBuilder().IgnoreFields().Build().Deserialize<Dictionary<string, string>?>(localizationData) ?? new Dictionary<string, string>())
{
localizationTexts[kv.Key] = kv.Value;
}
}
loadedTexts[language] = localizationTexts;
foreach (KeyValuePair<string, string> s in localizationTexts)
{
UpdatePlaceholderText(__instance, s.Key);
}
}
static Localizer()
{
Harmony harmony = new("org.bepinex.helpers.LocalizationManager");
harmony.Patch(AccessTools.DeclaredMethod(typeof(Localization), nameof(Localization.LoadCSV)), postfix: new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Localizer), nameof(LoadLocalization))));
}
private static byte[]? LoadTranslationFromAssembly(string language)
{
foreach (string extension in fileExtensions)
{
if (ReadEmbeddedFileBytes("translations." + language + extension) is { } data)
{
return data;
}
}
return null;
}
public static byte[]? ReadEmbeddedFileBytes(string resourceFileName, Assembly? containingAssembly = null)
{
using MemoryStream stream = new();
containingAssembly ??= Assembly.GetCallingAssembly();
if (containingAssembly.GetManifestResourceNames().FirstOrDefault(str => str.EndsWith(resourceFileName, StringComparison.Ordinal)) is { } name)
{
containingAssembly.GetManifestResourceStream(name)?.CopyTo(stream);
}
return stream.Length == 0 ? null : stream.ToArray();
}
}