-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathAssLocalization.cs
81 lines (68 loc) · 2.69 KB
/
AssLocalization.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Terraria.Localization;
using Terraria.ModLoader;
using Terraria.ModLoader.Core;
namespace AssortedCrazyThings
{
[Content(ConfigurationSystem.AllFlags)]
public class AssLocalization : AssSystem
{
private static Dictionary<Type, Dictionary<string, LocalizedText>> EnumTypeToLocalizationMapping { get; set; }
//Not all localizations are "code-ified", i.e. those pertaining to gear stat changes or general item tooltips as they are only used in the lang file itself
public static LocalizedText ConcatenateTwoText { get; private set; }
public static LocalizedText SelectedText { get; private set; }
public static LocalizedText BaseDamageText { get; private set; }
public static LocalizedText BaseKnockbackText { get; private set; }
public override void OnModLoad()
{
LoadEnumText();
string category = "Common.";
ConcatenateTwoText = Mod.GetLocalization($"{category}ConcatenateTwo");
SelectedText = Mod.GetLocalization($"{category}Selected");
BaseDamageText = Mod.GetLocalization($"{category}BaseDamage");
BaseKnockbackText = Mod.GetLocalization($"{category}BaseKnockback");
}
public override void OnModUnload()
{
EnumTypeToLocalizationMapping = null;
}
private void LoadEnumText()
{
EnumTypeToLocalizationMapping = new Dictionary<Type, Dictionary<string, LocalizedText>>();
foreach (var type in AssemblyManager.GetLoadableTypes(Mod.Code)
.Where(t => t.IsEnum && t.IsDefined(typeof(LocalizeEnumAttribute), false)))
{
var attr = (LocalizeEnumAttribute)Attribute.GetCustomAttribute(type, typeof(LocalizeEnumAttribute));
var category = attr.Category ?? type.Name;
var dict = EnumTypeToLocalizationMapping[type] = new Dictionary<string, LocalizedText>();
foreach (var name in Enum.GetNames(type))
{
dict[name] = RegisterEnumText(category, name);
}
}
}
private LocalizedText RegisterEnumText(string category, string suffix)
{
string commonKey = $"{category}.";
return Mod.GetLocalization($"{commonKey}{suffix}", () => Regex.Replace(suffix, "([A-Z])", " $1").Trim());
}
public static LocalizedText GetEnumText<T>(T enumValue) where T : Enum
{
return EnumTypeToLocalizationMapping[typeof(T)][enumValue.ToString()];
}
}
/// <summary>
/// Marker for localizing enums, automatically registered (<see cref="AssLocalization.RegisterEnumText"/>) and accessible (<see cref="AssLocalization.GetEnumText{T}(T)"/>)
/// </summary>
[AttributeUsage(AttributeTargets.Enum)]
public class LocalizeEnumAttribute : Attribute
{
/// <summary>
/// Can be null
/// </summary>
public string Category { get; init; } = null;
}
}