Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,36 @@ namespace WheelWizard.Test.Features.Localization;

public class TranslationFunctionsTests
{
[Fact]
public void ProviderForwardsOnlyActiveServiceChangesOnce()
{
var previous = LocalizationProvider.Current;
var first = new EmbeddedYamlLocalizationService();
var second = new EmbeddedYamlLocalizationService();
var notifications = 0;
EventHandler handler = (_, _) => notifications++;
LocalizationProvider.Use(first);
LocalizationProvider.LanguageChanged += handler;
try
{
first.SetLanguage("nl");
first.SetLanguage("NL");
Assert.Equal(1, notifications);
LocalizationProvider.Use(second);
Assert.Equal(2, notifications);
first.SetLanguage("fr");
Assert.Equal(2, notifications);
second.SetLanguage("fr");
Assert.Equal(3, notifications);
Assert.Equal(second.Translate("action.cancel"), TranslationFunctions.t("action.cancel"));
}
finally
{
LocalizationProvider.LanguageChanged -= handler;
LocalizationProvider.Use(previous);
}
}

[Fact(DisplayName = "Format with no params returns default string")]
public void FormatWithNoParams_ShouldReturnDefaultString()
{
Expand Down
20 changes: 20 additions & 0 deletions WheelWizard.UI.Test/ApplicationCompositionTests.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
using System.IO.Abstractions;
using System.Linq.Expressions;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Headless.XUnit;
using Avalonia.Threading;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using Testably.Abstractions.Testing;
using WheelWizard.ApplicationData;
using WheelWizard.Localization;
using WheelWizard.Settings;
using WheelWizard.Shared;
using WheelWizard.Shared.Services;
Expand Down Expand Up @@ -96,6 +98,24 @@ public async Task MainWindowAndPages_ConstructWithoutStaticServiceInitialization
original.UpdateLayout();
Assert.IsType<SettingsPage>(navigation.CurrentPage);
}
navigation.NavigateTo<SettingsPage>(typeof(WhWzSettings));
original.UpdateLayout();
await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Background);
var settingsPage = Assert.IsType<SettingsPage>(navigation.CurrentPage);
var content = settingsPage.FindControl<ContentControl>("SettingsContent")!;
var wizard = Assert.IsType<WhWzSettings>(content.Content);
var helper = wizard.FindControl<TextBlock>("MarioKartHelperText")!;
var before = helper.Text;
Assert.True(settings.Set(settings.WW_LANGUAGE, "nl"));
await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Background);
Assert.Same(original, desktop.MainWindow);
Assert.Same(settingsPage, navigation.CurrentPage);
Assert.Same(wizard, content.Content);
Assert.NotEqual(before, helper.Text);
Assert.StartsWith(TranslationFunctions.t("helper_text.end_with_x"), helper.Text);
var label = wizard.FindControl<WheelWizard.Views.Components.FormFieldLabel>("DolphinUserFolderLabel")!;
Assert.Equal(TranslationFunctions.t("option.dolphin_user_path"), label.Text);
settings.Set(settings.WW_LANGUAGE, "en");
windows.Refresh();
Assert.NotSame(original, desktop.MainWindow);
Assert.False(original.IsVisible);
Expand Down
37 changes: 37 additions & 0 deletions WheelWizard.UI.Test/LocalizationBindingTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using Avalonia.Controls;
using Avalonia.Data;
using Avalonia.Headless.XUnit;
using Avalonia.Threading;
using WheelWizard.Localization;

namespace WheelWizard.UI.Test;

