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

namespace NewLife.XCoder.Shell;

/// <summary>命令面板:输入即筛选,回车打开工具</summary>
public partial class CommandPaletteWindow : Window
{
    private readonly List<ToolDescriptor> _all = [.. ToolRegistry.Tools];

    /// <summary>实例化命令面板</summary>
    public CommandPaletteWindow()
    {
        InitializeComponent();

        Opened += (_, _) => Input.Focus();
        Input.TextChanged += (_, _) => Refresh();
        Input.KeyDown += OnKeyDown;
        List.DoubleTapped += (_, _) => Accept();

        Refresh();
    }

    private void Refresh()
    {
        var keyword = Input.Text?.Trim() ?? "";
        var list = _all.Where(e => ToolRegistry.Match(e, keyword)).ToList();
        List.ItemsSource = list;
        if (list.Count > 0) List.SelectedIndex = 0;
    }

    private void OnKeyDown(Object? sender, KeyEventArgs e)
    {
        switch (e.Key)
        {
            case Key.Enter:
                Accept();
                e.Handled = true;
                break;
            case Key.Escape:
                Close(null);
                e.Handled = true;
                break;
            case Key.Down:
                Move(1);
                e.Handled = true;
                break;
            case Key.Up:
                Move(-1);
                e.Handled = true;
                break;
        }
    }

    private void Move(Int32 delta)
    {
        if (List.ItemCount == 0) return;

        var index = Math.Clamp(List.SelectedIndex + delta, 0, List.ItemCount - 1);
        List.SelectedIndex = index;
    }

    private void Accept()
    {
        if (List.SelectedItem is ToolDescriptor tool) Close(tool);
    }
}