From 0730cf4e0a72ebef7e5203739000c42ba56e2665 Mon Sep 17 00:00:00 2001 From: Kyler Ramsey Date: Tue, 22 Sep 2026 04:59:06 -0700 Subject: [PATCH 1/2] PWA2: look up the panel and clear-button text through ILoc The building-panel section (heading, checkbox label and tooltip, ON/OFF badge, the three hints) and the top-right clear button (label with the pin count, tooltip) were hard-coded English literals, so the game could not translate them. They now come from 10 new keys in Localizations/enUS_PersistentWorkAreas.csv through the game's ILoc, which WorkAreaService and WorkAreaFragment now take from the container. The keys live in a new LocKeys class. The clear label is "Clear pinned areas ({0})", formatted with the pin count. The English text players see is unchanged, and log messages stay in English. Checks reads the mod DLL's #US string heap with System.Reflection.Metadata (part of net8.0, so no package is needed) and fails if any former UI literal or any enUS text is compiled in. It also checks that every LocKeys constant has enUS text, that every enUS key is used by LocKeys or a key-binding blueprint, that the CSV follows the game's ID,Text,Comment rules, that both classes take ILoc, and that the clear label formats the count. 38 -> 44 checks. The README now says where the UI text lives and how a translation is added. Display only: no simulation, save or network change. Co-Authored-By: Claude Opus 5 --- README.md | 2 +- .../enUS_PersistentWorkAreas.csv | 10 +++ source/LocKeys.cs | 18 +++++ source/WorkAreaFragment.cs | 18 ++--- source/WorkAreaService.cs | 13 ++-- tests/Program.cs | 78 +++++++++++++++++++ 6 files changed, 124 insertions(+), 15 deletions(-) create mode 100644 source/LocKeys.cs diff --git a/README.md b/README.md index 80011e5..fd5eb79 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ No extra dependency is required. Keep your existing BeaverBuddies Stability Fork The currently selected building still uses its normal game outline. Clearing pins restores normal selection behavior; deselecting that building then hides its normal outline. Pins reset on map exit, loading, and multiplayer resynchronization. They are not saved. Deleting a pinned building removes its pin. -The mod supports navigation-based working areas. It does not pin district road coloring, every kind of effect-radius overlay, or building-placement ghosts. UI text is currently English. +The mod supports navigation-based working areas. It does not pin district road coloring, every kind of effect-radius overlay, or building-placement ghosts. UI text is currently English. All of it is in `Localizations/enUS_PersistentWorkAreas.csv`, so a translation is one more file with the same keys, named for the game's language code (for example `deDE_PersistentWorkAreas.csv`). ## Compatibility and validation diff --git a/packaging/PersistentWorkAreas/version-1.1/Localizations/enUS_PersistentWorkAreas.csv b/packaging/PersistentWorkAreas/version-1.1/Localizations/enUS_PersistentWorkAreas.csv index f18148a..8105aaa 100644 --- a/packaging/PersistentWorkAreas/version-1.1/Localizations/enUS_PersistentWorkAreas.csv +++ b/packaging/PersistentWorkAreas/version-1.1/Localizations/enUS_PersistentWorkAreas.csv @@ -1,3 +1,13 @@ ID,Text,Comment PersistentWorkAreas.KeyBindings.Group,Persistent Work Areas, PersistentWorkAreas.KeyBindings.Clear,Clear all pinned working areas, +PersistentWorkAreas.Panel.Heading,WORKING AREA,Section heading in the building panel +PersistentWorkAreas.Pin.Title,Keep working area visible,Label of the pin checkbox +PersistentWorkAreas.Pin.Tooltip,Click to keep this building's working-area outline visible after deselection. Click again to unpin., +PersistentWorkAreas.State.On,ON,Short badge on the pin checkbox while pinned +PersistentWorkAreas.State.Off,OFF,Short badge on the pin checkbox while not pinned +PersistentWorkAreas.Hint.Unavailable,Working-area pinning is unavailable. Check the game log., +PersistentWorkAreas.Hint.Pinned,Pinned after deselection. Clear all using the top-right button., +PersistentWorkAreas.Hint.Unpinned,Click to pin this outline while planting or building., +PersistentWorkAreas.ClearAll,Clear pinned areas ({0}),Top-right button. {0} is the number of pinned buildings +PersistentWorkAreas.ClearAll.Tooltip,Remove all your pinned working-area outlines. You can also assign a shortcut in Settings > Key bindings > Persistent Work Areas., diff --git a/source/LocKeys.cs b/source/LocKeys.cs new file mode 100644 index 0000000..7f80014 --- /dev/null +++ b/source/LocKeys.cs @@ -0,0 +1,18 @@ +namespace PersistentWorkAreas +{ + // Keys into Localizations/enUS_PersistentWorkAreas.csv. A translation adds a + // _PersistentWorkAreas.csv with the same keys; tests/Program.cs checks the enUS file. + internal static class LocKeys + { + public const string Heading = "PersistentWorkAreas.Panel.Heading"; + public const string PinTitle = "PersistentWorkAreas.Pin.Title"; + public const string PinTooltip = "PersistentWorkAreas.Pin.Tooltip"; + public const string StateOn = "PersistentWorkAreas.State.On"; + public const string StateOff = "PersistentWorkAreas.State.Off"; + public const string HintUnavailable = "PersistentWorkAreas.Hint.Unavailable"; + public const string HintPinned = "PersistentWorkAreas.Hint.Pinned"; + public const string HintUnpinned = "PersistentWorkAreas.Hint.Unpinned"; + public const string ClearAll = "PersistentWorkAreas.ClearAll"; + public const string ClearAllTooltip = "PersistentWorkAreas.ClearAll.Tooltip"; + } +} diff --git a/source/WorkAreaFragment.cs b/source/WorkAreaFragment.cs index 784f799..c2081e5 100644 --- a/source/WorkAreaFragment.cs +++ b/source/WorkAreaFragment.cs @@ -1,6 +1,7 @@ using System; using Timberborn.BaseComponentSystem; using Timberborn.EntityPanelSystem; +using Timberborn.Localization; using UnityEngine; using UnityEngine.UIElements; @@ -11,6 +12,7 @@ public sealed class WorkAreaFragment : IEntityPanelFragment private static readonly Color Cream = new Color(1f, .95f, .79f); private static readonly Color Gold = new Color(.92f, .72f, .35f); private readonly WorkAreaService _service; + private readonly ILoc _loc; private VisualElement _root; private Button _toggle; private VisualElement _box; @@ -21,7 +23,7 @@ public sealed class WorkAreaFragment : IEntityPanelFragment private bool _pinned; private bool _hovered; private bool _focused; - public WorkAreaFragment(WorkAreaService service) { _service = service; } + public WorkAreaFragment(WorkAreaService service, ILoc loc) { _service = service; _loc = loc; } public VisualElement InitializeFragment() { @@ -35,7 +37,7 @@ public VisualElement InitializeFragment() _root.style.borderLeftWidth = 4; Round(_root, 5); - var heading = new Label("WORKING AREA"); + var heading = new Label(_loc.T(LocKeys.Heading)); heading.style.fontSize = 11; heading.style.unityFontStyleAndWeight = FontStyle.Bold; heading.style.color = Gold; @@ -47,7 +49,7 @@ public VisualElement InitializeFragment() _toggle = new Button(() => _service.SetPinned(_entity, !_service.IsPinned(_entity))) { name = "PersistentWorkAreasPin", - tooltip = "Click to keep this building's working-area outline visible after deselection. Click again to unpin." + tooltip = _loc.T(LocKeys.PinTooltip) }; _toggle.style.flexDirection = FlexDirection.Row; _toggle.style.alignItems = Align.Center; @@ -77,7 +79,7 @@ public VisualElement InitializeFragment() _check.style.marginTop = -4; _box.Add(_check); _toggle.Add(_box); - var title = new Label("Keep working area visible") { pickingMode = PickingMode.Ignore }; + var title = new Label(_loc.T(LocKeys.PinTitle)) { pickingMode = PickingMode.Ignore }; title.style.flexGrow = 1; title.style.flexShrink = 1; title.style.minWidth = 0; @@ -129,10 +131,8 @@ private void Refresh() _root.style.display = supports ? DisplayStyle.Flex : DisplayStyle.None; _pinned = supports && _service.IsPinned(_entity); _toggle.SetEnabled(_service.Available); - _hint.text = !_service.Available - ? "Working-area pinning is unavailable. Check the game log." - : _pinned ? "Pinned after deselection. Clear all using the top-right button." - : "Click to pin this outline while planting or building."; + _hint.text = _loc.T(!_service.Available ? LocKeys.HintUnavailable + : _pinned ? LocKeys.HintPinned : LocKeys.HintUnpinned); Paint(); } private void Paint() @@ -146,7 +146,7 @@ private void Paint() Border(_box, accent, 2); _box.style.backgroundColor = _pinned ? accent : new Color(.07f, .13f, .12f); _check.style.display = _pinned ? DisplayStyle.Flex : DisplayStyle.None; - _state.text = _pinned ? "ON" : "OFF"; + _state.text = _loc.T(_pinned ? LocKeys.StateOn : LocKeys.StateOff); _state.style.backgroundColor = _pinned ? accent : new Color(.29f, .29f, .21f); _state.style.color = _pinned ? new Color(.09f, .18f, .13f) : Cream; } diff --git a/source/WorkAreaService.cs b/source/WorkAreaService.cs index 9af453f..628469c 100644 --- a/source/WorkAreaService.cs +++ b/source/WorkAreaService.cs @@ -11,6 +11,7 @@ using Timberborn.EntitySystem; using Timberborn.InputSystem; using Timberborn.LevelVisibilitySystem; +using Timberborn.Localization; using Timberborn.MapStateSystem; using Timberborn.Navigation; using Timberborn.SceneLoading; @@ -41,6 +42,7 @@ public sealed class WorkAreaService : IPostLoadableSingleton, IUpdatableSingleto private readonly LoadingScreen _loading; private readonly UILayout _layout; private readonly InputService _input; + private readonly ILoc _loc; private NativeOutline _outline; private Button _clearButton; private EntityComponent _selected; @@ -56,11 +58,11 @@ public sealed class WorkAreaService : IPostLoadableSingleton, IUpdatableSingleto public WorkAreaService(INavigationRangeService navigation, ConstructionModeService construction, IBlockService blocks, PreviewBlockService previews, ILevelVisibilityService visibility, MapSize mapSize, ISpecService specs, EventBus events, LoadingScreen loading, - UILayout layout, InputService input) + UILayout layout, InputService input, ILoc loc) { _navigation = navigation; _construction = construction; _blocks = blocks; _previews = previews; _visibility = visibility; _mapSize = mapSize; _specs = specs; - _events = events; _loading = loading; _layout = layout; _input = input; + _events = events; _loading = loading; _layout = layout; _input = input; _loc = loc; } public void PostLoad() @@ -69,9 +71,10 @@ public void PostLoad() _events.Register(this); _loading.LoadingScreenEnabled += OnLoading; _input.AddInputProcessor(this); - _clearButton = WorkAreaFragment.MakeButton("Clear pinned areas", ClearAll); + // Notify() below sets the label, which shows the pin count. + _clearButton = WorkAreaFragment.MakeButton(string.Empty, ClearAll); _clearButton.name = "PersistentWorkAreasClearAll"; - _clearButton.tooltip = "Remove all your pinned working-area outlines. You can also assign a shortcut in Settings > Key bindings > Persistent Work Areas."; + _clearButton.tooltip = _loc.T(LocKeys.ClearAllTooltip); _clearButton.style.marginTop = 6; _layout.AddTopRight(_clearButton, 1000); Notify(); @@ -203,7 +206,7 @@ private void Notify() { if (_clearButton != null) { - _clearButton.text = "Clear pinned areas (" + Count + ")"; + _clearButton.text = _loc.T(LocKeys.ClearAll, Count); _clearButton.style.display = Count > 0 ? DisplayStyle.Flex : DisplayStyle.None; } Changed?.Invoke(); diff --git a/tests/Program.cs b/tests/Program.cs index 1355807..21cc271 100644 --- a/tests/Program.cs +++ b/tests/Program.cs @@ -1,6 +1,10 @@ using System.Reflection; +using System.Reflection.Metadata; +using System.Reflection.Metadata.Ecma335; +using System.Reflection.PortableExecutable; using System.Runtime.Loader; using System.Runtime.CompilerServices; +using System.Text; using System.Text.Json; using PersistentWorkAreas; @@ -91,8 +95,82 @@ void Method(Type type, string name, Type returns, params Type[] args) Check(manifest.RootElement.GetProperty("Version").GetString() == mod.GetName().Version!.ToString(3), "Manifest version matches assembly version"); using var binding = JsonDocument.Parse(File.ReadAllText(Path.Combine(packaging, "KeyBindings", "PersistentWorkAreas.Clear.blueprint.json"))); Check(binding.RootElement.GetProperty("KeyBindingSpec").GetProperty("Id").GetString() == (string)service.GetField("ClearKey")!.GetRawConstantValue()!, "Clear key binding matches input handler"); + +// Player-facing text comes from the enUS CSV through the game's ILoc, so it can be translated. +var locText = File.ReadAllText(Path.Combine(packaging, "Localizations", "enUS_PersistentWorkAreas.csv")); +var locRows = ReadCsv(locText); +var enUS = new Dictionary(); +bool locRowsValid = locRows.Count > 1 && locRows[0].SequenceEqual(new[] { "ID", "Text", "Comment" }); +foreach (var row in locRows.Skip(1)) + locRowsValid &= row.Length == 3 && row[0].Length > 0 && row[1].Length > 0 && !row.Any(x => x.EndsWith(' ')) && enUS.TryAdd(row[0], row[1]); +// The game's CSV validator rejects a space between a comma and a quote. +string unquoted = locText.Replace("\"\"", ""); +Check(locRowsValid && !unquoted.Contains(", \"") && !unquoted.Contains("\" ,"), "Localization CSV has the game's ID,Text,Comment layout with unique keys"); +var literals = new List(); +using (var modImage = new PEReader(File.OpenRead(modPath))) +{ + var metadata = modImage.GetMetadataReader(); + if (metadata.GetHeapSize(HeapIndex.UserString) > 1) + for (var handle = MetadataTokens.UserStringHandle(1); !handle.IsNil; handle = metadata.GetNextHandle(handle)) + literals.Add(metadata.GetUserString(handle)); +} +// The English the panel and button used to hard-code, plus every enUS text up to its first placeholder. +var english = new[] { "WORKING AREA", "Keep working area visible", "working-area outline visible", "Working-area pinning is unavailable", + "Pinned after deselection", "Click to pin this outline", "Clear pinned areas", "Remove all your pinned" } + .Concat(enUS.Values.Select(x => x.Split('{')[0].Trim()).Where(x => x.Length > 3)).ToArray(); +var hardCoded = literals.Where(x => x is "ON" or "OFF" || english.Any(x.Contains)).Distinct().ToArray(); +Check(hardCoded.Length == 0, "No hard-coded English UI text in the mod DLL" + string.Concat(hardCoded.Select(x => "\n \"" + x + "\""))); +var locKeys = mod.GetType("PersistentWorkAreas.LocKeys")?.GetFields(BindingFlags.Public | BindingFlags.Static) + .Where(x => x.IsLiteral).ToDictionary(x => x.Name, x => (string)x.GetRawConstantValue()!) ?? new Dictionary(); +var untranslated = locKeys.Values.Where(x => !enUS.ContainsKey(x)).ToArray(); +Check(locKeys.Count > 0 && untranslated.Length == 0, "Every LocKeys constant has enUS text" + string.Concat(untranslated.Select(x => "\n " + x))); +var usedKeys = new HashSet(locKeys.Values); +foreach (var file in Directory.EnumerateFiles(packaging, "*.blueprint.json", SearchOption.AllDirectories)) +{ + using var blueprint = JsonDocument.Parse(File.ReadAllText(file)); + usedKeys.UnionWith(BlueprintLocKeys(blueprint.RootElement)); +} +var unused = enUS.Keys.Where(x => !usedKeys.Contains(x)).ToArray(); +Check(unused.Length == 0, "Every enUS key is used by LocKeys or a key-binding blueprint" + string.Concat(unused.Select(x => "\n " + x))); +bool TakesLoc(Type type) => type.GetConstructors().Single().GetParameters().Any(x => x.ParameterType.FullName == "Timberborn.Localization.ILoc"); +Check(TakesLoc(service) && TakesLoc(fragment), "Panel and clear button look text up through the game's ILoc"); +Check(locKeys.TryGetValue("ClearAll", out var clearAllKey) && enUS.TryGetValue(clearAllKey, out var clearAll) && + clearAll.Contains("{0}") && string.Format(clearAll, 3) == clearAll.Replace("{0}", "3"), "Clear-all label formats the pin count"); Console.WriteLine($"{checks} checks passed. Unity rendering and multiplayer playtesting still require the game."); +// A minimal RFC 4180 reader: quoted fields may hold commas, doubled quotes and line breaks. +static List ReadCsv(string text) +{ + var rows = new List(); + var row = new List(); + var field = new StringBuilder(); + bool quoted = false; + for (int i = 0; i < text.Length; i++) + { + char c = text[i]; + if (quoted) + { + if (c != '"') field.Append(c); + else if (i + 1 < text.Length && text[i + 1] == '"') { field.Append('"'); i++; } + else quoted = false; + } + else if (c == '"') quoted = true; + else if (c == ',') { row.Add(field.ToString()); field.Clear(); } + else if (c == '\n') { row.Add(field.ToString()); field.Clear(); rows.Add(row.ToArray()); row.Clear(); } + else if (c != '\r') field.Append(c); + } + if (field.Length > 0 || row.Count > 0) { row.Add(field.ToString()); rows.Add(row.ToArray()); } + return rows; +} + +static IEnumerable BlueprintLocKeys(JsonElement element) => element.ValueKind switch +{ + JsonValueKind.Object => element.EnumerateObject().SelectMany(x => + x.Name == "LocKey" && x.Value.ValueKind == JsonValueKind.String ? new[] { x.Value.GetString()! } : BlueprintLocKeys(x.Value)), + JsonValueKind.Array => element.EnumerateArray().SelectMany(BlueprintLocKeys), + _ => Enumerable.Empty() +}; + sealed class EqualBuilding { public override bool Equals(object obj) => obj is EqualBuilding; From 3ce9d01eaa3adaeccf6bf33cbda919704f8686cc Mon Sep 17 00:00:00 2001 From: Kyler Ramsey Date: Tue, 22 Sep 2026 05:10:17 -0700 Subject: [PATCH 2/2] PWA2: guard the clear-button label and tighten the text checks Review follow-ups for the ILoc change. WorkAreaService.Notify formats "Clear pinned areas ({0})" through ILoc.T, which calls string.Format with no try/catch. Notify also runs from OnDeleted, inside the game's EntityDeletedEvent, and EventBus.Post does not catch handler exceptions. A translation file with a broken {0} would therefore throw out of entity deletion on that one machine. The label now comes from ClearLabel(), which catches FormatException, logs it and falls back to the unformatted text. The shipped enUS text formats cleanly, so nothing changes for players. Checks: - The DLL string check is now an allow-list. Every #US literal must be a key in the enUS CSV (or the key-binding id), a PersistentWorkAreas* element name, a type or member name of the game outline types the mod reflects on, or log text. A new or re-cased English label such as "WORK AREA" or "On" now fails, and so does a misspelled raw key. - Every LocKeys constant must also be used by the code, which also stops the literal scan from passing on an empty heap. - The IL must load the ClearAll key and call ILoc.T with it inside a try that catches FormatException. - 44 -> 45 checks. The README now gives the CSV's path both in the package and in the repository, and says to keep {0} in a translation of the clear label. Co-Authored-By: Claude Opus 5 --- README.md | 2 +- source/WorkAreaService.cs | 12 +++++++- tests/Program.cs | 61 +++++++++++++++++++++++++++++---------- 3 files changed, 58 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index fd5eb79..7b76442 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ No extra dependency is required. Keep your existing BeaverBuddies Stability Fork The currently selected building still uses its normal game outline. Clearing pins restores normal selection behavior; deselecting that building then hides its normal outline. Pins reset on map exit, loading, and multiplayer resynchronization. They are not saved. Deleting a pinned building removes its pin. -The mod supports navigation-based working areas. It does not pin district road coloring, every kind of effect-radius overlay, or building-placement ghosts. UI text is currently English. All of it is in `Localizations/enUS_PersistentWorkAreas.csv`, so a translation is one more file with the same keys, named for the game's language code (for example `deDE_PersistentWorkAreas.csv`). +The mod supports navigation-based working areas. It does not pin district road coloring, every kind of effect-radius overlay, or building-placement ghosts. UI text is currently English. The panel, button and key-binding text is all in `version-1.1/Localizations/enUS_PersistentWorkAreas.csv` (in the repository, under `packaging/PersistentWorkAreas/`), so a translation is one more file in that folder with the same keys, named for the game's language code (for example `deDE_PersistentWorkAreas.csv`). Keep `{0}` in the clear-button text: it becomes the pin count. ## Compatibility and validation diff --git a/source/WorkAreaService.cs b/source/WorkAreaService.cs index 628469c..a7f88d9 100644 --- a/source/WorkAreaService.cs +++ b/source/WorkAreaService.cs @@ -206,11 +206,21 @@ private void Notify() { if (_clearButton != null) { - _clearButton.text = _loc.T(LocKeys.ClearAll, Count); + _clearButton.text = ClearLabel(); _clearButton.style.display = Count > 0 ? DisplayStyle.Flex : DisplayStyle.None; } Changed?.Invoke(); } + // Notify also runs inside the game's EntityDeletedEvent, so a translation with a broken {0} must not throw. + private string ClearLabel() + { + try { return _loc.T(LocKeys.ClearAll, Count); } + catch (FormatException error) + { + Debug.LogError("[PersistentWorkAreas] Bad " + LocKeys.ClearAll + " text: " + error.Message); + return _loc.T(LocKeys.ClearAll); + } + } private void ReleaseOutline() { var outline = _outline; diff --git a/tests/Program.cs b/tests/Program.cs index 21cc271..2a499ae 100644 --- a/tests/Program.cs +++ b/tests/Program.cs @@ -106,24 +106,29 @@ void Method(Type type, string name, Type returns, params Type[] args) // The game's CSV validator rejects a space between a comma and a quote. string unquoted = locText.Replace("\"\"", ""); Check(locRowsValid && !unquoted.Contains(", \"") && !unquoted.Contains("\" ,"), "Localization CSV has the game's ID,Text,Comment layout with unique keys"); -var literals = new List(); -using (var modImage = new PEReader(File.OpenRead(modPath))) -{ - var metadata = modImage.GetMetadataReader(); - if (metadata.GetHeapSize(HeapIndex.UserString) > 1) - for (var handle = MetadataTokens.UserStringHandle(1); !handle.IsNil; handle = metadata.GetNextHandle(handle)) - literals.Add(metadata.GetUserString(handle)); -} -// The English the panel and button used to hard-code, plus every enUS text up to its first placeholder. -var english = new[] { "WORKING AREA", "Keep working area visible", "working-area outline visible", "Working-area pinning is unavailable", - "Pinned after deselection", "Click to pin this outline", "Clear pinned areas", "Remove all your pinned" } - .Concat(enUS.Values.Select(x => x.Split('{')[0].Trim()).Where(x => x.Length > 3)).ToArray(); -var hardCoded = literals.Where(x => x is "ON" or "OFF" || english.Any(x.Contains)).Distinct().ToArray(); +// Every string compiled into the mod must be a loc key, a VisualElement name, a name the outline +// reflects on, or log text. Anything else is hard-coded text a translation cannot reach. +using var modImage = new PEReader(File.OpenRead(modPath)); +var metadata = modImage.GetMetadataReader(); +var literals = new Dictionary(); +if (metadata.GetHeapSize(HeapIndex.UserString) > 1) + for (var handle = MetadataTokens.UserStringHandle(1); !handle.IsNil; handle = metadata.GetNextHandle(handle)) + if (metadata.GetUserString(handle) is { Length: > 0 } text) // the heap's zero padding reads as "" + literals.TryAdd(text, MetadataTokens.GetToken(handle)); +var clearKey = (string)service.GetField("ClearKey")!.GetRawConstantValue()!; +var reflected = new[] { drawer, calculator, bounds, layer }; +var reflectedNames = reflected.Select(x => x.FullName!).Concat(reflected.SelectMany(x => x.GetMembers( + BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly)).Select(x => x.Name)).ToHashSet(); +bool IsCode(string x) => x.StartsWith("PersistentWorkAreas.") ? x == clearKey || enUS.ContainsKey(x) + : x.StartsWith("[PersistentWorkAreas] ") || x.StartsWith(" loaded. ") // log text; Mod.cs splits its line around the version + || System.Text.RegularExpressions.Regex.IsMatch(x, "^PersistentWorkAreas[A-Z][A-Za-z]*$") || reflectedNames.Contains(x); +var hardCoded = literals.Keys.Where(x => !IsCode(x)).ToArray(); Check(hardCoded.Length == 0, "No hard-coded English UI text in the mod DLL" + string.Concat(hardCoded.Select(x => "\n \"" + x + "\""))); var locKeys = mod.GetType("PersistentWorkAreas.LocKeys")?.GetFields(BindingFlags.Public | BindingFlags.Static) .Where(x => x.IsLiteral).ToDictionary(x => x.Name, x => (string)x.GetRawConstantValue()!) ?? new Dictionary(); -var untranslated = locKeys.Values.Where(x => !enUS.ContainsKey(x)).ToArray(); -Check(locKeys.Count > 0 && untranslated.Length == 0, "Every LocKeys constant has enUS text" + string.Concat(untranslated.Select(x => "\n " + x))); +var untranslated = locKeys.Values.Where(x => !enUS.ContainsKey(x) || !literals.ContainsKey(x)) + .Select(x => x + (enUS.ContainsKey(x) ? " (never used by the code)" : " (no enUS text)")).ToArray(); +Check(locKeys.Count > 0 && untranslated.Length == 0, "Every LocKeys constant has enUS text and is used" + string.Concat(untranslated.Select(x => "\n " + x))); var usedKeys = new HashSet(locKeys.Values); foreach (var file in Directory.EnumerateFiles(packaging, "*.blueprint.json", SearchOption.AllDirectories)) { @@ -136,6 +141,32 @@ void Method(Type type, string name, Type returns, params Type[] args) Check(TakesLoc(service) && TakesLoc(fragment), "Panel and clear button look text up through the game's ILoc"); Check(locKeys.TryGetValue("ClearAll", out var clearAllKey) && enUS.TryGetValue(clearAllKey, out var clearAll) && clearAll.Contains("{0}") && string.Format(clearAll, 3) == clearAll.Replace("{0}", "3"), "Clear-all label formats the pin count"); +// In the IL: ldstr ClearAll, then within a few bytes callvirt ILoc.T, inside a try that catches FormatException, +// because Notify also runs in the game's EntityDeletedEvent and a translation with a broken {0} must not throw there. +string TypeRefName(EntityHandle handle) => handle.Kind == HandleKind.TypeReference + ? metadata.GetString(metadata.GetTypeReference((TypeReferenceHandle)handle).Namespace) + "." + metadata.GetString(metadata.GetTypeReference((TypeReferenceHandle)handle).Name) : ""; +var tOfInt = Enumerable.Range(1, metadata.GetTableRowCount(TableIndex.MethodSpec)).Select(MetadataTokens.MethodSpecificationHandle).Where(handle => +{ + var spec = metadata.GetMethodSpecification(handle); + if (spec.Method.Kind != HandleKind.MemberReference) return false; + var member = metadata.GetMemberReference((MemberReferenceHandle)spec.Method); + return metadata.GetString(member.Name) == "T" && TypeRefName(member.Parent) == "Timberborn.Localization.ILoc" + && metadata.GetBlobBytes(spec.Signature).SequenceEqual(new byte[] { 0x0A, 1, 0x08 }); // one generic argument: int +}).Select(x => MetadataTokens.GetToken(x)).ToArray(); +bool guardedCountLookup = false; +if (literals.TryGetValue(clearAllKey ?? "", out var clearAllToken)) + foreach (var body in metadata.MethodDefinitions.Select(x => metadata.GetMethodDefinition(x).RelativeVirtualAddress).Where(x => x != 0).Select(modImage.GetMethodBody)) + { + var il = body.GetILBytes(); + for (int i = 0; i + 5 <= il.Length; i++) + { + if (il[i] != 0x72 || BitConverter.ToInt32(il, i + 1) != clearAllToken) continue; + int call = Enumerable.Range(i + 5, 12).FirstOrDefault(j => j + 5 <= il.Length && il[j] == 0x6F && tOfInt.Contains(BitConverter.ToInt32(il, j + 1)), -1); + guardedCountLookup |= call > 0 && body.ExceptionRegions.Any(r => r.Kind == ExceptionRegionKind.Catch && + TypeRefName(r.CatchType) == "System.FormatException" && r.TryOffset <= i && call < r.TryOffset + r.TryLength); + } + } +Check(guardedCountLookup, "Clear-all label is looked up with the pin count, guarded against a bad translation"); Console.WriteLine($"{checks} checks passed. Unity rendering and multiplayer playtesting still require the game."); // A minimal RFC 4180 reader: quoted fields may hold commas, doubled quotes and line breaks.