Files
NebulaLauncher/Nebula.Launcher/Services/LocalizationService.cs

78 lines
2.4 KiB
C#
Raw Normal View History

2025-02-02 19:34:15 +03:00
using System;
2025-06-23 16:39:30 +03:00
using System.Collections.Generic;
2025-02-02 19:34:15 +03:00
using System.Globalization;
using System.IO;
2025-06-23 16:39:30 +03:00
using Avalonia.Markup.Xaml;
2025-02-02 19:34:15 +03:00
using Avalonia.Platform;
using Fluent.Net;
using Nebula.Shared;
using Nebula.Shared.Services;
namespace Nebula.Launcher.Services;
[ConstructGenerator, ServiceRegister]
2025-12-11 21:47:54 +03:00
public sealed partial class LocalizationService
2025-02-02 19:34:15 +03:00
{
[GenerateProperty] private ConfigurationService ConfigurationService { get; }
[GenerateProperty] private DebugService DebugService { get; }
2025-02-02 19:34:15 +03:00
private CultureInfo _currentCultureInfo = CultureInfo.CurrentCulture;
2025-06-23 16:39:30 +03:00
private static MessageContext? _currentMessageContext;
2025-02-02 19:34:15 +03:00
private void Initialise()
{
2025-06-23 16:39:30 +03:00
LoadLanguage(CultureInfo.GetCultureInfo(ConfigurationService.GetConfigValue(LauncherConVar.CurrentLang)!));
2025-02-02 19:34:15 +03:00
}
public void LoadLanguage(CultureInfo cultureInfo)
{
2025-06-23 16:39:30 +03:00
try
2025-02-02 19:34:15 +03:00
{
2025-06-23 16:39:30 +03:00
_currentCultureInfo = cultureInfo;
using var fs = AssetLoader.Open(new Uri($@"avares://Nebula.Launcher/Assets/lang/{_currentCultureInfo.Name}.ftl"));
using var sr = new StreamReader(fs);
var options = new MessageContextOptions { UseIsolating = false };
var mc = new MessageContext(cultureInfo.Name, options);
var errors = mc.AddMessages(sr);
foreach (var error in errors)
{
Console.WriteLine(error);
}
_currentMessageContext = mc;
} catch (Exception e) {
DebugService.GetLogger("localisationService").Error(e);
2025-06-23 16:39:30 +03:00
LoadLanguage(CultureInfo.GetCultureInfo("en-US"));
}
2025-02-02 19:34:15 +03:00
}
private void InitialiseInDesignMode()
{
Initialise();
}
2025-06-23 16:39:30 +03:00
2025-07-05 20:39:36 +03:00
public static string GetString(string locale, Dictionary<string, object>? options = null)
2025-06-23 16:39:30 +03:00
{
if (_currentMessageContext is null)
{
return locale;
}
var message = _currentMessageContext.GetMessage(locale);
if (message == null) return locale;
2025-07-05 20:39:36 +03:00
return _currentMessageContext.Format(message, options ?? []);
2025-06-23 16:39:30 +03:00
}
2025-03-12 14:51:47 +03:00
}
2025-06-23 16:39:30 +03:00
public class LocaledText : MarkupExtension
{
public string Key { get; set; }
2025-08-07 22:34:25 +03:00
public Dictionary<string, object>? Options { get; set; }
2025-06-23 16:39:30 +03:00
public LocaledText(string key) => Key = key;
public override object ProvideValue(IServiceProvider serviceProvider)
{
return LocalizationService.GetString(Key, Options);
2025-06-23 16:39:30 +03:00
}
}