借助网络配置,控制Modbus工具的日志显示,避免卡死界面
智能大石头 authored at 2021-12-11 22:09:19
14.41 KiB
XCoder
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Interactivity;
using NewLife;
using NewLife.XCoder.Services;

namespace NewLife.XCoder.Tools.Settings;

/// <summary>设置中心:主题、语言、目录、在线更新与外壳行为</summary>
public partial class SettingsToolView : UserControl
{
    private readonly List<String> _languageCodes = [LocalizationService.Auto, .. LocalizationService.Languages];
    private readonly ObservableCollection<String> _languageNames = [];
    private UpdateManifest? _update;
    private Boolean _loadingShell;
    private Boolean _loadingLanguage;
    private Boolean _refreshingLocalizedState;
    private Boolean _localizationSubscribed;
    private String _downloadedPath = "";

    /// <summary>实例化</summary>
    public SettingsToolView()
    {
        InitializeComponent();

        ThemeAutoButton.Click += (_, _) => SwitchTheme("auto");
        ThemeLightButton.Click += (_, _) => SwitchTheme("light");
        ThemeDarkButton.Click += (_, _) => SwitchTheme("dark");
        OpenConfigButton.Click += (_, _) => OpenPath(AppPaths.ConfigDirectory);
        OpenLogButton.Click += (_, _) => OpenPath(AppPaths.LogDirectory);
        OpenCacheButton.Click += (_, _) => OpenPath(AppPaths.CacheDirectory);
        RefreshCredentialButton.Click += (_, _) => RefreshCredentials();
        ClearCredentialButton.Click += (_, _) =>
        {
            CredentialStore.Instance.Clear();
            RefreshCredentials();
        };
        SaveQuickButton.Click += (_, _) => SaveQuickTools();
        ResetQuickButton.Click += (_, _) =>
        {
            QuickToolsStore.Reset();
            RefreshQuickTools();
            QuickText.Text = LocalizationService.T("Defaults restored");
        };
        CheckUpdateButton.Click += (_, _) => _ = CheckUpdateAsync();
        OpenDownloadButton.Click += (_, _) => OpenDownload();
        DownloadButton.Click += (_, _) => _ = DownloadAsync();
        RunInstallerButton.Click += (_, _) => RunInstaller();

        LanguageBox.SelectionChanged += OnLanguageSelectionChanged;
        RefreshLanguageBox();

        RefreshTexts();
        RefreshCredentials();
        RefreshQuickTools();
        RefreshShellPreference();

        CloseToTrayBox.IsCheckedChanged += SaveShellPreference;
        FloatOnTopBox.IsCheckedChanged += SaveShellPreference;
        HotkeyBox.LostFocus += SaveHotkey;
        HotkeyBox.KeyDown += (s, e) =>
        {
            if (e.Key == Avalonia.Input.Key.Enter) SaveHotkey(s, e);
        };

        SubscribeLocalization();
        AttachedToVisualTree += (_, _) =>
        {
            // 视图在后台时可能错过语言切换,重新显示时统一刷新一次
            SubscribeLocalization();
            RefreshLocalizedState();
        };
        DetachedFromVisualTree += (_, _) => UnsubscribeLocalization();
    }

    private void SubscribeLocalization()
    {
        if (_localizationSubscribed) return;

        _localizationSubscribed = true;
        LocalizationService.Changed += OnLanguageChanged;
    }

    private void UnsubscribeLocalization()
    {
        if (!_localizationSubscribed) return;

        _localizationSubscribed = false;
        LocalizationService.Changed -= OnLanguageChanged;
    }

    private void RefreshLanguageBox()
    {
        _loadingLanguage = true;
        try
        {
            var codes = _languageCodes;
            var names = new List<String>(codes.Count);
            foreach (var code in codes)
            {
                names.Add(code == LocalizationService.Auto
                    ? LocalizationService.Format("Follow system ({0})", LocalizationService.DisplayName(LocalizationService.AutoLanguage))
                    : $"{LocalizationService.DisplayName(code)}({code})");
            }

            // 原地更新条目,避免替换 ItemsSource 触发 ComboBox 重选并反噬语言切换
            if (LanguageBox.ItemsSource == null) LanguageBox.ItemsSource = _languageNames;
            if (_languageNames.Count == names.Count)
            {
                for (var i = 0; i < names.Count; i++)
                {
                    if (_languageNames[i] != names[i]) _languageNames[i] = names[i];
                }
            }
            else
            {
                _languageNames.Clear();
                foreach (var name in names) _languageNames.Add(name);
            }

            var index = codes.IndexOf(LocalizationService.Preference);
            LanguageBox.SelectedIndex = index >= 0 ? index : 0;
        }
        finally
        {
            _loadingLanguage = false;
        }
    }

