diff --git a/CHANGELOG.md b/CHANGELOG.md index e95ae17..bec9902 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## [1.3.1] - 2026-10-28 + +### Added +- **Load Table Method**: every table class gets `LoadTable()`, which loads the table for the selected locale + without blocking and returns `Task` / `Task`. With **UniTask Members** there is also + `LoadTableAsync(CancellationToken)`. Asset table classes also get `LoadEntries()` / `LoadEntriesAsync`, which + load the table and the assets of all its entries. Off by default; turning it on never renames existing members. +- `LocalizedTables.LoadStringTable` / `LoadAssetTable` / `LoadAssetTableEntries` and + `LocalizedTablesUniTask.LoadStringTableAsync` / `LoadAssetTableAsync` / `LoadAssetTableEntriesAsync`. + ## [1.3.0] - 2026-10-28 ### Added diff --git a/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs b/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs index 503c293..b74a798 100644 --- a/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs +++ b/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs @@ -16,7 +16,7 @@ namespace Severnbli.LocalizationCodegen.Installer public static partial class Installer { public const string PackageId = "com.severnbli.localization-codegen"; - public const string Version = "1.3.0"; + public const string Version = "1.3.1"; static Installer() { diff --git a/README.md b/README.md index 3d7198b..76c8662 100644 --- a/README.md +++ b/README.md @@ -134,7 +134,7 @@ Add the scoped registry and the dependency to `Packages/manifest.json`: } ], "dependencies": { - "com.severnbli.localization-codegen": "1.3.0" + "com.severnbli.localization-codegen": "1.3.1" } } ``` @@ -318,6 +318,26 @@ title.StringChanged += text => label.text = text; Asset entries use `LocalizedSprite`, `LocalizedAudioClip`, `LocalizedAsset` and the other built-in localized asset types when available. Each access creates a new reference, so keep the one you subscribed to. +### Loading a table + +Enable **Load Table Method** to give every table class a `LoadTable()` method that loads the table for the selected locale without blocking: + +```csharp +public static Task LoadTable() => LocalizedTables.LoadStringTable(TableName); +``` + +```csharp +await Ui.LoadTable(); // e.g. behind a loading screen +label.text = Ui.HelloWorld; // the table is loaded, so this does not wait +``` + +- Asset table classes return `Task`. `LoadTable()` loads only the table; each asset loads when it is requested. +- Asset table classes also get `LoadEntries()`, which loads the table and the assets of all its entries, so no asset lookup waits afterwards. Assets of a table whose **Preload Asset Table** metadata is **No Preload** are not loaded. +- With [UniTask Members](#unitask) there are also `LoadTableAsync(CancellationToken)` and, for asset tables, `LoadEntriesAsync(CancellationToken)`, returning `UniTask` / `UniTask`. +- The table is loaded for the current locale. After a locale change, call it again to load the new locale's table. +- If Localization is not configured, the task completes with `null`. +- Turning the option on never renames existing members. A key named `LoadTable` or `LoadEntries` keeps its name, and the method gets a suffix (`LoadTable_2`). A table collection named `Task`, `StringTable` or `AssetTable` gets the `Table` class suffix. + ### UniTask Install [UniTask](https://github.com/Cysharp/UniTask) (`com.cysharp.unitask` 2.x) and enable **UniTask Members** to emit an awaitable variant next to every member: @@ -360,6 +380,7 @@ Open **Project Settings > Localization Codegen**, or **Window > Localization Cod | Smart Parameter Types | `Object` | `Object`, `Inferred` or [`Mapping`](#parameter-types). | | Naming Convention | `Keep` | `Keep` or `PascalCase`. | | Key Separators | empty | Characters that create nested classes, e.g. `/`. | +| Load Table Method | off | Emit [`LoadTable()`](#loading-a-table) on every table class, and `LoadEntries()` on asset table classes, to load without blocking. | | UniTask Members | off | Also emit [`…Async` members](#unitask) returning `UniTask`. Requires UniTask. | | Generate .asmdef | off | Write an assembly definition into the output folder, so the generated code gets its own assembly. | | Fail CI On Smart String Mismatch | off | Make `CheckBatch` fail on locale placeholder mismatches. | diff --git a/Unity-Package/Assets/root/CHANGELOG.md b/Unity-Package/Assets/root/CHANGELOG.md index e95ae17..bec9902 100644 --- a/Unity-Package/Assets/root/CHANGELOG.md +++ b/Unity-Package/Assets/root/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## [1.3.1] - 2026-10-28 + +### Added +- **Load Table Method**: every table class gets `LoadTable()`, which loads the table for the selected locale + without blocking and returns `Task` / `Task`. With **UniTask Members** there is also + `LoadTableAsync(CancellationToken)`. Asset table classes also get `LoadEntries()` / `LoadEntriesAsync`, which + load the table and the assets of all its entries. Off by default; turning it on never renames existing members. +- `LocalizedTables.LoadStringTable` / `LoadAssetTable` / `LoadAssetTableEntries` and + `LocalizedTablesUniTask.LoadStringTableAsync` / `LoadAssetTableAsync` / `LoadAssetTableEntriesAsync`. + ## [1.3.0] - 2026-10-28 ### Added diff --git a/Unity-Package/Assets/root/Editor/CodeEmitter.cs b/Unity-Package/Assets/root/Editor/CodeEmitter.cs index 0bbb365..fa7f592 100644 --- a/Unity-Package/Assets/root/Editor/CodeEmitter.cs +++ b/Unity-Package/Assets/root/Editor/CodeEmitter.cs @@ -17,6 +17,9 @@ internal static class CodeEmitter const string UniTaskType = "Cysharp.Threading.Tasks.UniTask"; const string CancellationTokenType = "System.Threading.CancellationToken"; const string DictionaryType = "System.Collections.Generic.Dictionary"; + const string TaskType = "System.Threading.Tasks.Task"; + const string StringTableType = "UnityEngine.Localization.Tables.StringTable"; + const string AssetTableType = "UnityEngine.Localization.Tables.AssetTable"; const string CancellationTokenName = "cancellationToken"; /// @@ -31,6 +34,12 @@ internal static class CodeEmitter "UniTask", "CancellationToken", "Dictionary", "IEnumerable" }; + /// + /// Types only the LoadTable methods refer to. They are reserved only while the option is on, so turning + /// it on is the only thing that can rename a table class with one of these names. + /// + static readonly string[] s_LoadTableTypeNames = { "Task", "StringTable", "AssetTable" }; + /// Assigns deterministic, collision-free class names to every model. public static void AssignClassNames(IList models, EmitOptions options) { @@ -74,6 +83,8 @@ static HashSet ReservedClassNames(IList models, EmitOptions // Generated files refer to types by their simple names, which a table class must not hide. set.UnionWith(s_ReferencedTypeNames); + if (options.LoadTable) + set.UnionWith(s_LoadTableTypeNames); foreach (var model in models) { foreach (var entry in model.Entries) @@ -106,6 +117,20 @@ public static string Emit(TableModel model, EmitOptions options) root.ClassName = className; AssignMemberNames(root, options); + // Claimed after every key's name, so turning the option on never renames an existing member. + if (options.LoadTable) + { + root.LoadTableName = CodegenText.Unique("LoadTable", root.MemberUsed); + if (model.IsAsset) + root.LoadEntriesName = CodegenText.Unique("LoadEntries", root.MemberUsed); + if (options.UniTask) + { + root.LoadTableAsyncName = CodegenText.Unique("LoadTableAsync", root.MemberUsed); + if (model.IsAsset) + root.LoadEntriesAsyncName = CodegenText.Unique("LoadEntriesAsync", root.MemberUsed); + } + } + var hasNamespace = !string.IsNullOrEmpty(options.Namespace); var rootLevel = hasNamespace ? 1 : 0; @@ -159,6 +184,10 @@ sealed class Scope public readonly Dictionary MemberNames = new Dictionary(); public readonly Dictionary AsyncMemberNames = new Dictionary(); public readonly HashSet MemberUsed = new HashSet(StringComparer.Ordinal); + public string LoadTableName; + public string LoadTableAsyncName; + public string LoadEntriesName; + public string LoadEntriesAsyncName; } static Scope BuildScopeTree(TableModel model, EmitOptions options) @@ -286,6 +315,9 @@ static void EmitScope(StringBuilder sb, Scope scope, TableModel model, EmitOptio { sb.Append(Indent(level + 1)).Append("public const string TableName = ") .Append(CodegenText.Literal(model.Name)).Append(";\n"); + + if (scope.LoadTableName != null) + EmitLoadTable(sb, scope, model, options, types, level + 1); } var orderedEntries = scope.Entries @@ -416,6 +448,52 @@ static void EmitAsyncEntry(StringBuilder sb, EntryModel entry, string name, Emit sb.Append(tokenName).Append(");\n"); } + /// + /// Emits LoadTable, LoadEntries for asset tables, and their UniTask variants. + /// + static void EmitLoadTable(StringBuilder sb, Scope scope, TableModel model, EmitOptions options, TypeNames types, int level) + { + var table = types.Name(model.IsAsset ? AssetTableType : StringTableType); + var kind = model.IsAsset ? "Asset" : "String"; + const string tableDoc = "Loads the table for the selected locale without blocking."; + const string entriesDoc = "Loads the table and the assets of all its entries for the selected locale without blocking."; + + EmitLoadMethod(sb, scope.LoadTableName, "Load" + kind + "Table", table, tableDoc, options, types, level); + if (scope.LoadEntriesName != null) + EmitLoadMethod(sb, scope.LoadEntriesName, "LoadAssetTableEntries", table, entriesDoc, options, types, level); + + if (scope.LoadTableAsyncName != null) + EmitLoadAsyncMethod(sb, scope.LoadTableAsyncName, "Load" + kind + "TableAsync", table, tableDoc, options, types, level); + if (scope.LoadEntriesAsyncName != null) + EmitLoadAsyncMethod(sb, scope.LoadEntriesAsyncName, "LoadAssetTableEntriesAsync", table, entriesDoc, options, types, level); + } + + static void EmitLoadMethod( + StringBuilder sb, string name, string runtimeMethod, string table, string doc, + EmitOptions options, TypeNames types, int level) + { + sb.Append('\n'); + if (options.XmlDocs) + sb.Append(Indent(level)).Append("/// ").Append(doc).Append("\n"); + sb.Append(Indent(level)).Append("public static ").Append(types.Name(TaskType)).Append('<').Append(table).Append("> ") + .Append(name).Append("() => ").Append(types.Name(EmitOptions.RuntimeTypeName)) + .Append('.').Append(runtimeMethod).Append("(TableName);\n"); + } + + static void EmitLoadAsyncMethod( + StringBuilder sb, string name, string runtimeMethod, string table, string doc, + EmitOptions options, TypeNames types, int level) + { + sb.Append('\n'); + if (options.XmlDocs) + sb.Append(Indent(level)).Append("/// ").Append(doc).Append("\n"); + sb.Append(Indent(level)).Append("public static ").Append(types.Name(UniTaskType)).Append('<').Append(table).Append("> ") + .Append(name).Append('(').Append(types.Name(CancellationTokenType)).Append(' ') + .Append(CancellationTokenName).Append(" = default)\n"); + sb.Append(Indent(level)).Append(" => ").Append(types.Name(EmitOptions.UniTaskRuntimeTypeName)) + .Append('.').Append(runtimeMethod).Append("(TableName, ").Append(CancellationTokenName).Append(");\n"); + } + static void EmitRefClass(StringBuilder sb, TableModel model, EmitOptions options, TypeNames types, int level) { var strict = !string.IsNullOrEmpty(options.KeySeparators); diff --git a/Unity-Package/Assets/root/Editor/CodeGenerator.cs b/Unity-Package/Assets/root/Editor/CodeGenerator.cs index 61b65ad..3df04a5 100644 --- a/Unity-Package/Assets/root/Editor/CodeGenerator.cs +++ b/Unity-Package/Assets/root/Editor/CodeGenerator.cs @@ -291,6 +291,7 @@ static EmitOptions BuildEmitOptions(CodegenSettings settings) GenerateAsmdef = settings.GenerateAsmdef, // Generated code must compile, so the option only takes effect when the add-on is compiled. UniTask = settings.GenerateUniTask && UniTaskSupport.IsAvailable, + LoadTable = settings.GenerateLoadTable, TypeExists = LoadedTypeExists }; } diff --git a/Unity-Package/Assets/root/Editor/CodegenModel.cs b/Unity-Package/Assets/root/Editor/CodegenModel.cs index c27be9e..d765b0d 100644 --- a/Unity-Package/Assets/root/Editor/CodegenModel.cs +++ b/Unity-Package/Assets/root/Editor/CodegenModel.cs @@ -98,6 +98,9 @@ internal sealed class EmitOptions /// When true, every member also gets a UniTask-returning ...Async variant. public bool UniTask; + /// When true, every table class gets a LoadTable method (and LoadTableAsync with UniTask). + public bool LoadTable; + /// /// Optional check whether a namespace (empty for the global namespace) contains a type with the given simple /// name. Generated files keep a type global:: qualified when its simple name could bind to another type. @@ -107,8 +110,8 @@ internal sealed class EmitOptions /// Stable signature of every option that can change output. public string Signature() { - // UniTask is appended only when enabled, so existing hashes (and files) stay valid after upgrading. - return (UniTask ? "unitask|" : "") + string.Join("|", new[] + // UniTask and LoadTable are added only when enabled, so existing hashes (and files) stay valid after upgrading. + return (LoadTable ? "loadtable|" : "") + (UniTask ? "unitask|" : "") + string.Join("|", new[] { Namespace ?? "", "usings", diff --git a/Unity-Package/Assets/root/Editor/CodegenSettings.cs b/Unity-Package/Assets/root/Editor/CodegenSettings.cs index ef5a58f..3432bd0 100644 --- a/Unity-Package/Assets/root/Editor/CodegenSettings.cs +++ b/Unity-Package/Assets/root/Editor/CodegenSettings.cs @@ -40,6 +40,9 @@ public sealed class CodegenSettings : ScriptableSingleton // Options introduced in 1.2.0. Off by default, so no migration is needed. [SerializeField] private bool generateUniTask; + // Options introduced in 1.3.1. Off by default, so no migration is needed. + [SerializeField] private bool generateLoadTable; + public bool SetupCompleted { get => setupCompleted; set => setupCompleted = value; } public string OutputFolder { get => outputFolder; set => outputFolder = value; } public string Namespace { get => generatedNamespace; set => generatedNamespace = value; } @@ -58,6 +61,7 @@ public sealed class CodegenSettings : ScriptableSingleton public bool GenerateAsmdef { get => generateAsmdef; set => generateAsmdef = value; } public bool FailOnSmartStringMismatch { get => failOnSmartStringMismatch; set => failOnSmartStringMismatch = value; } public bool GenerateUniTask { get => generateUniTask; set => generateUniTask = value; } + public bool GenerateLoadTable { get => generateLoadTable; set => generateLoadTable = value; } public SmartStringMode SmartStrings { diff --git a/Unity-Package/Assets/root/Editor/SettingsGui.cs b/Unity-Package/Assets/root/Editor/SettingsGui.cs index 9d68db2..3cb6760 100644 --- a/Unity-Package/Assets/root/Editor/SettingsGui.cs +++ b/Unity-Package/Assets/root/Editor/SettingsGui.cs @@ -42,6 +42,8 @@ internal static class Content "Emit a nested Ref class with LocalizedString / LocalizedAsset references that follow locale changes."); public static readonly GUIContent UniTask = new GUIContent("UniTask Members", "Also emit ...Async members that return UniTask and accept a CancellationToken. Requires UniTask (com.cysharp.unitask)."); + public static readonly GUIContent LoadTable = new GUIContent("Load Table Method", + "Emit LoadTable() on every table class and LoadEntries() on asset table classes to load without blocking (and ...Async variants with UniTask Members)."); public static readonly GUIContent XmlDocs = new GUIContent("XML Documentation", "Emit XML doc comments containing the default locale text."); @@ -360,6 +362,7 @@ static void DrawMembers(CodegenSettings s) s.GenerateReferences = value; } + s.GenerateLoadTable = EditorGUILayout.Toggle(Content.LoadTable, s.GenerateLoadTable); s.GenerateUniTask = EditorGUILayout.Toggle(Content.UniTask, s.GenerateUniTask); if (s.GenerateUniTask && !UniTaskSupport.IsAvailable) EditorGUILayout.HelpBox(UniTaskSupport.MissingMessage, MessageType.Warning); diff --git a/Unity-Package/Assets/root/README.md b/Unity-Package/Assets/root/README.md index 3d7198b..76c8662 100644 --- a/Unity-Package/Assets/root/README.md +++ b/Unity-Package/Assets/root/README.md @@ -134,7 +134,7 @@ Add the scoped registry and the dependency to `Packages/manifest.json`: } ], "dependencies": { - "com.severnbli.localization-codegen": "1.3.0" + "com.severnbli.localization-codegen": "1.3.1" } } ``` @@ -318,6 +318,26 @@ title.StringChanged += text => label.text = text; Asset entries use `LocalizedSprite`, `LocalizedAudioClip`, `LocalizedAsset` and the other built-in localized asset types when available. Each access creates a new reference, so keep the one you subscribed to. +### Loading a table + +Enable **Load Table Method** to give every table class a `LoadTable()` method that loads the table for the selected locale without blocking: + +```csharp +public static Task LoadTable() => LocalizedTables.LoadStringTable(TableName); +``` + +```csharp +await Ui.LoadTable(); // e.g. behind a loading screen +label.text = Ui.HelloWorld; // the table is loaded, so this does not wait +``` + +- Asset table classes return `Task`. `LoadTable()` loads only the table; each asset loads when it is requested. +- Asset table classes also get `LoadEntries()`, which loads the table and the assets of all its entries, so no asset lookup waits afterwards. Assets of a table whose **Preload Asset Table** metadata is **No Preload** are not loaded. +- With [UniTask Members](#unitask) there are also `LoadTableAsync(CancellationToken)` and, for asset tables, `LoadEntriesAsync(CancellationToken)`, returning `UniTask` / `UniTask`. +- The table is loaded for the current locale. After a locale change, call it again to load the new locale's table. +- If Localization is not configured, the task completes with `null`. +- Turning the option on never renames existing members. A key named `LoadTable` or `LoadEntries` keeps its name, and the method gets a suffix (`LoadTable_2`). A table collection named `Task`, `StringTable` or `AssetTable` gets the `Table` class suffix. + ### UniTask Install [UniTask](https://github.com/Cysharp/UniTask) (`com.cysharp.unitask` 2.x) and enable **UniTask Members** to emit an awaitable variant next to every member: @@ -360,6 +380,7 @@ Open **Project Settings > Localization Codegen**, or **Window > Localization Cod | Smart Parameter Types | `Object` | `Object`, `Inferred` or [`Mapping`](#parameter-types). | | Naming Convention | `Keep` | `Keep` or `PascalCase`. | | Key Separators | empty | Characters that create nested classes, e.g. `/`. | +| Load Table Method | off | Emit [`LoadTable()`](#loading-a-table) on every table class, and `LoadEntries()` on asset table classes, to load without blocking. | | UniTask Members | off | Also emit [`…Async` members](#unitask) returning `UniTask`. Requires UniTask. | | Generate .asmdef | off | Write an assembly definition into the output folder, so the generated code gets its own assembly. | | Fail CI On Smart String Mismatch | off | Make `CheckBatch` fail on locale placeholder mismatches. | diff --git a/Unity-Package/Assets/root/Runtime/LocalizedTables.cs b/Unity-Package/Assets/root/Runtime/LocalizedTables.cs index 2425750..42eaf7b 100644 --- a/Unity-Package/Assets/root/Runtime/LocalizedTables.cs +++ b/Unity-Package/Assets/root/Runtime/LocalizedTables.cs @@ -1,5 +1,6 @@ using System.Collections; using System.Collections.Generic; +using System.Threading.Tasks; using UnityEngine; using UnityEngine.Localization; using UnityEngine.Localization.Settings; @@ -142,6 +143,85 @@ public static AsyncOperationHandle GetAssetAsync(string table, string key) (TableReference)table, (TableEntryReference)key); } + /// + /// Loads a string table for the selected locale without blocking, so later lookups do not wait for it. + /// Completes with when Localization is not configured. + /// + public static Task LoadStringTable(string table) + { + if (!HasSettings()) + return Task.FromResult(null); + return ToTask(LocalizationSettings.StringDatabase.GetTableAsync(table)); + } + + /// + /// Loads an asset table for the selected locale without blocking. The assets of its entries are loaded + /// when they are requested. Completes with when Localization is not configured. + /// + public static Task LoadAssetTable(string table) + { + if (!HasSettings()) + return Task.FromResult(null); + return ToTask(LocalizationSettings.AssetDatabase.GetTableAsync(table)); + } + + /// + /// Loads an asset table and the assets of all its entries for the selected locale without blocking, so later + /// lookups do not wait. A table whose Preload Asset Table metadata is No Preload loads without its assets. + /// Completes with when Localization is not configured. + /// + public static async Task LoadAssetTableEntries(string table) + { + if (!HasSettings()) + return null; + + await ToTask(LocalizationSettings.AssetDatabase.PreloadTables(table)); + return await LoadAssetTable(table); + } + + /// + /// Awaits a Localization operation through its completion callback, which also works on WebGL. The result is + /// read inside the callback because Localization may release the operation right after it completes. + /// + static Task ToTask(AsyncOperationHandle handle) + { + if (!handle.IsValid()) + return Task.FromException(new System.InvalidOperationException("The localization operation is not valid.")); + + var source = new TaskCompletionSource(); + handle.Completed += completed => + { + if (completed.Status == AsyncOperationStatus.Succeeded) + source.TrySetResult(completed.Result); + else + source.TrySetException(Failure(completed.Status, completed.OperationException)); + }; + return source.Task; + } + + /// Untyped variant of . + static Task ToTask(AsyncOperationHandle handle) + { + if (!handle.IsValid()) + return Task.FromException(new System.InvalidOperationException("The localization operation is not valid.")); + + var source = new TaskCompletionSource(); + handle.Completed += completed => + { + if (completed.Status == AsyncOperationStatus.Succeeded) + source.TrySetResult(true); + else + source.TrySetException(Failure(completed.Status, completed.OperationException)); + }; + return source.Task; + } + + static System.Exception Failure(AsyncOperationStatus status, System.Exception exception) + { + return exception ?? new System.InvalidOperationException( + "The localization operation failed with status " + status + "."); + } + static object[] ToArray(IList values) { var array = new object[values.Count]; diff --git a/Unity-Package/Assets/root/Runtime/UniTask/LocalizedTablesUniTask.cs b/Unity-Package/Assets/root/Runtime/UniTask/LocalizedTablesUniTask.cs index 33daa9d..9a7014e 100644 --- a/Unity-Package/Assets/root/Runtime/UniTask/LocalizedTablesUniTask.cs +++ b/Unity-Package/Assets/root/Runtime/UniTask/LocalizedTablesUniTask.cs @@ -5,6 +5,7 @@ using UnityEngine.Localization; using UnityEngine.Localization.Settings; using UnityEngine.Localization.SmartFormat.PersistentVariables; +using UnityEngine.Localization.Tables; using UnityEngine.ResourceManagement.AsyncOperations; namespace Severnbli.LocalizationCodegen @@ -78,6 +79,82 @@ public static UniTask GetAssetAsync(string table, string key, Cancellation return ToUniTask(handle, cancellationToken); } + /// + /// Loads a string table for the selected locale without blocking, so later lookups do not wait for it. + /// Completes with when Localization is not configured. + /// + public static UniTask LoadStringTableAsync(string table, CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) + return UniTask.FromCanceled(cancellationToken); + if (!LocalizedTables.HasSettings()) + return UniTask.FromResult(null); + + return ToUniTask(LocalizationSettings.StringDatabase.GetTableAsync(table), cancellationToken); + } + + /// + /// Loads an asset table for the selected locale without blocking. The assets of its entries are loaded + /// when they are requested. Completes with when Localization is not configured. + /// + public static UniTask LoadAssetTableAsync(string table, CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) + return UniTask.FromCanceled(cancellationToken); + if (!LocalizedTables.HasSettings()) + return UniTask.FromResult(null); + + return ToUniTask(LocalizationSettings.AssetDatabase.GetTableAsync(table), cancellationToken); + } + + /// + /// Loads an asset table and the assets of all its entries for the selected locale without blocking, so later + /// lookups do not wait. A table whose Preload Asset Table metadata is No Preload loads without its assets. + /// Completes with when Localization is not configured. + /// + public static async UniTask LoadAssetTableEntriesAsync( + string table, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!LocalizedTables.HasSettings()) + return null; + + await ToUniTask(LocalizationSettings.AssetDatabase.PreloadTables(table), cancellationToken); + return await LoadAssetTableAsync(table, cancellationToken); + } + + /// Untyped variant of . + static UniTask ToUniTask(AsyncOperationHandle handle, CancellationToken cancellationToken) + { + if (!handle.IsValid()) + return UniTask.FromException(new InvalidOperationException("The localization operation is not valid.")); + if (handle.IsDone) + { + return handle.Status == AsyncOperationStatus.Succeeded + ? UniTask.CompletedTask + : UniTask.FromException(handle.OperationException ?? new InvalidOperationException( + "The localization operation failed with status " + handle.Status + ".")); + } + + var source = new UniTaskCompletionSource(); + var registration = cancellationToken.CanBeCanceled + ? cancellationToken.RegisterWithoutCaptureExecutionContext(() => source.TrySetCanceled(cancellationToken)) + : default; + + handle.Completed += completed => + { + registration.Dispose(); + if (completed.Status == AsyncOperationStatus.Succeeded) + source.TrySetResult(); + else + source.TrySetException(completed.OperationException ?? new InvalidOperationException( + "The localization operation failed with status " + completed.Status + ".")); + }; + + return source.Task; + } + /// /// Awaits a Localization operation. The result is read inside the completion callback because Localization /// releases the operation right after it completes. diff --git a/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs b/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs index c3ef2c7..2990520 100644 --- a/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs +++ b/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs @@ -579,5 +579,131 @@ public void KeySeparators_CreateNestedClasses() StringAssert.Contains("public static string Quit =>", output); StringAssert.Contains("public static string Title =>", output); } + + static EmitOptions LoadTableOptions(bool uniTask = false) + { + return new EmitOptions { Namespace = "Localization", LoadTable = true, UniTask = uniTask }; + } + + [Test] + public void LoadTable_IsOffByDefault() + { + var model = Model("Ui", false, (1L, "Title")); + var options = LegacyOptions(); + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.DoesNotContain("LoadTable", output); + StringAssert.DoesNotContain("System.Threading.Tasks", output); + } + + [Test] + public void LoadTable_StringTable() + { + var model = Model("Ui", false, (1L, "Title")); + var options = LoadTableOptions(); + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains( + " public const string TableName = \"Ui\";\n" + + "\n" + + " public static Task LoadTable() => LocalizedTables.LoadStringTable(TableName);\n", + output); + StringAssert.Contains("using System.Threading.Tasks;\n", output); + StringAssert.Contains("using UnityEngine.Localization.Tables;\n", output); + StringAssert.DoesNotContain("LoadTableAsync", output); + } + + [Test] + public void LoadTable_AssetTable() + { + var model = Model("Ui", true, (1L, "Logo")); + var options = LoadTableOptions(); + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains( + "public static Task LoadTable() => LocalizedTables.LoadAssetTable(TableName);\n", output); + StringAssert.Contains( + "public static Task LoadEntries() => LocalizedTables.LoadAssetTableEntries(TableName);\n", + output); + } + + [Test] + public void LoadEntries_OnlyOnAssetTables() + { + var model = Model("Ui", false, (1L, "Title")); + var options = LoadTableOptions(uniTask: true); + CodeEmitter.AssignClassNames(new[] { model }, options); + + StringAssert.DoesNotContain("LoadEntries", CodeEmitter.Emit(model, options)); + } + + [Test] + public void LoadEntries_WithUniTask_EmitsAsyncVariant() + { + var model = Model("Ui", true, (1L, "Logo")); + var options = LoadTableOptions(uniTask: true); + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains( + " public static UniTask LoadEntriesAsync(CancellationToken cancellationToken = default)\n" + + " => LocalizedTablesUniTask.LoadAssetTableEntriesAsync(TableName, cancellationToken);\n", + output); + } + + [Test] + public void LoadEntries_DoesNotRenameAKeyWithTheSameName() + { + var model = Model("Ui", true, (1L, "LoadEntries")); + var options = LoadTableOptions(); + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains(" LoadEntries => LocalizedTables.GetAsset<", output); + StringAssert.Contains("public static Task LoadEntries_2()", output); + } + + [Test] + public void LoadTable_WithUniTask_EmitsAsyncVariant() + { + var model = Model("Ui", false, (1L, "Title")); + var options = LoadTableOptions(uniTask: true); + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains( + " public static UniTask LoadTableAsync(CancellationToken cancellationToken = default)\n" + + " => LocalizedTablesUniTask.LoadStringTableAsync(TableName, cancellationToken);\n", + output); + } + + [Test] + public void LoadTable_DoesNotRenameAKeyWithTheSameName() + { + var model = Model("Ui", false, (1L, "LoadTable"), (2L, "LoadTableAsync")); + var options = LoadTableOptions(uniTask: true); + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains("public static string LoadTable =>", output); + StringAssert.Contains("public static string LoadTableAsync =>", output); + StringAssert.Contains("public static Task LoadTable_2()", output); + StringAssert.Contains("public static UniTask LoadTableAsync_3(", output); + } + + [Test] + public void LoadTable_ReservesItsTypeNamesOnlyWhenOn() + { + var off = Model("Task", false, (1L, "Title")); + CodeEmitter.AssignClassNames(new[] { off }, LegacyOptions()); + Assert.AreEqual("Task", off.ClassName); + + var on = Model("Task", false, (1L, "Title")); + CodeEmitter.AssignClassNames(new[] { on }, LoadTableOptions()); + Assert.AreEqual("TaskTable", on.ClassName); + } } } diff --git a/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs b/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs index a194485..8ade489 100644 --- a/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs +++ b/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs @@ -159,7 +159,8 @@ static IEnumerable Variants(bool uniTask) SmartStrings = SmartStringMode.MethodsAndRefs, SmartParamTypes = SmartParamTypeMode.Inferred, KeySeparators = "/", - UniTask = uniTask + UniTask = uniTask, + LoadTable = true } }; diff --git a/Unity-Package/Assets/root/package.json b/Unity-Package/Assets/root/package.json index 65458fa..f884520 100644 --- a/Unity-Package/Assets/root/package.json +++ b/Unity-Package/Assets/root/package.json @@ -10,7 +10,7 @@ "Generation", "Code Generation" ], - "version": "1.3.0", + "version": "1.3.1", "unity": "2021.3", "description": "C# classes and properties generator from Unity Localization tables", "documentationUrl": "https://github.com/Severnbli/localization-codegen/blob/main/README.md",