public class LocalizationBindingTests
{
[AvaloniaFact]
public async Task ExistingBindingUpdatesOnUiThreadAndStopsAfterDisposal()
{
var previous = LocalizationProvider.Current;
var service = new EmbeddedYamlLocalizationService();
LocalizationProvider.Use(service);
try
{
var text = new TextBlock();
var binding = (BindingBase)new T("action.cancel").ProvideValue(null!);
var subscription = text.Bind(TextBlock.TextProperty, binding);
Assert.Equal(service.Translate("action.cancel"), text.Text);
await Task.Run(() => service.SetLanguage("nl"));
await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Background);
Assert.Equal(service.Translate("action.cancel"), text.Text);
Assert.NotEqual(service.TranslateForLanguage("action.cancel", "en"), text.Text);
subscription.Dispose();
var afterDisposal = text.Text;
service.SetLanguage("fr");
Assert.Equal(afterDisposal, text.Text);
}
finally
{
LocalizationProvider.Use(previous);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ namespace WheelWizard.Localization;

public sealed class EmbeddedYamlLocalizationService : ILocalizationService
{
public event EventHandler? LanguageChanged;

private const string DefaultLanguage = "en";
private readonly Dictionary<string, IReadOnlyDictionary<string, string>> _translations;
private readonly object _languageLock = new();
Expand Down Expand Up @@ -41,7 +43,12 @@ public void SetLanguage(string languageCode)
normalizedLanguage = DefaultLanguage;

lock (_languageLock)
{
if (_currentLanguage == normalizedLanguage)
return;
_currentLanguage = normalizedLanguage;
}
LanguageChanged?.Invoke(this, EventArgs.Empty);
}

public string Translate(string key)
Expand Down
1 change: 1 addition & 0 deletions WheelWizard/Features/Localization/ILocalizationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ namespace WheelWizard.Localization;

public interface ILocalizationService
{
event EventHandler? LanguageChanged;
string CurrentLanguage { get; }
IReadOnlyCollection<string> AvailableLanguages { get; }

Expand Down
7 changes: 1 addition & 6 deletions WheelWizard/Features/Localization/LocalizationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,7 @@ public static class LocalizationExtensions
{
public static IServiceCollection AddLocalization(this IServiceCollection services)
{
services.AddSingleton<ILocalizationService>(_ =>
{
var service = new EmbeddedYamlLocalizationService();
LocalizationProvider.Use(service);
return service;
});
services.AddSingleton<ILocalizationService, EmbeddedYamlLocalizationService>();

return services;
}
Expand Down
23 changes: 19 additions & 4 deletions WheelWizard/Features/Localization/LocalizationProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ namespace WheelWizard.Localization;

public static class LocalizationProvider
{
// #todo: let the app own the localization service and language events instead of sharing mutable state globally.
// Compatibility facade for global t() and XAML; the injected service owns the language.
private static readonly object ServiceLock = new();
private static ILocalizationService? _service;

Expand All @@ -13,7 +13,14 @@ public static ILocalizationService Current
get
{
lock (ServiceLock)
return _service ??= new EmbeddedYamlLocalizationService();
{
if (_service == null)
{
_service = new EmbeddedYamlLocalizationService();
_service.LanguageChanged += ForwardLanguageChanged;
}
return _service;
}
}
}

Expand All @@ -22,18 +29,26 @@ public static void Use(ILocalizationService service)
ArgumentNullException.ThrowIfNull(service);

lock (ServiceLock)
{
if (ReferenceEquals(_service, service))
return;
if (_service != null)
_service.LanguageChanged -= ForwardLanguageChanged;
_service = service;
_service.LanguageChanged += ForwardLanguageChanged;
}

NotifyLanguageChanged();
}

public static void SetLanguage(string languageCode)
{
Current.SetLanguage(languageCode);
NotifyLanguageChanged();
}

public static void NotifyLanguageChanged()
private static void ForwardLanguageChanged(object? sender, EventArgs args) => NotifyLanguageChanged();

private static void NotifyLanguageChanged()
{
LanguageChanged?.Invoke(null, EventArgs.Empty);
}
Expand Down
43 changes: 37 additions & 6 deletions WheelWizard/Features/Localization/T.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,51 @@
using Avalonia;
using Avalonia.Markup.Xaml;
using Avalonia.Threading;

namespace WheelWizard.Localization;

public sealed class T : MarkupExtension
{
public T() { }

public T(string key)
{
Key = key;
}
public T(string key) => Key = key;

public string Key { get; set; } = string.Empty;

public override object ProvideValue(IServiceProvider serviceProvider)
public override object ProvideValue(IServiceProvider serviceProvider) => new TranslationObservable(Key).ToBinding();

private sealed class TranslationObservable(string key) : IObservable<string>
{
public IDisposable Subscribe(IObserver<string> observer) => new Subscription(key, observer);
}

private sealed class Subscription : IDisposable
{
return TranslationFunctions.t(Key);
private readonly string _key;
private IObserver<string>? _observer;

public Subscription(string key, IObserver<string> observer)
{
_key = key;
_observer = observer;
LocalizationProvider.LanguageChanged += OnLanguageChanged;
Publish();
}

private void OnLanguageChanged(object? sender, EventArgs args)
{
if (Dispatcher.UIThread.CheckAccess())
Publish();
else
Dispatcher.UIThread.Post(Publish);
}

private void Publish() => _observer?.OnNext(TranslationFunctions.t(_key));

public void Dispose()
{
LocalizationProvider.LanguageChanged -= OnLanguageChanged;
_observer = null;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public void Initialize()
return;

_subscription = settingsSignalBus.Subscribe(OnSignal);
LocalizationProvider.Use(localizationService);
ApplyCurrentLanguage();
_initialized = true;
}
Expand Down Expand Up @@ -47,6 +48,5 @@ public void ApplyCurrentLanguage()
CultureInfo.CurrentUICulture = newCulture;

localizationService.SetLanguage(languageCode);
LocalizationProvider.Use(localizationService);
}
}
6 changes: 6 additions & 0 deletions WheelWizard/Views/Layout.axaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,12 @@ protected override void OnClosed(EventArgs e)

private void OnLanguageChanged(object? sender, EventArgs e)
{
if (!Avalonia.Threading.Dispatcher.UIThread.CheckAccess())
{
Avalonia.Threading.Dispatcher.UIThread.Post(() => OnLanguageChanged(sender, e));
return;
}
UpdatePlayerAndRoomCount();
UpdateModsButtonText();
UpdateMadeByText();
UpdateLiveAlert();
Expand Down
Loading
Loading