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.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using XFEToolBox.Client.Models;
using XFEToolBox.Client.Utilities;
using XFEToolBox.Client.ViewModel.Pages;
using XFEToolBox.Client.Views.Windows;

namespace XFEToolBox.Client.Wpf.Test;

public static class QuickSearchWindowTests
{
    [Test]
    public static void QuickSearchRendersGlobsAndDiscardsStaleQueries() => RunSta(() =>
    {
        using var tree = new TemporarySearchTree();
        tree.CreateFile("report1.txt", "first");
        tree.CreateFile("report2.txt", "second");
        tree.CreateFile("report12.csv", "not the final query");
        tree.CreateFile("other.txt", "not the final query");
        var readOnlyFolder = Directory.CreateDirectory(Path.Combine(tree.Root, "read-only-folder")).FullName;
        var accessibleFile = Path.Combine(readOnlyFolder, "report3.txt");
        File.WriteAllText(accessibleFile, "read-only folders remain searchable");
        File.SetAttributes(readOnlyFolder, File.GetAttributes(readOnlyFolder) | FileAttributes.ReadOnly);
        using var session = new SearchSession(tree);
        var window = session.Window;
        var query = Control<TextBox>(window, "SearchBox");
        var results = Control<ListBox>(window, "ResultList");
        window.ShowPalette("report?.txt");
        PumpUntil(() => FileNames(results).SequenceEqual(["report1.txt", "report2.txt", "report3.txt"]),
            "文件搜索未显示全部单字符通配符匹配,或漏掉了可访问的只读目录。");
        Ensure(window.SelectedSection == CommandPaletteSection.Files, "默认快速搜索没有进入第一栏文件搜索。");
        window.UpdateLayout();
        Ensure(results.ItemContainerGenerator.ContainerFromIndex(0) is ListBoxItem { ActualHeight: > 0 },
            "结果数据存在,但真实 WPF 列表未完成布局。");
        AssertRendered(window);

        query.Text = "report[12].txt | *.csv";
        PumpUntil(() => FileNames(results).SequenceEqual(["report1.txt", "report12.csv", "report2.txt"]),
            "字符集合与 OR 通配符查询未正确显示文件结果。");
        query.Text = "\"unfinished";
        PumpUntil(() => Control<TextBlock>(window, "EmptyTitle").Text == "请检查搜索语法" && results.Items.Count == 0,
            "无效搜索表达式未显示可恢复的语法提示。");

        query.Text = "other*";
        query.Text = "report12*";
        query.Text = "report?.txt";
        PumpUntil(() => FileNames(results).SequenceEqual(["report1.txt", "report2.txt", "report3.txt"]),
            "快速连续输入后,列表没有显示最终查询。");
        PumpFor(TimeSpan.FromMilliseconds(350));
        Ensure(FileNames(results).SequenceEqual(["report1.txt", "report2.txt", "report3.txt"]),
            "较早查询覆盖了最终查询的结果。");

        Ensure(results.SelectedIndex == 0, "搜索完成后没有选中第一项。");
        Ensure(PressKey(window, Key.Down).Handled && results.SelectedIndex == 1, "方向键向下未移动选中项。");
        Ensure(PressKey(window, Key.Up).Handled && results.SelectedIndex == 0, "方向键向上未移动选中项。");
        results.SelectedIndex = -1;
        Ensure(PressKey(window, Key.Enter).Handled && window.IsVisible, "没有选中项时 Enter 不应打开任何文件或关闭搜索。");
    });

