借助网络配置,控制Modbus工具的日志显示,避免卡死界面
智能大石头 authored at 2021-12-11 22:09:19
18.34 KiB
XCoder
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Avalonia.Media;
using Avalonia.Threading;
using NewLife;
using NewLife.Log;

namespace NewLife.XCoder.Services;

/// <summary>多语言服务:薄封装 NewLife.Core 的本地化机制</summary>
/// <remarks>
/// 英文原文即词表键,译文放在 <c>Locales/*.yml</c>,编译期由 NewLife.Core 源生成器写入程序集;
/// 偏好为 <see cref="Auto"/> 时跟随系统 UI 语言,否则锁定到指定语言。
/// 语言切换会触发 <see cref="Changed"/>,界面通过 <c>{loc:Tr ...}</c> 绑定即时刷新。
/// </remarks>
public static class LocalizationService
{
    /// <summary>跟随系统</summary>
    public const String Auto = "auto";

    /// <summary>语言偏好文件路径(测试可注入临时路径)</summary>
    public static String FilePath { get; set; } = Path.Combine(AppPaths.ConfigDirectory, "ui.lang");

    private static readonly String[] _Languages = ["zh-CN", "zh-TW", "en-US", "ja-JP", "ko-KR", "de-DE", "fr-FR", "es-ES", "pt-BR", "ru-RU", "ar-SA"];

    private static readonly Dictionary<String, LanguageInfo> _infos = Localization.GetLanguages().ToDictionary(e => e.Name, StringComparer.OrdinalIgnoreCase);

    private static String _preference = Auto;

    private static String? _systemLanguage;

    static LocalizationService() => LocalizationSource.EnsureSubscribed();

    /// <summary>当前偏好:<see cref="Auto"/> 或语言代码</summary>
    public static String Preference => _preference;

    /// <summary>是否跟随系统语言</summary>
    public static Boolean IsAuto => _preference == Auto;

    /// <summary>当前生效语言代码</summary>
    public static String Language => _preference == Auto ? AutoLanguage : _preference;

    /// <summary>当前生效语言的本地名称</summary>
    public static String LanguageName => Name(Language);

    /// <summary>当前偏好的显示名称;跟随系统时附带系统语言</summary>
    public static String PreferenceName => IsAuto ? Format("Follow system ({0})", LanguageName) : Name(_preference);

    /// <summary>可选语言</summary>
    public static IReadOnlyList<String> Languages => _Languages;

    /// <summary>语言切换通知,参数为生效语言代码</summary>
    public static event Action<String>? Changed;

    /// <summary>跟随系统时实际生效的语言代码</summary>
    public static String AutoLanguage => SystemLanguage;

    /// <summary>进程启动时的系统 UI 语言。在模块加载时捕获,避免被后续语言切换污染</summary>
    public static String SystemLanguage => _systemLanguage ?? Normalize(Localization.SystemCulture) ?? Normalize(CultureInfo.CurrentUICulture) ?? "en-US";

    /// <summary>捕获进程启动时的系统 UI 语言</summary>
    /// <remarks>由模块初始化器在 <c>Main</c> 之前调用;重复调用不会覆盖首次捕获值。</remarks>
    public static void CaptureSystemLanguage()
    {
        if (_systemLanguage != null) return;

        var culture = CultureInfo.CurrentUICulture;
        _systemLanguage = Localization.NormalizeCulture(culture.Name) ?? (culture.Name.IsNullOrEmpty() ? "en-US" : culture.Name);
    }

    /// <summary>语言代码的自称</summary>
    /// <param name="code">语言代码,如 zh-CN</param>
    /// <returns>自称;未知代码原样返回</returns>
    public static String Name(String code)
    {
        if (code.IsNullOrEmpty()) return "";

        return _infos.TryGetValue(code, out var info) && !info.NativeName.IsNullOrEmpty() ? info.NativeName : code;
    }

