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

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
返回提交历史

XFEstudio/XFEToolBox

改进文件图标加载、结果视图与缩放

调整并强化文件结果列表与图标加载:将 ShellFileIconService 从 FIFO 改为从尾部取出工作项(优先最新/可见请求),队列/缓存限额不变并添加顺序断言测试。修复 FileSearchResultViewModel 在图像为 null 或被取消时在锁内重置 iconRequested 并释放取消令牌,允许重试。 命令面板与结果行性能优化:在 CommandPaletteWindow 中新增 ResultViewScale 依赖属性与 Ctrl+滚轮 / Ctrl+0 缩放交互及提示文本;将部分搜索/启动器处理移入 Task.Run 以避免阻塞 UI;引入 PrepareFileRows(后台构建/复用 VM 列表,返回 Rows/Created/Retired/SelectedIndex)与 DisposeFileRows(异步处置被淘汰行),在合适位置释放旧行与取消令牌,最小化 Dispatcher 绑定开销并防止资源泄露。 测试与文档:新增 ShellFileIconTests 的顺序记录与 DroppedIconRequestCanRetryWhenTheSameResultIsRealizedAgain 测试;新增 QuickSearchViewBehaviorTests(STA UI 行为测试,含缩放、后台取消与行复用/图标重用验证)及相应测试输出;增加 SearchSession/DelayedService 等测试夹具。更新 README,记录图标加载策略、队列/缓存限制、缩放快捷键与索引服务说明。 总体效果:提高可见行优先加载真实 Windows 图标、增强 UI 响应性与资源控制,减少老请求阻塞/占用,并通过行复用与后台准备减少主线程负担。

6eec04a
XFE工作室室长 <mail@xfegzs.com>
提交于

代码差异