    [Test]
    public static void QuickSearchKeepsToolSearchInSecondTabAndHotkeyReopensFiles() => RunSta(() =>
    {
        using var tree = new TemporarySearchTree();
        tree.CreateFile("local-target.txt", "local target");
        using var session = new SearchSession(tree);
        var window = session.Window;
        var query = Control<TextBox>(window, "SearchBox");
        var results = Control<ListBox>(window, "ResultList");
        window.ShowPalette("local-target");
        PumpUntil(() => FileNames(results).SequenceEqual(["local-target.txt"]), "文件搜索没有返回测试文件。");
        Control<RadioButton>(window, "ToolsTab").IsChecked = true;
        query.Text = "选项设置";
        PumpUntil(() => window.SelectedSection == CommandPaletteSection.Tools &&
            results.Items.OfType<LauncherItemViewModel>().Any(item => item.Title == "选项设置"),
            "第二栏没有保留原来的页面和工具搜索结果。");
        Ensure(Control<CheckBox>(window, "IncludeContent").IsVisible == false,
            "工具搜索栏仍显示文件正文选项。");

        window.Hide();
        window.ShowPalette("选项设置", CommandPaletteSection.Tools);
        PumpUntil(() => window.SelectedSection == CommandPaletteSection.Tools &&
            results.Items.OfType<LauncherItemViewModel>().Any(item => item.Title == "选项设置"),
            "显式打开第二栏时工具搜索未恢复。");
        window.ShowPalette("local-target");
        PumpUntil(() => window.SelectedSection == CommandPaletteSection.Files &&
            FileNames(results).SequenceEqual(["local-target.txt"]), "再次默认唤起没有回到文件搜索第一栏。");

        // Exercise Enter's real event route with an in-memory action, never an OS file association.
        var executed = false;
        results.ItemsSource = new[] { new LauncherItemViewModel(new LauncherItem
        {
            Kind = LauncherItemKind.Command,
            TargetId = "quick-search-test-safe-action",
            Title = "Safe test action",
            IconReference = "/Resources/Image/console.png",
            ExecuteAsync = () => { executed = true; return Task.CompletedTask; }
        }) };
        results.SelectedIndex = 0;
        PressKey(window, Key.Enter);
        PumpUntil(() => executed && !window.IsVisible, "Enter 没有执行已选择的安全测试命令并隐藏搜索窗口。");
    });

    [Test]
    public static void QuickSearchOptInContentMatchesBodyAndHideCancelsPendingSearch() => RunSta(() =>
    {
        using var tree = new TemporarySearchTree();
        const string bodyOnly = "QuickSearchBodyOnlyNeedle938";
        tree.CreateFile("document.txt", "A sentence containing " + bodyOnly + " in its body.");
        using var session = new SearchSession(tree);
        var window = session.Window;
        var query = Control<TextBox>(window, "SearchBox");
        var results = Control<ListBox>(window, "ResultList");
        var includeContent = Control<CheckBox>(window, "IncludeContent");
        window.ShowPalette(bodyOnly);
        PumpUntil(() => Control<TextBlock>(window, "StatusText").Text.StartsWith("显示 0 项", StringComparison.Ordinal),
            "未启用正文时,文件名搜索未完成空结果查询。");
        Ensure(includeContent.IsChecked != true && session.Runtime.ContentStatus is null,
            "正文搜索应默认关闭,不能在用户选择之前读取并索引正文。");
        includeContent.IsChecked = true;
        PumpUntil(() => results.Items.OfType<FileSearchResultViewModel>().Any(item =>
            item.Title == "document.txt" && item.Match.ContentMatch && item.Snippet.Contains(bodyOnly, StringComparison.Ordinal)),
            "启用正文选项后没有返回仅正文包含关键词的文件和匹配摘要。", TimeSpan.FromSeconds(15));
        window.UpdateLayout();
        AssertRendered(window);

        var previousSource = results.ItemsSource;
        query.Text = "*.txt";
        window.Hide();
        PumpFor(TimeSpan.FromMilliseconds(400));
        Ensure(!window.IsVisible && ReferenceEquals(previousSource, results.ItemsSource),
            "隐藏窗口后,未完成搜索仍继续覆盖结果。");
        window.ShowPalette("document");
        PumpUntil(() => results.Items.OfType<FileSearchResultViewModel>().Any(item => item.Title == "document.txt"),
            "隐藏取消后,重新唤起无法再次搜索。");
        Ensure(PressKey(window, Key.Escape).Handled && !window.IsVisible, "Esc 未隐藏快速搜索窗口。");
    });

    private static T Control<T>(CommandPaletteWindow window, string name) where T : FrameworkElement =>
        window.FindName(name) as T ?? throw new InvalidOperationException($"未找到 {name} 控件。");

    private static string[] FileNames(ListBox list) => list.Items.OfType<FileSearchResultViewModel>()
        .Select(item => item.Title).OrderBy(name => name, StringComparer.Ordinal).ToArray();

    private static KeyEventArgs PressKey(Window window, Key key)
    {
        var source = PresentationSource.FromVisual(window) ?? throw new InvalidOperationException("搜索窗口尚未创建呈现源。");
        var args = new KeyEventArgs(Keyboard.PrimaryDevice, source, Environment.TickCount, key)
        { RoutedEvent = Keyboard.PreviewKeyDownEvent };
        window.RaiseEvent(args);
        return args;
    }