    /// <summary>语言代码在当前界面语言下的名称</summary>
    /// <param name="code">语言代码,如 zh-CN</param>
    /// <returns>当前界面语言下的名称;无法解析时回退自称</returns>
    public static String DisplayName(String code)
    {
        if (code.IsNullOrEmpty()) return "";

        try
        {
            return CultureInfo.GetCultureInfo(code).DisplayName;
        }
        catch (CultureNotFoundException)
        {
            return Name(code);
        }
        catch (ArgumentException)
        {
            return Name(code);
        }
    }

    /// <summary>启动时加载语言偏好</summary>
    public static void Initialize()
    {
        LocalizationSource.EnsureSubscribed();

        var preference = Auto;
        try
        {
            if (File.Exists(FilePath))
            {
                var text = File.ReadAllText(FilePath).Trim();
                if (text.Equals(Auto, StringComparison.OrdinalIgnoreCase) || Array.IndexOf(_Languages, text) >= 0) preference = text;
            }
        }
        catch (Exception ex)
        {
            XTrace.WriteException(ex);
        }

        Apply(preference, false);
    }

    /// <summary>切换语言</summary>
    /// <param name="language">语言代码,或 <see cref="Auto"/> 表示跟随系统</param>
    /// <param name="save">是否保存偏好</param>
    /// <returns>是否切换成功;不支持的语言返回 false</returns>
    public static Boolean Apply(String language, Boolean save = true)
    {
        var preference = language.IsNullOrWhiteSpace() || language.Equals(Auto, StringComparison.OrdinalIgnoreCase) ? Auto : language;

        String effective;
        if (preference == Auto)
        {
            Localization.SetLanguage(null);
            RestoreSystemCulture();
            effective = AutoLanguage;
        }
        else
        {
            var code = Localization.NormalizeCulture(preference);
            if (code.IsNullOrEmpty()) return false;

            Localization.SetLanguage(code);
            SetCurrentCulture(code);
            preference = code;
            effective = code;
        }

        _preference = preference;
        ApplyFontResources();

        if (save)
        {
            try
            {
                var dir = Path.GetDirectoryName(FilePath);
                if (!dir.IsNullOrEmpty()) Directory.CreateDirectory(dir);
                File.WriteAllText(FilePath, preference);
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
            }
        }

        Changed?.Invoke(effective);
        return true;
    }

    /// <summary>在 UI 线程上切换语言</summary>
    /// <param name="language">语言代码,或 <see cref="Auto"/></param>
    public static void ApplyOnUi(String language)
    {
        var dispatcher = Avalonia.Application.Current?.Dispatcher;
        if (dispatcher != null)
        {
            if (dispatcher.CheckAccess()) Apply(language);
            else dispatcher.Post(() => Apply(language));
            return;
        }

        if (Dispatcher.UIThread.CheckAccess()) Apply(language);
        else Dispatcher.UIThread.Post(() => Apply(language));
    }

    /// <summary>取译文</summary>
    /// <param name="source">英文原文(词表键)</param>
    /// <returns>当前语言译文;缺少译文时返回英文原文</returns>
    public static String T(String source) => source.IsNullOrEmpty() ? "" : L.T(source);

    /// <summary>取译文并格式化</summary>
    /// <param name="source">英文原文(词表键)</param>
    /// <param name="args">格式化参数</param>
    /// <returns>当前语言译文;缺少译文时返回英文原文</returns>
    public static String Format(String source, params Object[] args) => source.IsNullOrEmpty() ? "" : L.T(source, args);

    private static readonly String[] _dynamicPrefixes =
    [
        "连接失败:", "执行失败:", "操作失败:", "读取失败:", "导出失败:", "发送失败:",
        "生成失败:", "打开失败:", "保存失败:", "复制失败:", "加密失败:", "解密失败:",
        "计算失败:", "写入成功:", "已导出:", "错误:", "已选择 ", "密钥对已生成:",
        "生成 RSA 密钥失败:", "端口超出范围:", "异常响应:", "写入成功:地址=",
        "批量处理失败:", "连接成功:", "已保存 ", "已添加节点:", "已删除节点:",
        "已检测到 ", "文件不存在:", "目录不存在:", "频谱计算完成:", "正在枚举",
    ];