    private void OnLanguageSelectionChanged(Object? sender, SelectionChangedEventArgs e)
    {
        if (_loadingLanguage || _refreshingLocalizedState) return;

        var index = LanguageBox.SelectedIndex;
        if (index < 0 || index >= _languageCodes.Count) return;

        var language = _languageCodes[index];
        if (language != LocalizationService.Preference)
        {
            if (!LocalizationService.Apply(language)) RefreshLanguageBox();
            return;
        }

        RefreshTexts();
    }

    private void OnLanguageChanged(String language)
    {
        if (!LanguageBox.Dispatcher.CheckAccess())
        {
            LanguageBox.Dispatcher.Post(() => OnLanguageChanged(language));
            return;
        }

        RefreshLocalizedState();
    }

    private void RefreshLocalizedState()
    {
        if (_refreshingLocalizedState) return;

        _refreshingLocalizedState = true;
        try
        {
            RefreshLanguageBox();
            RefreshTexts();
            RefreshCredentials();
            RefreshQuickTools();
            RefreshShellPreference();
        }
        finally
        {
            _refreshingLocalizedState = false;
        }
    }

    private void RefreshCredentials()
    {
        var keys = CredentialStore.Instance.Keys;
        CredentialText.Text = keys.Count == 0
            ? LocalizationService.T("No credentials")
            : LocalizationService.Format("{0} items: {1}", keys.Count, String.Join(", ", keys));
    }

    private void RefreshShellPreference()
    {
        _loadingShell = true;
        try
        {
            var preference = ShellPreferenceStore.Load();
            CloseToTrayBox.IsChecked = preference.CloseToTray;
            FloatOnTopBox.IsChecked = preference.FloatOnTop;
            HotkeyBox.Text = preference.Hotkey;
            ShellHintText.Text = preference.CloseToTray
                ? LocalizationService.T("Current: stays in tray after closing; exit from tray menu")
                : LocalizationService.T("Current: exits when closed");
        }
        finally
        {
            _loadingShell = false;
        }
    }

    private void SaveShellPreference(Object? sender, RoutedEventArgs e)
    {
        if (_loadingShell) return;

        SaveCurrentShellPreference();
        RefreshShellPreference();
    }

    private void SaveCurrentShellPreference()
    {
        // 以外壳现有偏好为基线,避免设置页只改两项时把侧栏折叠等状态洗掉
        var preference = ShellPreferenceStore.Load() with
        {
            CloseToTray = CloseToTrayBox.IsChecked == true,
            FloatOnTop = FloatOnTopBox.IsChecked == true,
        };

        // 热键文本非法时不落盘,保留旧值并提示,避免下次启动静默失效
        if (!ShellPreferenceStore.TrySave(preference, HotkeyBox.Text, out var error))
        {
            ShellHintText.Text = LocalizationService.Format("Invalid hotkey: {0}", error);
        }
    }

    private void SaveHotkey(Object? sender, RoutedEventArgs e)
    {
        if (_loadingShell) return;

        SaveCurrentShellPreference();
        ShellHintText.Text = LocalizationService.T("Hotkey saved; restart the app to apply");
    }

    private void RefreshQuickTools()
    {
        var keys = QuickToolsStore.Load();
        QuickBox.Text = String.Join(',', keys);
        QuickText.Text = LocalizationService.Format("Quick access: {0} tools", keys.Count);
    }

    private void SaveQuickTools()
    {
        var input = QuickBox.Text;
        var keys = String.IsNullOrWhiteSpace(input) ? [] : QuickToolsStore.Split(input);
        if (keys.Count == 0)
        {
            QuickToolsStore.Reset();
            RefreshQuickTools();
            QuickText.Text = LocalizationService.T("Defaults restored");
            return;
        }

        var saved = QuickToolsStore.Save(keys);

        // 先刷新列表再写提示,否则"已保存"会被 Refresh 的"当前 N 个"覆盖
        RefreshQuickTools();
        QuickText.Text = LocalizationService.Format("Saved {0} tools", saved.Count);
    }

    private void SwitchTheme(String mode)
    {
        ThemeService.Apply(mode);
        RefreshTexts();
    }

    private async Task CheckUpdateAsync()
    {
        CheckUpdateButton.IsEnabled = false;
        UpdateText.Text = LocalizationService.T("Checking…");
        OpenDownloadButton.IsVisible = false;
        UpdateNoteText.IsVisible = false;

        try
        {
            var manifest = await UpdateChecker.FetchAsync();
            _update = manifest;

            if (manifest == null)
            {
                UpdateText.Text = LocalizationService.T("Update check failed (network unavailable or manifest unreachable); the app remains usable");
                return;
            }

            var current = AppInfo.Version;
            if (!UpdateChecker.IsNewer(current, manifest.Version))
            {
                UpdateText.Text = LocalizationService.Format("Already up to date ({0})", current);
                return;
            }

            UpdateText.Text = LocalizationService.Format("New version available: {0}", manifest.Version);
            if (!manifest.Notes.IsNullOrEmpty())
            {
                UpdateNoteText.Text = manifest.Notes;
                UpdateNoteText.IsVisible = true;
            }
            if (!manifest.Url.IsNullOrEmpty()) OpenDownloadButton.IsVisible = true;
            DownloadButton.IsVisible = !manifest.Url.IsNullOrEmpty();
        }
        finally
        {
            CheckUpdateButton.IsEnabled = true;
        }
    }