    private static void AssertRendered(Window window)
    {
        var bitmap = new RenderTargetBitmap((int)Math.Ceiling(window.ActualWidth),
            (int)Math.Ceiling(window.ActualHeight), 96, 96, PixelFormats.Pbgra32);
        bitmap.Render(window);
        var pixels = new byte[bitmap.PixelWidth * bitmap.PixelHeight * 4];
        bitmap.CopyPixels(pixels, bitmap.PixelWidth * 4, 0);
        Ensure(pixels.Where((_, index) => index % 4 == 3).Any(alpha => alpha != 0),
            "快速搜索窗口完成数据绑定后仍然呈现为空白。");
    }

    private static void PumpUntil(Func<bool> condition, string failure, TimeSpan? timeout = null)
    {
        if (condition()) return;
        var elapsed = Stopwatch.StartNew();
        var frame = new DispatcherFrame();
        var timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(15) };
        Exception? conditionFailure = null;
        timer.Tick += (_, _) =>
        {
            try
            {
                if (condition() || elapsed.Elapsed >= (timeout ?? TimeSpan.FromSeconds(10))) frame.Continue = false;
            }
            catch (Exception exception) { conditionFailure = exception; frame.Continue = false; }
        };
        timer.Start();
        try { Dispatcher.PushFrame(frame); }
        finally { timer.Stop(); }
        if (conditionFailure is not null) throw conditionFailure;
        Ensure(condition(), failure);
    }

    private static void PumpFor(TimeSpan duration)
    {
        var elapsed = Stopwatch.StartNew();
        PumpUntil(() => elapsed.Elapsed >= duration, "Dispatcher 等待超时。", duration + TimeSpan.FromSeconds(1));
    }

    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(45)), "快速搜索窗口回归测试超时。");
        if (failure is not null) throw new InvalidOperationException("快速搜索窗口回归失败。", failure);
    }

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

    private sealed class SearchSession : IDisposable
    {
        public FileSearchRuntime Runtime { get; }
        public CommandPaletteWindow Window { get; }

        public SearchSession(TemporarySearchTree tree)
        {
            Runtime = new FileSearchRuntime(tree.Cache);
            try
            {
                Runtime.SetScopeAsync(tree.Root).GetAwaiter().GetResult();
                Runtime.RebuildAsync().GetAwaiter().GetResult();
                Window = new CommandPaletteWindow(Runtime) { Topmost = false, ShowActivated = false };
            }
            catch
            {
                Runtime.DisposeAsync().AsTask().GetAwaiter().GetResult();
                throw;
            }
        }

        public void Dispose()
        {
            try
            {
                Window.Close();
                PumpFor(TimeSpan.FromMilliseconds(50));
            }
            finally { Runtime.DisposeAsync().AsTask().GetAwaiter().GetResult(); }
        }
    }

    private sealed class TemporarySearchTree : IDisposable
    {
        public string Root { get; } = Path.Combine(Path.GetTempPath(), "xfetoolbox-quick-search-window-tests-" + Guid.NewGuid().ToString("N"));
        public string Cache => Path.Combine(Root, ".cache");
        public TemporarySearchTree() => Directory.CreateDirectory(Root);
        public void CreateFile(string name, string body) => File.WriteAllText(Path.Combine(Root, name), body);

        public void Dispose()
        {
            var resolved = Path.GetFullPath(Root);
            var temporaryParent = Path.TrimEndingDirectorySeparator(Path.GetFullPath(Path.GetTempPath())) + Path.DirectorySeparatorChar;
            Ensure(resolved.StartsWith(temporaryParent, StringComparison.OrdinalIgnoreCase) &&
                Path.GetFileName(resolved).StartsWith("xfetoolbox-quick-search-window-tests-", StringComparison.Ordinal),
                "测试清理目标超出了专用临时目录。");
            if (!Directory.Exists(resolved)) return;
            foreach (var file in Directory.EnumerateFiles(resolved, "*", SearchOption.AllDirectories))
                File.SetAttributes(file, FileAttributes.Normal);
            foreach (var directory in Directory.EnumerateDirectories(resolved, "*", SearchOption.AllDirectories))
                File.SetAttributes(directory, File.GetAttributes(directory) & ~FileAttributes.ReadOnly);
            Directory.Delete(resolved, recursive: true);
        }
    }
}