    private static readonly (Regex Pattern, String Template)[] _dynamicPatterns =
    [
        (new Regex(@"^已连接源 (.+?),共 (\d+) 个表$", RegexOptions.Compiled), "Connected to source {0}, {1} tables"),
        (new Regex(@"^已连接目标 (.+)$", RegexOptions.Compiled), "Connected to target {0}"),
        (new Regex(@"^已连接 (.+?),共 (\d+) 个表$", RegexOptions.Compiled), "Connected to {0}, {1} tables"),
        (new Regex(@"^已刷新,共 (\d+) 个表$", RegexOptions.Compiled), "Refreshed, {0} tables"),
        (new Regex(@"^生成 (.+?) 完成!耗时:(.+)$", RegexOptions.Compiled), "Generated {0} in {1}"),
        (new Regex(@"^生成 (\d+) 个类完成!耗时:(.+)$", RegexOptions.Compiled), "Generated {0} classes in {1}"),
        (new Regex(@"^正在同步\.\.\.,(\d+) 个项目新增或更新数据(追加写入)$", RegexOptions.Compiled), "Syncing... {0} items inserted or updated (append mode)"),
        (new Regex(@"^已取消,收到 (\d+) 个服务$", RegexOptions.Compiled), "Canceled; {0} services received"),
        (new Regex(@"^发现 (\d+) 个服务$", RegexOptions.Compiled), "Found {0} services"),
        (new Regex(@"^扫描完成,发现 (\d+) 个服务(同一设备已去重)$", RegexOptions.Compiled), "Scan completed; found {0} services (duplicates removed)"),
        (new Regex(@"^共 (\d+) 个 Key$", RegexOptions.Compiled), "{0} keys"),
        (new Regex(@"^已添加节点:(.+)$", RegexOptions.Compiled), "Node added: {0}"),
        (new Regex(@"^已删除节点:(.+)$", RegexOptions.Compiled), "Node deleted: {0}"),
        (new Regex(@"^已保存 (.+?),(\d+) 个字符$", RegexOptions.Compiled), "Saved {0}, {1} characters"),
        (new Regex(@"^成功匹配 (\d+) 处!耗时 (\d+)ms$", RegexOptions.Compiled), "Matched {0} occurrences in {1} ms"),
        (new Regex(@"^成功替换 (\d+) 处!耗时 (\d+)ms$", RegexOptions.Compiled), "Replaced {0} occurrences in {1} ms"),
        (new Regex(@"^批量替换完成:(\d+) 个文件,(\d+) 处替换,耗时 (\d+)ms$", RegexOptions.Compiled), "Batch replace completed: {0} files, {1} replacements in {2} ms"),
        (new Regex(@"^已检测到 (\d+) 个语音资源$", RegexOptions.Compiled), "Detected {0} voice resources"),
        (new Regex(@"^已保存 ICO 到 (.+)$", RegexOptions.Compiled), "ICO saved to {0}"),
        (new Regex(@"^已保存到 (.+)$", RegexOptions.Compiled), "Saved to {0}"),
        (new Regex(@"^文件不存在:(.+)$", RegexOptions.Compiled), "File not found: {0}"),
        (new Regex(@"^已加载:(.+?),(\d+) Hz / (\d+) 位 / (\d+) 声道,时长 ([\d.]+) 秒$", RegexOptions.Compiled), "Loaded: {0}, {1} Hz / {2} bit / {3} channels, duration {4} s"),
        (new Regex(@"^频谱计算完成:(\d+) 帧 × (\d+) 频带,CSV 已写入 (.+)$", RegexOptions.Compiled), "Spectrum ready: {0} frames × {1} bands; CSV written to {2}"),
        (new Regex(@"^正在枚举(.+)…$", RegexOptions.Compiled), "Enumerating {0}..."),
        (new Regex(@"^未发现(.+)设备(可能缺少命令或无设备)。$", RegexOptions.Compiled), "No {0} devices found (missing command or no device)."),
        (new Regex(@"^(.+):(\d+) 项$", RegexOptions.Compiled), "{0}: {1} items"),
        (new Regex(@"^连接失败,返回 (.+)$", RegexOptions.Compiled), "Connection failed; returned {0}"),
        (new Regex(@"^已删除 (.+)$", RegexOptions.Compiled), "Deleted {0}"),
        (new Regex(@"^已打开:(.+) @ (.+) bps$", RegexOptions.Compiled), "Opened: {0} @ {1} bps"),
        (new Regex(@"^已关闭$", RegexOptions.Compiled), "Closed"),
        (new Regex(@"^请先打开通道$", RegexOptions.Compiled), "Please open the channel first"),
        (new Regex(@"^Modbus TCP 主站已就绪 (.+):(\d+)$", RegexOptions.Compiled), "Modbus TCP master ready {0}:{1}"),
        (new Regex(@"^Modbus TCP 从站已启动,监听 127\.0\.0\.1:(\d+),站号 (\d+)$", RegexOptions.Compiled), "Modbus TCP slave started; listening on 127.0.0.1:{0}, unit {1}"),
        (new Regex(@"^串口 (.+) 已打开,(.+)$", RegexOptions.Compiled), "Serial port {0} opened, {1}"),
        (new Regex(@"^Modbus RTU 已连接 (.+),(.+)$", RegexOptions.Compiled), "Modbus RTU connected {0}, {1}"),
        (new Regex(@"^已连接服务器 (.+)$", RegexOptions.Compiled), "Connected to server {0}"),
        (new Regex(@"^已连接 (.+),(.+)$", RegexOptions.Compiled), "Connected to {0}, {1}"),
        (new Regex(@"^已复制 (.+) 结果$", RegexOptions.Compiled), "Copied {0} result"),
        (new Regex(@"^共计算 (\d+) 条$", RegexOptions.Compiled), "Calculated {0} items"),
        (new Regex(@"^已填入表 (.+)$", RegexOptions.Compiled), "Filled table {0}"),
        (new Regex(@"^查询完成:(\d+) 行 · (\d+) ms(.*)$", RegexOptions.Compiled), "Query completed: {0} rows · {1} ms{2}"),
        (new Regex(@"^执行完成:影响 (\d+) 行 · (\d+) ms$", RegexOptions.Compiled), "Execution completed: {0} rows affected · {1} ms"),
        (new Regex(@"^已生成:(.+)(([\d.]+) MB)$", RegexOptions.Compiled), "Generated: {0} ({1} MB)"),
        (new Regex(@"^开始备份到 (.+)\.\.\.$", RegexOptions.Compiled), "Starting backup to {0}..."),
        (new Regex(@"^备份完成,共处理 (\d+) 个文件$", RegexOptions.Compiled), "Backup completed; processed {0} files"),
        (new Regex(@"^正在监听 (\d+)$", RegexOptions.Compiled), "Listening on {0}"),
        (new Regex(@"^监听中 · (?:127\.0\.0\.1:)?(\d+)$", RegexOptions.Compiled), "Listening on {0}"),
        (new Regex(@"^轮询已停止,共 (\d+) 次$", RegexOptions.Compiled), "Polling stopped; {0} polls"),
        (new Regex(@"^开始轮询,间隔 (\d+) ms,读 (\d+) 个寄存器 @ (\d+)$", RegexOptions.Compiled), "Polling started; interval {0} ms, reading {1} registers @ {2}"),
        (new Regex(@"^已选择 (.+),输入内容后按 Ctrl\+Enter 执行$", RegexOptions.Compiled), "Selected {0}; press Ctrl+Enter to run"),
        (new Regex(@"^已回填原文 · (.+) 格式 · 可继续下一步$", RegexOptions.Compiled), "Original restored · {0} format · continue with the next step"),
        (new Regex(@"^已套用模板:(.+)((.*))$", RegexOptions.Compiled), "Template applied: {0} ({1})"),
        (new Regex(@"^已转换为 (.+)((\d+) 字节(.*))$", RegexOptions.Compiled), "Converted to {0} ({1} bytes{2})"),
        (new Regex(@"^设备信息:型号=(.+) 版本=(.+)$", RegexOptions.Compiled), "Device info: model={0}, version={1}"),
        (new Regex(@"^权限提示:(.+)$", RegexOptions.Compiled), "Permission hint: {0}"),
        (new Regex(@"^也可临时授权:(.+)$", RegexOptions.Compiled), "Or grant temporary permission: {0}"),
        (new Regex(@"^刷新设备失败: (.+)$", RegexOptions.Compiled), "Failed to refresh devices: {0}"),
        (new Regex(@"^扫描出错:(.+)$", RegexOptions.Compiled), "Scan error: {0}"),
        (new Regex(@"^获取 API 列表失败: (.+)$", RegexOptions.Compiled), "Failed to get API list: {0}"),
        (new Regex(@"^请求失败: (.+)$", RegexOptions.Compiled), "Request failed: {0}"),
        (new Regex(@"^目标 IP 无效:(.+)$", RegexOptions.Compiled), "Invalid target IP: {0}"),
        (new Regex(@"^端口无效:(\d+)(应为 1~65535)$", RegexOptions.Compiled), "Invalid port: {0} (expected 1-65535)"),
        (new Regex(@"^订阅主题无效:(.+)$", RegexOptions.Compiled), "Invalid subscription topic: {0}"),
        (new Regex(@"^发布主题无效:(.+)$", RegexOptions.Compiled), "Invalid publish topic: {0}"),
        (new Regex(@"^地址无效:(.+)$", RegexOptions.Compiled), "Invalid address: {0}"),
        (new Regex(@"^错误: (.+)$", RegexOptions.Compiled), "Error: {0}"),
        (new Regex(@"^命令执行失败: (.+)$", RegexOptions.Compiled), "Command execution failed: {0}"),
        (new Regex(@"^找到 (\d+) 个 HUB$", RegexOptions.Compiled), "Found {0} hubs"),
    ];

