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

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using XFEToolBox.Client.Utilities;
using XFEToolBox.Client.Views.Windows;

namespace XFEToolBox.Client.Wpf.Test;

public static class QuickSearchInteractionTests
{
    [Test]
    public static void QuickSearchHeaderDragsOnlyBlankSpaceNotSearchTabsOrInput() => RunSta(() =>
    {
        using var session = new WindowSession();
        var window = session.Window;
        var header = Control<Grid>(window, "WindowDragSurface");
        Ensure(header.Background is not null && window.CanStartWindowDrag(header),
            "顶部空白处没有可命中的拖动区域。");
        var label = new TextBlock { Text = "drag surface test" };
        header.Children.Add(label);
        Ensure(window.CanStartWindowDrag(label), "拖动区域中的非交互内容不能拖动窗口。");
        header.Children.Remove(label);
        foreach (var name in new[] { "FilesTab", "ToolsTab", "SearchBox", "ClearSearchButton", "ResultList", "ScopeButton" })
            Ensure(!window.CanStartWindowDrag(Control<FrameworkElement>(window, name)),
                $"{name} 被错误识别为拖动区域,会打断点击或文本选择。");
        Ensure(!window.CanStartWindowDrag(header.Children.OfType<Button>().Single()) &&
            !window.CanStartWindowDrag(null), "Esc 按钮或未知来源触发了窗口拖动。");
        Ensure(!window.Topmost, "可拖动搜索窗口不应始终置顶。");
    });

    [Test]
    public static void QuickSearchReopenKeepsUnclearedQueryAndClearPersistsAcrossWindows() => RunSta(() =>
    {
        using var session = new WindowSession();
        var window = session.Window;
        var input = Control<TextBox>(window, "SearchBox");
        const string query = "报告 *.pdf | path:C:\\Projects\\**";
        window.PrepareQueryForOpen(query);
        window.PrepareQueryForOpen(null);
        Ensure(input.Text == query && input.CaretIndex == query.Length,
            "无新查询的再次打开清掉了上次搜索,或未将光标放在末尾。");
        PumpUntil(window.FlushRememberedQueryAsync);

        var second = new CommandPaletteWindow(session.Runtime, new QuickSearchQueryMemory(session.StatePath));
        try
        {
            var restoredInput = Control<TextBox>(second, "SearchBox");
            PumpUntil(() => restoredInput.Text == query, "新的窗口没有恢复持久化搜索内容。");
            var clear = Control<Button>(second, "ClearSearchButton");
            clear.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
            second.PrepareQueryForOpen(null);
            Ensure(restoredInput.Text.Length == 0 && Control<TextBlock>(second, "SearchHint").Visibility == Visibility.Visible,
                "清空后的再次打开恢复了旧查询,或提示没有恢复。");
            PumpUntil(second.FlushRememberedQueryAsync);
        }
        finally { second.Close(); }
        Ensure(new QuickSearchQueryMemory(session.StatePath).LoadAsync().GetAwaiter().GetResult() == string.Empty,
            "点击清空没有持久化,重启后仍会显示旧查询。");
    });

    [Test]
    public static void QuickSearchPendingRestoreNeverOverwritesExplicitEmptyOrNewTyping() => RunSta(() =>
    {
        using var session = new WindowSession();
        session.Window.PrepareQueryForOpen("persisted-old-query");
        PumpUntil(session.Window.FlushRememberedQueryAsync);
        foreach (var clear in new[] { false, true })
        {
            var window = new CommandPaletteWindow(session.Runtime, new QuickSearchQueryMemory(session.StatePath));
            try
            {
                var input = Control<TextBox>(window, "SearchBox");
                // Don't pump the dispatcher until after this edit: the queued
                // disk-load continuation must not replace the user's newer intent.
                if (clear) window.PrepareQueryForOpen(string.Empty);
                else input.Text = "user-is-typing";
                PumpUntil(window.FlushRememberedQueryAsync);
                Ensure(input.Text == (clear ? string.Empty : "user-is-typing"),
                    "后台恢复覆盖了显式清空或正在键入的新搜索。");
            }
            finally { window.Close(); }
        }
    });

    [Test]
    public static void QuickSearchClosedWindowIgnoresLateQueryRestoration() => RunSta(() =>
    {
        using var session = new WindowSession();
        var release = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
        var memory = new QuickSearchQueryMemory(session.StatePath, () => release.Task);
        var window = new CommandPaletteWindow(session.Runtime, memory);
        var input = Control<TextBox>(window, "SearchBox");
        var restore = memory.LoadAsync();
        window.Close();
        release.SetResult("late saved query");
        PumpUntil(() => restore.IsCompleted, "关闭后的状态读取没有完成。");
        Ensure(input.Text.Length == 0, "迟到的持久化恢复仍修改了已关闭窗口。");
        Ensure(!File.Exists(session.StatePath), "已关闭窗口的迟到恢复重新触发了保存。");
    });

    private static T Control<T>(CommandPaletteWindow window, string name) where T : FrameworkElement =>
        window.FindName(name) as T ?? throw new InvalidOperationException("缺少控件:" + name);

    private static void PumpUntil(Func<Task> taskFactory)
    {
        var task = taskFactory();
        PumpUntil(() => task.IsCompleted, "等待异步查询保存超时。");
        task.GetAwaiter().GetResult();
    }

    private static void PumpUntil(Func<bool> condition, string message)
    {
        var clock = Stopwatch.StartNew();
        var frame = new DispatcherFrame();
        var timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(10) };
        timer.Tick += (_, _) => { if (condition() || clock.Elapsed > TimeSpan.FromSeconds(5)) frame.Continue = false; };
        timer.Start();
        try { Dispatcher.PushFrame(frame); }
        finally { timer.Stop(); }
        Ensure(condition(), message);
    }

    private static void RunSta(Action action)
    {
        Exception? failure = null;
        var thread = new Thread(() =>
        {
            try
            {
                SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher));
                action();
            }
            catch (Exception exception) { failure = exception; }
            finally { Dispatcher.CurrentDispatcher.InvokeShutdown(); }
        }) { IsBackground = true };
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        Ensure(thread.Join(TimeSpan.FromSeconds(20)), "搜索窗口交互测试超时。");
        if (failure is not null) throw new InvalidOperationException(failure.Message, failure);
    }

    private static void Ensure(bool condition, string message)
    {
        if (!condition) throw new InvalidOperationException(message);
    }

    private sealed class WindowSession : IDisposable
    {
        private readonly string root = Path.Combine(Path.GetTempPath(), "xfetoolbox-search-interaction-" + Guid.NewGuid().ToString("N"));
        public string StatePath => Path.Combine(root, "last-query.json");
        public FileSearchRuntime Runtime { get; }
        public CommandPaletteWindow Window { get; }

        public WindowSession()
        {
            Directory.CreateDirectory(root);
            Runtime = new FileSearchRuntime(Path.Combine(root, "unused-cache"));
            Window = new CommandPaletteWindow(Runtime, new QuickSearchQueryMemory(StatePath));
            // Keep the window hidden; no native focus changes, crawling or service connection.
        }

        public void Dispose()
        {
            Window.Close();
            Runtime.DisposeAsync().AsTask().GetAwaiter().GetResult();
            Ensure(Path.GetDirectoryName(root) == Path.TrimEndingDirectorySeparator(Path.GetFullPath(Path.GetTempPath())) &&
                Path.GetFileName(root).StartsWith("xfetoolbox-search-interaction-", StringComparison.Ordinal), "测试清理路径越界。");
            if (File.Exists(StatePath)) File.Delete(StatePath);
            Directory.Delete(root);
        }
    }
}