XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Threading;
using Microsoft.Win32;
using XFEToolBox.Client.Core.Search;
using XFEToolBox.Client.Core.Search.Service;
using XFEToolBox.Client.Utilities;
using XFEToolBox.Client.ViewModel.Pages;
using Forms = System.Windows.Forms;
using XFEToolBox.QuickTools;

namespace XFEToolBox.Client.Views.Windows;

public enum CommandPaletteSection { Files, Tools }

public partial class CommandPaletteWindow : Window
{
    private readonly FileSearchRuntime fileSearch;
    private readonly QuickSearchQueryMemory? queryMemory;
    private readonly DispatcherTimer statusTimer;
    private long queryRevision;
    private CancellationTokenSource? searchCancellation;
    private int searchGeneration;
    private int indexDirty;
    private int resultLimit = 100;
    private bool ready;
    private bool isSearching;
    private bool changingScope;
    private long lastAutomaticRefresh;
    private bool expensiveSearch;
    private bool refreshingService;
    private nint previousWindow;
    private string? lastQuickQuery;
    private QuickResult[]? lastQuickResults;

    public static readonly DependencyProperty ResultViewScaleProperty = DependencyProperty.Register(
        nameof(ResultViewScale), typeof(double), typeof(CommandPaletteWindow), new PropertyMetadata(1d));
    public double ResultViewScale => (double)GetValue(ResultViewScaleProperty);

    public CommandPaletteSection SelectedSection { get; private set; } = CommandPaletteSection.Files;

    public CommandPaletteWindow() : this(FileSearchRuntime.Shared, QuickSearchQueryMemory.Shared) { }

