diff --git a/README.md b/README.md index 1ca34dc..c46da01 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. 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/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..a7f88d9 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,11 +206,21 @@ private void Notify() { if (_clearButton != null) { - _clearButton.text = "Clear pinned areas (" + 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 da77cc6..b48a374 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; @@ -30,7 +34,7 @@ void Check(bool ok, string name) // The checks above use only the mod's game-free sources, so CI runs them without arguments on a machine without // Timberborn. The rest need the installed game, the built mod DLL and its package folder. Add checks that need no game // files above this block, or CI never runs them: the count guard at the end cannot tell where a check was placed. -const int GameChecks = 27; // A full run fails if this stops matching the checks below. +const int GameChecks = 34; // A full run fails if this stops matching the checks below. int gameFreeChecks = checks; if (args.Length == 0) { @@ -107,11 +111,116 @@ 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"); +// 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) || !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)) +{ + 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"); +// 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"); if (checks - gameFreeChecks != GameChecks) throw new Exception($"FAIL: {checks - gameFreeChecks} checks ran after the game-free block but GameChecks says {GameChecks}; move any new check that needs no game files above that block, then set GameChecks to the number that still needs the game"); Console.WriteLine($"{checks} checks passed. Unity rendering and multiplayer playtesting still require the game."); return 0; +// 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;