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

namespace NewLife.XCoder.Tools.Crypto;

/// <summary>加密解密工具</summary>
public partial class CryptoToolView : UserControl
{
    private sealed class CommandGroup
    {
        public TextBlock Header { get; init; } = null!;
        public WrapPanel Panel { get; init; } = null!;
        public List<(CryptoCommandInfo Info, Button Button)> Items { get; } = [];
    }

    private sealed class ResultState
    {
        public String Label { get; init; } = "";
        public String Value { get; set; } = "";
        public CryptoInputFormat Format { get; init; }
    }

    private readonly List<CommandGroup> _groups = [];
    private readonly Dictionary<CryptoCommand, Button> _buttons = [];
    private readonly List<ResultState> _results = [];
    private readonly List<String> _chain = [];
    private CryptoCommandInfo _current = CryptoCommands.All[0];
    private String _parameterScope = "";
    private Boolean _running;
    private Boolean _applyingFormats;
    private Boolean _updatingInput;

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

        BuildCommandList();
        SelectCommand(CryptoCommands.Find(CryptoCommand.Md5_32));

        RunButton.Click += (_, _) => Run();
        SwapButton.Click += (_, _) => Swap();
        SwapTopButton.Click += (_, _) => Swap();
        ClearButton.Click += (_, _) => Clear();
        CopyButton.Click += (_, _) => _ = CopyPrimaryAsync();
        CopyResultButton.Click += (_, _) => _ = CopyPrimaryAsync();
        GenerateKeyButton.Click += OnGenerateKey;

        InputBox.TextChanged += (_, _) =>
        {
            UpdateInputInfo();
            if (!_updatingInput && _chain.Count > 0)
            {
                _chain.Clear();
                ChainText.Text = LocalizationService.T("Not executed yet");
            }
        };
        InputTextRadio.IsCheckedChanged += (_, _) => UpdateInputInfo();
        InputHexRadio.IsCheckedChanged += (_, _) => UpdateInputInfo();
        InputBase64Radio.IsCheckedChanged += (_, _) => UpdateInputInfo();
        OutputTextBox.IsCheckedChanged += (_, _) => OnOutputFormatChanged();
        OutputHexBox.IsCheckedChanged += (_, _) => OnOutputFormatChanged();
        OutputBase64Box.IsCheckedChanged += (_, _) => OnOutputFormatChanged();

        FilterBox.TextChanged += (_, _) => ApplyFilter();
        FilterBox.KeyDown += OnFilterKeyDown;

        AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);

        ClearResults();
        UpdateInputInfo();
        SetStatus("等待执行", false);
    }

    #region 命令栏
    private void BuildCommandList()
    {
        foreach (var group in CryptoCommands.All.GroupBy(e => e.Group))
        {
            var header = new TextBlock { Text = LocalizationService.T(group.Key) };
            header.Classes.Add("sideLabel");

            var panel = new WrapPanel
            {
                Orientation = Orientation.Horizontal,
                ItemWidth = 110,
                ItemHeight = 26,
                ItemSpacing = 4,
                LineSpacing = 2,
            };
            var ui = new CommandGroup { Header = header, Panel = panel };
            foreach (var info in group)
            {
                var button = new Button
                {
                    Content = info.DisplayTitle,
                    Tag = info.Command,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    HorizontalContentAlignment = HorizontalAlignment.Left,
                };
                button.Classes.Add("cmd");
                ToolTip.SetTip(button, info.DisplayDescription);
                button.Click += OnCommandClick;

                panel.Children.Add(button);
                ui.Items.Add((info, button));
                _buttons[info.Command] = button;
            }

            CommandPanel.Children.Add(header);
            CommandPanel.Children.Add(panel);
            _groups.Add(ui);
        }
    }

    private void ApplyFilter()
    {
        var key = FilterBox.Text?.Trim();
        var has = !key.IsNullOrEmpty();
        foreach (var group in _groups)
        {
            var any = false;
            foreach (var (info, button) in group.Items)
            {
                var visible = !has || Match(info, key!);
                button.IsVisible = visible;
                any |= visible;
            }

            group.Header.IsVisible = any;
            group.Panel.IsVisible = any;
        }
    }

    private static Boolean Match(CryptoCommandInfo info, String key) =>
        info.Title.Contains(key, StringComparison.OrdinalIgnoreCase) ||
        info.Description.Contains(key, StringComparison.OrdinalIgnoreCase) ||
        info.SearchKeys.Contains(key, StringComparison.OrdinalIgnoreCase) ||
        info.Group.Contains(key, StringComparison.OrdinalIgnoreCase);

    private void OnCommandClick(Object? sender, RoutedEventArgs e)
    {
        if (sender is not Button { Tag: CryptoCommand command }) return;
        if (_running) return;

        var info = CryptoCommands.Find(command);
        SelectCommand(info);
        RunOrFocus(info);
    }

    private void RunOrFocus(CryptoCommandInfo info)
    {
        if (!info.RequiresInput || (InputBox.Text?.Length ?? 0) > 0)
        {
            Run();
            return;
        }

        SetStatus($"已选择 {info.Title},输入内容后按 Ctrl+Enter 执行", false);
        if (InputPanel.IsVisible) InputBox.Focus();
    }

    private void OnFilterKeyDown(Object? sender, KeyEventArgs e)
    {
        if (e.Key != Key.Enter) return;

        foreach (var group in _groups)
        {
            foreach (var (info, button) in group.Items)
            {
                if (!button.IsVisible) continue;

                SelectCommand(info);
                RunOrFocus(info);
                e.Handled = true;
                return;
            }
        }
    }

    private void SelectCommand(CryptoCommandInfo info)
    {
        var changed = _current.Command != info.Command;
        _current = info;
        TitleText.Text = info.DisplayTitle;
        DescText.Text = info.DisplayDescription;
        InputBox.PlaceholderText = info.DisplayInputPlaceholder;
        SetActiveButton(info.Command);

        ParamPanel.IsVisible = info.UsesRsaKey || info.UsesSignature || info.UsesParameter;
        RsaPanel.IsVisible = info.UsesRsaKey;
        SignaturePanel.IsVisible = info.UsesSignature;
        ParamRow.IsVisible = info.UsesParameter && !info.UsesRsaKey;
        ParamFormatPanel.IsVisible = info.UsesParameterFormat;
        GenerateKeyButton.IsVisible = info.UsesRsaKey;

        if (info.UsesRsaKey)
            ParamLabel.Text = info.UsesSignature ? LocalizationService.T("RSA key and signature") : LocalizationService.T("RSA key (private key decrypt / sign, public key encrypt / verify)");
        else if (info.UsesParameter)
            ParamLabel.Text = info.DisplayParameterTitle;
        else
            ParamLabel.Text = "";

        if (info.UsesParameter)
        {
            ParamBox.PlaceholderText = info.DisplayParameterPlaceholder;
            if (_parameterScope != info.ParameterScope)
            {
                ParamBox.Text = "";
                _parameterScope = info.ParameterScope;
            }
        }
        else
        {
            _parameterScope = "";
        }

        InputPanel.IsVisible = info.UsesInput;
        PipelineGrid.RowDefinitions[0].Height = info.UsesInput
            ? new GridLength(1, GridUnitType.Star)
            : new GridLength(0);
        InputFormatPanel.IsVisible = info.UsesInputFormat;
        OutputFormatPanel.IsVisible = info.UsesOutputFormats;
        SwapButton.IsEnabled = InputPanel.IsVisible && _results.Count > 0;
        SwapTopButton.IsEnabled = SwapButton.IsEnabled;

        if (info.UsesOutputFormats)
        {
            var (text, hex, base64) = info.Command switch
            {
                CryptoCommand.RsaEncrypt or CryptoCommand.RsaSign => (false, false, true),
                CryptoCommand.RsaDecrypt => (true, false, false),
                _ => (false, true, true),
            };
            _applyingFormats = true;
            OutputTextBox.IsChecked = text;
            OutputHexBox.IsChecked = hex;
            OutputBase64Box.IsChecked = base64;
            _applyingFormats = false;
        }

        if (changed && info.UsesInputFormat)
        {
            if (info.Command == CryptoCommand.RsaDecrypt && InputTextRadio.IsChecked == true && InputBox.Text.IsNullOrEmpty())
                InputBase64Radio.IsChecked = true;

            // 切换算法时保留用户已有的输入格式,便于同一份数据继续处理
        }

        UpdateInputInfo();
    }

    private void SetActiveButton(CryptoCommand command)
    {
        foreach (var item in _buttons)
        {
            item.Value.Classes.Set("active", item.Key == command);
        }
    }
    #endregion

    #region 执行
    private async void Run()
    {
        if (_running) return;

        var info = _current;
        var input = InputBox.Text ?? "";
        if (info.UsesInput && info.RequiresInput && input.Length == 0)
        {
            SetStatus("请先输入待处理内容", true);
            InputBox.Focus();
            return;
        }

        if (info.UsesRsaKey)
        {
            try
            {
                EnsureRsaKey(info);
            }
            catch (Exception ex)
            {
                SetStatus("生成 RSA 密钥失败:" + ex.Message, true);
                return;
            }
        }

        var options = BuildOptions(info);
        if (info.UsesOutputFormats && !options.TextOutput && !options.HexOutput && !options.Base64Output)
        {
            SetStatus("请至少选择一种输出格式", true);
            return;
        }

        _running = true;
        RunButton.IsEnabled = false;
        SwapButton.IsEnabled = false;
        SwapTopButton.IsEnabled = false;
        SetStatus("执行中…", false);
        var sw = Stopwatch.StartNew();
        try
        {
            var result = await Task.Run(() => CryptoService.Execute(info.Command, input, options));
            sw.Stop();
            if (_current.Command != info.Command) return;

            RenderResult(result);
            OutputInfoText.Text = $"{info.Title} · {sw.ElapsedMilliseconds} ms";
            AppendChain(info.Title);

            if (result.IsError)
                SetStatus(result.Text, true);
            else
                SetStatus($"完成 · {sw.ElapsedMilliseconds} ms · {GetResultSize(result)}", false);
        }
        catch (Exception ex)
        {
            var error = new CryptoResult { Text = LocalizationService.T("Execution failed:") + " " + ex.Message, IsError = true };
            RenderResult(error);
            OutputInfoText.Text = LocalizationService.Format("{0} · Failed", info.Title);
            SetStatus("执行失败:" + ex.Message, true);
        }
        finally
        {
            _running = false;
            RunButton.IsEnabled = true;
            UpdateActionState();
        }
    }

    private CryptoOptions BuildOptions(CryptoCommandInfo info) => new()
    {
        InputFormat = GetInputFormat(),
        ParameterFormat = ParamHexRadio.IsChecked == true
            ? CryptoInputFormat.Hex
            : ParamBase64Radio.IsChecked == true ? CryptoInputFormat.Base64 : CryptoInputFormat.Text,
        TextOutput = OutputTextBox.IsChecked == true,
        HexOutput = OutputHexBox.IsChecked == true,
        Base64Output = OutputBase64Box.IsChecked == true,
        Key = ResolveRsaKey(info),
        Signature = SignatureBox.Text ?? "",
        Parameter = ParamBox.Text ?? "",
    };

    private CryptoInputFormat GetInputFormat()
    {
        if (InputHexRadio.IsChecked == true) return CryptoInputFormat.Hex;
        if (InputBase64Radio.IsChecked == true) return CryptoInputFormat.Base64;

        return CryptoInputFormat.Text;
    }

    private void SetInputFormat(CryptoInputFormat format)
    {
        InputTextRadio.IsChecked = format == CryptoInputFormat.Text;
        InputHexRadio.IsChecked = format == CryptoInputFormat.Hex;
        InputBase64Radio.IsChecked = format == CryptoInputFormat.Base64;
    }

    private void UpdateInputInfo()
    {
        var text = InputBox.Text ?? "";
        if (text.Length == 0)
        {
            InputInfoText.Text = "";
            InputInfoText.Classes.Set("error", false);
            return;
        }

        var format = _current.UsesInputFormat ? GetInputFormat() : CryptoInputFormat.Text;
        if (format == CryptoInputFormat.Text)
        {
            InputInfoText.Text = LocalizationService.Format("{0} chars · {1} bytes", text.Length, Encoding.UTF8.GetByteCount(text));
            InputInfoText.Classes.Set("error", false);
            return;
        }

        var label = format == CryptoInputFormat.Hex ? "HEX" : "Base64";
        try
        {
            var bytes = CryptoService.ParseInput(text, format);
            InputInfoText.Text = LocalizationService.Format("{0} · {1} bytes", label, bytes.Length);
            InputInfoText.Classes.Set("error", false);
        }
        catch
        {
            InputInfoText.Text = LocalizationService.Format("{0} format is invalid", label);
            InputInfoText.Classes.Set("error", true);
        }
    }

    private void OnOutputFormatChanged()
    {
        if (_applyingFormats || _running || !_current.UsesOutputFormats || _results.Count == 0) return;

        Run();
    }

    private void RenderResult(CryptoResult result)
    {
        ResultPanel.Children.Clear();
        _results.Clear();

        var outputs = result.Outputs.Count > 0
            ? result.Outputs
            : [new CryptoOutput { Label = result.IsError ? "错误" : "结果", Value = result.Text, Format = CryptoInputFormat.Text }];

        foreach (var output in outputs)
        {
            if (output.Value.Length == 0) continue;

            var state = new ResultState { Label = output.Label, Value = output.Value, Format = output.Format };
            _results.Add(state);
            ResultPanel.Children.Add(CreateResultRow(output, state));
        }

        EmptyHint.IsVisible = _results.Count == 0;
        UpdateActionState();
    }

    private Control CreateResultRow(CryptoOutput output, ResultState state)
    {
        var row = new Border();
        row.Classes.Add("resultRow");

        var grid = new Grid
        {
            ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto,Auto,Auto"),
            ColumnSpacing = 8,
        };

        var badge = new Border { VerticalAlignment = VerticalAlignment.Center };
        badge.Classes.Add("resultBadge");
        badge.Child = new TextBlock
        {
            Text = output.Label,
            VerticalAlignment = VerticalAlignment.Center,
        };
        badge.Child.Classes.Add("resultBadgeText");
        grid.Children.Add(badge);

        var valueBox = new TextBox
        {
            Text = state.Value,
            IsReadOnly = true,
            AcceptsReturn = true,
            TextWrapping = TextWrapping.Wrap,
            MaxHeight = 112,
            MinHeight = 24,
            VerticalContentAlignment = VerticalAlignment.Top,
            VerticalAlignment = VerticalAlignment.Center,
        };
        valueBox.Classes.Add("resultValue");
        grid.Children.Add(valueBox);
        Grid.SetColumn(valueBox, 1);

        var column = 2;
        if (output.Variants.Count > 1)
        {
            var combo = new ComboBox
            {
                Width = 96,
                FontSize = 11,
                VerticalAlignment = VerticalAlignment.Center,
                ItemsSource = output.Variants.Select(e => e.Label).ToList(),
                SelectedIndex = 0,
            };
            combo.SelectionChanged += (_, _) =>
            {
                var index = combo.SelectedIndex;
                if (index < 0 || index >= output.Variants.Count) return;

                state.Value = output.Variants[index].Value;
                valueBox.Text = state.Value;
            };
            grid.Children.Add(combo);
            Grid.SetColumn(combo, column++);
        }

        var copy = new Button
        {
            Content = LocalizationService.T("Copy"),
            FontSize = 11,
            Padding = new Thickness(6, 2),
            VerticalAlignment = VerticalAlignment.Center,
        };
        copy.Classes.Add("ghost");
        ToolTip.SetTip(copy, LocalizationService.T("Copy this result"));
        copy.Click += async (_, _) => await CopyTextAsync(valueBox.Text ?? "", output.Label);
        grid.Children.Add(copy);
        Grid.SetColumn(copy, column++);

        var toInput = new Button
        {
            Content = LocalizationService.T("↑ Original"),
            FontSize = 11,
            Padding = new Thickness(6, 2),
            VerticalAlignment = VerticalAlignment.Center,
        };
        toInput.Classes.Add("ghost");
        ToolTip.SetTip(toInput, LocalizationService.T("Fill the original back and switch to this format automatically; continue with the next step"));
        toInput.Click += (_, _) => SendToInput(valueBox.Text ?? "", output.Format);
        grid.Children.Add(toInput);
        Grid.SetColumn(toInput, column);

        row.Child = grid;

        return row;
    }

    private void SendToInput(String value, CryptoInputFormat format)
    {
        SetInputFormat(format);
        _updatingInput = true;
        InputBox.Text = value;
        _updatingInput = false;
        UpdateInputInfo();
        SetStatus($"已回填原文 · {FormatLabel(format)} 格式 · 可继续下一步", false);
        if (InputPanel.IsVisible) InputBox.Focus();
    }

    private static String FormatLabel(CryptoInputFormat format) => format switch
    {
        CryptoInputFormat.Hex => "HEX",
        CryptoInputFormat.Base64 => "Base64",
        _ => "字符串",
    };

    private static String GetResultSize(CryptoResult result)
    {
        var bytes = 0;
        try
        {
            bytes = Encoding.UTF8.GetByteCount(result.Text);
        }
        catch
        {
            // 极端文本无法计数时忽略
        }

        return bytes > 0 ? $"输出 {result.Text.Length} 字符 / {bytes} 字节" : $"输出 {result.Text.Length} 字符";
    }

    private void AppendChain(String title)
    {
        _chain.Add(title);
        if (_chain.Count > 6) _chain.RemoveAt(0);

        ChainText.Text = _chain.Count == 0 ? LocalizationService.T("Not executed yet") : LocalizationService.T("Chain: ") + String.Join(" → ", _chain.TakeLast(4));
    }

    private void UpdateActionState()
    {
        var hasResults = _results.Count > 0;
        SwapButton.IsEnabled = InputPanel.IsVisible && hasResults;
        SwapTopButton.IsEnabled = SwapButton.IsEnabled;
        CopyButton.IsEnabled = hasResults;
        CopyResultButton.IsEnabled = hasResults;
    }

    private String ResolveRsaKey(CryptoCommandInfo info)
    {
        var privateKey = PrivateKeyBox.Text?.Trim() ?? "";
        var publicKey = PublicKeyBox.Text?.Trim() ?? "";

        return info.Command is CryptoCommand.RsaDecrypt or CryptoCommand.RsaSign
            ? privateKey
            : publicKey.Length > 0 ? publicKey : privateKey;
    }

    private void EnsureRsaKey(CryptoCommandInfo info)
    {
        if (info.Command is not (CryptoCommand.RsaEncrypt or CryptoCommand.RsaSign)) return;
        if (ResolveRsaKey(info).Length > 0) return;

        var keys = CryptoService.GenerateRsaKeyPair();
        PrivateKeyBox.Text = keys.PrivateKey;
        PublicKeyBox.Text = keys.PublicKey;
    }

    private async void OnGenerateKey(Object? sender, RoutedEventArgs e)
    {
        GenerateKeyButton.IsEnabled = false;
        SetStatus("正在生成 2048 位 RSA 密钥对…", false);
        try
        {
            var keys = await Task.Run(() => CryptoService.GenerateRsaKeyPair());
            PrivateKeyBox.Text = keys.PrivateKey;
            PublicKeyBox.Text = keys.PublicKey;
            SetStatus("密钥对已生成:私钥用于解密/签名,公钥用于加密/验签", false);
        }
        catch (Exception ex)
        {
            SetStatus("生成失败:" + ex.Message, true);
        }
        finally
        {
            GenerateKeyButton.IsEnabled = true;
        }
    }

    private void OnPreviewKeyDown(Object? sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter && e.KeyModifiers.HasFlag(KeyModifiers.Control))
        {
            Run();
            e.Handled = true;
        }
    }
    #endregion

    #region 辅助
    /// <summary>把主结果与原文互换,并按结果格式切换输入格式</summary>
    private void Swap()
    {
        if (_results.Count == 0)
        {
            SetStatus("没有可交换的结果", true);
            return;
        }

        var primary = _results[0];
        var oldText = InputBox.Text ?? "";
        var oldFormat = GetInputFormat();

        SetInputFormat(primary.Format);
        _updatingInput = true;
        InputBox.Text = primary.Value;
        _updatingInput = false;
        UpdateInputInfo();

        ResultPanel.Children.Clear();
        _results.Clear();
        if (!oldText.IsNullOrEmpty())
        {
            var output = new CryptoOutput { Label = "互换前原文", Value = oldText, Format = oldFormat };
            var state = new ResultState { Label = output.Label, Value = output.Value, Format = output.Format };
            _results.Add(state);
            ResultPanel.Children.Add(CreateResultRow(output, state));
        }

        EmptyHint.IsVisible = _results.Count == 0;
        OutputInfoText.Text = LocalizationService.T("Swapped");
        SetStatus(LocalizationService.Format("Swapped: result ({0}) → original; continue with the next step", FormatLabel(primary.Format)), false);
        UpdateActionState();
    }

    private void Clear()
    {
        InputBox.Text = "";
        _chain.Clear();
        ChainText.Text = LocalizationService.T("Not executed yet");
        ClearResults();
        SetStatus(LocalizationService.T("Cleared"), false);
        if (InputPanel.IsVisible) InputBox.Focus();
    }

    private void ClearResults()
    {
        ResultPanel.Children.Clear();
        _results.Clear();
        EmptyHint.IsVisible = true;
        OutputInfoText.Text = "";
        UpdateActionState();
    }

    private async Task CopyPrimaryAsync()
    {
        if (_results.Count == 0)
        {
            SetStatus("没有可复制的结果", true);
            return;
        }

        await CopyTextAsync(_results[0].Value, _results[0].Label);
    }

    private async Task CopyTextAsync(String text, String label)
    {
        if (text.Length == 0)
        {
            SetStatus("没有可复制的结果", true);
            return;
        }

        var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
        if (clipboard == null)
        {
            SetStatus("当前环境无法访问剪贴板", true);
            return;
        }

        await clipboard.SetTextAsync(text);
        SetStatus($"已复制 {label} 结果", false);
    }

    private void SetStatus(String text, Boolean error)
    {
        StatusText.Text = NewLife.XCoder.Services.LocalizationService.Translate(text);
        StatusText.Classes.Set("error", error);
        StatusText.Classes.Set("ok", !error && (text.StartsWith("完成") || text.StartsWith("已复制") || text.StartsWith("已互换") || text.StartsWith("已回填") || text.StartsWith("验证通过") || text.StartsWith("密钥对已生成")));
    }
    #endregion
}