    internal CommandPaletteWindow(FileSearchRuntime fileSearch, QuickSearchQueryMemory? queryMemory = null)
    {
        this.fileSearch = fileSearch;
        this.queryMemory = queryMemory;
        InitializeComponent();
        statusTimer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromSeconds(1) };
        statusTimer.Tick += StatusTimer_Tick;
        fileSearch.Changed += FileSearch_Changed;
        Closed += (_, _) =>
        {
            queryRevision++;
            statusTimer.Stop();
            CancelSearch();
            fileSearch.Changed -= FileSearch_Changed;
            DisposeFileRows(ResultList.ItemsSource as FileSearchResultViewModel[]);
        };
        ready = true;
        if (queryMemory is not null) _ = RestoreQueryAsync();
    }

    public void ShowPalette(string? initialQuery = null, CommandPaletteSection section = CommandPaletteSection.Files)
    {
        var foreground=SystemActions.ForegroundWindow();
        if(foreground!=new WindowInteropHelper(this).Handle)previousWindow=foreground;
        lastQuickQuery=null;lastQuickResults=null;
        SetSection(section);
        PrepareQueryForOpen(initialQuery);
        PositionOnCurrentScreen();
        if (!IsVisible) Show();
        WindowState = WindowState.Normal;
        Activate();
        SearchBox.Focus();
        resultLimit = 100;
        _ = RefreshResultsAsync(debounce: false);
    }

    internal void PrepareQueryForOpen(string? initialQuery)
    {
        // A hotkey/tray reopen has no new query. Only an explicit query (including
        // an explicit empty one) replaces the user's last input.
        if (initialQuery is not null)
        {
            queryRevision++;
            SearchBox.Text = initialQuery;
            queryMemory?.Remember(QuickQuery.IsQuery(initialQuery)?string.Empty:initialQuery);
        }
        SearchBox.CaretIndex = SearchBox.Text.Length;
    }

    private async Task RestoreQueryAsync()
    {
        var revision = queryRevision;
        var query = await queryMemory!.LoadAsync();
        // Loading never overwrites typing/clear/explicit query that happened
        // while the tiny state file was being read on a worker.
        if (revision != queryRevision) return;
        SearchBox.Text = query;
        SearchBox.CaretIndex = SearchBox.Text.Length;
    }

    internal Task FlushRememberedQueryAsync() => queryMemory?.FlushAsync() ?? Task.CompletedTask;

    private void Window_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        if (!ready) return;
        if (IsVisible)
        {
            statusTimer.Start();
            if (SelectedSection == CommandPaletteSection.Files) _ = InitializeFilesAsync();
        }
        else
        {
            statusTimer.Stop();
            CancelSearch();
            SearchHelpPopup.IsOpen = false;
        }
    }

    private async Task InitializeFilesAsync()
    {
        try
        {
            await fileSearch.InitializeAsync();
            UpdateIndexStatus();
            Interlocked.Exchange(ref indexDirty, 1);
        }
        catch (Exception exception) { StatusText.Text = $"文件索引暂时不可用:{exception.Message}"; }
    }

    private void Section_Checked(object sender, RoutedEventArgs e)
    {
        if (!ready) return;
        SetSection(ReferenceEquals(sender, ToolsTab) ? CommandPaletteSection.Tools : CommandPaletteSection.Files);
        resultLimit = 100;
        _ = RefreshResultsAsync(debounce: false);
    }

    private void SetSection(CommandPaletteSection section)
    {
        SelectedSection = section;
        FilesTab.IsChecked = section == CommandPaletteSection.Files;
        ToolsTab.IsChecked = section == CommandPaletteSection.Tools;
        FileOptions.Visibility = section == CommandPaletteSection.Files ? Visibility.Visible : Visibility.Collapsed;
        ToolsHint.Visibility = section == CommandPaletteSection.Tools ? Visibility.Visible : Visibility.Collapsed;
        HelpButton.Visibility = section == CommandPaletteSection.Files ? Visibility.Visible : Visibility.Collapsed;
        CarryClipboard.Visibility = section == CommandPaletteSection.Tools ? Visibility.Visible : Visibility.Collapsed;
        SearchHint.Text = section == CommandPaletteSection.Files ? "输入文件名、路径或通配符…" : "搜索工具、软件、页面、项目和命令…";
        SearchHelpPopup.IsOpen = false;
        if (IsVisible && section == CommandPaletteSection.Files) _ = InitializeFilesAsync();
        UpdateIndexStatus();
    }

    private async void SearchBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (!ready) return;
        queryRevision++;
        queryMemory?.Remember(QuickQuery.IsQuery(SearchBox.Text)?string.Empty:SearchBox.Text);
        SearchHint.Visibility = SearchBox.Text.Length == 0 ? Visibility.Visible : Visibility.Collapsed;
        resultLimit = 100;
        await RefreshResultsAsync();
    }

    private async Task RefreshResultsAsync(bool debounce = true)
    {
        if (!ready || !IsVisible || changingScope) return;
        CancelSearch();
        var generation = searchGeneration;
        var cancellation = searchCancellation = new CancellationTokenSource();
        var token = cancellation.Token;
        var query = SearchBox.Text;
        var section = SelectedSection;
        var includeContent = IncludeContent.IsChecked == true;
        var selection = SelectedKey();
        isSearching = true;
        try
        {
            // Replaced keystrokes are ordinary control flow, not cancellation exceptions.
            if (debounce) await Task.Delay(120);
            if (token.IsCancellationRequested || generation != searchGeneration || !IsVisible) return;
            StatusText.Text = "正在搜索…";
            if(QuickQuery.IsQuery(query))
            {
                var quick=query==lastQuickQuery&&lastQuickResults is not null?lastQuickResults:await Task.Run(()=>QuickQuery.Execute(query),token);
                if(token.IsCancellationRequested||generation!=searchGeneration||!IsVisible)return;
                lastQuickQuery=query;lastQuickResults=quick;
                DisposeFileRows(ResultList.ItemsSource as FileSearchResultViewModel[]);ResultList.ItemsSource=quick;ResultList.SelectedIndex=quick.Length>0?0:-1;
                EmptyState.Visibility=quick.Length==0?Visibility.Visible:Visibility.Collapsed;LoadMoreButton.Visibility=Visibility.Collapsed;
                StatusText.Text="快捷操作 · Enter 复制 / 打开 · F5 刷新 · 计算与文本输入不保存到搜索历史";
                return;
            }
            if (section == CommandPaletteSection.Files)
            {
                var page = await fileSearch.SearchAsync(query, includeContent, resultLimit, token);
                if (page.IsCancelled || token.IsCancellationRequested || generation != searchGeneration || !IsVisible) return;
                var existing = ResultList.ItemsSource as FileSearchResultViewModel[];
                // Large result windows are prepared off the dispatcher; icon requests only
                // start when a virtualized row binds IconSource. Preserve unchanged models.
                var prepared = await Task.Run(() => PrepareFileRows(page.Items, existing, selection, token));
                if (prepared is null) return;
                if (token.IsCancellationRequested || generation != searchGeneration || !IsVisible)
                {
                    DisposeFileRows(prepared.Created);
                    return;
                }
                var cards = prepared.Rows;
                if (!ReferenceEquals(existing, cards))
                {
                    ResultList.ItemsSource = cards;
                    ResultList.SelectedIndex = prepared.SelectedIndex;
                    DisposeFileRows(prepared.Retired);
                }
                expensiveSearch = page.Elapsed.TotalMilliseconds >= 100;
                var canLoadMore = page.HasMore && (!fileSearch.IsUsingIndexingService ||
                    resultLimit < IndexingServiceProtocol.MaximumResults);
                LoadMoreButton.Visibility = canLoadMore ? Visibility.Visible : Visibility.Collapsed;
                EmptyState.Visibility = cards.Length == 0 ? Visibility.Visible : Visibility.Collapsed;
                EmptyTitle.Text = page.Error is not null ? "请检查搜索语法" : string.IsNullOrWhiteSpace(query)
                    ? "从文件名开始,快速找到所需文件" : "没有找到匹配的文件";
                EmptyHint.Text = page.Error ?? (string.IsNullOrWhiteSpace(query)
                    ? "例如:项目计划  ·  *.pdf  ·  ext:cs;json 配置"
                    : fileSearch.Status?.IsScanning == true ? "索引仍在建立,结果会自动补充。" : "可尝试其他关键词、通配符或调整搜索范围。");
                StatusText.Text = page.Error ?? (string.IsNullOrWhiteSpace(query) ? "输入关键词开始搜索"
                    : $"显示 {cards.Length:N0} 项{(canLoadMore ? " · 可加载更多" : page.HasMore ? " · 请缩小搜索范围以查看其他结果" : "")} · {page.Elapsed.TotalMilliseconds:0} ms");
            }
            else
            {
                // Even a completed async cache lookup must never put catalog ranking or
                // bitmap preparation back on the input dispatcher.
                var items = await Task.Run(async () => (await LauncherService.SearchAsync(query)
                    .ConfigureAwait(false)).Select(item => new LauncherItemViewModel(item)).ToArray());
                if (token.IsCancellationRequested || generation != searchGeneration || !IsVisible) return;
                DisposeFileRows(ResultList.ItemsSource as FileSearchResultViewModel[]);
                ResultList.ItemsSource = items;
                LoadMoreButton.Visibility = Visibility.Collapsed;
                EmptyState.Visibility = items.Length == 0 ? Visibility.Visible : Visibility.Collapsed;
                EmptyTitle.Text = "没有找到匹配项";
                EmptyHint.Text = "可搜索工具、软件、页面、项目和命令";
                StatusText.Text = items.Length == 0 ? "没有匹配结果" : $"{items.Length} 个结果";
                RestoreSelection(selection);
            }
            UpdateIndexStatus();
        }
        catch (OperationCanceledException) when (token.IsCancellationRequested) { }
        catch (Exception exception)
        {
            if (generation == searchGeneration)
            {
                StatusText.Text = $"搜索暂时不可用:{exception.Message}";
                EmptyState.Visibility = ResultList.Items.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
                EmptyTitle.Text = "暂时无法完成搜索";
                EmptyHint.Text = "可调整关键词或重新扫描索引后再试。";
            }
        }
        finally
        {
            if (generation == searchGeneration) isSearching = false;
            if (ReferenceEquals(searchCancellation, cancellation)) searchCancellation = null;
            cancellation.Dispose();
        }
    }

    private sealed record PreparedFileRows(FileSearchResultViewModel[] Rows,
        FileSearchResultViewModel[] Created, FileSearchResultViewModel[] Retired, int SelectedIndex);

    private static PreparedFileRows? PrepareFileRows(IReadOnlyList<FileSearchMatch> matches,
        FileSearchResultViewModel[]? previous, string? selection, CancellationToken token)
    {
        var reusable = previous?.ToDictionary(row => row.FullPath, StringComparer.OrdinalIgnoreCase);
        var rows = new FileSearchResultViewModel[matches.Count];
        var created = new List<FileSearchResultViewModel>();
        var retained = new HashSet<FileSearchResultViewModel>();
        var same = previous?.Length == rows.Length;
        var selectedIndex = rows.Length == 0 ? -1 : 0;
        for (var index = 0; index < matches.Count; index++)
        {
            if (token.IsCancellationRequested)
            {
                foreach (var abandoned in created) abandoned.Dispose();
                return null;
            }
            var match = matches[index];
            FileSearchResultViewModel row;
            if (reusable is not null && reusable.TryGetValue(match.Entry.FullPath, out var old) &&
                old.FullPath == match.Entry.FullPath && old.Match.Score == match.Score &&
                old.Match.Entry.IsDirectory == match.Entry.IsDirectory && old.Match.ContentMatch == match.ContentMatch &&
                old.Snippet == (match.Snippet ?? string.Empty)) row = old;
            else { row = new(match); created.Add(row); }
            rows[index] = row;
            retained.Add(row);
            same &= previous is not null && index < previous.Length && ReferenceEquals(previous[index], row);
            if (string.Equals(row.FullPath, selection, StringComparison.OrdinalIgnoreCase)) selectedIndex = index;
        }
        var retired = previous?.Where(row => !retained.Contains(row)).ToArray() ?? [];
        return new(same ? previous! : rows, created.ToArray(), retired, selectedIndex);
    }

    private static void DisposeFileRows(FileSearchResultViewModel[]? rows)
    {
        if (rows is not { Length: > 0 }) return;
        _ = Task.Run(() => { foreach (var row in rows) row.Dispose(); });
    }

    private void CancelSearch()
    {
        ++searchGeneration;
        if (searchCancellation is { } cancellation)
            _ = cancellation.CancelAsync();
        isSearching = false;
    }

    private string? SelectedKey() => ResultList.SelectedItem switch
    {
        FileSearchResultViewModel file => file.FullPath,
        LauncherItemViewModel tool => tool.Item.Key,
        QuickResult quick => quick.Title,
        _ => null
    };

    private void RestoreSelection(string? key)
    {
        var found = ResultList.Items.Cast<object>().FirstOrDefault(item => item switch
        {
            FileSearchResultViewModel file => string.Equals(file.FullPath, key, StringComparison.OrdinalIgnoreCase),
            LauncherItemViewModel tool => string.Equals(tool.Item.Key, key, StringComparison.OrdinalIgnoreCase),
            QuickResult quick => quick.Title==key,
            _ => false
        });
        if (found is not null) ResultList.SelectedItem = found;
        else ResultList.SelectedIndex = ResultList.Items.Count > 0 ? 0 : -1;
    }

    private void FileSearch_Changed(object? sender, EventArgs e) => Interlocked.Exchange(ref indexDirty, 1);

    private void StatusTimer_Tick(object? sender, EventArgs e)
    {
        if(QuickQuery.IsQuery(SearchBox.Text))return;
        if (!refreshingService && SelectedSection == CommandPaletteSection.Files)
            _ = RefreshServiceStatusAsync();
        UpdateIndexStatus();
        // Broad queries should not monopolize the index's reader lock throughout
        // a full-disk build. Typing/search actions still execute immediately.
        if (expensiveSearch &&
            Stopwatch.GetElapsedTime(lastAutomaticRefresh) < TimeSpan.FromSeconds(3)) return;
        if (SelectedSection == CommandPaletteSection.Files && !isSearching && !changingScope &&
            Interlocked.Exchange(ref indexDirty, 0) != 0 && !string.IsNullOrWhiteSpace(SearchBox.Text))
        {
            lastAutomaticRefresh = Stopwatch.GetTimestamp();
            _ = RefreshResultsAsync(debounce: false);
        }
    }

    private async Task RefreshServiceStatusAsync()
    {
        refreshingService = true;
        try { await fileSearch.RefreshIndexingServiceAsync(); }
        catch (OperationCanceledException) { }
        catch (ObjectDisposedException) { }
        finally { refreshingService = false; }
    }

    private void UpdateIndexStatus()
    {
        if (!ready) return;
        ScopeButton.Content = fileSearch.ScopeText + " ▾";
        ScopeButton.ToolTip = fileSearch.ScopePath ?? "搜索当前用户可访问的本地固定磁盘,跳过无法访问的目录和目录链接。";
        if (SelectedSection == CommandPaletteSection.Tools)
        {
            IndexStatusText.Text = "= 计算 · port 端口 · json 格式化 · uuid";
            return;
        }
        var status = fileSearch.Status;
        var service = fileSearch.ServiceStatus;
        var label = service is not null
            ? $"独立 NTFS 索引服务 · {service.ReadyVolumes}/{service.Volumes} 卷就绪" +
              (service.IsIndexing ? " · 首次建立/USN 增量同步中" : service.ReadyVolumes > 0
                  ? " · USN 实时更新" : " · 暂无可用 NTFS 卷") +
              (service.UnavailableRoots.Count > 0 ? " · 不支持的磁盘使用普通权限扫描" : "")
            : status is null ? "正在准备本地文件索引…" : fileSearch.IsRestoringIndex
            ? $"正在恢复索引 · {status.IndexedCount:N0} 项 · 已恢复的文件可直接搜索" : status.IsNativeWarmup
            ? $"NTFS 元数据预热 · {status.IndexedCount:N0} 项 · 结果可直接搜索" : status.IsReconciling
            ? $"后台校准文件变更 · {status.IndexedCount:N0} 项 · 搜索可继续使用" : status.IsScanning
            ? $"首次建立索引 · {status.IndexedCount:N0} 项" : status.UsingCachedSnapshot
            ? $"本地缓存 · {status.IndexedCount:N0} 项" + (status.VerificationPending ? " · 离线变更待后台校准" : "")
            : $"本地索引 · {status.IndexedCount:N0} 项";
        if (status?.SkippedDirectories > 0) label += $" · {status.SkippedDirectories:N0} 个目录不可访问或已跳过";
        if (!string.IsNullOrWhiteSpace(status?.Error)) label += " · " + status.Error;
        if (IncludeContent.IsChecked == true && fileSearch.ContentStatus is { } body)
        {
            label += body.IsIndexing ? $" · 正文索引中 {body.IndexedCount:N0}" : $" · 正文 {body.IndexedCount:N0} 项";
            if (!string.IsNullOrWhiteSpace(body.Error)) label += " · " + body.Error;
        }
        IndexStatusText.Text = label;
        IndexStatusText.ToolTip = label;
    }

    private async void IncludeContent_Changed(object sender, RoutedEventArgs e)
    {
        if (!ready) return;
        try
        {
            CancelSearch();
            await fileSearch.SetContentEnabledAsync(IncludeContent.IsChecked == true);
            await RefreshResultsAsync(debounce: false);
        }
        catch (Exception exception) { StatusText.Text = $"正文索引暂时不可用:{exception.Message}"; }
    }

    private async void LoadMoreButton_Click(object sender, RoutedEventArgs e)
    {
        resultLimit += 100;
        if (fileSearch.IsUsingIndexingService) resultLimit = Math.Min(resultLimit, IndexingServiceProtocol.MaximumResults);
        await RefreshResultsAsync(debounce: false);
    }

    private void ScopeButton_Click(object sender, RoutedEventArgs e)
    {
        ScopeButton.ContextMenu.PlacementTarget = ScopeButton;
        ScopeButton.ContextMenu.IsOpen = true;
    }

    private async void AllDrivesMenuItem_Click(object sender, RoutedEventArgs e) => await ChangeScopeAsync(null);

    private async void ChooseFolderMenuItem_Click(object sender, RoutedEventArgs e)
    {
        var dialog = new OpenFolderDialog { Title = "选择文件搜索范围", Multiselect = false };
        if (fileSearch.ScopePath is { } scope) dialog.InitialDirectory = scope;
        if (dialog.ShowDialog(this) == true) await ChangeScopeAsync(dialog.FolderName);
    }

    private async Task ChangeScopeAsync(string? folder)
    {
        CancelSearch();
        changingScope = true;
        ScopeButton.IsEnabled = false;
        try
        {
            StatusText.Text = "正在切换搜索范围…";
            DisposeFileRows(ResultList.ItemsSource as FileSearchResultViewModel[]);
            ResultList.ItemsSource = null;
            await fileSearch.SetScopeAsync(folder);
        }
        catch (Exception exception) { StatusText.Text = $"无法切换搜索范围:{exception.Message}"; }
        finally { changingScope = false; ScopeButton.IsEnabled = true; }
        await RefreshResultsAsync(debounce: false);
    }

    private async void RebuildIndexMenuItem_Click(object sender, RoutedEventArgs e)
    {
        try { await fileSearch.RebuildAsync(); }
        catch (OperationCanceledException) { }
        catch (Exception exception) { StatusText.Text = $"重新扫描失败:{exception.Message}"; }
        UpdateIndexStatus();
    }

    private void HelpButton_Click(object sender, RoutedEventArgs e) => SearchHelpPopup.IsOpen = !SearchHelpPopup.IsOpen;
    private void CloseButton_Click(object sender, RoutedEventArgs e) => Hide();
    private void ClearButton_Click(object sender, RoutedEventArgs e)
    {
        // Remember the deliberate clear even if the textbox is already empty
        // and a persisted query is still loading in the background.
        PrepareQueryForOpen(string.Empty);
        SearchBox.Focus();
    }
    private void SearchInputSurface_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) => SearchBox.Focus();

    internal bool CanStartWindowDrag(DependencyObject? source)
    {
        while (source is not null)
        {
            if (source is ButtonBase or TextBoxBase or Selector or RangeBase or PasswordBox or MenuItem)
                return false;
            if (ReferenceEquals(source, WindowDragSurface)) return true;
            source = source is Visual or System.Windows.Media.Media3D.Visual3D
                ? VisualTreeHelper.GetParent(source) : LogicalTreeHelper.GetParent(source);
        }
        return false;
    }

    private void WindowDragSurface_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (e.ChangedButton != MouseButton.Left || e.LeftButton != MouseButtonState.Pressed ||
            !CanStartWindowDrag(e.OriginalSource as DependencyObject)) return;
        // DragMove delegates to the native window manager, retaining mixed-DPI
        // monitor dragging without moving/recreating the search controls.
        e.Handled = true;
        DragMove();
    }

    private void Window_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
    {
        if (AdjustResultViewScale(e.Delta, Keyboard.Modifiers)) e.Handled = true;
    }

    internal bool AdjustResultViewScale(int delta, ModifierKeys modifiers)
    {
        if ((modifiers & ModifierKeys.Control) == 0 || delta == 0) return false;
        SetResultViewScale(ResultViewScale + Math.Sign(delta) * .1);
        return true;
    }

    private void SetResultViewScale(double value)
    {
        SetValue(ResultViewScaleProperty, Math.Clamp(Math.Round(value, 1), .7, 1.6));
        ViewScaleText.Text = $"{ResultViewScale:P0} · Ctrl+滚轮缩放 · ↑↓ 选择 · Enter 打开";
    }

    private async void Window_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if ((Keyboard.Modifiers & ModifierKeys.Control) != 0 && e.Key is Key.D0 or Key.NumPad0)
        {
            SetResultViewScale(1d);
            e.Handled = true;
            return;
        }
        if ((Keyboard.Modifiers & ModifierKeys.Control) != 0 && e.Key is Key.D1 or Key.D2 or Key.Tab)
        {
            SetSection(e.Key == Key.D1 ? CommandPaletteSection.Files : e.Key == Key.D2
                ? CommandPaletteSection.Tools : SelectedSection == CommandPaletteSection.Files ? CommandPaletteSection.Tools : CommandPaletteSection.Files);
            SearchBox.Focus();
            await RefreshResultsAsync(debounce: false);
            e.Handled = true;
            return;
        }
        switch (e.Key)
        {
            case Key.Escape: Hide(); e.Handled = true; break;
            case Key.Down:
            case Key.Up:
                if (ResultList.Items.Count > 0)
                {
                    ResultList.SelectedIndex = Math.Clamp(ResultList.SelectedIndex + (e.Key == Key.Down ? 1 : -1), 0, ResultList.Items.Count - 1);
                    ResultList.ScrollIntoView(ResultList.SelectedItem);
                }
                e.Handled = true;
                break;
            case Key.Enter: await ExecuteSelectedAsync(); e.Handled = true; break;
            case Key.F5 when QuickQuery.IsQuery(SearchBox.Text):
                lastQuickQuery=null;lastQuickResults=[];
                await RefreshResultsAsync(debounce:false);e.Handled=true;break;
            case Key.F5 when SelectedSection == CommandPaletteSection.Files:
                RebuildIndexMenuItem_Click(sender, e); e.Handled = true; break;
        }
    }

    private async void ResultList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        if (e.OriginalSource is DependencyObject source &&
            ItemsControl.ContainerFromElement(ResultList, source) is ListBoxItem)
            await ExecuteSelectedAsync();
    }

    private async Task ExecuteSelectedAsync()
    {
        try
        {
            switch (ResultList.SelectedItem)
            {
                case FileSearchResultViewModel file: file.Open(); Hide(); break;
                case LauncherItemViewModel tool when tool.Item.TargetId.StartsWith("quick-",StringComparison.Ordinal)&&Enum.TryParse<QuickToolKind>(tool.Item.TargetId[6..],out var kind):
                    var context=ReadQuickContext();Hide();QuickToolsBridge.Show(kind,context);break;
                case LauncherItemViewModel tool: Hide(); await tool.ExecuteAsync(); break;
                case QuickResult quick when quick.CopyText is not null: Clipboard.SetText(quick.CopyText);StatusText.Text="已复制结果。";break;
                case QuickResult quick when quick.Tool.HasValue: Hide();QuickToolsBridge.Show(quick.Tool.Value,new(quick.Input,PreviousWindow:previousWindow));break;
            }
        }
        catch (Exception exception)
        {
            if (!IsVisible) Show();
            StatusText.Text = $"无法打开:{exception.Message}";
        }
    }

    private void OpenFileMenuItem_Click(object sender, RoutedEventArgs e) => FileAction(sender, file => { file.Open(); Hide(); });
    private void RevealFileMenuItem_Click(object sender, RoutedEventArgs e) => FileAction(sender, file => { file.Reveal(); Hide(); });
    private void CopyPathMenuItem_Click(object sender, RoutedEventArgs e) => FileAction(sender, file => { file.CopyPath(); StatusText.Text = "已复制完整路径"; });
    private QuickToolContext ReadQuickContext()
    {
        string? text=null;
        if(CarryClipboard.IsChecked==true&&Clipboard.ContainsText()){text=Clipboard.GetText();if(text.Length>65536)throw new InvalidOperationException("剪贴板文本超过 64 KiB,未自动传入。");}
        return new(text,PreviousWindow:previousWindow);
    }
    private void QuickRenameMenuItem_Click(object sender,RoutedEventArgs e)=>FileAction(sender,file=>{Hide();QuickToolsBridge.Show(QuickToolKind.Rename,new(Files:[file.FullPath],PreviousWindow:previousWindow));});
    private async void QuickHashMenuItem_Click(object sender,RoutedEventArgs e)
    {
        if(sender is not MenuItem{DataContext:FileSearchResultViewModel file})return;
        try{StatusText.Text="正在计算文件摘要…";var output=await Task.Run(()=>TextActions.FileHashes(file.FullPath));QuickToolsBridge.Show(QuickToolKind.Text,new(output));StatusText.Text="摘要已打开。";}
        catch(Exception error){StatusText.Text="计算失败:"+error.Message;}
    }

    private void FileAction(object sender, Action<FileSearchResultViewModel> action)
    {
        if (sender is not MenuItem { DataContext: FileSearchResultViewModel file }) return;
        try { action(file); }
        catch (Exception exception) { StatusText.Text = exception.Message; }
    }

    private async void PinMenuItem_Click(object sender, RoutedEventArgs e)
    {
        if (sender is not MenuItem { DataContext: LauncherItemViewModel item }) return;
        if (!item.TogglePinned()) StatusText.Text = $"最多只能固定 {PinnedItemService.MaximumPinnedItems} 项";
        else await RefreshResultsAsync(debounce: false);
    }

    private void PositionOnCurrentScreen()
    {
        var cursor = Forms.Control.MousePosition;
        var area = Forms.Screen.FromPoint(cursor).WorkingArea;
        var handle = new WindowInteropHelper(this).EnsureHandle();
        CenterNativeWindow(handle, area);
        CenterNativeWindow(handle, area);
    }

    private static void CenterNativeWindow(IntPtr handle, System.Drawing.Rectangle area)
    {
        if (!GetWindowRect(handle, out var bounds)) return;
        var width = bounds.Right - bounds.Left;
        var height = bounds.Bottom - bounds.Top;
        var left = area.Left + (area.Width - width) / 2;
        var top = area.Top + (area.Height - height) / 2;
        width = Math.Min(width, area.Width - 20);
        height = Math.Min(height, area.Height - 20);
        left = area.Left + (area.Width - width) / 2;
        top = area.Top + (area.Height - height) / 2;
        SetWindowPos(handle, IntPtr.Zero, left, top, width, height, 0x0004 | 0x0010);
    }

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool GetWindowRect(IntPtr windowHandle, out NativeRect rectangle);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool SetWindowPos(
        IntPtr windowHandle,
        IntPtr insertAfter,
        int x,
        int y,
        int width,
        int height,
        uint flags);

    [StructLayout(LayoutKind.Sequential)]
    private struct NativeRect
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }
}