mirror of
https://github.com/Flow-Launcher/Flow.Launcher.git
synced 2026-03-11 08:54:32 +00:00
- Create Internationalization service that parses WPF XAML language files - Load translations from main Languages/ folder and all plugin Languages/ folders - Add LocalizeExtension markup extension and Translator helper for XAML/code - Fix IPublicAPI.GetTranslation to use the i18n service for plugin context menus - Update MainWindow to use localized placeholder text
94 lines
2.2 KiB
C#
94 lines
2.2 KiB
C#
using Avalonia.Data;
|
|
using Avalonia.Markup.Xaml;
|
|
using Avalonia.Markup.Xaml.MarkupExtensions;
|
|
using System;
|
|
|
|
namespace Flow.Launcher.Avalonia.Resource;
|
|
|
|
/// <summary>
|
|
/// Markup extension for accessing localized strings in XAML.
|
|
/// Usage: Text="{i18n:Localize queryTextBoxPlaceholder}"
|
|
/// </summary>
|
|
public class LocalizeExtension : MarkupExtension
|
|
{
|
|
public LocalizeExtension()
|
|
{
|
|
}
|
|
|
|
public LocalizeExtension(string key)
|
|
{
|
|
Key = key;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The translation key to look up.
|
|
/// </summary>
|
|
public string Key { get; set; } = string.Empty;
|
|
|
|
/// <summary>
|
|
/// Fallback value if translation is not found.
|
|
/// </summary>
|
|
public string? Fallback { get; set; }
|
|
|
|
public override object ProvideValue(IServiceProvider serviceProvider)
|
|
{
|
|
if (string.IsNullOrEmpty(Key))
|
|
{
|
|
return Fallback ?? "[No Key]";
|
|
}
|
|
|
|
var i18n = App.I18n;
|
|
if (i18n == null)
|
|
{
|
|
return Fallback ?? $"[{Key}]";
|
|
}
|
|
|
|
if (i18n.HasTranslation(Key))
|
|
{
|
|
return i18n.GetTranslation(Key);
|
|
}
|
|
|
|
return Fallback ?? $"[{Key}]";
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Static helper class for accessing translations from code-behind.
|
|
/// </summary>
|
|
public static class Translator
|
|
{
|
|
/// <summary>
|
|
/// Get a translated string by key.
|
|
/// </summary>
|
|
/// <param name="key">The translation key</param>
|
|
/// <returns>The translated string or the key in brackets if not found</returns>
|
|
public static string GetString(string key)
|
|
{
|
|
var i18n = App.I18n;
|
|
if (i18n == null)
|
|
{
|
|
return $"[{key}]";
|
|
}
|
|
|
|
return i18n.GetTranslation(key);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Get a translated string with format arguments.
|
|
/// </summary>
|
|
/// <param name="key">The translation key</param>
|
|
/// <param name="args">Format arguments</param>
|
|
/// <returns>The formatted translated string</returns>
|
|
public static string GetString(string key, params object[] args)
|
|
{
|
|
var template = GetString(key);
|
|
try
|
|
{
|
|
return string.Format(template, args);
|
|
}
|
|
catch
|
|
{
|
|
return template;
|
|
}
|
|
}
|
|
}
|