    private async Task DownloadAsync()
    {
        var url = _update?.Url;
        if (url.IsNullOrEmpty())
        {
            UpdateText.Text = LocalizationService.T("No update package is available for download");
            return;
        }

        DownloadButton.IsEnabled = false;
        RunInstallerButton.IsVisible = false;
        UpdateText.Text = LocalizationService.T("Downloading installer…");
        try
        {
            var path = await UpdateChecker.DownloadAsync(url!);
            _downloadedPath = path;
            UpdateText.Text = LocalizationService.Format("Downloaded: {0}", path);

            // 只有 exe / msi 才提供直接运行入口,压缩包仍走「打开目录」
            RunInstallerButton.IsVisible = UpdateChecker.IsInstallerFile(path);
            OpenPath(Path.GetDirectoryName(path) ?? AppPaths.CacheDirectory);
        }
        catch (Exception ex)
        {
            UpdateText.Text = LocalizationService.Format("Download failed: {0} (use Open download page to download manually)", ex.Message);
        }
        finally
        {
            DownloadButton.IsEnabled = true;
        }
    }

    private void RunInstaller()
    {
        var path = _downloadedPath;
        if (path.IsNullOrEmpty() || !UpdateChecker.IsInstallerFile(path))
        {
            UpdateText.Text = LocalizationService.T("Installer not found; please download again");
            return;
        }

        try
        {
            Process.Start(new ProcessStartInfo(path!) { UseShellExecute = true });
            UpdateText.Text = LocalizationService.T("Installer started; follow the prompts to finish");
        }
        catch (Exception ex)
        {
            UpdateText.Text = LocalizationService.Format("Failed to start installer: {0} (run it manually from the download folder)", ex.Message);
        }
    }

    private void OpenDownload()
    {
        var url = _update?.Url;
        if (url.IsNullOrEmpty()) return;

        try
        {
            Process.Start(new ProcessStartInfo(url!) { UseShellExecute = true });
        }
        catch (Exception)
        {
            // 打不开浏览器不影响界面
        }
    }

    private void RefreshTexts()
    {
        ThemeText.Text = ThemeService.Label;
        LanguageText.Text = LocalizationService.PreferenceName;

        switch (ThemeService.Mode)
        {
            case "light": ThemeLightButton.Classes.Set("primary", true); ThemeAutoButton.Classes.Set("primary", false); ThemeDarkButton.Classes.Set("primary", false); break;
            case "dark": ThemeDarkButton.Classes.Set("primary", true); ThemeAutoButton.Classes.Set("primary", false); ThemeLightButton.Classes.Set("primary", false); break;
            default: ThemeAutoButton.Classes.Set("primary", true); ThemeLightButton.Classes.Set("primary", false); ThemeDarkButton.Classes.Set("primary", false); break;
        }

        PathText.Text = LocalizationService.Format("Config: {0}", AppPaths.ConfigDirectory) + Environment.NewLine
            + LocalizationService.Format("Logs: {0}", AppPaths.LogDirectory) + Environment.NewLine
            + LocalizationService.Format("Cache: {0}", AppPaths.CacheDirectory);

        var version = AppInfo.Version;
        VersionText.Text = LocalizationService.Format("Version: {0} · {1}", version, RuntimeInformation.OSDescription);

        if (_update != null)
        {
            UpdateText.Text = UpdateChecker.IsNewer(AppInfo.Version, _update.Version)
                ? LocalizationService.Format("New version available: {0}", _update.Version)
                : LocalizationService.Format("Already up to date ({0})", AppInfo.Version);
        }
    }

    private void OpenPath(String path)
    {
        try
        {
            if (AppPaths.IsWindows) Process.Start(new ProcessStartInfo("explorer.exe", $"\"{path}\"") { UseShellExecute = true });
            else if (AppPaths.IsMacOS) Process.Start(new ProcessStartInfo("open", $"\"{path}\"") { UseShellExecute = true });
            else Process.Start(new ProcessStartInfo("xdg-open", $"\"{path}\"") { UseShellExecute = true });
        }
        catch (Exception)
        {
            // 打不开目录不影响功能,界面上依然能看到路径
        }
    }
}