diff --git a/.agents/references/reviews/ui-parity.md b/.agents/references/reviews/ui-parity.md index b40e4e7..08617dc 100644 --- a/.agents/references/reviews/ui-parity.md +++ b/.agents/references/reviews/ui-parity.md @@ -20,6 +20,8 @@ both, so anything that is not framework-specific belongs there rather than in on | Composite-format arguments | `Argument` children in `LocalizeExtension.Arguments` | `Argument` children in `LocalizeExtension.Arguments` | | Assigning a binding to `Argument.Value`, `LocalizeEnumExtension.Value` or `LocalizeExtension.Key` instead of applying it | `[AssignBinding]` on the property | the `XamlSetMarkupExtension` handler of `Argument`, of `LocalizeEnumExtension` and of `LocalizeExtension` | | An argument, enum-value or key binding that is a `MultiBinding` or a `PriorityBinding` | accepted | rejected by `ProvideValue`: WPF's `MultiBinding` accepts only plain `Binding` children | +| Select the previewer's language | `DesignTime.Culture`, an attached property on `AvaloniaObject`; design mode from `Design.IsDesignMode` | `DesignTime.Culture`, an attached property on `DependencyObject`; design mode from the internal `DesignMode.IsInDesignMode` | +| A designer that supplies the target property as a CLR property (Rider's WPF previewer) | no fallback: the Avalonia previewer evaluates bindings | deliberate difference: `LocalizeExtension` and `LocalizeEnumExtension` return the lookup without arguments as a string, before validation, when `DesignMode.ShouldReturnDesignTimeText` is true | Where the frameworks genuinely differ, the difference is expected to be **local and explained**: `LocalizeExtension` and `LocalizeEnumExtension` build their `MultiBinding` through diff --git a/CHANGELOG.md b/CHANGELOG.md index c087ba1..38c74c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,12 @@ this project adheres to [Semantic Versioning](https://semver.org/). `Localizer.Current.UseMessageFormat()`, which parses every resolved value as an ICU message, with or without arguments, optionally with a configured `MessageFormatter` of the `MessageFormat` library. See [ICU MessageFormat](docs/guides/message-format.md). +- `DesignTime.Culture`, an attached property in both UI packages that selects the language of XAML + previewers (``). It sets `Localizer.Current.CurrentCulture` inside + a previewer and has no effect at run time. See [Design time and previewers](docs/guides/design-time.md). +- A workaround for a defect in Rider's WPF XAML previewer (RIDER-143207): localized strings, which + rendered nothing there, now render their raw resource pattern under the default formatter, for example + `{0} people invited`. See [Design time and previewers](docs/guides/design-time.md). ### Changed diff --git a/docs/guides/design-time.md b/docs/guides/design-time.md new file mode 100644 index 0000000..8eeeffd --- /dev/null +++ b/docs/guides/design-time.md @@ -0,0 +1,204 @@ +# Design time and previewers + +XAML previewers show localized strings like the running application does: the Avalonia previewer and +the Visual Studio WPF designer evaluate `{l:Localize}` and `{l:LocalizeEnum}` as live bindings. This +page covers how to choose the language a previewer shows, what a previewer needs to resolve search-all +lookups, and what to expect in Rider's WPF previewer. + +## Choose the preview language: `DesignTime.Culture` + +Set the attached property `DesignTime.Culture` on the root element of a view to preview it in another +language, without changing initialization code or the machine's language: + +**Avalonia:** + +```xml + + + +``` + +**WPF:** + +```xml + + + +``` + +`xmlns:l` is the same namespace import that `{l:Localize}` uses. + +- **Process-wide.** Inside a previewer, the property assigns `Localizer.Current.CurrentCulture`. Strings + that a view model looks up in code, such as `Localizer.Current.Get(AppStringsKeys.Greeting)`, therefore + agree with the XAML. +- **No run-time effect.** Outside a previewer, setting the property only stores the value; the culture of + `Localizer.Current` stays as it is. Nothing has to be hidden with `mc:Ignorable`. +- **Re-renders on edit.** Changing the value, for example from `de` to `en`, re-renders the preview in the + new language. +- **Removing the attribute keeps the language.** When you delete `l:DesignTime.Culture`, nothing assigns + the culture, so the previewer keeps showing the last language it was set to. To go back just close the preview + and re-open it. +- **Typing is safe.** An empty value and a name that `CultureInfo` rejects, such as a half-typed one, leave + the culture unchanged; nothing throws. + +## The culture a previewer uses without it + +Without `DesignTime.Culture`, a previewer uses the machine's UI culture - the default of +`Localizer.Current.CurrentCulture` is `CultureInfo.CurrentUICulture` - unless initialization that the +previewer executes selects another culture. + +- **Avalonia:** the previewer runs `BuildAvaloniaApp`, so a culture assigned there applies in the previewer + too. +- **WPF:** the designer does not call `App.OnStartup`, so a culture assigned there does not apply at design + time. A `[ModuleInitializer]` of the application assembly does run in the designer; the WPF sample + application selects English in its module initializer for this reason (see the next section). + +`DesignTime.Culture` overrides a culture selected by such initialization: with +`l:DesignTime.Culture="de"`, the WPF sample's views preview in German although its module initializer +selects English. + +## Initialization for the WPF designer: a module initializer + +Because the WPF designer does not call `App.OnStartup`, a search-all lookup such as +`{l:Localize Greeting}` renders the failure text there when the resource files are registered only in +`OnStartup`. The same holds for `Localizer.Current.UseMessageFormat()` of the +`ResXLocalization.MessageFormat` package: called only in `OnStartup`, it does not apply in the designer, +which then formats with the default formatter. + +Do this initialization in a `[ModuleInitializer]` of the application assembly instead. It runs before the +first use of the assembly - at run time before `Main`, and in the WPF designer before the first view is +rendered: + +```csharp +using System.Globalization; +using System.Runtime.CompilerServices; +using RentADeveloper.ResXLocalization; +using RentADeveloper.ResXLocalization.MessageFormat; // only with the MessageFormat package +using YourApp.Resources; + +internal static class LocalizationInitializer +{ + [ModuleInitializer] + internal static void Initialize() + { + Localizer.Current.CurrentCulture = new CultureInfo("en"); + Localizer.Current.RegisterResourceManager(AppStringsKeys.ResourceManager); + Localizer.Current.UseMessageFormat(); // only with the MessageFormat package + } +} +``` + +[Registering resource files](registration.md#wpf) covers registration in a module initializer in more +detail, including views in a class library; [ICU MessageFormat](message-format.md#opting-in) covers +`UseMessageFormat()`. + +## Rider's WPF previewer + +**The running application, the Visual Studio WPF designer and the Avalonia previewer (in Visual Studio +and in Rider) are not affected by anything in this section.** + +Rider's XAML previewer has a number of defects that prevent ResXLocalization from working correctly in +it, and the same defects break many other WPF libraries - this is not a ResXLocalization shortcoming or a +support decision. + +Rider's WPF previewer supplies a target property to a markup extension as a CLR property instead of a WPF +dependency property, and WPF then throws for every binding a markup extension returns. In Rider's WPF +previewer only, `{l:Localize}` and `{l:LocalizeEnum}` therefore return a plain string instead of a +binding, outside style setters, so the window renders (style setters are covered below). Which text you +see there depends on how the key is written, because Rider delivers some keys to the markup extension and +not others. + +**Rendered: the raw resource value.** A key written as the first value inside the braces, or as the +`Key` attribute of an `` element, renders its resource value as written, under the default +formatter. The value is looked up without arguments, because the `` bindings have no data +context yet when the markup extension produces the string: + +```xml + + + + + + + + + + +``` + +**Rendered empty.** Rider does not deliver a key written with `{x:Static}` inside the braces, a key +assigned with `Key=` inside the braces, or a bound key: + +```xml + + + + +``` + +**Enum values.** The same rules apply to the enum value of `{l:LocalizeEnum}`, its `Value` property; here +`xmlns:m` is the namespace of the enum type `FileSortOrder`. A fixed enum member written as the `Value` +attribute of an `` element renders its text; a fixed member inside the braces and a bound +enum value render empty: + +```xml + + + + + + + + + + +``` + +More differences in Rider's WPF previewer: + +- **Style setters** keep a live binding, as at run time, when Rider delivers the key. When Rider does not + deliver it, the setter's text renders empty, and Rider's previewer reports the error + `{l:Localize} has no Key` for the setter's `Value` property, although the key is written correctly; the + running application and the Visual Studio designer render the text. This error is a consequence of the + Rider defect, not of your markup: + + ```xml + + + + + + ``` + +- **Texts bound to a view model** render empty when Rider cannot create the design-time view model, for + example one without a parameterless constructor. +- **Errors in the markup** outside style setters, such as a `{l:Localize}` without a key, are not reported + in Rider's previewer; the running application and the Visual Studio designer report them. +- **`DesignTime.Culture`** changes the culture, but the previewer silently shows the neutral resources: + Rider loads the project assemblies in a way that prevents .NET from finding the satellite assemblies of + other languages. The lookup succeeds with the neutral value, so neither the failure text nor + `Localizer.Current.LookupFailed` reports it. + +With ICU MessageFormat installed through `Localizer.Current.UseMessageFormat()`, the previewer's lookup +without arguments is still parsed as ICU: escaping such as `It''s ready` is interpreted, and a value that +needs a variable, such as `Hello {Name}`, renders the failure text and raises +`Localizer.Current.LookupFailed` - see [Every resolved value is ICU](message-format.md#every-resolved-value-is-icu). + +The defects are reported to JetBrains: + +- [RIDER-143207](https://youtrack.jetbrains.com/issue/RIDER-143207/WPF-XAML-previewer-supplies-RuntimePropertyInfo-instead-of-DependencyProperty-to-a-custom-markup-extension-causing-exceptions): + the previewer supplies a CLR property instead of a dependency property to a markup extension. +- [RIDER-143052](https://youtrack.jetbrains.com/issue/RIDER-143052/WPF-previewer-fails-to-resolve-ResX-satellite-assemblies-when-loading-project-assemblies-from-bytes): + the previewer does not resolve the satellite assemblies of other languages. +- [RIDER-143208](https://youtrack.jetbrains.com/issue/RIDER-143208): the previewer reports that it is not + in design mode for the root `Window` and supplies no target property for `Window.Title`. + +Further defects were found that are not on this list. When JetBrains fixes the previewer so that it +supplies dependency properties, `{l:Localize}` and `{l:LocalizeEnum}` return live bindings there too, +without a change to your application or to ResXLocalization. diff --git a/docs/guides/message-format.md b/docs/guides/message-format.md index 02a46ee..462c1f4 100644 --- a/docs/guides/message-format.md +++ b/docs/guides/message-format.md @@ -57,6 +57,11 @@ When you opt in, review every resource value for ICU syntax, including the texts wrapper. The default formatter (`StringFormatMessageFormatter`) keeps returning a value without arguments unchanged. +> [!NOTE] +> In Rider's WPF previewer, `{l:Localize}` and `{l:LocalizeEnum}` look up their text without arguments +> (see [Design time and previewers](design-time.md#riders-wpf-previewer)). With ICU installed there, +> escaping is interpreted, and a value that needs a variable renders the failure text. + ## `plural` and `select` | Key | `AppStrings.resx` (English) | `AppStrings.de.resx` (German) | diff --git a/docs/guides/migration-2.0.md b/docs/guides/migration-2.0.md index 9015a38..7523b84 100644 --- a/docs/guides/migration-2.0.md +++ b/docs/guides/migration-2.0.md @@ -1,6 +1,7 @@ # Migrating to 2.0 -2.0 is a major version; each section below is one breaking change, with what to do. +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. ## A formatting failure returns the failure text instead of throwing @@ -532,3 +533,14 @@ After: ``` + +## Rider's WPF previewer renders raw patterns (not a breaking change) + +Listed for completeness; nothing to do. In Rider's WPF XAML previewer, localized strings rendered nothing, +because of a defect in the previewer (JetBrains +[RIDER-143207](https://youtrack.jetbrains.com/issue/RIDER-143207/WPF-XAML-previewer-supplies-RuntimePropertyInfo-instead-of-DependencyProperty-to-a-custom-markup-extension-causing-exceptions)). +As a workaround, they now render their raw resource pattern there under the default formatter, for +example `{0} people invited`. With ICU MessageFormat installed, that lookup without arguments interprets +escaping and returns the failure text for a variable it is not given. The running application, the Visual +Studio WPF designer and the Avalonia previewer are unchanged. See +[Design time and previewers](design-time.md#riders-wpf-previewer). diff --git a/docs/index.md b/docs/index.md index 25563bc..1b33cd2 100644 --- a/docs/index.md +++ b/docs/index.md @@ -16,6 +16,7 @@ installation and a quick start. These pages are the full documentation. | [Localizing enum values](guides/enums.md) | The naming convention, item templates, the converter, custom prefixes and scoping | | [Dynamic format arguments](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](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](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](guides/native-aot.md) | What to declare, how to publish, and why the repository's own gate runs the native binary | | [Migrating to 2.0](guides/migration-2.0.md) | Each breaking change of 2.0, with what to do | diff --git a/docs/toc.yml b/docs/toc.yml index d9405fa..6f082b6 100644 --- a/docs/toc.yml +++ b/docs/toc.yml @@ -12,6 +12,8 @@ href: guides/format-arguments.md - name: ICU MessageFormat href: guides/message-format.md + - name: Design time and previewers + href: guides/design-time.md - name: Native AOT and trimming href: guides/native-aot.md - name: Migrating to 2.0 diff --git a/samples/ResXLocalization.WPF.Sample/ViewModels/MainWindowViewModel.cs b/samples/ResXLocalization.WPF.Sample/ViewModels/MainWindowViewModel.cs index 19dda28..1c68ed3 100644 --- a/samples/ResXLocalization.WPF.Sample/ViewModels/MainWindowViewModel.cs +++ b/samples/ResXLocalization.WPF.Sample/ViewModels/MainWindowViewModel.cs @@ -33,6 +33,14 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposable private readonly ILocalizer localizer; + /// + /// Initializes a new instance of the class over + /// . XAML designers need a parameterless constructor to create the + /// design-time data context that d:DesignInstance in declares. + /// + public MainWindowViewModel() + : this(Localizer.Current) { } + /// /// Initializes a new instance of the class. /// diff --git a/samples/ResXLocalization.WPF.Sample/Views/MainWindow.xaml b/samples/ResXLocalization.WPF.Sample/Views/MainWindow.xaml index 5633f70..c8bd940 100644 --- a/samples/ResXLocalization.WPF.Sample/Views/MainWindow.xaml +++ b/samples/ResXLocalization.WPF.Sample/Views/MainWindow.xaml @@ -11,7 +11,8 @@ Title="{l:Localize {x:Static res:ApplicationStringsKeys.WindowTitle}}" Width="900" Height="857" - d:DataContext="{d:DesignInstance viewModels:MainWindowViewModel}" + d:DataContext="{d:DesignInstance viewModels:MainWindowViewModel, + IsDesignTimeCreatable=True}" Background="White" Icon="../Assets/logo.ico" WindowStartupLocation="CenterScreen" diff --git a/src/ResXLocalization.Avalonia/DesignTime.cs b/src/ResXLocalization.Avalonia/DesignTime.cs new file mode 100644 index 0000000..54ba7f7 --- /dev/null +++ b/src/ResXLocalization.Avalonia/DesignTime.cs @@ -0,0 +1,83 @@ +using Avalonia.Controls; + +namespace RentADeveloper.ResXLocalization.Avalonia; + +/// +/// Hosts the DesignTime.Culture attached property, which selects the language the Avalonia XAML +/// previewer shows. Set it on the root element: <Window ... l:DesignTime.Culture="de">. +/// +/// +/// +/// The property is for design time only and has no effect at run time. Inside the previewer it assigns +/// of the process-wide , so strings +/// that view models look up in code agree with the XAML. It overrides a culture selected by initialization +/// that the previewer executes, such as a culture assigned in BuildAvaloniaApp. +/// +/// +/// Without it, the previewer uses the machine's UI culture, unless initialization that the previewer +/// executes selects another culture. +/// +/// +/// An empty name and a name that rejects, such as a half-typed one, leave the +/// culture unchanged. +/// +/// +public sealed class DesignTime : AvaloniaObject +{ + /// + /// Identifies the DesignTime.Culture attached property: the name of the culture the previewer + /// shows, such as de. + /// + public static readonly AttachedProperty CultureProperty = AvaloniaProperty.RegisterAttached< + DesignTime, + AvaloniaObject, + string? + >("Culture"); + + /// + /// Hooks the change handler of once, for the lifetime of the process. + /// + static DesignTime() => + _ = CultureProperty.Changed.AddClassHandler( + static (_, e) => OnCultureChanged(e.NewValue.GetValueOrDefault()) + ); + + private DesignTime() { } + + /// Gets the culture name set on for the previewer. + /// The element to read the value from. + /// The culture name, or if none is set. + public static string? GetCulture(AvaloniaObject element) => element.GetValue(CultureProperty); + + /// + /// Sets the culture name the previewer shows. Inside the previewer this assigns + /// of ; at run time it only stores + /// the value. + /// + /// The element to set the value on, usually the root element of the view. + /// The culture name, such as de. + public static void SetCulture(AvaloniaObject element, string? value) => element.SetValue(CultureProperty, value); + + /// + /// Assigns the new culture to of + /// inside the previewer; does nothing at run time, for an empty name and for a name that + /// rejects. + /// + /// The new culture name. + private static void OnCultureChanged(string? newValue) + { + if (!Design.IsDesignMode || newValue is not { Length: > 0 } name) + { + return; + } + + try + { + Localizer.Current.CurrentCulture = new(name); + } + catch (CultureNotFoundException) + { + // A half-typed culture name must not take the preview down. + } + } +} diff --git a/src/ResXLocalization.Avalonia/PublicAPI.Unshipped.txt b/src/ResXLocalization.Avalonia/PublicAPI.Unshipped.txt index 6687f5e..aa23363 100644 --- a/src/ResXLocalization.Avalonia/PublicAPI.Unshipped.txt +++ b/src/ResXLocalization.Avalonia/PublicAPI.Unshipped.txt @@ -38,6 +38,7 @@ RentADeveloper.ResXLocalization.Avalonia.Argument.Name.get -> string? RentADeveloper.ResXLocalization.Avalonia.Argument.Name.set -> void RentADeveloper.ResXLocalization.Avalonia.Argument.Value.get -> object? RentADeveloper.ResXLocalization.Avalonia.Argument.Value.set -> void +RentADeveloper.ResXLocalization.Avalonia.DesignTime RentADeveloper.ResXLocalization.Avalonia.LocalizeEnumConverter.ArgumentNames.get -> string? RentADeveloper.ResXLocalization.Avalonia.LocalizeEnumConverter.ArgumentNames.set -> void RentADeveloper.ResXLocalization.Avalonia.LocalizeEnumConverter.KeyPrefix.get -> string? @@ -48,3 +49,6 @@ RentADeveloper.ResXLocalization.Avalonia.LocalizeEnumExtension.Value.get -> obje RentADeveloper.ResXLocalization.Avalonia.LocalizeEnumExtension.Value.set -> void RentADeveloper.ResXLocalization.Avalonia.LocalizeExtension.Arguments.get -> System.Collections.ObjectModel.Collection! RentADeveloper.ResXLocalization.Avalonia.LocalizeExtension.Key.get -> object? +static readonly RentADeveloper.ResXLocalization.Avalonia.DesignTime.CultureProperty -> Avalonia.AttachedProperty! +static RentADeveloper.ResXLocalization.Avalonia.DesignTime.GetCulture(Avalonia.AvaloniaObject! element) -> string? +static RentADeveloper.ResXLocalization.Avalonia.DesignTime.SetCulture(Avalonia.AvaloniaObject! element, string? value) -> void diff --git a/src/ResXLocalization.WPF/DesignMode.cs b/src/ResXLocalization.WPF/DesignMode.cs new file mode 100644 index 0000000..2bbeb25 --- /dev/null +++ b/src/ResXLocalization.WPF/DesignMode.cs @@ -0,0 +1,85 @@ +using System.ComponentModel; + +namespace RentADeveloper.ResXLocalization.WPF; + +/// +/// Detects whether the code runs inside a XAML designer/previewer - the Visual Studio WPF designer or Rider's WPF +/// previewer - and decides when the markup extensions return a design-time string instead of a binding. +/// +internal static class DesignMode +{ + /// + /// The detected or forced value that determines whether the code runs inside a XAML designer/previewer; + /// until the first read. + /// + private static bool? isInDesignMode; + + /// + /// Gets or sets a value indicating whether the code runs inside a XAML designer/previewer. Detected on the first + /// read; tests set it to force design mode on or off. + /// + internal static bool IsInDesignMode + { + get => isInDesignMode ??= IsRunningInsideXamlDesigner(); + set => isInDesignMode = value; + } + + /// + /// Determines whether and return a + /// design-time string instead of a binding: inside a XAML designer, when the target property is not a + /// and the target object is not a , a + /// or a . + /// + /// + /// Rider's WPF previewer supplies a dependency property as a CLR PropertyInfo (JetBrains + /// RIDER-143207), and WPF throws a XamlParseException when a binding is provided for such a + /// target. Every clause is needed. Outside a designer, a PropertyInfo target is legitimate in + /// , and , which handle + /// markup extensions themselves, and a string there would stop live culture updates inside styles. The + /// Visual Studio designer supplies those three with a PropertyInfo target too, and a real + /// everywhere else, so it keeps live bindings. + /// + /// The service provider supplied by the XAML loader. + /// + /// if the markup extension returns a design-time string; otherwise + /// . + /// + internal static bool ShouldReturnDesignTimeText(IServiceProvider? serviceProvider) + { + var target = serviceProvider?.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget; + + return IsInDesignMode + && target?.TargetProperty is not DependencyProperty + && target?.TargetObject is not (Setter or DataTrigger or Condition); + } + + /// + /// Determines whether the current process is one in which an IDE renders XAML for a preview - the process + /// of the Visual Studio WPF designer or of Rider's WPF previewer - rather than a running application or a + /// test run. calls it once, on its first read. + /// + /// + /// Two checks are combined, because each of them recognizes only one of the two IDEs: + /// + /// + /// The Visual Studio WPF designer changes the default value of the dependency property + /// DesignerProperties.IsInDesignModeProperty to for the whole process. Rider + /// does not. + /// + /// + /// Rider sets the environment variable XAML_PREVIEW_HOST_PROCESS for the process in which its WPF + /// previewer runs. Visual Studio does not. + /// + /// + /// The per-element method DesignerProperties.GetIsInDesignMode(element) is not used: Rider replaces + /// a root with a wrapper object and reports for it + /// (JetBrains RIDER-143208). + /// + /// + /// in the process of the Visual Studio WPF designer or of Rider's WPF previewer; + /// otherwise . + /// + private static bool IsRunningInsideXamlDesigner() => + DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof(DependencyObject)).DefaultValue is true + || Environment.GetEnvironmentVariable("XAML_PREVIEW_HOST_PROCESS") is not null; +} diff --git a/src/ResXLocalization.WPF/DesignTime.cs b/src/ResXLocalization.WPF/DesignTime.cs new file mode 100644 index 0000000..c672ab5 --- /dev/null +++ b/src/ResXLocalization.WPF/DesignTime.cs @@ -0,0 +1,75 @@ +namespace RentADeveloper.ResXLocalization.WPF; + +/// +/// Hosts the DesignTime.Culture attached property, which selects the language a XAML designer +/// previews. Set it on the root element: <Window ... l:DesignTime.Culture="de">. +/// +/// +/// +/// The property is for design time only and has no effect at run time. Inside the Visual Studio WPF +/// designer or Rider's WPF previewer it assigns of the process-wide +/// , so strings that view models look up in code agree with the XAML. It +/// overrides a culture selected by initialization that the designer executes, such as a +/// [ModuleInitializer] that selects English. +/// +/// +/// Without it, the designer uses the machine's UI culture, unless initialization that the designer executes +/// selects another culture. The designer does not call Application.OnStartup, so a culture selected +/// there does not apply at design time. +/// +/// +/// An empty name and a name that rejects, such as a half-typed one, leave the +/// culture unchanged. +/// +/// +public static class DesignTime +{ + /// + /// Identifies the DesignTime.Culture attached property: the name of the culture a XAML designer + /// previews, such as de. + /// + public static readonly DependencyProperty CultureProperty = DependencyProperty.RegisterAttached( + "Culture", + typeof(string), + typeof(DesignTime), + new PropertyMetadata(null, OnCultureChanged) + ); + + /// Gets the culture name set on for the XAML designer. + /// The element to read the value from. + /// The culture name, or if none is set. + public static string? GetCulture(DependencyObject element) => (string?)element.GetValue(CultureProperty); + + /// + /// Sets the culture name a XAML designer previews. Inside a designer this assigns + /// of ; at run time it only stores + /// the value. + /// + /// The element to set the value on, usually the root element of the view. + /// The culture name, such as de. + public static void SetCulture(DependencyObject element, string? value) => element.SetValue(CultureProperty, value); + + /// + /// Assigns the new culture to of + /// inside a XAML designer; does nothing at run time, for an empty name and for a name that + /// rejects. + /// + /// The element the value was set on. + /// The old and the new culture name. + private static void OnCultureChanged(DependencyObject element, DependencyPropertyChangedEventArgs e) + { + if (!DesignMode.IsInDesignMode || e.NewValue is not string { Length: > 0 } name) + { + return; + } + + try + { + Localizer.Current.CurrentCulture = new(name); + } + catch (CultureNotFoundException) + { + // A half-typed culture name must not take the preview down. + } + } +} diff --git a/src/ResXLocalization.WPF/LocalizeEnumExtension.cs b/src/ResXLocalization.WPF/LocalizeEnumExtension.cs index dbae16d..06195e0 100644 --- a/src/ResXLocalization.WPF/LocalizeEnumExtension.cs +++ b/src/ResXLocalization.WPF/LocalizeEnumExtension.cs @@ -63,7 +63,11 @@ public LocalizeEnumExtension() { } /// The service provider supplied by the XAML loader. /// /// The binding expression of a WPF multi-binding that yields the localized string, or the multi-binding - /// itself when the target is not a dependency property, such as a value. + /// itself when the target is not a dependency property, such as a value. Inside a + /// XAML designer that supplies the target property as a CLR property instead of a dependency property, + /// such as Rider's WPF previewer, a string instead, without validation: the lookup of a constant + /// without arguments, or an empty string for any other + /// . /// /// /// is , a constant that is not an , or a @@ -73,6 +77,13 @@ public LocalizeEnumExtension() { } /// public override object ProvideValue(IServiceProvider serviceProvider) { + // Before the validation: Rider's previewer does not deliver bound values, and an exception takes the + // preview down. + if (DesignMode.ShouldReturnDesignTimeText(serviceProvider)) + { + return this.GetDesignTimeText(); + } + this.ValidateValue(); LocalizedMultiBindingBuilder.ValidateArguments(this.Arguments); @@ -102,6 +113,17 @@ targetObject is LocalizeEnumExtension extension } } + /// + /// Gets the design-time text: the lookup of a constant without + /// arguments, or an empty string for any other , such as a binding, because there is no + /// enumeration value to look up. + /// + /// The design-time text. + private string GetDesignTimeText() => + this.Value is Enum value + ? Localizer.Current.Get(value, resourceManager: this.ResourceManager, keyPrefix: this.KeyPrefix) + : string.Empty; + /// Checks that is a plain binding or an member. /// /// is , a constant that is not an , or a diff --git a/src/ResXLocalization.WPF/LocalizeExtension.cs b/src/ResXLocalization.WPF/LocalizeExtension.cs index f4c9c89..0481538 100644 --- a/src/ResXLocalization.WPF/LocalizeExtension.cs +++ b/src/ResXLocalization.WPF/LocalizeExtension.cs @@ -69,7 +69,10 @@ public LocalizeExtension() { } /// The service provider supplied by the XAML loader. /// /// The value of the WPF multi-binding for the target: the binding expression for a dependency property, - /// the multi-binding itself for a Setter. + /// the multi-binding itself for a Setter. Inside a XAML designer that supplies the target property + /// as a CLR property instead of a dependency property, such as Rider's WPF previewer, a string instead, + /// without validation: the lookup of a constant without arguments, or an empty string + /// when is or a binding. /// /// /// is , a constant that is neither a nor a @@ -84,6 +87,13 @@ public LocalizeExtension() { } /// public override object ProvideValue(IServiceProvider serviceProvider) { + // Before the validation: Rider's previewer often delivers Key as null, and an exception takes the + // preview down. + if (DesignMode.ShouldReturnDesignTimeText(serviceProvider)) + { + return this.GetDesignTimeText(); + } + this.ValidateKey(); LocalizedMultiBindingBuilder.ValidateArguments(this.Arguments); @@ -115,6 +125,20 @@ targetObject is LocalizeExtension extension } } + /// + /// Gets the design-time text: the lookup of a constant without arguments - under the + /// default formatter the resource value as written, such as {0} people invited - or an empty string + /// for any other , because there is no key to look up. + /// + /// The design-time text. + private string GetDesignTimeText() => + this.Key switch + { + ResourceKey { Manager: not null } resourceKey => Localizer.Current.Get(resourceKey), + string { Length: > 0 } key => Localizer.Current.Get(key, resourceManager: this.ResourceManager), + _ => string.Empty, + }; + /// /// Checks that is a , a usable resource key or a plain binding. /// diff --git a/src/ResXLocalization.WPF/PublicAPI.Unshipped.txt b/src/ResXLocalization.WPF/PublicAPI.Unshipped.txt index e054360..b2c6750 100644 --- a/src/ResXLocalization.WPF/PublicAPI.Unshipped.txt +++ b/src/ResXLocalization.WPF/PublicAPI.Unshipped.txt @@ -38,6 +38,7 @@ RentADeveloper.ResXLocalization.WPF.Argument.Name.get -> string? RentADeveloper.ResXLocalization.WPF.Argument.Name.set -> void RentADeveloper.ResXLocalization.WPF.Argument.Value.get -> object? RentADeveloper.ResXLocalization.WPF.Argument.Value.set -> void +RentADeveloper.ResXLocalization.WPF.DesignTime RentADeveloper.ResXLocalization.WPF.LocalizeEnumConverter.ArgumentNames.get -> string? RentADeveloper.ResXLocalization.WPF.LocalizeEnumConverter.ArgumentNames.set -> void RentADeveloper.ResXLocalization.WPF.LocalizeEnumConverter.KeyPrefix.get -> string? @@ -48,3 +49,6 @@ RentADeveloper.ResXLocalization.WPF.LocalizeEnumExtension.Value.get -> object? RentADeveloper.ResXLocalization.WPF.LocalizeEnumExtension.Value.set -> void RentADeveloper.ResXLocalization.WPF.LocalizeExtension.Arguments.get -> System.Collections.ObjectModel.Collection! RentADeveloper.ResXLocalization.WPF.LocalizeExtension.Key.get -> object? +static readonly RentADeveloper.ResXLocalization.WPF.DesignTime.CultureProperty -> System.Windows.DependencyProperty! +static RentADeveloper.ResXLocalization.WPF.DesignTime.GetCulture(System.Windows.DependencyObject! element) -> string? +static RentADeveloper.ResXLocalization.WPF.DesignTime.SetCulture(System.Windows.DependencyObject! element, string? value) -> void diff --git a/src/ResXLocalization.WPF/ResXLocalization.WPF.csproj b/src/ResXLocalization.WPF/ResXLocalization.WPF.csproj index 480e62e..069c2e1 100644 --- a/src/ResXLocalization.WPF/ResXLocalization.WPF.csproj +++ b/src/ResXLocalization.WPF/ResXLocalization.WPF.csproj @@ -25,6 +25,11 @@ + + + + + diff --git a/tests/ResXLocalization.Avalonia.Sample.Tests/DesignTimeTests.cs b/tests/ResXLocalization.Avalonia.Sample.Tests/DesignTimeTests.cs new file mode 100644 index 0000000..2cea1a9 --- /dev/null +++ b/tests/ResXLocalization.Avalonia.Sample.Tests/DesignTimeTests.cs @@ -0,0 +1,27 @@ +namespace RentADeveloper.ResXLocalization.Avalonia.Sample.Tests; + +/// +/// Covers .Culture at run time. Its design-time effect cannot be tested here, because +/// Design.IsDesignMode has no public setter; the maintainer checks it in the previewer. +/// +public class DesignTimeTests +{ + [AvaloniaFact] + public void DesignTime_DoesNothing_AtRunTime() + { + TestSupport.ResetToEnglishWithTestCatalogs(); + var textBlock = new TextBlock(); + + try + { + DesignTime.SetCulture(textBlock, "de"); + + Localizer.Current.CurrentCulture.Name.Should().Be("en"); + DesignTime.GetCulture(textBlock).Should().Be("de"); + } + finally + { + Localizer.Current.CurrentCulture = TestSupport.English; + } + } +} diff --git a/tests/ResXLocalization.WPF.Sample.Tests/DesignTimeTests.cs b/tests/ResXLocalization.WPF.Sample.Tests/DesignTimeTests.cs new file mode 100644 index 0000000..3bf00de --- /dev/null +++ b/tests/ResXLocalization.WPF.Sample.Tests/DesignTimeTests.cs @@ -0,0 +1,188 @@ +using System.Reflection; + +namespace RentADeveloper.ResXLocalization.WPF.Sample.Tests; + +/// +/// Covers .Culture and the design-time fallback of and +/// : inside a XAML designer that supplies the target property as a CLR +/// property, as Rider's WPF previewer does, the extensions return a string instead of a binding. +/// +public class DesignTimeTests +{ + /// Setter.Value, a CLR property in every host. + private static readonly PropertyInfo SetterValue = typeof(Setter).GetProperty(nameof(Setter.Value))!; + + /// TextBlock.Text as a CLR property, the way Rider's WPF previewer supplies it. + private static readonly PropertyInfo TextBlockTextProperty = typeof(TextBlock).GetProperty(nameof(TextBlock.Text))!; + + [Fact] + public void DesignTime_DoesNothing_AtRunTime() => + WpfThread.Invoke(() => + { + TestSupport.ResetToEnglishWithTestCatalogs(); + using var scope = new TestSupport.DesignModeScope(false); + var textBlock = new TextBlock(); + + try + { + DesignTime.SetCulture(textBlock, "de"); + + Localizer.Current.CurrentCulture.Name.Should().Be("en"); + DesignTime.GetCulture(textBlock).Should().Be("de"); + } + finally + { + Localizer.Current.CurrentCulture = TestSupport.English; + } + }); + + [Fact] + public void DesignTime_EmptyOrInvalidName_LeavesTheCultureUnchanged() => + WpfThread.Invoke(() => + { + TestSupport.ResetToEnglishWithTestCatalogs(); + using var scope = new TestSupport.DesignModeScope(true); + var textBlock = new TextBlock(); + + try + { + DesignTime.SetCulture(textBlock, "invalid!culture"); + Localizer.Current.CurrentCulture.Name.Should().Be("en"); + + DesignTime.SetCulture(textBlock, ""); + Localizer.Current.CurrentCulture.Name.Should().Be("en"); + } + finally + { + Localizer.Current.CurrentCulture = TestSupport.English; + } + }); + + [Fact] + public void DesignTime_SetsTheCulture_InDesignMode() => + WpfThread.Invoke(() => + { + TestSupport.ResetToEnglishWithTestCatalogs(); + using var scope = new TestSupport.DesignModeScope(true); + + try + { + DesignTime.SetCulture(new TextBlock(), "de"); + + Localizer.Current.CurrentCulture.Name.Should().Be("de"); + } + finally + { + Localizer.Current.CurrentCulture = TestSupport.English; + } + }); + + [Fact] + public void Fallback_BoundKey_ReturnsAnEmptyString() => + WpfThread.Invoke(() => + { + TestSupport.ResetToEnglishWithTestCatalogs(); + using var scope = new TestSupport.DesignModeScope(true); + + var value = new LocalizeExtension(new Binding("Key")).ProvideValue(ClrTextTarget()); + + value.Should().Be(""); + }); + + [Fact] + public void Fallback_Enum_ReturnsTheConstantMemberText_OrAnEmptyStringForABinding() => + WpfThread.Invoke(() => + { + TestSupport.ResetToEnglishWithTestCatalogs(); + using var scope = new TestSupport.DesignModeScope(true); + + var bound = new LocalizeEnumExtension { Value = new Binding(nameof(TestViewModel.SortOrder)) }.ProvideValue( + ClrTextTarget() + ); + var constant = new LocalizeEnumExtension { Value = FileSortOrder.Ascending }.ProvideValue(ClrTextTarget()); + + bound.Should().Be(""); + constant.Should().Be("Ascending"); + }); + + [Fact] + public void Fallback_MissingKey_ReturnsTheFailureText() => + WpfThread.Invoke(() => + { + TestSupport.ResetToEnglishWithTestCatalogs(); + using var scope = new TestSupport.DesignModeScope(true); + + var value = new LocalizeExtension("ThisKeyDoesNotExist").ProvideValue(ClrTextTarget()); + + value.Should().Be("!ThisKeyDoesNotExist!"); + }); + + [Fact] + public void Fallback_PrecedesValidation() => + WpfThread.Invoke(() => + { + TestSupport.ResetToEnglishWithTestCatalogs(); + using var scope = new TestSupport.DesignModeScope(true); + + var withoutKey = () => new LocalizeExtension().ProvideValue(ClrTextTarget()); + var withUnsetArgument = () => + new LocalizeExtension("Greeting") { Arguments = { new Argument() } }.ProvideValue(ClrTextTarget()); + + withoutKey.Should().NotThrow().Which.Should().Be(""); + withUnsetArgument.Should().NotThrow().Which.Should().Be("Hello and welcome!"); + }); + + [Fact] + public void Fallback_TypedKey_ReturnsTheRawPattern_ForAClrTargetProperty() => + WpfThread.Invoke(() => + { + TestSupport.ResetToEnglishWithTestCatalogs(); + using var scope = new TestSupport.DesignModeScope(true); + + var value = PeopleInvitedWithArgument().ProvideValue(ClrTextTarget()); + + value.Should().Be("{0} people invited"); + }); + + [Fact] + public void NoFallback_ForADependencyPropertyTarget_InDesignMode() => + WpfThread.Invoke(() => + { + TestSupport.ResetToEnglishWithTestCatalogs(); + using var scope = new TestSupport.DesignModeScope(true); + + var value = PeopleInvitedWithArgument().ProvideValue(Target(new TextBlock(), TextBlock.TextProperty)); + + value.Should().BeOfType(); + }); + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void NoFallback_ForASetter(bool isInDesignMode) => + WpfThread.Invoke(() => + { + TestSupport.ResetToEnglishWithTestCatalogs(); + using var scope = new TestSupport.DesignModeScope(isInDesignMode); + var setter = new Setter(); + + var value = PeopleInvitedWithArgument().ProvideValue(Target(setter, SetterValue)); + + // WPF's Setter handles markup extensions itself: the MultiBinding is returned, or assigned to + // Setter.Value. + (value is MultiBinding || setter.Value is MultiBinding) + .Should() + .BeTrue(); + }); + + private static IServiceProvider ClrTextTarget() => Target(new TextBlock(), TextBlockTextProperty); + + private static LocalizeExtension PeopleInvitedWithArgument() => + new(ApplicationStringsKeys.PeopleInvited) + { + Arguments = { new Argument { Value = new Binding(nameof(TestViewModel.Count)) } }, + }; + + private static IServiceProvider Target(object targetObject, object targetProperty) => + new TestSupport.SimpleServiceProvider(new TestSupport.SimpleProvideValueTarget(targetObject, targetProperty)); +} diff --git a/tests/ResXLocalization.WPF.Sample.Tests/TestSupport.cs b/tests/ResXLocalization.WPF.Sample.Tests/TestSupport.cs index c931054..7baa081 100644 --- a/tests/ResXLocalization.WPF.Sample.Tests/TestSupport.cs +++ b/tests/ResXLocalization.WPF.Sample.Tests/TestSupport.cs @@ -1,3 +1,6 @@ +using System.Windows.Markup; +using System.Xaml; + namespace RentADeveloper.ResXLocalization.WPF.Sample.Tests; /// @@ -113,6 +116,61 @@ private static IEnumerable LogicalDescendants(DependencyObject } } + /// + /// Forces DesignMode.IsInDesignMode to a value and restores the previous value on dispose. The suite + /// runs without parallelization, so the process-wide value cannot leak into a concurrent test. + /// + internal sealed class DesignModeScope : IDisposable + { + private readonly bool previousValue; + + /// Initializes a new instance of the class. + /// The value DesignMode.IsInDesignMode has until the scope is disposed. + public DesignModeScope(bool value) + { + this.previousValue = DesignMode.IsInDesignMode; + DesignMode.IsInDesignMode = value; + } + + public void Dispose() => DesignMode.IsInDesignMode = this.previousValue; + } + + /// An with a fixed target object and target property. + /// The object whose property the markup extension provides a value for. + /// + /// The target property: a , or a CLR PropertyInfo as Rider's WPF + /// previewer supplies it. + /// + internal sealed class SimpleProvideValueTarget(object targetObject, object targetProperty) : IProvideValueTarget + { + public object TargetObject { get; } = targetObject; + + public object TargetProperty { get; } = targetProperty; + } + + /// + /// A service provider that supplies an and, as the XAML loader does, an + /// . WPF needs the schema context to let a + /// receive a binding for its Value property; without it, WPF throws for a . + /// + /// The target to supply. + internal sealed class SimpleServiceProvider(IProvideValueTarget target) + : IServiceProvider, + IXamlSchemaContextProvider + { + private static readonly XamlSchemaContext SharedSchemaContext = new(); + + public XamlSchemaContext SchemaContext => SharedSchemaContext; + + public object? GetService(Type serviceType) => + serviceType switch + { + _ when serviceType == typeof(IProvideValueTarget) => target, + _ when serviceType == typeof(IXamlSchemaContextProvider) => this, + _ => null, + }; + } + private sealed class EmptyServiceProvider : IServiceProvider { public static readonly EmptyServiceProvider Instance = new();