    /// <summary>翻译运行期消息(状态、日志)</summary>
    /// <param name="text">中文原文或动态拼接文本</param>
    /// <returns>当前语言译文;未命中时返回原文,长消息按已知前缀翻译</returns>
    /// <remarks>
    /// 动态消息往往由中文模板拼接异常信息,无法逐条登记为词表键;
    /// 这里先做整串匹配,再按常见前缀翻译,保留尾部动态内容。
    /// </remarks>
    public static String Translate(String text)
    {
        if (text.IsNullOrEmpty()) return "";

        var translated = L.T(text);
        if (translated != text) return translated;

        foreach (var (pattern, template) in _dynamicPatterns)
        {
            var match = pattern.Match(text);
            if (!match.Success) continue;

            var args = new Object[match.Groups.Count - 1];
            for (var i = 0; i < args.Length; i++) args[i] = match.Groups[i + 1].Value;

            return Format(template, args);
        }

        foreach (var prefix in _dynamicPrefixes)
        {
            if (text.Length > prefix.Length && text.StartsWith(prefix, StringComparison.Ordinal))
            {
                var head = L.T(prefix);
                if (head != prefix) return head + text[prefix.Length..];
            }
        }

        return text;
    }

    private static void ApplyFontResources()
    {
        var app = Avalonia.Application.Current;
        if (app == null) return;

        app.Resources["FontUI"] = new FontFamily(FontOptions.GetUiFontFamily(Language));
        app.Resources["FontMono"] = new FontFamily(FontOptions.GetMonoFallback(Language));
    }

    private static void RestoreSystemCulture()
    {
        var code = SystemLanguage;
        if (!code.IsNullOrEmpty()) SetCurrentCulture(code);
    }

    private static void SetCurrentCulture(String code)
    {
        try
        {
            var culture = new CultureInfo(code);
            CultureInfo.CurrentUICulture = culture;
            CultureInfo.DefaultThreadCurrentUICulture = culture;
        }
        catch (CultureNotFoundException) { }
        catch (ArgumentException) { }
    }

    private static String? Normalize(CultureInfo? culture)
    {
        if (culture == null || culture.Name.IsNullOrEmpty()) return null;

        var code = Localization.NormalizeCulture(culture.Name);
        return code.IsNullOrEmpty() ? null : code;
    }
}