diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 5907c7b..abed684 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -8,12 +8,14 @@ body: label: Package description: > Which package is affected? ResXLocalization.Core is the shared engine both UI packages depend on; - pick it when the problem shows in a lookup made from code rather than from markup. "Not sure" is a - real answer and is fine. + pick it when the problem shows in a lookup made from code rather than from markup. Pick + ResXLocalization.MessageFormat when the problem shows only after Localizer.Current.UseMessageFormat(). + "Not sure" is a real answer and is fine. options: - ResXLocalization.Avalonia - ResXLocalization.WPF - ResXLocalization.Core + - ResXLocalization.MessageFormat - More than one, or not sure validations: required: true diff --git a/AGENTS.md b/AGENTS.md index a0d3598..2a41825 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,21 +9,26 @@ together. ## What this is ResXLocalization is a .NET library that gives XAML applications type-safe `.resx` localization with live -language switching. It ships as two NuGet packages — `ResXLocalization.Avalonia` and `ResXLocalization.WPF` — -over one shared, UI-agnostic engine. Consumers keep the `.resx` files and editors they already have. +language switching. It ships as two UI packages — `ResXLocalization.Avalonia` and `ResXLocalization.WPF` — +over one shared, UI-agnostic engine, `ResXLocalization.Core`, plus the opt-in package +`ResXLocalization.MessageFormat`, which formats every localized text as ICU MessageFormat. Consumers keep +the `.resx` files and editors they already have. Two things separate it from plain `.resx`: -- **Compile-checked keys.** A source generator turns every eligible `.resx` into a `Keys` class of - `ResourceKey` fields, each carrying both its key name and the `ResourceManager` it belongs to. A renamed or - deleted resource becomes a build error instead of a runtime surprise. +- **Compile-checked keys.** A source generator turns every neutral `.resx`, with or without a `.Designer.cs`, + into a `Keys` class with its own `ResourceManager` property and one `ResourceKey` field per string + entry, each carrying both its key name and that `ResourceManager`. A renamed or deleted resource becomes a + build error instead of a runtime surprise. - **Live culture switching.** Assigning `Localizer.Current.CurrentCulture` re-resolves every `{l:Localize}` binding in place — no window reload, no view rebuild, no restart. Around those: three lookup modes (typed, scoped, and search-all across registered resource managers) over -.NET's own culture fallback chain, enum localization by naming convention, format arguments in code and in -XAML, a `!key!` failure text plus a `TranslationNotFound` event for missing translations, and Native AOT and -trimming support on the Avalonia side (WPF supports neither). +.NET's own culture fallback chain, enum localization by naming convention, format arguments in code +(`MessageArguments`) and in XAML (`` children of `{l:Localize}` and `{l:LocalizeEnum}`), one +replaceable message formatter for every lookup, a `!key!` failure text plus a `LookupFailed` event for +missing translations and formatting failures, and Native AOT and trimming support on the Avalonia side (WPF +supports neither). [`README.md`](README.md) is the user-facing version of the same story, with the quick start and the examples. @@ -31,12 +36,13 @@ trimming support on the Avalonia side (WPF supports neither). | Path | What it is | | --- | --- | -| `src/ResXLocalization.Core` | The UI-agnostic engine: `ILocalizer`, `Localizer`, `ResourceKey`, the events. Both UI packages depend on it, and one copy satisfies both | -| `src/ResXLocalization.SourceGenerators` | The incremental generator that emits the typed `…Keys` classes. `netstandard2.0`. Ships **inside** the UI packages as an analyzer; it is not a package of its own | +| `src/ResXLocalization.Core` | The UI-agnostic engine: `ILocalizer`, `Localizer`, `ResourceKey`, `MessageArguments`, the message formatter, the events. Both UI packages depend on it, and one copy satisfies both | +| `src/ResXLocalization.MessageFormat` | The opt-in ICU MessageFormat formatter, installed with `Localizer.Current.UseMessageFormat()`. Depends on Core and the `MessageFormat` library, not on a UI package | +| `src/ResXLocalization.SourceGenerators` | The incremental generator that emits the typed `…Keys` classes. It reads each `.resx` and the MSBuild resource name the build wiring passes for it, and needs no `.Designer.cs`. `netstandard2.0`. Ships **inside** the UI packages as an analyzer; it is not a package of its own | | `src/ResXLocalization.Avalonia` | The Avalonia markup extensions and converter, plus the packaged generator and resx wiring | | `src/ResXLocalization.WPF` | The same for WPF. Windows-only, no Native AOT | | `samples/` | Two runnable showcases, one per UI framework. Excluded from coverage | -| `tests/` | Four suites: Core (both frameworks), the generator, and one sample-test suite per UI framework | +| `tests/` | Five suites: Core and `tests/ResXLocalization.MessageFormat.Tests` (both on both frameworks), the generator, and one sample-test suite per UI framework | | `tests/package-consumption/` | Package-only consumers. The repository's `Directory.Build.*` deliberately does **not** apply there | | `build/` | The shared resx and packaging targets, and the DocFX configuration | | `scripts/` | Every check and workflow, as PowerShell 7 | @@ -103,8 +109,8 @@ change rendering rather than layout, are in `__wpftmp` name, and `_TargetAssemblyProjectName` carries the real one. The root `Directory.Build.props` resolves `_ConventionProjectName` from it, and every condition that has to hold in that pass tests that property rather than `MSBuildProjectName`. -- **Native AOT covers Core and Avalonia only.** WPF has no AOT support, and `src/Directory.Build.props` - excludes it from `IsAotCompatible` deliberately. +- **Native AOT covers Core, Avalonia and MessageFormat only.** WPF has no AOT support, and + `src/Directory.Build.props` excludes it from `IsAotCompatible` deliberately. - **The package consumers are outside everything.** `tests/package-consumption/` carries empty `Directory.Build.props` and `Directory.Build.targets` files that stop MSBuild's upward search, so those projects receive the library only from the packed packages. Do not add a project reference, a repository @@ -122,15 +128,15 @@ The .NET 8 SDK step needs an 8.0 SDK installed next to the pinned one. It exists more than their compiler - for example in WPF's temporary markup-compile pass, see the comment "WPF's temporary markup-compile pass" in `build/ResXLocalization.Resx.targets`. Nothing is trimmed on the just-in-time compiler, so **no test suite in this repository can see trimming -damage**. The AOT gate publishes a package-only consumer natively and runs it; that is the only check that -can. See [`docs/guides/native-aot.md`](docs/guides/native-aot.md). +damage**. The AOT gate publishes the package-only consumers `AvaloniaConsumer` and `MessageFormatConsumer` +natively and runs them; that is the only check that can. See [`docs/guides/native-aot.md`](docs/guides/native-aot.md). Invoke a reviewer only when its scope applies. Both are read-only by construction — see [`.agents/README.md`](.agents/README.md). ## Public API -The three runtime projects declare their public surface in `PublicAPI.Shipped.txt` and +The four runtime projects declare their public surface in `PublicAPI.Shipped.txt` and `PublicAPI.Unshipped.txt`. An undeclared public member is `RS0016`; a declared one that is gone is `RS0017`. Both are build errors. @@ -145,6 +151,26 @@ equivalent is analyzer release tracking in `AnalyzerReleases.*.md`. `Directory.Build.props`, the release date, promoting `Unshipped` to `Shipped`, and the tag are the maintainer's, at release time. +## Pending maintainer tasks for the release after 2.0.0 + +The package validation is set up for the 2.0.0 release: its baseline is 1.1.0, and +`ResXLocalization.MessageFormat`, which has no 1.1.0 version, is excluded from the baseline. When the +maintainer prepares the next release after 2.0.0 - a `` bump, a dated changelog section, or a +question about releasing - remind them of these steps, as part of `CONTRIBUTING.md`'s release step 3. Do +not do them yourself; they are the maintainer's, like the version. + +1. Set `PackageValidationBaselineVersion` in `src/Directory.Build.props` to `2.0.0`. +2. In the same file, remove `AND '$(_ConventionProjectName)' != 'ResXLocalization.MessageFormat'` from the + condition of the `PropertyGroup` that sets `PackageValidationBaselineVersion`, and remove the comment + about `ResXLocalization.MessageFormat` in it. Keep the group and the property: the condition becomes + `'$(_IsShippingPackage)' == 'true'`, so the MessageFormat package is validated against 2.0.0 like the + others. +3. Delete `CompatibilitySuppressions.xml` in `src/ResXLocalization.Core`, `src/ResXLocalization.Avalonia` + and `src/ResXLocalization.WPF`: they accept breaks against the 1.1.0 baseline only. Then run + `dotnet pack ResXLocalization.slnx -c Release` once to confirm that package validation passes without + them. +4. Remove this section from `AGENTS.md`. + ## Commits and branches [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) with a lowercase, imperative summary: diff --git a/CHANGELOG.md b/CHANGELOG.md index 38c74c3..8055b53 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -105,7 +105,6 @@ this project adheres to [Semantic Versioning](https://semver.org/). - **BREAKING:** Two neutral `.resx` files that produce the same keys class report `RXLGEN004` and generate neither class, instead of merging into one partial class. See the [migration guide](docs/guides/migration-2.0.md). - - **BREAKING:** `Localizer.RegisterResourceManager` throws `ArgumentException` naming the base name for a plain `ResourceManager` for which no resources exist under its base name, instead of registering it and letting every search-all lookup that reaches it throw `MissingManifestResourceException`. Fix the base diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ea9a04e..0f00a0d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,7 +19,7 @@ This project has a [Code of Conduct](CODE_OF_CONDUCT.md); by participating, you | You need | For | | --- | --- | | **.NET 10 SDK** | Everything. It is pinned in `global.json` | -| **.NET 8 SDK** | Running the Core tests on `net8.0`, and reproducing the minimum-SDK consumer checks | +| **.NET 8 SDK** | Running the Core and MessageFormat tests on `net8.0`, and reproducing the minimum-SDK consumer checks | | **PowerShell 7** (`pwsh`) | Every script in `scripts/`. They declare `#requires -Version 7.0` and stop on the first line under an older host | | **Windows** | The WPF projects, the WPF tests, and the full package and documentation build | | **A C++ toolchain** | The Native AOT gate only. MSVC and the Windows SDK on Windows; `clang` and `zlib1g-dev` on Linux | @@ -45,14 +45,14 @@ dotnet build ResXLocalization.NonWindows.slnf -c Release ``` ```shell -# Test. One command; dotnet test discovers the suites and every target framework, so the Core suite -# runs on net8.0 and net10.0 from here. +# Test. One command; dotnet test discovers the suites and every target framework, so the Core and +# MessageFormat suites run on net8.0 and net10.0 from here. dotnet test ResXLocalization.slnx -c Release # Windows dotnet test ResXLocalization.NonWindows.slnf -c Release # Linux/macOS, without the WPF suite ``` -There are four suites: the Core engine (on both target frameworks), the source generator, and one -sample-driven suite per UI framework. The Avalonia suite runs headless; the WPF suite drives a real +There are five suites: the Core engine and the ICU MessageFormat formatter (each on both target +frameworks), the source generator, and one sample-driven suite per UI framework. The Avalonia suite runs headless; the WPF suite drives a real dispatcher on its own thread and is Windows-only. ### One optional per-clone setting @@ -88,7 +88,7 @@ The script names them, with their trigger and their command, in its own summary | Run it when the change touches | Command | | --- | --- | | Resource lookup, culture fallback, satellite discovery, the generated keys, or the packaging that carries them | `pwsh -File scripts/verify-package-aot.ps1 -Pack` | -| What the packages contain, the `buildTransitive` wiring, the generated keys, or a dependency version | `pwsh -File scripts/pre-release-gate.ps1 -SkipNativeAot -SkipDocumentation`, which packs and then runs every consumer on the pinned SDK, on both of AvaloniaConsumer's target frameworks, and again on the .NET 8 SDK, on net8.0 | +| What the packages contain, the `buildTransitive` wiring, the generated keys, or a dependency version | `pwsh -File scripts/pre-release-gate.ps1 -SkipNativeAot -SkipDocumentation`, which packs and then runs every consumer on the pinned SDK, on both target frameworks of AvaloniaConsumer and MessageFormatConsumer, and again on the .NET 8 SDK, on net8.0 | **`pre-release-gate.ps1`** is everything CI checks that can honestly be checked on your machine, in CI's order, stopping at the first failure: the ignored-revision check, line endings, tidiness, a Release build, @@ -168,20 +168,20 @@ Anything that is not framework-specific belongs in `ResXLocalization.Core`, wher ## Native AOT -`ResXLocalization.Avalonia` and `ResXLocalization.Core` publish with `PublishAot=true` and produce no IL2xxx -or IL3xxx diagnostic, from anywhere. Keep it that way: no reflection over resources, no new suppressed IL +`ResXLocalization.Avalonia`, `ResXLocalization.Core` and `ResXLocalization.MessageFormat` publish with +`PublishAot=true` and produce no IL2xxx or IL3xxx diagnostic, from anywhere. Keep it that way: no reflection over resources, no new suppressed IL diagnostic, and no `[RequiresUnreferencedCode]` or `[RequiresDynamicCode]` on a public member. **Nothing is trimmed on the just-in-time compiler, so no test suite here can see trimming damage.** A satellite that is no longer loaded or a resource name that no longer resolves produces a binary that builds, -starts and answers wrongly. `scripts/verify-package-aot.ps1` publishes a package-only consumer natively and -**runs** it, asserting exact strings; that is the only check that can see it. +starts and answers wrongly. `scripts/verify-package-aot.ps1` publishes the package-only consumers +`AvaloniaConsumer` and `MessageFormatConsumer` natively and **runs** them, asserting exact strings; that is the only check that can see it. The WPF package is exempt — WPF does not support Native AOT. ## Public API -The three runtime projects track their public surface with +The four runtime projects track their public surface with [PublicApiAnalyzers](https://github.com/dotnet/roslyn/tree/main/src/RoslynAnalyzers/PublicApiAnalyzers). An undeclared public member is `RS0016` and a declared one that is gone is `RS0017` — both build errors here. diff --git a/PACKAGE_README.md b/PACKAGE_README.md index 2061dbd..e8f654a 100644 --- a/PACKAGE_README.md +++ b/PACKAGE_README.md @@ -10,12 +10,13 @@ you keep the `.resx` files and editors you already use, and get **compile-checke ## Highlights - ⚡ **Live, no-reload language switching** - set one property and every bound string updates in place. -- 🔒 **Type-safe, compile-checked keys** - a source generator turns every `.resx` into strongly-typed keys, so a renamed or deleted resource becomes a **compile error**, not a runtime surprise. +- 🔒 **Type-safe, compile-checked keys** - a source generator turns every neutral `.resx` into strongly-typed keys, with or without a `.Designer.cs`, so a renamed or deleted resource becomes a **compile error**, not a runtime surprise. - 📦 **Zero configuration** - install the package and build; the source generator and MSBuild wiring are included. - 🗂️ **First-class multiple `.resx` support** - look up by typed key, scope to one file, or search across all registered files. - 🔤 **Enum localization built in** - localize enum members by naming convention. -- 🧮 **Format arguments** - `Get(key, args…)` formats in the active culture; in XAML, give `{l:Localize}` `` children with constant or bound values. -- 🩺 **Missing-translation diagnostics** - a visible, configurable `!key!` failure text plus a `TranslationNotFound` event. +- 🧮 **Format arguments on the binding** - in XAML, give `{l:Localize}` and `{l:LocalizeEnum}` `` children with constant or bound values, so enum labels take arguments too; in code, pass `MessageArguments.FromValues(…)` to `Localizer.Current.Get`. +- 🔢 **ICU MessageFormat, opt-in** - `plural` and `select` messages such as `1 file` / `5 files`, in code and in XAML, with the separate package `ResXLocalization.MessageFormat`. +- 🩺 **Lookup-failure diagnostics** - a visible, configurable `!key!` failure text plus a `LookupFailed` event, for a missing translation and for a value that cannot be formatted. - 🌐 **Language-picker ready** - `GetAvailableCultures()` discovers the cultures your app actually ships. - 🚀 **Native AOT & trim clean** (Avalonia package) - no reflection over your resources. @@ -36,27 +37,35 @@ source generator and the same MSBuild wiring, all of which arrive with the packa `ResXLocalization.Core` comes along as a dependency, and one copy of it satisfies both UI packages in an application that uses them together. +For messages whose wording depends on the arguments - `plural` and `select`, such as `1 file` / +`5 files` - add the opt-in package `ResXLocalization.MessageFormat` and call +`Localizer.Current.UseMessageFormat()` to format every localized text as ICU MessageFormat. + ## Requirements - An app targeting **.NET 8** or later, built with the **.NET 8 SDK or later**. - For **Avalonia**: **Avalonia 12**. For **WPF**: **Windows**. -- `.resx` files with the standard sibling `*.Designer.cs` accessor, as generated by Visual Studio's - or Rider's classic resx tooling (SDK-only `GenerateResxSource` accessors are not eligible). +- `.resx` files. A `.Designer.cs` accessor is not required: every neutral `.resx` gets typed keys, + with or without one. ## In three steps **1. Add a neutral `.resx` and a satellite file per culture** - `Resources/AppStrings.resx` and `Resources/AppStrings.de.resx`, with the same key names. -**2. Build.** The source generator emits a typed key class per eligible `.resx`, named -`Keys`, in the same namespace as your resource accessor. Only string entries become keys. +**2. Build.** The source generator emits a typed key class per neutral `.resx`, named +`Keys` - by default in the namespace of the folder the `.resx` sits in. Only string entries +become keys. ```csharp // - for AppStrings.resx: public static partial class AppStringsKeys { - public static readonly ResourceKey Greeting = new("Greeting", AppStrings.ResourceManager); - public static readonly ResourceKey WindowTitle = new("WindowTitle", AppStrings.ResourceManager); + // The resource manager of AppStrings.resx - the one instance every key of this class uses. + public static ResourceManager ResourceManager { get; } = new("YourApp.Resources.AppStrings", typeof(AppStringsKeys).Assembly); + + public static readonly ResourceKey Greeting = new("Greeting", ResourceManager); + public static readonly ResourceKey WindowTitle = new("WindowTitle", ResourceManager); } ``` @@ -89,16 +98,17 @@ xmlns:l="clr-namespace:RentADeveloper.ResXLocalization.WPF;assembly=ResXLocaliza A **typed** key carries its own `ResourceManager`, and a **scoped** lookup is given one, so neither needs any registration. Registration exists for the **search-all** lookups - `{l:Localize Greeting}`, `{l:LocalizeEnum}`, and `Get("Greeting")` - which search the registered managers in registration -order: +order. Register the generated `Keys.ResourceManager`, the instance the typed keys use: ```csharp -Localizer.Current.RegisterResourceManager(AppStrings.ResourceManager); +Localizer.Current.RegisterResourceManager(AppStringsKeys.ResourceManager); ``` ## Documentation -The full documentation - lookup modes and fallback, enum localization, dynamic format arguments, -Native AOT publishing, and which `.resx` files qualify for generated keys - is at +The full documentation - lookup modes and fallback, registering resource files, enum localization, +dynamic format arguments, ICU MessageFormat, design time and previewers, Native AOT publishing, which +`.resx` files qualify for generated keys, and migrating to 2.0 - is at [rent-a-developer.github.io/ResXLocalization](https://rent-a-developer.github.io/ResXLocalization/), which also hosts the complete [API reference](https://rent-a-developer.github.io/ResXLocalization/api/). The [project README](https://github.com/rent-a-developer/ResXLocalization#readme) has the quick start diff --git a/README.md b/README.md index a52fc97..be565de 100644 --- a/README.md +++ b/README.md @@ -44,13 +44,14 @@ Localizer.Current.CurrentCulture = new CultureInfo("de"); ## Highlights - ⚡ **Live, no-reload language switching** - set one property and every bound string updates in place. No window reload, no view rebuild, no restart. -- 🔒 **Type-safe, compile-checked keys** - a source generator turns every `.resx` into strongly-typed keys with full IntelliSense. +- 🔒 **Type-safe, compile-checked keys** - a source generator turns every neutral `.resx` into strongly-typed keys with full IntelliSense, with or without a `.Designer.cs`. - 📦 **Zero configuration** - install one NuGet package and build; typed keys are generated automatically, nothing else to set up. - 🚀 **Native AOT & trim clean (Avalonia)** - no reflection over your resources; publishes with `PublishAot=true` out of the box. *(WPF is Windows-only and does not support Native AOT.)* - 🗂️ **First-class multiple `.resx`** - look up by **typed key**, **scope** to one file, or **search across all** registered files in a defined order. - 🔤 **Enum localization built in** - localize enum members by naming convention, in item templates and as bound values. -- 🧮 **Format arguments** - `Get(key, args…)` formats the translation in the active culture; in XAML, give `{l:Localize}` `` children with constant or bound values. -- 🩺 **Missing-translation diagnostics** - a visible `!key!` failure text (configurable) plus a `TranslationNotFound` event for logging and coverage reports. +- 🧮 **Format arguments on the binding** - in XAML, give `{l:Localize}` and `{l:LocalizeEnum}` `` children with constant or bound values, so enum labels take arguments too; in code, pass `MessageArguments.FromValues(…)` to `Localizer.Current.Get`. +- 🔢 **ICU MessageFormat, opt-in** - `plural` and `select` messages such as `1 file` / `5 files`, in code and in XAML, with the separate package `ResXLocalization.MessageFormat` - see [ICU MessageFormat](#icu-messageformat-opt-in). +- 🩺 **Lookup-failure diagnostics** - a visible `!key!` failure text (configurable) plus a `LookupFailed` event for logging and coverage reports, for a missing translation and for a value that cannot be formatted. - 🌐 **Language-picker ready** - `GetAvailableCultures()` discovers the cultures your app actually ships. - 🧩 **MVVM-friendly** - an injectable `ILocalizer` service with `INotifyPropertyChanged`, markup extensions for XAML, and a clean code-behind API. - 🪶 **Leak-safe** - discarded controls stay collectable (Avalonia uses weak events; WPF binds to the singleton through WPF's own weak binding-target references). @@ -61,9 +62,8 @@ Localizer.Current.CurrentCulture = new CultureInfo("de"); - An app targeting **.NET 8** or later, built with the **.NET 8 SDK or later**. - For **Avalonia**: **Avalonia 12**. For **WPF**: **Windows**. -- **`.resx`** resource files with the standard sibling `*.Designer.cs` accessor, as generated by - Visual Studio's or Rider's classic resx tooling. SDK-only `GenerateResxSource` accessors are not - eligible - see [Generated keys](docs/reference/generated-keys.md). +- **`.resx`** resource files. A `.Designer.cs` accessor is not required: every neutral `.resx` gets + typed keys, with or without one - see [Generated keys](docs/reference/generated-keys.md). ## Installation @@ -123,7 +123,7 @@ Add a `.resx` file the normal way - for example `Resources/AppStrings.resx` (you ### 2. Let the generator create typed keys -On every build, the source generator inspects each eligible `.resx` and emits a typed key class named `Keys` in the same namespace as your resource file. For `AppStrings.resx` you get: +On every build, the source generator inspects every neutral `.resx` (not the culture satellites such as `AppStrings.de.resx`) and emits a typed key class named `Keys`, by default in the namespace of the folder the `.resx` sits in. No `.Designer.cs` is needed. For `AppStrings.resx` you get: ```csharp // @@ -131,13 +131,16 @@ namespace YourApp.Resources; public static partial class AppStringsKeys { - public static readonly ResourceKey Greeting = new("Greeting", AppStrings.ResourceManager); - public static readonly ResourceKey WindowTitle = new("WindowTitle", AppStrings.ResourceManager); + // The resource manager of AppStrings.resx - the one instance every key of this class uses. + public static ResourceManager ResourceManager { get; } = new("YourApp.Resources.AppStrings", typeof(AppStringsKeys).Assembly); + + public static readonly ResourceKey Greeting = new("Greeting", ResourceManager); + public static readonly ResourceKey WindowTitle = new("WindowTitle", ResourceManager); // …one ResourceKey per string entry, sorted, with sanitized member names. } ``` -Each `ResourceKey` carries **both** the key name and the `ResourceManager` it belongs to - that is what makes typed lookups direct and collision-free. Which files qualify, what becomes a key, and the two generator diagnostics are in [Generated keys](docs/reference/generated-keys.md). +Each `ResourceKey` carries **both** the key name and the `ResourceManager` it belongs to - that is what makes typed lookups direct and collision-free. Which files qualify, how the namespace is chosen, what becomes a key, and the generator diagnostics are in [Generated keys](docs/reference/generated-keys.md). ### 3. Register your resources at startup @@ -150,7 +153,7 @@ using System.Globalization; using RentADeveloper.ResXLocalization; using YourApp.Resources; -Localizer.Current.RegisterResourceManager(AppStrings.ResourceManager); +Localizer.Current.RegisterResourceManager(AppStringsKeys.ResourceManager); Localizer.Current.CurrentCulture = new CultureInfo("en"); ``` @@ -167,17 +170,35 @@ public partial class App : Application protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); - Localizer.Current.RegisterResourceManager(AppStrings.ResourceManager); + Localizer.Current.RegisterResourceManager(AppStringsKeys.ResourceManager); Localizer.Current.CurrentCulture = new CultureInfo("en"); } } ``` +Register the generated `AppStringsKeys.ResourceManager`: it is the instance the typed keys use. Registration is only needed for **search-all** lookups; typed and scoped lookups need no registration. > [!TIP] > In Avalonia, put the registration (and the initial `CurrentCulture`) inside **`BuildAvaloniaApp()`** rather than `Main`. `BuildAvaloniaApp` runs at runtime *and* under the XAML previewer, so search-all lookups like `{l:Localize Greeting}` resolve at design time too instead of showing the `!Greeting!` failure text. +> [!TIP] +> In WPF, the designer does not call `App.OnStartup`, so search-all lookups show the failure text there. Register in a **`[ModuleInitializer]`** of the application assembly instead: it runs at runtime before `Main` *and* in the designer. See [Registering resource files](docs/guides/registration.md#wpf). +> +> ```csharp +> using System.Runtime.CompilerServices; +> +> internal static class ResourceRegistration +> { +> [ModuleInitializer] +> internal static void Register() +> { +> Localizer.Current.CurrentCulture = new CultureInfo("en"); +> Localizer.Current.RegisterResourceManager(AppStringsKeys.ResourceManager); +> } +> } +> ``` + ### 4. Use it in XAML Add the namespaces and bind with the `{l:Localize}` markup extension. @@ -226,28 +247,95 @@ Every `{l:Localize}` binding re-resolves **immediately**. No reload, no flicker. Three lookup modes, one fallback chain: ```csharp -Localizer.Current.Get(AppStringsKeys.Greeting); // typed - compile-checked, one file -Localizer.Current.Get("Greeting", AppStrings.ResourceManager); // scoped - this key, in this file -Localizer.Current.Get("Greeting"); // search-all - registered files, in order +Localizer.Current.Get(AppStringsKeys.Greeting); // typed - compile-checked, one file +Localizer.Current.Get("Greeting", resourceManager: AppStringsKeys.ResourceManager); // scoped - this key, in this file +Localizer.Current.Get("Greeting"); // search-all - registered files, in order ``` Fallback is .NET's own: a missing `de-DE` entry falls back to `de`, then to the neutral resources. A key that cannot be resolved anywhere renders the configurable `!key!` failure text and raises -`TranslationNotFound`. Because fallback runs first, a key that resolves from a parent or neutral +`LookupFailed`. Because fallback runs first, a key that resolves from a parent or neutral value is not reported as missing. Enum members are localized by naming convention - one `.resx` entry per member, named -`Enum__` - and composite-format resources take their arguments from -`Get(key, args…)` in code or from `` children of `{l:Localize}` in XAML. +`Enum__`. Composite-format resources take their arguments in code from +`Localizer.Current.Get(key, MessageArguments.FromValues(…))` - or as named arguments from +`MessageArguments.FromTuples`, `FromDictionary` and `FromObject` - and in XAML from `` +children of `{l:Localize}` and `{l:LocalizeEnum}`. + +For messages whose wording depends on the arguments, such as `1 file` / `5 files`, the opt-in package +`ResXLocalization.MessageFormat` adds ICU MessageFormat - see [ICU MessageFormat](#icu-messageformat-opt-in). + +## ICU MessageFormat (opt-in) + +`string.Format` cannot change a message's wording by its arguments: `1 file deleted`, but +`5 files deleted`. The opt-in package `ResXLocalization.MessageFormat` formats every localized text as +[ICU MessageFormat](https://unicode-org.github.io/icu/userguide/format_parse/messages/) instead, whose +`plural` and `select` choose the wording by the arguments. Add it next to your UI package: + +```shell +dotnet add package ResXLocalization.MessageFormat +``` + +Then install the ICU formatter once, at startup - in Avalonia in `BuildAvaloniaApp()`, in WPF in +`App.OnStartup` and, for the WPF designer, in the `[ModuleInitializer]` from step 3 of the quick start: + +```csharp +using RentADeveloper.ResXLocalization.MessageFormat; + +Localizer.Current.UseMessageFormat(); +``` + +Write the resource values in ICU syntax: + +| Key | `AppStrings.resx` (English) | `AppStrings.de.resx` (German) | +| -------------- | ---------------------------------------------------------------- | -------------------------------------------------------------------- | +| `FilesDeleted` | `{Count, plural, one {# file deleted} other {# files deleted}}` | `{Count, plural, one {# Datei gelöscht} other {# Dateien gelöscht}}` | + +and pass named arguments - in code with `MessageArguments`, in XAML with named `` children: + +```csharp +Localizer.Current.Get(AppStringsKeys.FilesDeleted, MessageArguments.FromTuples(("Count", 1))); // "1 file deleted" +Localizer.Current.Get(AppStringsKeys.FilesDeleted, MessageArguments.FromObject(new { Count = 5 })); // "5 files deleted" +``` + +```xml + + + + + + + +``` + +`{l:LocalizeEnum}` takes the same `` children, so an enum label can be a `plural` or +`select` message too. Like the Avalonia package, `ResXLocalization.MessageFormat` is Native AOT and +trim clean. + +> [!IMPORTANT] +> After `UseMessageFormat()`, **every** resolved resource value is parsed as an ICU message, also a value +> looked up without arguments: `It''s ready` renders `It's ready`, a literal `{` or `}` is ICU syntax, and +> composite-format spellings such as `{0:N0}` or `{{literal}}` render the failure text and raise +> `Localizer.Current.LookupFailed`. Review your resource values before you opt in - +> [Migrating resource values](docs/guides/message-format.md#migrating-resource-values) shows what to search +> for and how to rewrite it. + +Plural categories per language, `select`, how arguments reach ICU, the format culture and number and +date styles are in [ICU MessageFormat](docs/guides/message-format.md). ## Documentation | Page | What it covers | | --- | --- | | [Lookup modes and culture fallback](docs/guides/lookup-and-fallback.md) | Typed, scoped and search-all lookups, registration order, the fallback chain, missing-translation diagnostics, dependency injection, subscription lifetime | +| [Registering resource files](docs/guides/registration.md) | What to register for search-all lookups, where - including the WPF designer and class libraries - dependency injection, resources from other assemblies | | [Localizing enum values](docs/guides/enums.md) | The naming convention, item templates, `LocalizeEnumConverter`, custom prefixes and scoping | -| [Dynamic format arguments](docs/guides/format-arguments.md) | `Get(key, args…)` and `` children of `{l:Localize}` | +| [Dynamic format arguments](docs/guides/format-arguments.md) | `Get(key, MessageArguments.FromValues(…))`, the `MessageArguments` factory, and `` children of `{l:Localize}` with constant or bound values, optionally named | +| [ICU MessageFormat](docs/guides/message-format.md) | The opt-in `ResXLocalization.MessageFormat` package: `plural` and `select` through `Localizer.Current.UseMessageFormat()`, argument mapping, format culture, styles, and migrating resource values to ICU syntax | +| [Design time and previewers](docs/guides/design-time.md) | `DesignTime.Culture` for the preview language, the culture a previewer uses without it, search-all lookups and ICU in the WPF designer, and what to expect in Rider's WPF previewer | | [Native AOT and trimming](docs/guides/native-aot.md) | What to declare, how to publish, and what a trimming failure looks like | +| [Migrating to 2.0](docs/guides/migration-2.0.md) | Each breaking change of 2.0, with what to do | | [Generated keys](docs/reference/generated-keys.md) | Which `.resx` files qualify, what becomes a key, the generator diagnostics, the Roslyn floor | | [API reference](https://rent-a-developer.github.io/ResXLocalization/) | Every public type and member | @@ -256,13 +344,23 @@ Enum members are localized by naming convention - one `.resx` entry per member, **A string shows up as `!key!`.** The key could not be resolved in the current culture's complete fallback chain. Check that the key exists in the neutral `.resx`, and - for search-all lookups like `{l:Localize Greeting}` or `{l:LocalizeEnum}` - that the resource manager was registered with -`RegisterResourceManager`. Subscribe to `TranslationNotFound` to log every miss. See +`Localizer.Current.RegisterResourceManager(Keys.ResourceManager)`. Subscribe to +`Localizer.Current.LookupFailed` to log every miss. See [Lookup modes and culture fallback](docs/guides/lookup-and-fallback.md). -**No typed `…Keys` class is generated.** The neutral file's name must be dot-free and a classic -`.Designer.cs` accessor must sit in the same folder; SDK `GenerateResxSource` output does not -qualify. `RXLGEN001` identifies malformed `.resx` XML, `RXLGEN002` a missing accessor. See -[Generated keys](docs/reference/generated-keys.md). +**No typed `…Keys` class is generated.** Every neutral `.resx` produces a `Keys` class, +with or without a `.Designer.cs`; culture satellites such as `AppStrings.de.resx` produce none. A +designer is not required, and there is no `RXLGEN002`. Check the generator warnings: `RXLGEN001` +reports malformed `.resx` XML, `RXLGEN003` a `.resx` whose MSBuild resource name did not reach the +generator, and `RXLGEN004` two neutral `.resx` files that would produce the same keys class - neither +class is generated then. See [Generated keys](docs/reference/generated-keys.md). + +**A string does not switch language.** It is probably read through a designer property such as +`AppStrings.Greeting`, in code or as `{x:Static res:AppStrings.Greeting}`. A designer property reads +in `CultureInfo.CurrentUICulture`, which the localizer never changes, so it does not follow +`Localizer.Current.CurrentCulture`. Read the string through a typed key, `Localizer.Current.Get` or +`{l:Localize}` instead. See the warning in +[Lookup modes and culture fallback](docs/guides/lookup-and-fallback.md#registration-is-only-for-search-all). **A translation is right when you run it and wrong after publishing.** List the cultures you ship in `SatelliteResourceLanguages`, or the satellite assemblies are not published. See @@ -274,13 +372,15 @@ normally. ## The sample applications -Two complete, runnable showcases exercise **every** feature and combination - a scrolling window with a live language `ComboBox`: +Two complete, runnable showcases, one per UI framework - a scrolling window with a live language `ComboBox` and one card each for typed keys, search-all and scoped lookups, enum values in item templates and through `LocalizeEnumConverter`, `` children, a key bound from the view model, and lookups from code-behind: ```shell dotnet run --project samples/ResXLocalization.Avalonia.Sample dotnet run --project samples/ResXLocalization.WPF.Sample # Windows only ``` +The samples use the default formatter; for ICU MessageFormat, see [ICU MessageFormat](#icu-messageformat-opt-in). + ## Building from source You need the **.NET 10 SDK** (see `global.json`); the produced packages target .NET 8 and .NET 10. diff --git a/docs/guides/format-arguments.md b/docs/guides/format-arguments.md index a36984e..1a749ec 100644 --- a/docs/guides/format-arguments.md +++ b/docs/guides/format-arguments.md @@ -147,7 +147,7 @@ package finds a named argument under its name too, so `File {0} of {Total}` work - **Per-argument format specifiers belong in the resource string** — `{0:N0} people invited` — where a translator can adjust them per language. - **No arguments, no formatting.** Under the default formatter, a lookup without arguments returns the - resource value unchanged - in code `Localizer.Current.Get(key, MessageArguments.FromValues())` or + resource value unchanged - in code `Localizer.Current.Get(key, MessageArguments.Empty)` or `Get(key, null)`, like `Get(key)`, and in XAML a `{l:Localize}` without `` children. A resource value containing a literal `{` or `}` keeps working without `{{` escaping. The failure text of a missing key is never formatted. diff --git a/docs/guides/migration-2.0.md b/docs/guides/migration-2.0.md index 7523b84..5e5a046 100644 --- a/docs/guides/migration-2.0.md +++ b/docs/guides/migration-2.0.md @@ -1,172 +1,53 @@ # Migrating to 2.0 -2.0 is a major version; each section below is one breaking change, with what to do. The last section -is a design-time change that needs no action. +2.0 is a major version; each section below is one breaking change, with what to do, starting with the +changes that affect the most applications. Two sections need no action: the optional section on the enum +key prefix, and the last section, a design-time change. -## A formatting failure returns the failure text instead of throwing +## `LocalizeArgs` is replaced by `` -A resource value that cannot be formatted with the supplied arguments - `Broken {0`, or -`File {0} of {1}` with one argument - no longer throws `FormatException` from -`Localizer.Current.Get(key, args)` and its scoped and typed siblings. The lookup returns the failure -text (by default `!key!`) and raises `ILocalizer.LookupFailed` with -`LookupFailureReason.MessageFormatFailed`. Code that caught `FormatException` subscribes to the event -instead. +The attached properties `LocalizeArgs.Arg0`...`Arg8` are removed from both packages. Format arguments +are `` children of `{l:Localize}`, each with a constant or bound `Value` and an optional +`Name`. A localized text with arguments is written in element syntax. Before: -```csharp -try -{ - text = Localizer.Current.Get(AppStringsKeys.FilesCopied, copied); -} -catch (FormatException exception) -{ - logger.LogWarning(exception, "Broken translation"); -} -``` - -After: - -```csharp -Localizer.Current.LookupFailed += (_, args) => - logger.LogWarning(args.Failure.Exception, "Broken translation {Key} in {Culture}", args.Failure.Key, args.Failure.Culture); - -text = Localizer.Current.Get(AppStringsKeys.FilesCopied, copied); +```xml + ``` -## A formatting failure in XAML renders the failure text - -`{l:Localize}` with arguments whose resource value cannot be formatted renders the -failure text, in both frameworks, and raises `LookupFailed`. In 1.x, Avalonia reported a binding -error and kept the previous text, and WPF showed an empty text. - -Before (1.x): an Avalonia binding error, or an empty WPF `TextBlock`. - After: ```xml - - - + + - -``` - -## An empty arguments array no longer formats - -`Localizer.Current.Get(key, args)` with an empty array (from 2.0, `Get(key, MessageArguments.FromValues())`) returns the resource value unformatted, exactly -like `Get(key)`: `{{x}}` stays `{{x}}`, and a value containing `{0}` no longer throws. - -Before: - -```csharp -// Resource "Template" = "Literal {{braces}} for {0}" -Localizer.Current.Get("Template", Array.Empty()); // 1.x: FormatException -``` - -After: - -```csharp -Localizer.Current.Get("Template", MessageArguments.FromValues()); // "Literal {{braces}} for {0}" -``` - -## Custom `ILocalizer` implementations have new members - -A custom `ILocalizer` implementation must implement: - -- `ILocalizer.LookupFailed`, replacing `TranslationNotFound` (see below); -- `ILocalizer.MessageFormatter`; -- `ILocalizer.RefreshTriggeringRevision` - advance it and raise `PropertyChanged` on every change that - can change a lookup's result; from 2.0 the XAML bindings re-resolve on it, not on `CurrentCulture`; -- `ILocalizer.Get(string key, MessageArguments? arguments = null, ResourceManager? resourceManager = null)`, - the one entry point every lookup goes through, together with the other two `Get` overloads and - `EnumKeyBuilder` (see - [A custom `ILocalizer` implements three `Get` overloads](#a-custom-ilocalizer-implements-three-get-overloads-and-enumkeybuilder)). - -It also replaces `MissingTranslationFormat` with `LookupFailureTextBuilder` (see below), raises -`LookupFailed` and builds the failure text for both `LookupFailureReason`s. - -Before: - -```csharp -public sealed class MyLocalizer : ILocalizer -{ - public event EventHandler? TranslationNotFound; - public string MissingTranslationFormat { get; set; } = "!{0}!"; - // ... -} -``` - -After: - -```csharp -public sealed class MyLocalizer : ILocalizer -{ - public event EventHandler? LookupFailed; - public IMessageFormatter MessageFormatter { get; set; } = StringFormatMessageFormatter.Instance; - public int RefreshTriggeringRevision { get; private set; } - public Func LookupFailureTextBuilder { get; set; } = failure => $"!{failure.Key}!"; - - public string Get(string key, MessageArguments? arguments = null, ResourceManager? resourceManager = null) => - /* resolve, then MessageFormatter.Format(value, arguments, CurrentCulture); - on a failure raise LookupFailed, then return LookupFailureTextBuilder(failure) */; - // ... -} ``` -## `MissingTranslationFormat` is replaced by `LookupFailureTextBuilder` - -`ILocalizer.MissingTranslationFormat`, a composite format string, is replaced by -`ILocalizer.LookupFailureTextBuilder`, a `Func`. It produces the failure text for -a missing translation and, new in 2.0, for a formatting failure; `LookupFailure.Reason` tells them -apart. The compiler reports every use of the old property; code that read the format string calls the -function instead. The `ArgumentException` for a malformed format no longer exists. The documentation -calls the text the "failure text" instead of the "sentinel". - -Before: - -```csharp -Localizer.Current.MissingTranslationFormat = "[{0}]"; -``` - -After: - -```csharp -Localizer.Current.LookupFailureTextBuilder = failure => $"[{failure.Key}]"; -``` - -See [Lookup modes and culture fallback](lookup-and-fallback.md#failure-text) for more examples. - -## `TranslationNotFound` is replaced by `LookupFailed` +## `LocalizeExtension.ResourceKey` is replaced by `Key` -`ILocalizer.TranslationNotFound` and `TranslationNotFoundEventArgs` are replaced by -`ILocalizer.LookupFailed` and `LookupFailedEventArgs`. The new event reports every failed lookup - a key -that no resource file contains, and, new in 2.0, a value that cannot be formatted. Its -`LookupFailedEventArgs.Failure` is a `LookupFailure`, the same value `LookupFailureTextBuilder` -receives; `Failure.Reason` tells the two cases apart. To keep logging only missing translations, check -the reason. +`LocalizeExtension.ResourceKey` is removed. `Key` takes a `string` or a `ResourceKey`; a `ResourceKey` +resolves through its own resource manager and ignores `ResourceManager`. Code that read +`LocalizeExtension.Key` as a `string` reads an `object?`. A constructor argument or a `Key` that is +neither a `string` nor a `ResourceKey` throws an `InvalidOperationException` when the view loads; +before, it produced an empty key. Before: -```csharp -Localizer.Current.TranslationNotFound += (_, args) => - logger.LogWarning("No translation for {Key} in {Culture}", args.Key, args.Culture); +```xml + ``` After: -```csharp -Localizer.Current.LookupFailed += (_, args) => -{ - if (args.Failure.Reason == LookupFailureReason.TranslationNotFound) - { - logger.LogWarning("No translation for {Key} in {Culture}", args.Failure.Key, args.Failure.Culture); - } -}; +```xml + + ``` ## Format arguments are built with `MessageArguments` @@ -225,93 +106,79 @@ Localizer.Current.Get(sortOrder, keyPrefix: "Display_"); Localizer.Current.Get(sortOrder, resourceManager: rm, keyPrefix: "Display_"); ``` -## `null` no longer throws for a manager or a key prefix +## Optional: set the enum key prefix once -A `null` resource manager means search-all, and a `null` key prefix means the default convention of -`ILocalizer.EnumKeyBuilder`. In 1.x both threw `ArgumentNullException`. This applies in code and in -XAML: `LocalizeEnumExtension.KeyPrefix` and `LocalizeEnumConverter.KeyPrefix` are `string?` and default -to `null`, and `KeyPrefix="{x:Null}"` no longer throws. +Not a break. An application that passes the same prefix on every enum lookup can make it the default +of `ILocalizer.EnumKeyBuilder` instead, for code and XAML alike. Before: ```csharp -Localizer.Current.Get("Key", (ResourceManager)null!); // 1.x: ArgumentNullException -Localizer.Current.Get(sortOrder, (string)null!); // 1.x: ArgumentNullException +Localizer.Current.Get(sortOrder, "MyPrefix_"); +``` + +```xml + ``` After: ```csharp -Localizer.Current.Get("Key", resourceManager: null); // search-all -Localizer.Current.Get(sortOrder, keyPrefix: null); // the EnumKeyBuilder's default, Enum_ -``` +Localizer.Current.EnumKeyBuilder = static (value, keyPrefix) => + (keyPrefix ?? "MyPrefix_") + value.GetType().Name + "_" + value; -## Recompile assemblies that call `Get` +Localizer.Current.Get(sortOrder); +``` -Every 1.x `Get` signature is removed, including `Get(string)` and `Get(ResourceKey)`, whose calls still -compile unchanged against 2.0. An assembly compiled against 1.x throws `MissingMethodException` at the -first `Get` call until it is recompiled. +```xml + +``` -## A custom `ILocalizer` implements three `Get` overloads and `EnumKeyBuilder` +## `{l:LocalizeEnum}` takes its value from `Value` -A custom `ILocalizer` implementation replaces its `Get` overloads with exactly three, one per key kind, -and implements `EnumKeyBuilder`. +`{l:LocalizeEnum}` no longer reads the enum value from the target's `DataContext`; `Value` is required, +and a `{l:LocalizeEnum}` without it throws `InvalidOperationException` when the view loads. In an item +template, where the item is the `DataContext`, write `Value={Binding}`; for a view-model property, bind +it; for a fixed member, use `{x:Static}`. Before: -```csharp -public string Get(string key) => /* ... */; -public string Get(string key, ResourceManager resourceManager) => /* ... */; -public string Get(string key, params object?[] arguments) => /* ... */; -public string Get(string key, ResourceManager resourceManager, params object?[] arguments) => /* ... */; -public string Get(ResourceKey key) => /* ... */; -public string Get(ResourceKey key, params object?[] arguments) => /* ... */; -public string Get(Enum value, string keyPrefix = "Enum_") => /* ... */; -public string Get(Enum value, ResourceManager resourceManager, string keyPrefix = "Enum_") => /* ... */; +```xml + ``` After: -```csharp -public Func EnumKeyBuilder { get; set; } = - static (value, keyPrefix) => (keyPrefix ?? "Enum_") + value.GetType().Name + "_" + value; - -public string Get(string key, MessageArguments? arguments = null, ResourceManager? resourceManager = null) => - /* the one lookup; null arguments means none, a null manager means search-all */; - -public string Get(ResourceKey key, MessageArguments? arguments = null) => - this.Get(key.Name, arguments, key.Manager); - -public string Get(Enum value, MessageArguments? arguments = null, ResourceManager? resourceManager = null, string? keyPrefix = null) => - this.Get(this.EnumKeyBuilder(value, keyPrefix), arguments, resourceManager); +```xml + + + ``` -## Optional: set the enum key prefix once +## `LocalizeEnumConverter` has a new child order -Not a break. An application that passes the same prefix on every enum lookup can make it the default -of `ILocalizer.EnumKeyBuilder` instead, for code and XAML alike. +`LocalizeEnumConverter` reads child 0 as the refresh trigger, `RefreshTriggeringRevision` of +`Localizer.Current`, child 1 as the enum value, and children from index 2 on as format arguments. A +`MultiBinding` in the old order - the enum first, then `CurrentCulture` - renders an empty string until +it is rewritten, and nothing reports it, so search for every use of `LocalizeEnumConverter`. Extra +children that served only to re-trigger the conversion are now format arguments; remove them. Before: -```csharp -Localizer.Current.Get(sortOrder, "MyPrefix_"); -``` - ```xml - + + + + ``` After: -```csharp -Localizer.Current.EnumKeyBuilder = static (value, keyPrefix) => - (keyPrefix ?? "MyPrefix_") + value.GetType().Name + "_" + value; - -Localizer.Current.Get(sortOrder); -``` - ```xml - + + + + ``` ## Typed keys use the generated `ResourceManager` @@ -411,50 +278,120 @@ Localizer.Current.RegisterResourceManager(new ResourceManager("MyApp.Strngs", ty Localizer.Current.RegisterResourceManager(AppStringsKeys.ResourceManager); ``` -## `LocalizeArgs` is replaced by `` +## `TranslationNotFound` is replaced by `LookupFailed` -The attached properties `LocalizeArgs.Arg0`...`Arg8` are removed from both packages. Format arguments -are `` children of `{l:Localize}`, each with a constant or bound `Value` and an optional -`Name`. A localized text with arguments is written in element syntax. +`ILocalizer.TranslationNotFound` and `TranslationNotFoundEventArgs` are replaced by +`ILocalizer.LookupFailed` and `LookupFailedEventArgs`. The new event reports every failed lookup - a key +that no resource file contains, and, new in 2.0, a value that cannot be formatted. Its +`LookupFailedEventArgs.Failure` is a `LookupFailure`, the same value `LookupFailureTextBuilder` +receives; `Failure.Reason` tells the two cases apart. To keep logging only missing translations, check +the reason. Before: -```xml - +```csharp +Localizer.Current.TranslationNotFound += (_, args) => + logger.LogWarning("No translation for {Key} in {Culture}", args.Key, args.Culture); ``` After: -```xml - - - - - - - +```csharp +Localizer.Current.LookupFailed += (_, args) => +{ + if (args.Failure.Reason == LookupFailureReason.TranslationNotFound) + { + logger.LogWarning("No translation for {Key} in {Culture}", args.Failure.Key, args.Failure.Culture); + } +}; ``` -## `LocalizeExtension.ResourceKey` is replaced by `Key` +## `MissingTranslationFormat` is replaced by `LookupFailureTextBuilder` -`LocalizeExtension.ResourceKey` is removed. `Key` takes a `string` or a `ResourceKey`; a `ResourceKey` -resolves through its own resource manager and ignores `ResourceManager`. Code that read -`LocalizeExtension.Key` as a `string` reads an `object?`. A constructor argument or a `Key` that is -neither a `string` nor a `ResourceKey` throws an `InvalidOperationException` when the view loads; -before, it produced an empty key. +`ILocalizer.MissingTranslationFormat`, a composite format string, is replaced by +`ILocalizer.LookupFailureTextBuilder`, a `Func`. It produces the failure text for +a missing translation and, new in 2.0, for a formatting failure; `LookupFailure.Reason` tells them +apart. The compiler reports every use of the old property; code that read the format string calls the +function instead. The `ArgumentException` for a malformed format no longer exists. The documentation +calls the text the "failure text" instead of the "sentinel". + +Before: + +```csharp +Localizer.Current.MissingTranslationFormat = "[{0}]"; +``` + +After: + +```csharp +Localizer.Current.LookupFailureTextBuilder = failure => $"[{failure.Key}]"; +``` + +See [Lookup modes and culture fallback](lookup-and-fallback.md#failure-text) for more examples. + +## A formatting failure returns the failure text instead of throwing + +A resource value that cannot be formatted with the supplied arguments - `Broken {0`, or +`File {0} of {1}` with one argument - no longer throws `FormatException` from +`Localizer.Current.Get(key, args)` and its scoped and typed siblings. The lookup returns the failure +text (by default `!key!`) and raises `ILocalizer.LookupFailed` with +`LookupFailureReason.MessageFormatFailed`. Code that caught `FormatException` subscribes to the event +instead and checks `LookupFailure.Reason`, because the event reports missing translations too. + +Before: + +```csharp +try +{ + text = Localizer.Current.Get(AppStringsKeys.FilesCopied, copied); +} +catch (FormatException exception) +{ + logger.LogWarning(exception, "Broken translation"); +} +``` + +After: + +```csharp +Localizer.Current.LookupFailed += (_, args) => +{ + if (args.Failure.Reason == LookupFailureReason.MessageFormatFailed) + { + logger.LogWarning(args.Failure.Exception, "Broken translation {Key} in {Culture}", args.Failure.Key, args.Failure.Culture); + } +}; + +text = Localizer.Current.Get(AppStringsKeys.FilesCopied, MessageArguments.FromValues(copied)); +``` + +## A formatting failure in XAML renders the failure text + +`{l:Localize}` with arguments whose resource value cannot be formatted renders the +failure text, in both frameworks, and raises `LookupFailed`. In 1.x, Avalonia reported a binding +error and kept the previous text, and WPF showed an empty text. Before: ```xml - + + + ``` After: ```xml - - + + + + + + + + + ``` ## Avalonia: arguments in a style setter or a resource are formatted @@ -487,51 +424,143 @@ After: ``` -## `{l:LocalizeEnum}` takes its value from `Value` +## An empty arguments array no longer formats -`{l:LocalizeEnum}` no longer reads the enum value from the target's `DataContext`; `Value` is required, -and a `{l:LocalizeEnum}` without it throws `InvalidOperationException` when the view loads. In an item -template, where the item is the `DataContext`, write `Value={Binding}`; for a view-model property, bind -it; for a fixed member, use `{x:Static}`. +`Localizer.Current.Get(key, args)` with an empty array (from 2.0, `Get(key, MessageArguments.Empty)`) returns the resource value unformatted, exactly +like `Get(key)`: `{{x}}` stays `{{x}}`, and a value containing `{0}` no longer throws. Before: -```xml - +```csharp +// Resource "Template" = "Literal {{braces}} for {0}" +Localizer.Current.Get("Template", Array.Empty()); // 1.x: FormatException ``` After: -```xml - - - +```csharp +Localizer.Current.Get("Template", MessageArguments.Empty); // "Literal {{braces}} for {0}" ``` -## `LocalizeEnumConverter` has a new child order +## `null` no longer throws for a manager or a key prefix -`LocalizeEnumConverter` reads child 0 as the refresh trigger, `RefreshTriggeringRevision` of -`Localizer.Current`, child 1 as the enum value, and children from index 2 on as format arguments. A -`MultiBinding` in the old order - the enum first, then `CurrentCulture` - renders an empty string until -it is rewritten, and nothing reports it, so search for every use of `LocalizeEnumConverter`. Extra -children that served only to re-trigger the conversion are now format arguments; remove them. +A `null` resource manager means search-all, and a `null` key prefix means the default convention of +`ILocalizer.EnumKeyBuilder`. In 1.x both threw `ArgumentNullException`. This applies in code and in +XAML: `LocalizeEnumExtension.KeyPrefix` and `LocalizeEnumConverter.KeyPrefix` are `string?` and default +to `null`, and `KeyPrefix="{x:Null}"` no longer throws. Before: -```xml - - - - +```csharp +Localizer.Current.Get("Key", (ResourceManager)null!); // 1.x: ArgumentNullException +Localizer.Current.Get(sortOrder, (string)null!); // 1.x: ArgumentNullException ``` After: -```xml - - - - +```csharp +Localizer.Current.Get("Key", resourceManager: null); // search-all +Localizer.Current.Get(sortOrder, keyPrefix: null); // the EnumKeyBuilder's default, Enum_ +``` + +## Recompile assemblies that call `Get` + +Every 1.x `Get` signature is removed, including `Get(string)` and `Get(ResourceKey)`, whose calls still +compile unchanged against 2.0. An assembly compiled against 1.x throws `MissingMethodException` at the +first `Get` call until it is recompiled. + +Before: + +```text +MyLibrary.dll, compiled against 1.x, calls Localizer.Current.Get("Greeting") under 2.0 + -> MissingMethodException: Method not found: 'System.String RentADeveloper.ResXLocalization.ILocalizer.Get(System.String)'. +``` + +After: + +```text +MyLibrary.dll, recompiled against 2.0 without a source change, calls Localizer.Current.Get("Greeting") + -> the translation of "Greeting", as with 1.x +``` + +## Custom `ILocalizer` implementations have new members + +A custom `ILocalizer` implementation must implement: + +- `ILocalizer.LookupFailed`, replacing `TranslationNotFound` (see + [`TranslationNotFound` is replaced by `LookupFailed`](#translationnotfound-is-replaced-by-lookupfailed)); +- `ILocalizer.MessageFormatter`; +- `ILocalizer.RefreshTriggeringRevision` - advance it and raise `PropertyChanged` on every change that + can change a lookup's result; from 2.0 the XAML bindings re-resolve on it, not on `CurrentCulture`; +- `ILocalizer.Get(string key, MessageArguments? arguments = null, ResourceManager? resourceManager = null)`, + the one entry point every lookup goes through, together with the other two `Get` overloads and + `EnumKeyBuilder` (see + [A custom `ILocalizer` implements three `Get` overloads](#a-custom-ilocalizer-implements-three-get-overloads-and-enumkeybuilder)). + +It also replaces `MissingTranslationFormat` with `LookupFailureTextBuilder` (see +[`MissingTranslationFormat` is replaced by `LookupFailureTextBuilder`](#missingtranslationformat-is-replaced-by-lookupfailuretextbuilder)), raises +`LookupFailed` and builds the failure text for both `LookupFailureReason`s. + +Before: + +```csharp +public sealed class MyLocalizer : ILocalizer +{ + public event EventHandler? TranslationNotFound; + public string MissingTranslationFormat { get; set; } = "!{0}!"; + // ... +} +``` + +After: + +```csharp +public sealed class MyLocalizer : ILocalizer +{ + public event EventHandler? LookupFailed; + public IMessageFormatter MessageFormatter { get; set; } = StringFormatMessageFormatter.Instance; + public int RefreshTriggeringRevision { get; private set; } + public Func LookupFailureTextBuilder { get; set; } = failure => $"!{failure.Key}!"; + + public string Get(string key, MessageArguments? arguments = null, ResourceManager? resourceManager = null) => + /* resolve, then MessageFormatter.Format(value, arguments, CurrentCulture); + on a failure raise LookupFailed, then return LookupFailureTextBuilder(failure) */; + // ... +} +``` + +## A custom `ILocalizer` implements three `Get` overloads and `EnumKeyBuilder` + +A custom `ILocalizer` implementation replaces its `Get` overloads with exactly three, one per key kind, +and implements `EnumKeyBuilder`. + +Before: + +```csharp +public string Get(string key) => /* ... */; +public string Get(string key, ResourceManager resourceManager) => /* ... */; +public string Get(string key, params object?[] arguments) => /* ... */; +public string Get(string key, ResourceManager resourceManager, params object?[] arguments) => /* ... */; +public string Get(ResourceKey key) => /* ... */; +public string Get(ResourceKey key, params object?[] arguments) => /* ... */; +public string Get(Enum value, string keyPrefix = "Enum_") => /* ... */; +public string Get(Enum value, ResourceManager resourceManager, string keyPrefix = "Enum_") => /* ... */; +``` + +After: + +```csharp +public Func EnumKeyBuilder { get; set; } = + static (value, keyPrefix) => (keyPrefix ?? "Enum_") + value.GetType().Name + "_" + value; + +public string Get(string key, MessageArguments? arguments = null, ResourceManager? resourceManager = null) => + /* the one lookup; null arguments means none, a null manager means search-all */; + +public string Get(ResourceKey key, MessageArguments? arguments = null) => + this.Get(key.Name, arguments, key.Manager); + +public string Get(Enum value, MessageArguments? arguments = null, ResourceManager? resourceManager = null, string? keyPrefix = null) => + this.Get(this.EnumKeyBuilder(value, keyPrefix), arguments, resourceManager); ``` ## Rider's WPF previewer renders raw patterns (not a breaking change) diff --git a/tests/ResXLocalization.Avalonia.Sample.Tests/Resources/Catalog.resx b/tests/ResXLocalization.Avalonia.Sample.Tests/Resources/Catalog.resx index 3487780..7e60028 100644 --- a/tests/ResXLocalization.Avalonia.Sample.Tests/Resources/Catalog.resx +++ b/tests/ResXLocalization.Avalonia.Sample.Tests/Resources/Catalog.resx @@ -1,8 +1,8 @@