14 个文件 +1340 -24
Modified .gitignore +1 -0
@@ -359,6 +359,7 @@ XFEToolBox.Server/Data/
359 359 # Local validation build outputs
360 360 .BuildValidation/final-*-release/
361 361 .BuildValidation/live-index-*-release/
362 .BuildValidation/quick-search-view-behavior-release/
362 363
363 364 # Backup folder for Package Reference Convert tool in Visual Studio 2017
364 365 MigrationBackup/
Added XFEToolBox.Client.Wpf.Test/QuickSearchContextMenuTests.cs +204 -0
@@ -0,0 +1,204 @@
1 using System.IO;
2 using System.Reflection;
3 using System.Windows;
4 using System.Windows.Controls;
5 using System.Windows.Controls.Primitives;
6 using System.Windows.Media;
7 using System.Windows.Media.Imaging;
8 using System.Windows.Threading;
9
10 namespace XFEToolBox.Client.Wpf.Test;
11
12 public static class QuickSearchContextMenuTests
13 {
14 [Test]
15 public static void QuickSearchContextMenuUsesTransparentPopupAndRoundedOutlinedSurfaceWithoutShadows() => RunSta(() =>
16 {
17 var menu = CreateMenu(out var host);
18 try
19 {
20 menu.IsOpen = true;
21 menu.ApplyTemplate();
22 Pump();
23 menu.UpdateLayout();
24
25 var popup = LogicalTreeHelper.GetParent(menu) as Popup ??
26 typeof(ContextMenu).GetField("_parentPopup", BindingFlags.NonPublic | BindingFlags.Instance)?.GetValue(menu) as Popup;
27 Ensure(popup is { AllowsTransparency: true, IsOpen: true },
28 $"真实右键菜单没有使用透明 Popup:menuOpen={menu.IsOpen}, popup={popup?.GetType().Name}, open={popup?.IsOpen}, transparency={popup?.AllowsTransparency}, size={menu.ActualWidth}x{menu.ActualHeight}。");
29 var root = VisualRoot(menu);
30 // The native popup remains invisible while its actual menu is rendered offscreen.
31 root.Opacity = 0;
32 menu.Opacity = 1;
33 Ensure(!menu.HasDropShadow && menu.Effect is null &&
34 menu.Background is SolidColorBrush { Color.A: 0 }, "菜单仍开启系统阴影、外部 Effect 或不透明方形背景。");
35 Ensure(Descendants<UIElement>(menu).All(element => element.Effect is null),
36 "菜单模板或菜单项仍继承了全局阴影 Effect。");
37 var surface = menu.Template.FindName("MenuSurface", menu) as Border;
38 Ensure(surface is { CornerRadius.TopLeft: 12, BorderThickness.Top: 1 } &&
39 surface.BorderBrush is SolidColorBrush borderBrush && borderBrush.Color == Color.FromRgb(201, 201, 235),
40 "菜单缺少主页配色的一像素圆角边框。");
41 Ensure(menu.Padding.Top >= 7 && menu.Padding.Bottom >= 7,
42 "菜单上下间距不足,最下方悬停圆角会靠近底边。");
43
44 var bitmap = Render(menu);
45 var pixels = new byte[bitmap.PixelWidth * bitmap.PixelHeight * 4];
46 bitmap.CopyPixels(pixels, bitmap.PixelWidth * 4, 0);
47 Ensure(Alpha(0, 0) == 0 && Alpha(bitmap.PixelWidth - 1, 0) == 0 &&
48 Alpha(0, bitmap.PixelHeight - 1) == 0 && Alpha(bitmap.PixelWidth - 1, bitmap.PixelHeight - 1) == 0,
49 "菜单圆角外像素不透明:仍有黑/灰色方形背景或被裁切的阴影。");
50 Ensure(Alpha(bitmap.PixelWidth / 2, 0) > 0 && Alpha(0, bitmap.PixelHeight / 2) > 0,
51 "菜单边缘没有渲染出可见边框。");
52 Save(bitmap, "normal");
53
54 var lastItem = (MenuItem)menu.Items[2];
55 var highlightKey = (DependencyPropertyKey?)typeof(MenuItem).GetField("IsHighlightedPropertyKey", BindingFlags.NonPublic | BindingFlags.Static)?.GetValue(null)
56 ?? throw new InvalidOperationException("未找到 MenuItem 的测试用高亮状态键。");
57 lastItem.SetValue(highlightKey, true);
58 Pump();
59 menu.UpdateLayout();
60 var itemSurface = (Border)lastItem.Template.FindName("ItemSurface", lastItem)!;
61 Ensure(itemSurface.Background is SolidColorBrush hover && hover.Color == Color.FromRgb(233, 233, 251),
62 "菜单项悬停没有使用浅紫色圆角高亮。");
63 var lastBounds = lastItem.TransformToAncestor(menu).TransformBounds(new Rect(lastItem.RenderSize));
64 Ensure(menu.ActualHeight - lastBounds.Bottom >= 7, "最下方菜单项没有保留底部空隙。");
65 Save(Render(menu), "last-item-highlighted");
66 Console.WriteLine($"Quick-search context menu: transparent native popup; no effects; outlined 12 DIP rounded border; {bitmap.PixelWidth}x{bitmap.PixelHeight} offscreen render.");
67
68 byte Alpha(int x, int y) => pixels[(y * bitmap.PixelWidth + x) * 4 + 3];
69 }
70 finally { menu.IsOpen = false; host.Close(); Pump(); }
71 });
72
73 [Test]
74 public static void QuickSearchContextMenuKeepsActionsAndSeparatorsUsableDespiteGlobalMenuTheme() => RunSta(() =>
75 {
76 var menu = CreateMenu(out var host);
77 var clicks = 0;
78 var action = (MenuItem)menu.Items[0];
79 action.Click += (_, _) => clicks++;
80 var separator = new Separator();
81 menu.Items.Insert(1, separator);
82 try
83 {
84 menu.IsOpen = true;
85 menu.ApplyTemplate();
86 Pump();
87 menu.UpdateLayout();
88 VisualRoot(menu).Opacity = 0;
89 menu.Opacity = 1;
90 Ensure(menu.Items.OfType<MenuItem>().All(item => item.Template.FindName("ItemSurface", item) is Border { CornerRadius.TopLeft: 8 }),
91 "显式菜单样式没有覆盖全局菜单项模板。");
92 Ensure(separator.Height == 1 && Math.Abs(separator.ActualHeight - 1) <= 1 / VisualTreeHelper.GetDpi(separator).DpiScaleY && separator.Margin.Top == 5 &&
93 separator.Background is SolidColorBrush { Color.R: 228, Color.G: 228, Color.B: 243 },
94 $"快速搜索分隔线没有匹配专用菜单样式:height={separator.ActualHeight}, margin={separator.Margin}, background={separator.Background}。");
95 action.RaiseEvent(new RoutedEventArgs(MenuItem.ClickEvent, action));
96 Ensure(clicks == 1 && action.IsEnabled, "自定义菜单模板破坏了原有菜单动作。");
97 }
98 finally { menu.IsOpen = false; host.Close(); Pump(); }
99 });
100
101 private static ContextMenu CreateMenu(out Window host)
102 {
103 var menu = new ContextMenu
104 {
105 Placement = PlacementMode.AbsolutePoint,
106 HorizontalOffset = -10000,
107 VerticalOffset = -10000,
108 Opacity = 0,
109 Focusable = false,
110 IsHitTestVisible = false
111 };
112 // Construct a FrameworkElement before the first pack URI is resolved in a
113 // standalone filtered test process; WPF installs its pack URI parser here.
114 var resources = new ResourceDictionary
115 { Source = new Uri("/XFEToolBox;component/Resources/Style/QuickSearchContextMenuResources.xaml", UriKind.Relative) };
116 menu.Style = (Style)resources["QuickSearchContextMenuStyle"];
117 // The theme belongs to the owner/window scope, not to the ContextMenu's own
118 // Resources. The explicit menu style's scoped resources must win over it.
119 var themedOwner = new Border { ContextMenu = menu };
120 themedOwner.Resources.MergedDictionaries.Add(resources);
121 themedOwner.Resources.MergedDictionaries.Add(new ResourceDictionary
122 { Source = new Uri("/XFEToolBox.WpfCore;component/Resources/Style/ToolThemeResources.xaml", UriKind.Relative) });
123 themedOwner.Resources.MergedDictionaries.Add(new ResourceDictionary
124 { Source = new Uri("/XFEToolBox;component/Resources/Style/MainStyle.xaml", UriKind.Relative) });
125 menu.PlacementTarget = themedOwner;
126 menu.Items.Add(new MenuItem { Header = "打开", Focusable = false });
127 menu.Items.Add(new MenuItem { Header = "打开所在文件夹", Focusable = false });
128 menu.Items.Add(new MenuItem { Header = "复制完整路径", Focusable = false });
129 host = new Window
130 {
131 Left = -10000, Top = -10000, Width = 1, Height = 1,
132 ShowActivated = false, ShowInTaskbar = false, WindowStyle = WindowStyle.None,
133 AllowsTransparency = true, Background = Brushes.Transparent, Opacity = 0,
134 WindowStartupLocation = WindowStartupLocation.Manual, Content = themedOwner
135 };
136 host.Show();
137 Pump();
138 return menu;
139 }
140
141 private static UIElement VisualRoot(UIElement element)
142 {
143 DependencyObject current = element;
144 while (VisualTreeHelper.GetParent(current) is { } parent) current = parent;
145 return (UIElement)current;
146 }
147
148 private static IEnumerable<T> Descendants<T>(DependencyObject parent) where T : DependencyObject
149 {
150 for (var index = 0; index < VisualTreeHelper.GetChildrenCount(parent); index++)
151 {
152 var child = VisualTreeHelper.GetChild(parent, index);
153 if (child is T typed) yield return typed;
154 foreach (var descendant in Descendants<T>(child)) yield return descendant;
155 }
156 }
157
158 private static RenderTargetBitmap Render(FrameworkElement element)
159 {
160 var bitmap = new RenderTargetBitmap((int)Math.Ceiling(element.ActualWidth),
161 (int)Math.Ceiling(element.ActualHeight), 96, 96, PixelFormats.Pbgra32);
162 bitmap.Render(element);
163 return bitmap;
164 }
165
166 private static void Save(BitmapSource bitmap, string suffix)
167 {
168 var root = new DirectoryInfo(AppContext.BaseDirectory);
169 while (root is not null && !Directory.Exists(Path.Combine(root.FullName, "XFEToolBox.Client.Wpf.Test"))) root = root.Parent;
170 if (root is null) return;
171 var target = Directory.CreateDirectory(Path.Combine(root.FullName, ".BuildValidation", "final-quick-search-context-menu-release"));
172 var encoder = new PngBitmapEncoder();
173 encoder.Frames.Add(BitmapFrame.Create(bitmap));
174 using var output = File.Create(Path.Combine(target.FullName, "context-menu-" + suffix + ".png"));
175 encoder.Save(output);
176 }
177
178 private static void Pump()
179 {
180 var frame = new DispatcherFrame();
181 Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(() => frame.Continue = false));
182 Dispatcher.PushFrame(frame);
183 }
184
185 private static void RunSta(Action action)
186 {
187 Exception? failure = null;
188 var thread = new Thread(() =>
189 {
190 try { action(); }
191 catch (Exception exception) { failure = exception; }
192 finally { Dispatcher.CurrentDispatcher.InvokeShutdown(); }
193 }) { IsBackground = true };
194 thread.SetApartmentState(ApartmentState.STA);
195 thread.Start();
196 Ensure(thread.Join(TimeSpan.FromSeconds(20)), "快速搜索右键菜单测试超时。");
197 if (failure is not null) throw new InvalidOperationException("快速搜索右键菜单回归失败:" + failure, failure);
198 }
199
200 private static void Ensure(bool condition, string message)
201 {
202 if (!condition) throw new InvalidOperationException(message);
203 }
204 }
Added XFEToolBox.Client.Wpf.Test/QuickSearchInteractionTests.cs +174 -0
@@ -0,0 +1,174 @@
1 using System.Diagnostics;
2 using System.IO;
3 using System.Windows;
4 using System.Windows.Controls;
5 using System.Windows.Threading;
6 using XFEToolBox.Client.Utilities;
7 using XFEToolBox.Client.Views.Windows;
8
9 namespace XFEToolBox.Client.Wpf.Test;
10
11 public static class QuickSearchInteractionTests
12 {
13 [Test]
14 public static void QuickSearchHeaderDragsOnlyBlankSpaceNotSearchTabsOrInput() => RunSta(() =>
15 {
16 using var session = new WindowSession();
17 var window = session.Window;
18 var header = Control<Grid>(window, "WindowDragSurface");
19 Ensure(header.Background is not null && window.CanStartWindowDrag(header),
20 "顶部空白处没有可命中的拖动区域。");
21 var label = new TextBlock { Text = "drag surface test" };
22 header.Children.Add(label);
23 Ensure(window.CanStartWindowDrag(label), "拖动区域中的非交互内容不能拖动窗口。");
24 header.Children.Remove(label);
25 foreach (var name in new[] { "FilesTab", "ToolsTab", "SearchBox", "ClearSearchButton", "ResultList", "ScopeButton" })
26 Ensure(!window.CanStartWindowDrag(Control<FrameworkElement>(window, name)),
27 $"{name} 被错误识别为拖动区域,会打断点击或文本选择。");
28 Ensure(!window.CanStartWindowDrag(header.Children.OfType<Button>().Single()) &&
29 !window.CanStartWindowDrag(null), "Esc 按钮或未知来源触发了窗口拖动。");
30 Ensure(!window.Topmost, "可拖动搜索窗口不应始终置顶。");
31 });
32
33 [Test]
34 public static void QuickSearchReopenKeepsUnclearedQueryAndClearPersistsAcrossWindows() => RunSta(() =>
35 {
36 using var session = new WindowSession();
37 var window = session.Window;
38 var input = Control<TextBox>(window, "SearchBox");
39 const string query = "报告 *.pdf | path:C:\\Projects\\**";
40 window.PrepareQueryForOpen(query);
41 window.PrepareQueryForOpen(null);
42 Ensure(input.Text == query && input.CaretIndex == query.Length,
43 "无新查询的再次打开清掉了上次搜索,或未将光标放在末尾。");
44 PumpUntil(window.FlushRememberedQueryAsync);
45
46 var second = new CommandPaletteWindow(session.Runtime, new QuickSearchQueryMemory(session.StatePath));
47 try
48 {
49 var restoredInput = Control<TextBox>(second, "SearchBox");
50 PumpUntil(() => restoredInput.Text == query, "新的窗口没有恢复持久化搜索内容。");
51 var clear = Control<Button>(second, "ClearSearchButton");
52 clear.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
53 second.PrepareQueryForOpen(null);
54 Ensure(restoredInput.Text.Length == 0 && Control<TextBlock>(second, "SearchHint").Visibility == Visibility.Visible,
55 "清空后的再次打开恢复了旧查询,或提示没有恢复。");
56 PumpUntil(second.FlushRememberedQueryAsync);
57 }
58 finally { second.Close(); }
59 Ensure(new QuickSearchQueryMemory(session.StatePath).LoadAsync().GetAwaiter().GetResult() == string.Empty,
60 "点击清空没有持久化,重启后仍会显示旧查询。");
61 });
62
63 [Test]
64 public static void QuickSearchPendingRestoreNeverOverwritesExplicitEmptyOrNewTyping() => RunSta(() =>
65 {
66 using var session = new WindowSession();
67 session.Window.PrepareQueryForOpen("persisted-old-query");
68 PumpUntil(session.Window.FlushRememberedQueryAsync);
69 foreach (var clear in new[] { false, true })
70 {
71 var window = new CommandPaletteWindow(session.Runtime, new QuickSearchQueryMemory(session.StatePath));
72 try
73 {
74 var input = Control<TextBox>(window, "SearchBox");
75 // Don't pump the dispatcher until after this edit: the queued
76 // disk-load continuation must not replace the user's newer intent.
77 if (clear) window.PrepareQueryForOpen(string.Empty);
78 else input.Text = "user-is-typing";
79 PumpUntil(window.FlushRememberedQueryAsync);
80 Ensure(input.Text == (clear ? string.Empty : "user-is-typing"),
81 "后台恢复覆盖了显式清空或正在键入的新搜索。");
82 }
83 finally { window.Close(); }
84 }
85 });
86
87 [Test]
88 public static void QuickSearchClosedWindowIgnoresLateQueryRestoration() => RunSta(() =>
89 {
90 using var session = new WindowSession();
91 var release = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
92 var memory = new QuickSearchQueryMemory(session.StatePath, () => release.Task);
93 var window = new CommandPaletteWindow(session.Runtime, memory);
94 var input = Control<TextBox>(window, "SearchBox");
95 var restore = memory.LoadAsync();
96 window.Close();
97 release.SetResult("late saved query");
98 PumpUntil(() => restore.IsCompleted, "关闭后的状态读取没有完成。");
99 Ensure(input.Text.Length == 0, "迟到的持久化恢复仍修改了已关闭窗口。");
100 Ensure(!File.Exists(session.StatePath), "已关闭窗口的迟到恢复重新触发了保存。");
101 });
102
103 private static T Control<T>(CommandPaletteWindow window, string name) where T : FrameworkElement =>
104 window.FindName(name) as T ?? throw new InvalidOperationException("缺少控件:" + name);
105
106 private static void PumpUntil(Func<Task> taskFactory)
107 {
108 var task = taskFactory();
109 PumpUntil(() => task.IsCompleted, "等待异步查询保存超时。");
110 task.GetAwaiter().GetResult();
111 }
112
113 private static void PumpUntil(Func<bool> condition, string message)
114 {
115 var clock = Stopwatch.StartNew();
116 var frame = new DispatcherFrame();
117 var timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(10) };
118 timer.Tick += (_, _) => { if (condition() || clock.Elapsed > TimeSpan.FromSeconds(5)) frame.Continue = false; };
119 timer.Start();
120 try { Dispatcher.PushFrame(frame); }
121 finally { timer.Stop(); }
122 Ensure(condition(), message);
123 }
124
125 private static void RunSta(Action action)
126 {
127 Exception? failure = null;
128 var thread = new Thread(() =>
129 {
130 try
131 {
132 SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher));
133 action();
134 }
135 catch (Exception exception) { failure = exception; }
136 finally { Dispatcher.CurrentDispatcher.InvokeShutdown(); }
137 }) { IsBackground = true };
138 thread.SetApartmentState(ApartmentState.STA);
139 thread.Start();
140 Ensure(thread.Join(TimeSpan.FromSeconds(20)), "搜索窗口交互测试超时。");
141 if (failure is not null) throw new InvalidOperationException(failure.Message, failure);
142 }
143
144 private static void Ensure(bool condition, string message)
145 {
146 if (!condition) throw new InvalidOperationException(message);
147 }
148
149 private sealed class WindowSession : IDisposable
150 {
151 private readonly string root = Path.Combine(Path.GetTempPath(), "xfetoolbox-search-interaction-" + Guid.NewGuid().ToString("N"));
152 public string StatePath => Path.Combine(root, "last-query.json");
153 public FileSearchRuntime Runtime { get; }
154 public CommandPaletteWindow Window { get; }
155
156 public WindowSession()
157 {
158 Directory.CreateDirectory(root);
159 Runtime = new FileSearchRuntime(Path.Combine(root, "unused-cache"));
160 Window = new CommandPaletteWindow(Runtime, new QuickSearchQueryMemory(StatePath));
161 // Keep the window hidden; no native focus changes, crawling or service connection.
162 }
163
164 public void Dispose()
165 {
166 Window.Close();
167 Runtime.DisposeAsync().AsTask().GetAwaiter().GetResult();
168 Ensure(Path.GetDirectoryName(root) == Path.TrimEndingDirectorySeparator(Path.GetFullPath(Path.GetTempPath())) &&
169 Path.GetFileName(root).StartsWith("xfetoolbox-search-interaction-", StringComparison.Ordinal), "测试清理路径越界。");
170 if (File.Exists(StatePath)) File.Delete(StatePath);
171 Directory.Delete(root);
172 }
173 }
174 }
Added XFEToolBox.Client.Wpf.Test/QuickSearchQueryMemoryTests.cs +113 -0
@@ -0,0 +1,113 @@
1 using System.Diagnostics;
2 using System.IO;
3 using System.Text.Json;
4 using XFEToolBox.Client.Utilities;
5
6 namespace XFEToolBox.Client.Wpf.Test;
7
8 public static class QuickSearchQueryMemoryTests
9 {
10 [Test]
11 public static void QuickSearchLastQuerySurvivesNewInstanceAndExplicitClear()
12 {
13 using var fixture = new StateFixture();
14 const string query = " 报告 *2026?.pdf | C:\\项目\\** ";
15 var first = new QuickSearchQueryMemory(fixture.StatePath);
16 Ensure(first.LoadAsync().GetAwaiter().GetResult() == string.Empty, "首次打开不应恢复不存在的查询。");
17 first.Remember(query);
18 first.FlushAsync().GetAwaiter().GetResult();
19 var reopened = new QuickSearchQueryMemory(fixture.StatePath);
20 Ensure(reopened.LoadAsync().GetAwaiter().GetResult() == query, "重新启动没有精确保留中文、空格、路径或通配符。");
21 reopened.Remember(string.Empty);
22 reopened.FlushAsync().GetAwaiter().GetResult();
23 Ensure(new QuickSearchQueryMemory(fixture.StatePath).LoadAsync().GetAwaiter().GetResult() == string.Empty,
24 "明确清空后的查询在重新启动时又恢复了。");
25 Ensure(Directory.EnumerateFiles(fixture.Root).Count() == 1, "查询保存遗留了临时文件或多条历史记录。");
26 }
27
28 [Test]
29 public static void QuickSearchLastQueryRecoversFromCorruptAndInaccessibleState()
30 {
31 using var fixture = new StateFixture();
32 File.WriteAllText(fixture.StatePath, "{broken-json");
33 var memory = new QuickSearchQueryMemory(fixture.StatePath);
34 Ensure(memory.LoadAsync().GetAwaiter().GetResult() == string.Empty, "损坏配置应安全恢复为空。");
35 memory.Remember("recovered");
36 memory.FlushAsync().GetAwaiter().GetResult();
37 Ensure(new QuickSearchQueryMemory(fixture.StatePath).LoadAsync().GetAwaiter().GetResult() == "recovered",
38 "损坏配置恢复后不能继续保存。");
39
40 var blockedPath = Path.Combine(fixture.Root, "directory-not-a-file");
41 Directory.CreateDirectory(blockedPath);
42 var blocked = new QuickSearchQueryMemory(blockedPath);
43 Ensure(blocked.LoadAsync().GetAwaiter().GetResult() == string.Empty, "不可读状态应安全返回空查询。");
44 blocked.Remember("cannot-save");
45 blocked.FlushAsync().GetAwaiter().GetResult();
46 Ensure(blocked.LoadAsync().GetAwaiter().GetResult() == "cannot-save", "保存失败不应丢掉本次内存查询。");
47 }
48
49 [Test]
50 public static void QuickSearchLastQueryCoalescesRapidTypingWithoutCallerDiskIo()
51 {
52 using var fixture = new StateFixture();
53 var memory = new QuickSearchQueryMemory(fixture.StatePath);
54 var watch = Stopwatch.StartNew();
55 for (var index = 0; index < 2_000; index++) memory.Remember("typing-" + index);
56 watch.Stop();
57 Ensure(watch.Elapsed < TimeSpan.FromSeconds(1), $"记忆连续输入阻塞了调用线程:{watch.Elapsed.TotalMilliseconds:F1} ms。");
58 memory.FlushAsync().GetAwaiter().GetResult();
59 Ensure(JsonSerializer.Deserialize<string>(File.ReadAllText(fixture.StatePath)) == "typing-1999",
60 "快速输入的后台写入覆盖了最新查询。");
61 Ensure(new QuickSearchQueryMemory(fixture.StatePath).LoadAsync().GetAwaiter().GetResult() == "typing-1999",
62 "快速输入后跨实例恢复的不是最后一项。");
63 }
64
65 [Test]
66 public static void QuickSearchLastQueryDoesNotOverwriteTypingOrClearWithDelayedRestoration()
67 {
68 using var fixture = new StateFixture();
69 foreach (var latest in new[] { "new user input", string.Empty })
70 {
71 var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
72 var release = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
73 var callerThread = Environment.CurrentManagedThreadId;
74 var readThread = 0;
75 var memory = new QuickSearchQueryMemory(fixture.StatePath, () =>
76 {
77 readThread = Environment.CurrentManagedThreadId;
78 entered.SetResult();
79 return release.Task;
80 });
81 var restoration = memory.LoadAsync();
82 Ensure(entered.Task.Wait(TimeSpan.FromSeconds(3)) && !restoration.IsCompleted,
83 "延迟恢复没有保持异步,或阻塞了调用线程。");
84 Ensure(readThread != callerThread, "首次读取在调用线程执行了磁盘逻辑。");
85 memory.Remember(latest);
86 release.SetResult("stale saved query");
87 Ensure(restoration.GetAwaiter().GetResult() == latest && memory.LoadAsync().GetAwaiter().GetResult() == latest,
88 "用户已经输入或清空后,首次磁盘恢复又覆盖了新内容。");
89 memory.FlushAsync().GetAwaiter().GetResult();
90 Ensure(new QuickSearchQueryMemory(fixture.StatePath).LoadAsync().GetAwaiter().GetResult() == latest,
91 "首次恢复竞争后持久化的不是用户最终内容。");
92 }
93 }
94
95 private sealed class StateFixture : IDisposable
96 {
97 public string Root { get; } = Path.Combine(Path.GetTempPath(), "xfetoolbox-query-memory-" + Guid.NewGuid().ToString("N"));
98 public string StatePath => Path.Combine(Root, "last-query.json");
99
100 public StateFixture() => Directory.CreateDirectory(Root);
101
102 public void Dispose()
103 {
104 // The fixture owns this exact random directory and no application/user configuration.
105 if (Directory.Exists(Root)) Directory.Delete(Root, recursive: true);
106 }
107 }
108
109 private static void Ensure(bool condition, string message)
110 {
111 if (!condition) throw new InvalidOperationException(message);
112 }
113 }
Added XFEToolBox.Client.Wpf.Test/QuickSearchViewBehaviorTests.cs +316 -0
@@ -0,0 +1,316 @@
1 using System.Collections.Concurrent;
2 using System.Diagnostics;
3 using System.IO;
4 using System.Reflection;
5 using System.Windows;
6 using System.Windows.Controls;
7 using System.Windows.Input;
8 using System.Windows.Media;
9 using System.Windows.Threading;
10 using XFEToolBox.Client.Core.Search;
11 using XFEToolBox.Client.Core.Search.Service;
12 using XFEToolBox.Client.Utilities;
13 using XFEToolBox.Client.ViewModel.Pages;
14 using XFEToolBox.Client.Views.Windows;
15
16 namespace XFEToolBox.Client.Wpf.Test;
17
18 public static class QuickSearchViewBehaviorTests
19 {
20 [Test]
21 public static void QuickSearchCtrlWheelScalesRealizedRowsWithoutLosingVirtualizationOrNormalWindowOrder() => RunSta(() =>
22 {
23 using var session = new SearchSession(resultCount: 250);
24 var window = session.Window;
25 var results = session.Results;
26 session.Input.Text = "zoom";
27 PumpUntil(() => results.Items.Count == 100, "缩放测试未显示服务提供的文件结果。");
28 PumpUntil(() => ((FileSearchResultViewModel)results.Items[0]).IconSource is { IsFrozen: true },
29 "缩放测试的可见文件图标未完成异步加载。");
30 window.UpdateLayout();
31 Ensure(!window.Topmost, "快速搜索窗口仍始终置于顶层。");
32 Ensure(results.ItemContainerGenerator.ContainerFromIndex(0) is ListBoxItem,
33 "搜索结果没有生成真实 WPF 行容器。");
34 var row = (ListBoxItem)results.ItemContainerGenerator.ContainerFromIndex(0)!;
35 var title = Descendants<TextBlock>(row).First(text => text.Text == ((FileSearchResultViewModel)results.Items[0]).Title);
36 var icon = Descendants<Image>(row).First();
37 var originalRowHeight = row.ActualHeight;
38 var originalIconWidth = RenderedBounds(icon, row).Width;
39 var originalTextHeight = RenderedBounds(title, row).Height;
40 Ensure(!window.AdjustResultViewScale(120, ModifierKeys.None) && window.ResultViewScale == 1,
41 "普通滚轮错误地改变了视图缩放,或被缩放处理器拦截。");
42 Ensure(!window.AdjustResultViewScale(0, ModifierKeys.Control), "零滚轮增量不应被标记为已处理。");
43 // Exercise the actual preview handler without synthesizing or changing OS keyboard state.
44 if ((Keyboard.Modifiers & ModifierKeys.Control) == 0)
45 {
46 var ordinaryWheel = new MouseWheelEventArgs(Mouse.PrimaryDevice, Environment.TickCount, 120)
47 { RoutedEvent = Mouse.PreviewMouseWheelEvent };
48 window.RaiseEvent(ordinaryWheel);
49 Ensure(!ordinaryWheel.Handled && window.ResultViewScale == 1, "不按 Ctrl 时窗口吞掉了普通滚动事件。");
50 }
51 Ensure(window.AdjustResultViewScale(120, ModifierKeys.Control), "Ctrl+滚轮未启用缩放。");
52 Pump();
53 window.UpdateLayout();
54 Ensure(Math.Abs(window.ResultViewScale - 1.1) < .001 && row.ActualHeight > originalRowHeight &&
55 RenderedBounds(icon, row).Width > originalIconWidth * 1.05 &&
56 RenderedBounds(title, row).Height > originalTextHeight * 1.05,
57 $"Ctrl+滚轮没有缩放真实控件:scale {window.ResultViewScale:F2}, row {originalRowHeight:F2}/{row.ActualHeight:F2}, icon {originalIconWidth:F2}/{RenderedBounds(icon, row).Width:F2}, text {originalTextHeight:F2}/{RenderedBounds(title, row).Height:F2}。");
58 for (var index = 0; index < 30; index++) window.AdjustResultViewScale(120, ModifierKeys.Control);
59 Ensure(window.ResultViewScale == 1.6, "视图放大没有限制到 160%。");
60 for (var index = 0; index < 30; index++) window.AdjustResultViewScale(-120, ModifierKeys.Control);
61 Ensure(window.ResultViewScale == .7, "视图缩小没有限制到 70%。");
62 Pump();
63 window.UpdateLayout();
64 var panel = Descendants<VirtualizingStackPanel>(results).FirstOrDefault();
65 var realized = Enumerable.Range(0, results.Items.Count)
66 .Count(index => results.ItemContainerGenerator.ContainerFromIndex(index) is not null);
67 Ensure(ScrollViewer.GetCanContentScroll(results) && VirtualizingPanel.GetIsVirtualizing(results) &&
68 VirtualizingPanel.GetVirtualizationMode(results) == VirtualizationMode.Recycling &&
69 VirtualizingPanel.GetScrollUnit(results) == ScrollUnit.Pixel && panel is not null &&
70 realized > 0 && realized < results.Items.Count / 2,
71 $"缩放破坏了列表虚拟化:已实现 {realized}/{results.Items.Count} 行。");
72 session.AssertNoLocalCrawler();
73 Console.WriteLine($"Quick-search zoom: rendered row {originalRowHeight:F1} DIP; virtualized {realized}/{results.Items.Count}; 70%-160% bounds; non-topmost.");
74 });
75
76 [Test]
77 public static void QuickSearchTypingKeepsInputResponsiveAndSilentlyDiscardsSlowSupersededServiceQueries() => RunSta(() =>
78 {
79 using var session = new SearchSession(resultCount: 1, delayMilliseconds: 200);
80 var clock = Stopwatch.StartNew();
81 var lastPulse = clock.Elapsed;
82 var maximumGap = TimeSpan.Zero;
83 var maximumInput = TimeSpan.Zero;
84 var pulses = 0;
85 var writes = 0;
86 var staleResultShown = false;
87 var heartbeat = new DispatcherTimer(DispatcherPriority.Input) { Interval = TimeSpan.FromMilliseconds(10) };
88 heartbeat.Tick += (_, _) =>
89 {
90 var now = clock.Elapsed;
91 maximumGap = now - lastPulse > maximumGap ? now - lastPulse : maximumGap;
92 lastPulse = now;
93 pulses++;
94 };
95 var typing = new DispatcherTimer(DispatcherPriority.Input) { Interval = TimeSpan.FromMilliseconds(15) };
96 typing.Tick += (_, _) =>
97 {
98 var inputClock = Stopwatch.StartNew();
99 session.Input.Text = writes < 24 ? "typing-" + writes : "latest-final";
100 maximumInput = inputClock.Elapsed > maximumInput ? inputClock.Elapsed : maximumInput;
101 writes++;
102 staleResultShown |= session.Results.Items.OfType<FileSearchResultViewModel>().Any(row => row.Title.StartsWith("old-", StringComparison.Ordinal));
103 if (writes == 25) typing.Stop();
104 };
105 try
106 {
107 heartbeat.Start();
108 session.Input.Text = "old";
109 PumpUntil(() => session.Service.Queries.Contains("old"), "慢搜索未开始,无法验证替换查询取消。");
110 typing.Start();
111 PumpUntil(() => writes == 25 && session.Results.Items.OfType<FileSearchResultViewModel>()
112 .Any(row => row.Title == "latest-final-0000.txt"), "连续输入后没有显示最新查询结果。");
113 PumpFor(TimeSpan.FromMilliseconds(250));
114 }
115 finally
116 {
117 typing.Stop();
118 heartbeat.Stop();
119 }
120 Ensure(!staleResultShown && session.Results.Items.OfType<FileSearchResultViewModel>()
121 .Select(row => row.Title).SequenceEqual(["latest-final-0000.txt"]), "过期查询覆盖了正在输入或最终查询的结果。");
122 Ensure(session.Service.CancelledQueries > 0, "被替换的慢查询没有收到取消信号。");
123 Ensure(session.Service.UiCalls == 0, "文件搜索或服务探测仍在前端线程执行。");
124 Ensure(pulses >= 10 && maximumInput < TimeSpan.FromMilliseconds(250) && maximumGap < TimeSpan.FromMilliseconds(250),
125 $"输入/心跳出现前端阻塞:输入 {maximumInput.TotalMilliseconds:F1} ms,心跳 {maximumGap.TotalMilliseconds:F1} ms,共 {pulses} 次。");
126 Ensure(session.Service.Queries.Count <= 3, "连续键入把大量陈旧查询提交给了索引服务。");
127 Ensure(!Control<TextBlock>(session.Window, "StatusText").Text.Contains("暂时不可用", StringComparison.Ordinal),
128 "正常取消被当成错误显示给用户。");
129 session.AssertNoLocalCrawler();
130 Console.WriteLine($"Quick-search typing: maximum input {maximumInput.TotalMilliseconds:F1} ms; input heartbeat {maximumGap.TotalMilliseconds:F1} ms; {session.Service.Queries.Count} service queries, {session.Service.CancelledQueries} cancelled quietly.");
131 });
132
133 [Test]
134 public static void QuickSearchUnchangedRefreshReusesRowsItemsSourceSelectionAndLoadedShellIcon() => RunSta(() =>
135 {
136 using var session = new SearchSession(resultCount: 3);
137 session.Input.Text = "reuse";
138 PumpUntil(() => session.Results.Items.Count == 3, "复用测试没有显示文件结果。");
139 session.Window.UpdateLayout();
140 var originalSource = session.Results.ItemsSource;
141 var originalRows = session.Results.Items.Cast<FileSearchResultViewModel>().ToArray();
142 PumpUntil(() => originalRows[0].IconSource is { IsFrozen: true } && originalRows[0].HasIcon,
143 "可见文件行没有加载 Windows 文件类型关联图标。");
144 var originalIcon = originalRows[0].IconSource;
145 session.Results.SelectedIndex = 1;
146 for (var attempt = 0; attempt < 4; attempt++)
147 {
148 var refresh = (Task)typeof(CommandPaletteWindow).GetMethod("RefreshResultsAsync", BindingFlags.NonPublic | BindingFlags.Instance)!
149 .Invoke(session.Window, [false])!;
150 PumpUntil(() => refresh.IsCompleted, "相同结果刷新未完成。");
151 refresh.GetAwaiter().GetResult();
152 Ensure(ReferenceEquals(originalSource, session.Results.ItemsSource) && session.Results.Items.Count == originalRows.Length &&
153 originalRows.Select((row, index) => ReferenceEquals(row, session.Results.Items[index])).All(equal => equal) &&
154 ReferenceEquals(originalIcon, originalRows[0].IconSource) && originalRows[0].HasIcon && session.Results.SelectedIndex == 1,
155 "结果不变时重新创建了集合/VM、丢失已加载图标,或重置选中项。");
156 }
157 session.AssertNoLocalCrawler();
158 });
159
160 private static Rect RenderedBounds(FrameworkElement element, Visual ancestor) =>
161 element.TransformToAncestor(ancestor).TransformBounds(new Rect(0, 0, element.ActualWidth, element.ActualHeight));
162
163 private static IEnumerable<T> Descendants<T>(DependencyObject parent) where T : DependencyObject
164 {
165 for (var index = 0; index < VisualTreeHelper.GetChildrenCount(parent); index++)
166 {
167 var child = VisualTreeHelper.GetChild(parent, index);
168 if (child is T typed) yield return typed;
169 foreach (var descendant in Descendants<T>(child)) yield return descendant;
170 }
171 }
172
173 private static T Control<T>(CommandPaletteWindow window, string name) where T : FrameworkElement =>
174 window.FindName(name) as T ?? throw new InvalidOperationException("缺少控件:" + name);
175
176 private static void Pump()
177 {
178 var frame = new DispatcherFrame();
179 Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(() => frame.Continue = false));
180 Dispatcher.PushFrame(frame);
181 }
182
183 private static void PumpUntil(Func<bool> condition, string message, TimeSpan? timeout = null)
184 {
185 if (condition()) return;
186 var clock = Stopwatch.StartNew();
187 var frame = new DispatcherFrame();
188 var timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(10) };
189 timer.Tick += (_, _) =>
190 {
191 if (condition() || clock.Elapsed > (timeout ?? TimeSpan.FromSeconds(8))) frame.Continue = false;
192 };
193 timer.Start();
194 try { Dispatcher.PushFrame(frame); }
195 finally { timer.Stop(); }
196 Ensure(condition(), message);
197 }
198
199 private static void PumpFor(TimeSpan duration)
200 {
201 var clock = Stopwatch.StartNew();
202 PumpUntil(() => clock.Elapsed >= duration, "等待 Dispatcher 事件超时。", duration + TimeSpan.FromSeconds(2));
203 }
204
205 private static void RunSta(Action test)
206 {
207 Exception? failure = null;
208 var thread = new Thread(() =>
209 {
210 try
211 {
212 SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher));
213 test();
214 }
215 catch (Exception error) { failure = error; }
216 finally { Dispatcher.CurrentDispatcher.InvokeShutdown(); }
217 }) { IsBackground = true };
218 thread.SetApartmentState(ApartmentState.STA);
219 thread.Start();
220 Ensure(thread.Join(TimeSpan.FromSeconds(30)), "搜索视图行为测试超时。");
221 if (failure is not null) throw new InvalidOperationException("搜索视图行为回归失败:" + failure.Message, failure);
222 }
223
224 private static void Ensure(bool condition, string message)
225 {
226 if (!condition) throw new InvalidOperationException(message);
227 }
228
229 private sealed class SearchSession : IDisposable
230 {
231 private readonly string root = Path.Combine(Path.GetTempPath(), "xfetoolbox-search-view-" + Guid.NewGuid().ToString("N"));
232 private readonly string scope;
233 private readonly string cache;
234 public FileSearchRuntime Runtime { get; }
235 public DelayedService Service { get; }
236 public CommandPaletteWindow Window { get; }
237 public TextBox Input => Control<TextBox>(Window, "SearchBox");
238 public ListBox Results => Control<ListBox>(Window, "ResultList");
239
240 public SearchSession(int resultCount, int delayMilliseconds = 0)
241 {
242 scope = Directory.CreateDirectory(Path.Combine(root, "scope")).FullName;
243 cache = Path.Combine(root, "cache");
244 Service = new DelayedService(scope, resultCount, delayMilliseconds, Environment.CurrentManagedThreadId);
245 Runtime = new FileSearchRuntime(cache, Service);
246 Runtime.SetScopeAsync(scope).GetAwaiter().GetResult();
247 AssertNoLocalCrawler();
248 Window = new CommandPaletteWindow(Runtime)
249 {
250 ShowActivated = false,
251 ShowInTaskbar = false,
252 Left = -10000,
253 Top = -10000,
254 WindowStartupLocation = WindowStartupLocation.Manual
255 };
256 Window.Resources.MergedDictionaries.Add(new ResourceDictionary
257 { Source = new Uri("/XFEToolBox.WpfCore;component/Resources/Style/ToolThemeResources.xaml", UriKind.Relative) });
258 Window.Resources.MergedDictionaries.Add(new ResourceDictionary
259 { Source = new Uri("/XFEToolBox;component/Resources/Style/MainStyle.xaml", UriKind.Relative) });
260 // ShowPalette intentionally activates/centers the window; this fixture never calls it.
261 Window.Show();
262 ((DispatcherTimer)typeof(CommandPaletteWindow).GetField("statusTimer", BindingFlags.NonPublic | BindingFlags.Instance)!
263 .GetValue(Window)!).Stop();
264 Pump();
265 Window.UpdateLayout();
266 }
267
268 public void AssertNoLocalCrawler() => Ensure(Runtime.IsUsingIndexingService &&
269 typeof(FileSearchRuntime).GetField("files", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(Runtime) is null &&
270 !File.Exists(Path.Combine(cache, "files.v1.gz")), "隔离服务测试意外启动了本地/全盘回退扫描。");
271
272 public void Dispose()
273 {
274 Window.Close();
275 Pump();
276 Runtime.DisposeAsync().AsTask().GetAwaiter().GetResult();
277 Ensure(Path.GetDirectoryName(root) == Path.TrimEndingDirectorySeparator(Path.GetFullPath(Path.GetTempPath())) &&
278 Path.GetFileName(root).StartsWith("xfetoolbox-search-view-", StringComparison.Ordinal), "测试清理目标超出了专用临时目录。");
279 // This fixture owns only settings.json plus two empty directories; never recursively delete.
280 if (File.Exists(Path.Combine(cache, "settings.json"))) File.Delete(Path.Combine(cache, "settings.json"));
281 if (Directory.Exists(cache)) Directory.Delete(cache);
282 Directory.Delete(scope);
283 Directory.Delete(root);
284 }
285 }
286
287 private sealed class DelayedService(string scope, int resultCount, int delayMilliseconds, int uiThread) : IIndexingServiceClient
288 {
289 private int cancelledQueries;
290 private int uiCalls;
291 public int CancelledQueries => Volatile.Read(ref cancelledQueries);
292 public int UiCalls => Volatile.Read(ref uiCalls);
293 public ConcurrentQueue<string> Queries { get; } = new();
294 private IndexingServiceStatus State => new(false, resultCount, 1, 1) { IndexedRoots = [scope] };
295
296 public Task<IndexingServiceStatus?> GetStatusAsync(CancellationToken cancellationToken = default)
297 {
298 if (Environment.CurrentManagedThreadId == uiThread) Interlocked.Increment(ref uiCalls);
299 return Task.FromResult<IndexingServiceStatus?>(State);
300 }
301
302 public async Task<IndexingServiceSearchResponse?> SearchAsync(string query, string? requestedScope, int limit,
303 CancellationToken cancellationToken = default)
304 {
305 if (Environment.CurrentManagedThreadId == uiThread) Interlocked.Increment(ref uiCalls);
306 Ensure(requestedScope == scope, "测试查询离开了专用隔离目录。");
307 Queries.Enqueue(query);
308 if (delayMilliseconds > 0) await Task.Delay(delayMilliseconds).ConfigureAwait(false);
309 if (cancellationToken.IsCancellationRequested) Interlocked.Increment(ref cancelledQueries);
310 // Deliberately return a late response even when cancelled: the runtime/UI must discard it quietly.
311 var matches = Enumerable.Range(0, Math.Min(resultCount, limit)).Select(index => new FileSearchMatch(
312 new FileSearchEntry(Path.Combine(scope, $"{query}-{index:D4}.txt"), false), 0)).ToArray();
313 return new(matches, resultCount > limit, TimeSpan.FromMilliseconds(delayMilliseconds), State);
314 }
315 }
316 }
Modified XFEToolBox.Client.Wpf.Test/ShellFileIconTests.cs +47 -1
@@ -47,10 +47,12 @@ public static class ShellFileIconTests
47 47 public static async Task FileIconQueueAndCacheStayBoundedAndCancelledRowsDoNotCallShell()
48 48 {
49 49 var calls = 0;
50 var order = new List<string>();
50 51 using var entered = new ManualResetEventSlim();
51 52 using var release = new ManualResetEventSlim();
52 using var service = new ShellFileIconService(1, 8, 4, (_, _, _) =>
53 using var service = new ShellFileIconService(1, 8, 4, (path, _, _) =>
53 54 {
55 lock (order) order.Add(path);
54 56 if (Interlocked.Increment(ref calls) == 1)
55 57 {
56 58 entered.Set();
@@ -73,11 +75,55 @@ public static class ShellFileIconTests
73 75 release.Set();
74 76 Ensure(await active is not null && await latest is not null, "最新图标请求没有完成。");
75 77 await Task.WhenAll(obsolete);
78 Ensure(order.Count >= 2 && order[1] == @"C:\latest.lnk", "最新可见请求没有优先于积压的旧图标请求执行。");
76 79 Ensure(calls <= 9 && service.Counts.Cached <= 4, "图标 Shell 调用数量或缓存超出上限。");
77 80 var cached = await service.GetIconAsync(@"C:\latest.lnk", false);
78 81 Ensure(cached is { IsFrozen: true }, "路径专用图标没有进入冻结缓存。");
79 82 }
80 83
84 [Test]
85 public static void DroppedIconRequestCanRetryWhenTheSameResultIsRealizedAgain()
86 {
87 RunSta(() =>
88 {
89 using var entered = new ManualResetEventSlim();
90 using var release = new ManualResetEventSlim();
91 using var service = new ShellFileIconService(1, 1, 4, (path, _, _) =>
92 {
93 if (path == @"C:\blocking.exe")
94 {
95 entered.Set();
96 release.Wait(TimeSpan.FromSeconds(5));
97 }
98 return TestImage();
99 });
100 var blocking = service.GetIconAsync(@"C:\blocking.exe", false);
101 Ensure(entered.Wait(TimeSpan.FromSeconds(3)), "图标工作线程未开始。");
102 using var row = new FileSearchResultViewModel(new FileSearchMatch(new FileSearchEntry(@"C:\retry.exe", false), 0), service);
103 Ensure(row.IconSource is null && service.Counts.Queued == 1, "首次图标请求未排队。");
104 var newer = service.GetIconAsync(@"C:\newer.exe", false); // Bounded queue evicts the row's first request.
105 var watch = Stopwatch.StartNew();
106 while (!newer.IsCompleted && watch.Elapsed < TimeSpan.FromSeconds(3))
107 {
108 Pump();
109 _ = row.IconSource; // A later realization/binding re-reads the same VM's icon property.
110 Thread.Sleep(1);
111 }
112 Ensure(newer.IsCompletedSuccessfully && newer.Result is null && row.IconSource is null && service.Counts.Queued == 1,
113 "被队列丢弃的请求标记未重置,同一条目重新实现绑定后没有重试图标请求。");
114 release.Set();
115 watch.Restart();
116 while (!row.HasIcon && watch.Elapsed < TimeSpan.FromSeconds(3))
117 {
118 Pump();
119 Thread.Sleep(1);
120 }
121 Ensure(row.IconSource is { IsFrozen: true }, "同一条目被丢弃的图标请求重试后仍永久显示 glyph。");
122 Ensure(blocking.IsCompletedSuccessfully && newer.IsCompletedSuccessfully && newer.Result is null,
123 "重新绑定后的最新请求没有替换旧排队请求。");
124 });
125 }
126
81 127 [Test]
82 128 public static void SearchResultIconsAreLazyAndNotifyTheUiWithoutBlockingIt()
83 129 {
Modified XFEToolBox/App.xaml.cs +6 -0
@@ -138,6 +138,12 @@ public partial class App : Application
138 138 IsExiting = true;
139 139 try
140 140 {
141 // Finish a last keystroke/clear without synchronously writing on the dispatcher.
142 if (commandPaletteWindow is not null)
143 {
144 try { await commandPaletteWindow.FlushRememberedQueryAsync().WaitAsync(TimeSpan.FromSeconds(2)); }
145 catch (TimeoutException) { }
146 }
141 147 await FileSearchRuntime.StopSharedAsync();
142 148 await ShutdownChatRuntimeAsync();
143 149 }
Added XFEToolBox/Resources/Style/QuickSearchContextMenuResources.xaml +131 -0
@@ -0,0 +1,131 @@
1 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
2 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
3 <!-- Keep this menu independent of the application menu template: its shadow effect
4 paints beyond rounded corners and is clipped by the ContextMenu popup. -->
5 <Style x:Key="QuickSearchMenuItemStyle" TargetType="MenuItem">
6 <Setter Property="Foreground" Value="#414156"/>
7 <Setter Property="Background" Value="Transparent"/>
8 <Setter Property="FontSize" Value="12"/>
9 <Setter Property="MinHeight" Value="32"/>
10 <Setter Property="Padding" Value="10,7"/>
11 <Setter Property="Margin" Value="0,1"/>
12 <Setter Property="Cursor" Value="Hand"/>
13 <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
14 <Setter Property="SnapsToDevicePixels" Value="True"/>
15 <Setter Property="Template">
16 <Setter.Value>
17 <ControlTemplate TargetType="MenuItem">
18 <Grid>
19 <Border x:Name="ItemSurface" Background="{TemplateBinding Background}"
20 CornerRadius="8" Padding="{TemplateBinding Padding}">
21 <Grid>
22 <Grid.ColumnDefinitions>
23 <ColumnDefinition Width="Auto"/>
24 <ColumnDefinition Width="*"/>
25 <ColumnDefinition Width="Auto"/>
26 <ColumnDefinition Width="Auto"/>
27 </Grid.ColumnDefinitions>
28 <Grid x:Name="IconSlot" Width="16" Margin="0,0,8,0">
29 <ContentPresenter x:Name="IconPresenter" ContentSource="Icon" VerticalAlignment="Center"/>
30 <TextBlock x:Name="CheckMark" Text="✓" VerticalAlignment="Center" Visibility="Collapsed"/>
31 </Grid>
32 <ContentPresenter Grid.Column="1" ContentSource="Header" RecognizesAccessKey="True" VerticalAlignment="Center"/>
33 <TextBlock x:Name="GestureHint" Grid.Column="2" Text="{TemplateBinding InputGestureText}" Margin="16,0,0,0"
34 Foreground="#9292AC" VerticalAlignment="Center"/>
35 <TextBlock x:Name="SubmenuArrow" Grid.Column="3" Text="›" FontSize="16"
36 Margin="10,0,0,0" VerticalAlignment="Center" Visibility="Collapsed"/>
37 </Grid>
38 </Border>
39 <Popup x:Name="PART_Popup" Placement="Right" Focusable="False" AllowsTransparency="True"
40 IsOpen="{Binding IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}"
41 PopupAnimation="None">
42 <Border Background="#FAFAFF" BorderBrush="#C9C9EB" BorderThickness="1"
43 CornerRadius="12" Padding="6,7" SnapsToDevicePixels="True">
44 <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Cycle"/>
45 </Border>
46 </Popup>
47 </Grid>
48 <ControlTemplate.Triggers>
49 <Trigger Property="IsHighlighted" Value="True">
50 <Setter TargetName="ItemSurface" Property="Background" Value="#E9E9FB"/>
51 <Setter Property="Foreground" Value="#6868BF"/>
52 </Trigger>
53 <Trigger Property="IsKeyboardFocused" Value="True">
54 <Setter TargetName="ItemSurface" Property="Background" Value="#E9E9FB"/>
55 <Setter Property="Foreground" Value="#6868BF"/>
56 </Trigger>
57 <Trigger Property="IsEnabled" Value="False">
58 <Setter Property="Opacity" Value="0.45"/>
59 <Setter Property="Cursor" Value="Arrow"/>
60 </Trigger>
61 <Trigger Property="HasItems" Value="True">
62 <Setter TargetName="SubmenuArrow" Property="Visibility" Value="Visible"/>
63 </Trigger>
64 <Trigger Property="IsChecked" Value="True">
65 <Setter TargetName="CheckMark" Property="Visibility" Value="Visible"/>
66 <Setter TargetName="IconPresenter" Property="Visibility" Value="Collapsed"/>
67 </Trigger>
68 <Trigger Property="Icon" Value="{x:Null}">
69 <Setter TargetName="IconPresenter" Property="Visibility" Value="Collapsed"/>
70 </Trigger>
71 <MultiTrigger>
72 <MultiTrigger.Conditions>
73 <Condition Property="Icon" Value="{x:Null}"/>
74 <Condition Property="IsCheckable" Value="False"/>
75 </MultiTrigger.Conditions>
76 <Setter TargetName="IconSlot" Property="Visibility" Value="Collapsed"/>
77 </MultiTrigger>
78 <Trigger Property="InputGestureText" Value="">
79 <Setter TargetName="GestureHint" Property="Visibility" Value="Collapsed"/>
80 </Trigger>
81 </ControlTemplate.Triggers>
82 </ControlTemplate>
83 </Setter.Value>
84 </Setter>
85 </Style>
86
87 <Style x:Key="QuickSearchSeparatorStyle" TargetType="Separator">
88 <Setter Property="Height" Value="1"/>
89 <Setter Property="Margin" Value="8,5"/>
90 <Setter Property="Background" Value="#E4E4F3"/>
91 <Setter Property="Template">
92 <Setter.Value>
93 <ControlTemplate TargetType="Separator">
94 <Border Height="1" Background="{TemplateBinding Background}"/>
95 </ControlTemplate>
96 </Setter.Value>
97 </Setter>
98 </Style>
99
100 <Style x:Key="QuickSearchContextMenuStyle" TargetType="ContextMenu">
101 <Style.Resources>
102 <Style TargetType="MenuItem" BasedOn="{StaticResource QuickSearchMenuItemStyle}"/>
103 <Style TargetType="Separator" BasedOn="{StaticResource QuickSearchSeparatorStyle}"/>
104 <!-- MenuBase assigns this special resource key to Separator containers. -->
105 <Style x:Key="{x:Static MenuItem.SeparatorStyleKey}" TargetType="Separator"
106 BasedOn="{StaticResource QuickSearchSeparatorStyle}"/>
107 </Style.Resources>
108 <Setter Property="Background" Value="Transparent"/>
109 <Setter Property="BorderBrush" Value="#C9C9EB"/>
110 <Setter Property="BorderThickness" Value="1"/>
111 <Setter Property="Padding" Value="6,7"/>
112 <Setter Property="MinWidth" Value="174"/>
113 <Setter Property="HasDropShadow" Value="False"/>
114 <Setter Property="Effect" Value="{x:Null}"/>
115 <Setter Property="UseLayoutRounding" Value="True"/>
116 <Setter Property="SnapsToDevicePixels" Value="True"/>
117 <Setter Property="TextOptions.TextFormattingMode" Value="Display"/>
118 <Setter Property="Template">
119 <Setter.Value>
120 <ControlTemplate TargetType="ContextMenu">
121 <Border x:Name="MenuSurface" Background="#FAFAFF" BorderBrush="{TemplateBinding BorderBrush}"
122 BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="12"
123 Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">
124 <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Cycle"/>
125 </Border>
126 </ControlTemplate>
127 </Setter.Value>
128 </Setter>
129 </Style>
130 <Style TargetType="ContextMenu" BasedOn="{StaticResource QuickSearchContextMenuStyle}"/>
131 </ResourceDictionary>
Added XFEToolBox/Utilities/QuickSearchQueryMemory.cs +138 -0
Modified XFEToolBox/Utilities/ShellFileIconService.cs +2 -2
@@ -132,8 +132,8 @@ public sealed class ShellFileIconService : IDisposable
132 132 {
133 133 while (!stopping && queue.Count == 0) Monitor.Wait(gate);
134 134 if (stopping) return;
135 work = queue.First!.Value;
136 queue.RemoveFirst();
135 work = queue.Last!.Value;
136 queue.RemoveLast();
137 137 work.Node = null;
138 138 }
139 139 ImageSource? image = null;
Modified XFEToolBox/ViewModel/Pages/FileSearchResultViewModel.cs +13 -1
Modified XFEToolBox/Views/Windows/CommandPaletteWindow.xaml +10 -4
Modified XFEToolBox/Views/Windows/CommandPaletteWindow.xaml.cs +164 -16
Modified tests/QuickSearch.Validation/README.md +21 -0