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
代码差异
@@ -359,6 +359,7 @@ XFEToolBox.Server/Data/
# Local validation build outputs
.BuildValidation/final-*-release/
.BuildValidation/live-index-*-release/
.BuildValidation/quick-search-view-behavior-release/
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
@@ -0,0 +1,204 @@
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
namespace XFEToolBox.Client.Wpf.Test;
public static class QuickSearchContextMenuTests
{
[Test]
public static void QuickSearchContextMenuUsesTransparentPopupAndRoundedOutlinedSurfaceWithoutShadows() => RunSta(() =>
{
var menu = CreateMenu(out var host);
try
{
menu.IsOpen = true;
menu.ApplyTemplate();
Pump();
menu.UpdateLayout();
var popup = LogicalTreeHelper.GetParent(menu) as Popup ??
typeof(ContextMenu).GetField("_parentPopup", BindingFlags.NonPublic | BindingFlags.Instance)?.GetValue(menu) as Popup;
Ensure(popup is { AllowsTransparency: true, IsOpen: true },
$"真实右键菜单没有使用透明 Popup:menuOpen={menu.IsOpen}, popup={popup?.GetType().Name}, open={popup?.IsOpen}, transparency={popup?.AllowsTransparency}, size={menu.ActualWidth}x{menu.ActualHeight}。");
var root = VisualRoot(menu);
// The native popup remains invisible while its actual menu is rendered offscreen.
root.Opacity = 0;
menu.Opacity = 1;
Ensure(!menu.HasDropShadow && menu.Effect is null &&
menu.Background is SolidColorBrush { Color.A: 0 }, "菜单仍开启系统阴影、外部 Effect 或不透明方形背景。");
Ensure(Descendants<UIElement>(menu).All(element => element.Effect is null),
"菜单模板或菜单项仍继承了全局阴影 Effect。");
var surface = menu.Template.FindName("MenuSurface", menu) as Border;
Ensure(surface is { CornerRadius.TopLeft: 12, BorderThickness.Top: 1 } &&
surface.BorderBrush is SolidColorBrush borderBrush && borderBrush.Color == Color.FromRgb(201, 201, 235),
"菜单缺少主页配色的一像素圆角边框。");
Ensure(menu.Padding.Top >= 7 && menu.Padding.Bottom >= 7,
"菜单上下间距不足,最下方悬停圆角会靠近底边。");
var bitmap = Render(menu);
var pixels = new byte[bitmap.PixelWidth * bitmap.PixelHeight * 4];
bitmap.CopyPixels(pixels, bitmap.PixelWidth * 4, 0);
Ensure(Alpha(0, 0) == 0 && Alpha(bitmap.PixelWidth - 1, 0) == 0 &&
Alpha(0, bitmap.PixelHeight - 1) == 0 && Alpha(bitmap.PixelWidth - 1, bitmap.PixelHeight - 1) == 0,
"菜单圆角外像素不透明:仍有黑/灰色方形背景或被裁切的阴影。");
Ensure(Alpha(bitmap.PixelWidth / 2, 0) > 0 && Alpha(0, bitmap.PixelHeight / 2) > 0,
"菜单边缘没有渲染出可见边框。");
Save(bitmap, "normal");
var lastItem = (MenuItem)menu.Items[2];
var highlightKey = (DependencyPropertyKey?)typeof(MenuItem).GetField("IsHighlightedPropertyKey", BindingFlags.NonPublic | BindingFlags.Static)?.GetValue(null)
?? throw new InvalidOperationException("未找到 MenuItem 的测试用高亮状态键。");
lastItem.SetValue(highlightKey, true);
Pump();
menu.UpdateLayout();
var itemSurface = (Border)lastItem.Template.FindName("ItemSurface", lastItem)!;
Ensure(itemSurface.Background is SolidColorBrush hover && hover.Color == Color.FromRgb(233, 233, 251),
"菜单项悬停没有使用浅紫色圆角高亮。");
var lastBounds = lastItem.TransformToAncestor(menu).TransformBounds(new Rect(lastItem.RenderSize));
Ensure(menu.ActualHeight - lastBounds.Bottom >= 7, "最下方菜单项没有保留底部空隙。");
Save(Render(menu), "last-item-highlighted");
Console.WriteLine($"Quick-search context menu: transparent native popup; no effects; outlined 12 DIP rounded border; {bitmap.PixelWidth}x{bitmap.PixelHeight} offscreen render.");
byte Alpha(int x, int y) => pixels[(y * bitmap.PixelWidth + x) * 4 + 3];
}
finally { menu.IsOpen = false; host.Close(); Pump(); }
});
[Test]
public static void QuickSearchContextMenuKeepsActionsAndSeparatorsUsableDespiteGlobalMenuTheme() => RunSta(() =>
{
var menu = CreateMenu(out var host);
var clicks = 0;
var action = (MenuItem)menu.Items[0];
action.Click += (_, _) => clicks++;
var separator = new Separator();
menu.Items.Insert(1, separator);
try
{
menu.IsOpen = true;
menu.ApplyTemplate();
Pump();
menu.UpdateLayout();
VisualRoot(menu).Opacity = 0;
menu.Opacity = 1;
Ensure(menu.Items.OfType<MenuItem>().All(item => item.Template.FindName("ItemSurface", item) is Border { CornerRadius.TopLeft: 8 }),
"显式菜单样式没有覆盖全局菜单项模板。");
Ensure(separator.Height == 1 && Math.Abs(separator.ActualHeight - 1) <= 1 / VisualTreeHelper.GetDpi(separator).DpiScaleY && separator.Margin.Top == 5 &&
separator.Background is SolidColorBrush { Color.R: 228, Color.G: 228, Color.B: 243 },
$"快速搜索分隔线没有匹配专用菜单样式:height={separator.ActualHeight}, margin={separator.Margin}, background={separator.Background}。");
action.RaiseEvent(new RoutedEventArgs(MenuItem.ClickEvent, action));
Ensure(clicks == 1 && action.IsEnabled, "自定义菜单模板破坏了原有菜单动作。");
}
finally { menu.IsOpen = false; host.Close(); Pump(); }
});
private static ContextMenu CreateMenu(out Window host)
{
var menu = new ContextMenu
{
Placement = PlacementMode.AbsolutePoint,
HorizontalOffset = -10000,
VerticalOffset = -10000,
Opacity = 0,
Focusable = false,
IsHitTestVisible = false
};
// Construct a FrameworkElement before the first pack URI is resolved in a
// standalone filtered test process; WPF installs its pack URI parser here.
var resources = new ResourceDictionary
{ Source = new Uri("/XFEToolBox;component/Resources/Style/QuickSearchContextMenuResources.xaml", UriKind.Relative) };
menu.Style = (Style)resources["QuickSearchContextMenuStyle"];
// The theme belongs to the owner/window scope, not to the ContextMenu's own
// Resources. The explicit menu style's scoped resources must win over it.
var themedOwner = new Border { ContextMenu = menu };
themedOwner.Resources.MergedDictionaries.Add(resources);
themedOwner.Resources.MergedDictionaries.Add(new ResourceDictionary
{ Source = new Uri("/XFEToolBox.WpfCore;component/Resources/Style/ToolThemeResources.xaml", UriKind.Relative) });
themedOwner.Resources.MergedDictionaries.Add(new ResourceDictionary
{ Source = new Uri("/XFEToolBox;component/Resources/Style/MainStyle.xaml", UriKind.Relative) });
menu.PlacementTarget = themedOwner;
menu.Items.Add(new MenuItem { Header = "打开", Focusable = false });
menu.Items.Add(new MenuItem { Header = "打开所在文件夹", Focusable = false });
menu.Items.Add(new MenuItem { Header = "复制完整路径", Focusable = false });
host = new Window
{
Left = -10000, Top = -10000, Width = 1, Height = 1,
ShowActivated = false, ShowInTaskbar = false, WindowStyle = WindowStyle.None,
AllowsTransparency = true, Background = Brushes.Transparent, Opacity = 0,
WindowStartupLocation = WindowStartupLocation.Manual, Content = themedOwner
};
host.Show();
Pump();
return menu;
}
private static UIElement VisualRoot(UIElement element)
{
DependencyObject current = element;
while (VisualTreeHelper.GetParent(current) is { } parent) current = parent;
return (UIElement)current;
}
private static IEnumerable<T> Descendants<T>(DependencyObject parent) where T : DependencyObject
{
for (var index = 0; index < VisualTreeHelper.GetChildrenCount(parent); index++)
{
var child = VisualTreeHelper.GetChild(parent, index);
if (child is T typed) yield return typed;
foreach (var descendant in Descendants<T>(child)) yield return descendant;
}
}
private static RenderTargetBitmap Render(FrameworkElement element)
{
var bitmap = new RenderTargetBitmap((int)Math.Ceiling(element.ActualWidth),
(int)Math.Ceiling(element.ActualHeight), 96, 96, PixelFormats.Pbgra32);
bitmap.Render(element);
return bitmap;
}
private static void Save(BitmapSource bitmap, string suffix)
{
var root = new DirectoryInfo(AppContext.BaseDirectory);
while (root is not null && !Directory.Exists(Path.Combine(root.FullName, "XFEToolBox.Client.Wpf.Test"))) root = root.Parent;
if (root is null) return;
var target = Directory.CreateDirectory(Path.Combine(root.FullName, ".BuildValidation", "final-quick-search-context-menu-release"));
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
using var output = File.Create(Path.Combine(target.FullName, "context-menu-" + suffix + ".png"));
encoder.Save(output);
}
private static void Pump()
{
var frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(() => frame.Continue = false));
Dispatcher.PushFrame(frame);
}
private static void RunSta(Action action)
{
Exception? failure = null;
var thread = new Thread(() =>
{
try { 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, failure);
}
private static void Ensure(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
}
@@ -0,0 +1,174 @@
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);
}
}
}
@@ -0,0 +1,113 @@
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using XFEToolBox.Client.Utilities;
namespace XFEToolBox.Client.Wpf.Test;
public static class QuickSearchQueryMemoryTests
{
[Test]
public static void QuickSearchLastQuerySurvivesNewInstanceAndExplicitClear()
{
using var fixture = new StateFixture();
const string query = " 报告 *2026?.pdf | C:\\项目\\** ";
var first = new QuickSearchQueryMemory(fixture.StatePath);
Ensure(first.LoadAsync().GetAwaiter().GetResult() == string.Empty, "首次打开不应恢复不存在的查询。");
first.Remember(query);
first.FlushAsync().GetAwaiter().GetResult();
var reopened = new QuickSearchQueryMemory(fixture.StatePath);
Ensure(reopened.LoadAsync().GetAwaiter().GetResult() == query, "重新启动没有精确保留中文、空格、路径或通配符。");
reopened.Remember(string.Empty);
reopened.FlushAsync().GetAwaiter().GetResult();
Ensure(new QuickSearchQueryMemory(fixture.StatePath).LoadAsync().GetAwaiter().GetResult() == string.Empty,
"明确清空后的查询在重新启动时又恢复了。");
Ensure(Directory.EnumerateFiles(fixture.Root).Count() == 1, "查询保存遗留了临时文件或多条历史记录。");
}
[Test]
public static void QuickSearchLastQueryRecoversFromCorruptAndInaccessibleState()
{
using var fixture = new StateFixture();
File.WriteAllText(fixture.StatePath, "{broken-json");
var memory = new QuickSearchQueryMemory(fixture.StatePath);
Ensure(memory.LoadAsync().GetAwaiter().GetResult() == string.Empty, "损坏配置应安全恢复为空。");
memory.Remember("recovered");
memory.FlushAsync().GetAwaiter().GetResult();
Ensure(new QuickSearchQueryMemory(fixture.StatePath).LoadAsync().GetAwaiter().GetResult() == "recovered",
"损坏配置恢复后不能继续保存。");
var blockedPath = Path.Combine(fixture.Root, "directory-not-a-file");
Directory.CreateDirectory(blockedPath);
var blocked = new QuickSearchQueryMemory(blockedPath);
Ensure(blocked.LoadAsync().GetAwaiter().GetResult() == string.Empty, "不可读状态应安全返回空查询。");
blocked.Remember("cannot-save");
blocked.FlushAsync().GetAwaiter().GetResult();
Ensure(blocked.LoadAsync().GetAwaiter().GetResult() == "cannot-save", "保存失败不应丢掉本次内存查询。");
}
[Test]
public static void QuickSearchLastQueryCoalescesRapidTypingWithoutCallerDiskIo()
{
using var fixture = new StateFixture();
var memory = new QuickSearchQueryMemory(fixture.StatePath);
var watch = Stopwatch.StartNew();
for (var index = 0; index < 2_000; index++) memory.Remember("typing-" + index);
watch.Stop();
Ensure(watch.Elapsed < TimeSpan.FromSeconds(1), $"记忆连续输入阻塞了调用线程:{watch.Elapsed.TotalMilliseconds:F1} ms。");
memory.FlushAsync().GetAwaiter().GetResult();
Ensure(JsonSerializer.Deserialize<string>(File.ReadAllText(fixture.StatePath)) == "typing-1999",
"快速输入的后台写入覆盖了最新查询。");
Ensure(new QuickSearchQueryMemory(fixture.StatePath).LoadAsync().GetAwaiter().GetResult() == "typing-1999",
"快速输入后跨实例恢复的不是最后一项。");
}
[Test]
public static void QuickSearchLastQueryDoesNotOverwriteTypingOrClearWithDelayedRestoration()
{
using var fixture = new StateFixture();
foreach (var latest in new[] { "new user input", string.Empty })
{
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
var callerThread = Environment.CurrentManagedThreadId;
var readThread = 0;
var memory = new QuickSearchQueryMemory(fixture.StatePath, () =>
{
readThread = Environment.CurrentManagedThreadId;
entered.SetResult();
return release.Task;
});
var restoration = memory.LoadAsync();
Ensure(entered.Task.Wait(TimeSpan.FromSeconds(3)) && !restoration.IsCompleted,
"延迟恢复没有保持异步,或阻塞了调用线程。");
Ensure(readThread != callerThread, "首次读取在调用线程执行了磁盘逻辑。");
memory.Remember(latest);
release.SetResult("stale saved query");
Ensure(restoration.GetAwaiter().GetResult() == latest && memory.LoadAsync().GetAwaiter().GetResult() == latest,
"用户已经输入或清空后,首次磁盘恢复又覆盖了新内容。");
memory.FlushAsync().GetAwaiter().GetResult();
Ensure(new QuickSearchQueryMemory(fixture.StatePath).LoadAsync().GetAwaiter().GetResult() == latest,
"首次恢复竞争后持久化的不是用户最终内容。");
}
}
private sealed class StateFixture : IDisposable
{
public string Root { get; } = Path.Combine(Path.GetTempPath(), "xfetoolbox-query-memory-" + Guid.NewGuid().ToString("N"));
public string StatePath => Path.Combine(Root, "last-query.json");
public StateFixture() => Directory.CreateDirectory(Root);
public void Dispose()
{
// The fixture owns this exact random directory and no application/user configuration.
if (Directory.Exists(Root)) Directory.Delete(Root, recursive: true);
}
}
private static void Ensure(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
}
@@ -0,0 +1,316 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using XFEToolBox.Client.Core.Search;
using XFEToolBox.Client.Core.Search.Service;
using XFEToolBox.Client.Utilities;
using XFEToolBox.Client.ViewModel.Pages;
using XFEToolBox.Client.Views.Windows;
namespace XFEToolBox.Client.Wpf.Test;
public static class QuickSearchViewBehaviorTests
{
[Test]
public static void QuickSearchCtrlWheelScalesRealizedRowsWithoutLosingVirtualizationOrNormalWindowOrder() => RunSta(() =>
{
using var session = new SearchSession(resultCount: 250);
var window = session.Window;
var results = session.Results;
session.Input.Text = "zoom";
PumpUntil(() => results.Items.Count == 100, "缩放测试未显示服务提供的文件结果。");
PumpUntil(() => ((FileSearchResultViewModel)results.Items[0]).IconSource is { IsFrozen: true },
"缩放测试的可见文件图标未完成异步加载。");
window.UpdateLayout();
Ensure(!window.Topmost, "快速搜索窗口仍始终置于顶层。");
Ensure(results.ItemContainerGenerator.ContainerFromIndex(0) is ListBoxItem,
"搜索结果没有生成真实 WPF 行容器。");
var row = (ListBoxItem)results.ItemContainerGenerator.ContainerFromIndex(0)!;
var title = Descendants<TextBlock>(row).First(text => text.Text == ((FileSearchResultViewModel)results.Items[0]).Title);
var icon = Descendants<Image>(row).First();
var originalRowHeight = row.ActualHeight;
var originalIconWidth = RenderedBounds(icon, row).Width;
var originalTextHeight = RenderedBounds(title, row).Height;
Ensure(!window.AdjustResultViewScale(120, ModifierKeys.None) && window.ResultViewScale == 1,
"普通滚轮错误地改变了视图缩放,或被缩放处理器拦截。");
Ensure(!window.AdjustResultViewScale(0, ModifierKeys.Control), "零滚轮增量不应被标记为已处理。");
// Exercise the actual preview handler without synthesizing or changing OS keyboard state.
if ((Keyboard.Modifiers & ModifierKeys.Control) == 0)
{
var ordinaryWheel = new MouseWheelEventArgs(Mouse.PrimaryDevice, Environment.TickCount, 120)
{ RoutedEvent = Mouse.PreviewMouseWheelEvent };
window.RaiseEvent(ordinaryWheel);
Ensure(!ordinaryWheel.Handled && window.ResultViewScale == 1, "不按 Ctrl 时窗口吞掉了普通滚动事件。");
}
Ensure(window.AdjustResultViewScale(120, ModifierKeys.Control), "Ctrl+滚轮未启用缩放。");
Pump();
window.UpdateLayout();
Ensure(Math.Abs(window.ResultViewScale - 1.1) < .001 && row.ActualHeight > originalRowHeight &&
RenderedBounds(icon, row).Width > originalIconWidth * 1.05 &&
RenderedBounds(title, row).Height > originalTextHeight * 1.05,
$"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}。");
for (var index = 0; index < 30; index++) window.AdjustResultViewScale(120, ModifierKeys.Control);
Ensure(window.ResultViewScale == 1.6, "视图放大没有限制到 160%。");
for (var index = 0; index < 30; index++) window.AdjustResultViewScale(-120, ModifierKeys.Control);
Ensure(window.ResultViewScale == .7, "视图缩小没有限制到 70%。");
Pump();
window.UpdateLayout();
var panel = Descendants<VirtualizingStackPanel>(results).FirstOrDefault();
var realized = Enumerable.Range(0, results.Items.Count)
.Count(index => results.ItemContainerGenerator.ContainerFromIndex(index) is not null);
Ensure(ScrollViewer.GetCanContentScroll(results) && VirtualizingPanel.GetIsVirtualizing(results) &&
VirtualizingPanel.GetVirtualizationMode(results) == VirtualizationMode.Recycling &&
VirtualizingPanel.GetScrollUnit(results) == ScrollUnit.Pixel && panel is not null &&
realized > 0 && realized < results.Items.Count / 2,
$"缩放破坏了列表虚拟化:已实现 {realized}/{results.Items.Count} 行。");
session.AssertNoLocalCrawler();
Console.WriteLine($"Quick-search zoom: rendered row {originalRowHeight:F1} DIP; virtualized {realized}/{results.Items.Count}; 70%-160% bounds; non-topmost.");
});
[Test]
public static void QuickSearchTypingKeepsInputResponsiveAndSilentlyDiscardsSlowSupersededServiceQueries() => RunSta(() =>
{
using var session = new SearchSession(resultCount: 1, delayMilliseconds: 200);
var clock = Stopwatch.StartNew();
var lastPulse = clock.Elapsed;
var maximumGap = TimeSpan.Zero;
var maximumInput = TimeSpan.Zero;
var pulses = 0;
var writes = 0;
var staleResultShown = false;
var heartbeat = new DispatcherTimer(DispatcherPriority.Input) { Interval = TimeSpan.FromMilliseconds(10) };
heartbeat.Tick += (_, _) =>
{
var now = clock.Elapsed;
maximumGap = now - lastPulse > maximumGap ? now - lastPulse : maximumGap;
lastPulse = now;
pulses++;
};
var typing = new DispatcherTimer(DispatcherPriority.Input) { Interval = TimeSpan.FromMilliseconds(15) };
typing.Tick += (_, _) =>
{
var inputClock = Stopwatch.StartNew();
session.Input.Text = writes < 24 ? "typing-" + writes : "latest-final";
maximumInput = inputClock.Elapsed > maximumInput ? inputClock.Elapsed : maximumInput;
writes++;
staleResultShown |= session.Results.Items.OfType<FileSearchResultViewModel>().Any(row => row.Title.StartsWith("old-", StringComparison.Ordinal));
if (writes == 25) typing.Stop();
};
try
{
heartbeat.Start();
session.Input.Text = "old";
PumpUntil(() => session.Service.Queries.Contains("old"), "慢搜索未开始,无法验证替换查询取消。");
typing.Start();
PumpUntil(() => writes == 25 && session.Results.Items.OfType<FileSearchResultViewModel>()
.Any(row => row.Title == "latest-final-0000.txt"), "连续输入后没有显示最新查询结果。");
PumpFor(TimeSpan.FromMilliseconds(250));
}
finally
{
typing.Stop();
heartbeat.Stop();
}
Ensure(!staleResultShown && session.Results.Items.OfType<FileSearchResultViewModel>()
.Select(row => row.Title).SequenceEqual(["latest-final-0000.txt"]), "过期查询覆盖了正在输入或最终查询的结果。");
Ensure(session.Service.CancelledQueries > 0, "被替换的慢查询没有收到取消信号。");
Ensure(session.Service.UiCalls == 0, "文件搜索或服务探测仍在前端线程执行。");
Ensure(pulses >= 10 && maximumInput < TimeSpan.FromMilliseconds(250) && maximumGap < TimeSpan.FromMilliseconds(250),
$"输入/心跳出现前端阻塞:输入 {maximumInput.TotalMilliseconds:F1} ms,心跳 {maximumGap.TotalMilliseconds:F1} ms,共 {pulses} 次。");
Ensure(session.Service.Queries.Count <= 3, "连续键入把大量陈旧查询提交给了索引服务。");
Ensure(!Control<TextBlock>(session.Window, "StatusText").Text.Contains("暂时不可用", StringComparison.Ordinal),
"正常取消被当成错误显示给用户。");
session.AssertNoLocalCrawler();
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.");
});
[Test]
public static void QuickSearchUnchangedRefreshReusesRowsItemsSourceSelectionAndLoadedShellIcon() => RunSta(() =>
{
using var session = new SearchSession(resultCount: 3);
session.Input.Text = "reuse";
PumpUntil(() => session.Results.Items.Count == 3, "复用测试没有显示文件结果。");
session.Window.UpdateLayout();
var originalSource = session.Results.ItemsSource;
var originalRows = session.Results.Items.Cast<FileSearchResultViewModel>().ToArray();
PumpUntil(() => originalRows[0].IconSource is { IsFrozen: true } && originalRows[0].HasIcon,
"可见文件行没有加载 Windows 文件类型关联图标。");
var originalIcon = originalRows[0].IconSource;
session.Results.SelectedIndex = 1;
for (var attempt = 0; attempt < 4; attempt++)
{
var refresh = (Task)typeof(CommandPaletteWindow).GetMethod("RefreshResultsAsync", BindingFlags.NonPublic | BindingFlags.Instance)!
.Invoke(session.Window, [false])!;
PumpUntil(() => refresh.IsCompleted, "相同结果刷新未完成。");
refresh.GetAwaiter().GetResult();
Ensure(ReferenceEquals(originalSource, session.Results.ItemsSource) && session.Results.Items.Count == originalRows.Length &&
originalRows.Select((row, index) => ReferenceEquals(row, session.Results.Items[index])).All(equal => equal) &&
ReferenceEquals(originalIcon, originalRows[0].IconSource) && originalRows[0].HasIcon && session.Results.SelectedIndex == 1,
"结果不变时重新创建了集合/VM、丢失已加载图标,或重置选中项。");
}
session.AssertNoLocalCrawler();
});
private static Rect RenderedBounds(FrameworkElement element, Visual ancestor) =>
element.TransformToAncestor(ancestor).TransformBounds(new Rect(0, 0, element.ActualWidth, element.ActualHeight));
private static IEnumerable<T> Descendants<T>(DependencyObject parent) where T : DependencyObject
{
for (var index = 0; index < VisualTreeHelper.GetChildrenCount(parent); index++)
{
var child = VisualTreeHelper.GetChild(parent, index);
if (child is T typed) yield return typed;
foreach (var descendant in Descendants<T>(child)) yield return descendant;
}
}
private static T Control<T>(CommandPaletteWindow window, string name) where T : FrameworkElement =>
window.FindName(name) as T ?? throw new InvalidOperationException("缺少控件:" + name);
private static void Pump()
{
var frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(() => frame.Continue = false));
Dispatcher.PushFrame(frame);
}
private static void PumpUntil(Func<bool> condition, string message, TimeSpan? timeout = null)
{
if (condition()) return;
var clock = Stopwatch.StartNew();
var frame = new DispatcherFrame();
var timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(10) };
timer.Tick += (_, _) =>
{
if (condition() || clock.Elapsed > (timeout ?? TimeSpan.FromSeconds(8))) frame.Continue = false;
};
timer.Start();
try { Dispatcher.PushFrame(frame); }
finally { timer.Stop(); }
Ensure(condition(), message);
}
private static void PumpFor(TimeSpan duration)
{
var clock = Stopwatch.StartNew();
PumpUntil(() => clock.Elapsed >= duration, "等待 Dispatcher 事件超时。", duration + TimeSpan.FromSeconds(2));
}
private static void RunSta(Action test)
{
Exception? failure = null;
var thread = new Thread(() =>
{
try
{
SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher));
test();
}
catch (Exception error) { failure = error; }
finally { Dispatcher.CurrentDispatcher.InvokeShutdown(); }
}) { IsBackground = true };
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
Ensure(thread.Join(TimeSpan.FromSeconds(30)), "搜索视图行为测试超时。");
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 SearchSession : IDisposable
{
private readonly string root = Path.Combine(Path.GetTempPath(), "xfetoolbox-search-view-" + Guid.NewGuid().ToString("N"));
private readonly string scope;
private readonly string cache;
public FileSearchRuntime Runtime { get; }
public DelayedService Service { get; }
public CommandPaletteWindow Window { get; }
public TextBox Input => Control<TextBox>(Window, "SearchBox");
public ListBox Results => Control<ListBox>(Window, "ResultList");
public SearchSession(int resultCount, int delayMilliseconds = 0)
{
scope = Directory.CreateDirectory(Path.Combine(root, "scope")).FullName;
cache = Path.Combine(root, "cache");
Service = new DelayedService(scope, resultCount, delayMilliseconds, Environment.CurrentManagedThreadId);
Runtime = new FileSearchRuntime(cache, Service);
Runtime.SetScopeAsync(scope).GetAwaiter().GetResult();
AssertNoLocalCrawler();
Window = new CommandPaletteWindow(Runtime)
{
ShowActivated = false,
ShowInTaskbar = false,
Left = -10000,
Top = -10000,
WindowStartupLocation = WindowStartupLocation.Manual
};
Window.Resources.MergedDictionaries.Add(new ResourceDictionary
{ Source = new Uri("/XFEToolBox.WpfCore;component/Resources/Style/ToolThemeResources.xaml", UriKind.Relative) });
Window.Resources.MergedDictionaries.Add(new ResourceDictionary
{ Source = new Uri("/XFEToolBox;component/Resources/Style/MainStyle.xaml", UriKind.Relative) });
// ShowPalette intentionally activates/centers the window; this fixture never calls it.
Window.Show();
((DispatcherTimer)typeof(CommandPaletteWindow).GetField("statusTimer", BindingFlags.NonPublic | BindingFlags.Instance)!
.GetValue(Window)!).Stop();
Pump();
Window.UpdateLayout();
}
public void AssertNoLocalCrawler() => Ensure(Runtime.IsUsingIndexingService &&
typeof(FileSearchRuntime).GetField("files", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(Runtime) is null &&
!File.Exists(Path.Combine(cache, "files.v1.gz")), "隔离服务测试意外启动了本地/全盘回退扫描。");
public void Dispose()
{
Window.Close();
Pump();
Runtime.DisposeAsync().AsTask().GetAwaiter().GetResult();
Ensure(Path.GetDirectoryName(root) == Path.TrimEndingDirectorySeparator(Path.GetFullPath(Path.GetTempPath())) &&
Path.GetFileName(root).StartsWith("xfetoolbox-search-view-", StringComparison.Ordinal), "测试清理目标超出了专用临时目录。");
// This fixture owns only settings.json plus two empty directories; never recursively delete.
if (File.Exists(Path.Combine(cache, "settings.json"))) File.Delete(Path.Combine(cache, "settings.json"));
if (Directory.Exists(cache)) Directory.Delete(cache);
Directory.Delete(scope);
Directory.Delete(root);
}
}
private sealed class DelayedService(string scope, int resultCount, int delayMilliseconds, int uiThread) : IIndexingServiceClient
{
private int cancelledQueries;
private int uiCalls;
public int CancelledQueries => Volatile.Read(ref cancelledQueries);
public int UiCalls => Volatile.Read(ref uiCalls);
public ConcurrentQueue<string> Queries { get; } = new();
private IndexingServiceStatus State => new(false, resultCount, 1, 1) { IndexedRoots = [scope] };
public Task<IndexingServiceStatus?> GetStatusAsync(CancellationToken cancellationToken = default)
{
if (Environment.CurrentManagedThreadId == uiThread) Interlocked.Increment(ref uiCalls);
return Task.FromResult<IndexingServiceStatus?>(State);
}
public async Task<IndexingServiceSearchResponse?> SearchAsync(string query, string? requestedScope, int limit,
CancellationToken cancellationToken = default)
{
if (Environment.CurrentManagedThreadId == uiThread) Interlocked.Increment(ref uiCalls);
Ensure(requestedScope == scope, "测试查询离开了专用隔离目录。");
Queries.Enqueue(query);
if (delayMilliseconds > 0) await Task.Delay(delayMilliseconds).ConfigureAwait(false);
if (cancellationToken.IsCancellationRequested) Interlocked.Increment(ref cancelledQueries);
// Deliberately return a late response even when cancelled: the runtime/UI must discard it quietly.
var matches = Enumerable.Range(0, Math.Min(resultCount, limit)).Select(index => new FileSearchMatch(
new FileSearchEntry(Path.Combine(scope, $"{query}-{index:D4}.txt"), false), 0)).ToArray();
return new(matches, resultCount > limit, TimeSpan.FromMilliseconds(delayMilliseconds), State);
}
}
}
@@ -47,10 +47,12 @@ public static class ShellFileIconTests
public static async Task FileIconQueueAndCacheStayBoundedAndCancelledRowsDoNotCallShell()
{
var calls = 0;
var order = new List<string>();
using var entered = new ManualResetEventSlim();
using var release = new ManualResetEventSlim();
using var service = new ShellFileIconService(1, 8, 4, (_, _, _) =>
using var service = new ShellFileIconService(1, 8, 4, (path, _, _) =>
{
lock (order) order.Add(path);
if (Interlocked.Increment(ref calls) == 1)
{
entered.Set();
@@ -73,11 +75,55 @@ public static class ShellFileIconTests
release.Set();
Ensure(await active is not null && await latest is not null, "最新图标请求没有完成。");
await Task.WhenAll(obsolete);
Ensure(order.Count >= 2 && order[1] == @"C:\latest.lnk", "最新可见请求没有优先于积压的旧图标请求执行。");
Ensure(calls <= 9 && service.Counts.Cached <= 4, "图标 Shell 调用数量或缓存超出上限。");
var cached = await service.GetIconAsync(@"C:\latest.lnk", false);
Ensure(cached is { IsFrozen: true }, "路径专用图标没有进入冻结缓存。");
}
[Test]
public static void DroppedIconRequestCanRetryWhenTheSameResultIsRealizedAgain()
{
RunSta(() =>
{
using var entered = new ManualResetEventSlim();
using var release = new ManualResetEventSlim();
using var service = new ShellFileIconService(1, 1, 4, (path, _, _) =>
{
if (path == @"C:\blocking.exe")
{
entered.Set();
release.Wait(TimeSpan.FromSeconds(5));
}
return TestImage();
});
var blocking = service.GetIconAsync(@"C:\blocking.exe", false);
Ensure(entered.Wait(TimeSpan.FromSeconds(3)), "图标工作线程未开始。");
using var row = new FileSearchResultViewModel(new FileSearchMatch(new FileSearchEntry(@"C:\retry.exe", false), 0), service);
Ensure(row.IconSource is null && service.Counts.Queued == 1, "首次图标请求未排队。");
var newer = service.GetIconAsync(@"C:\newer.exe", false); // Bounded queue evicts the row's first request.
var watch = Stopwatch.StartNew();
while (!newer.IsCompleted && watch.Elapsed < TimeSpan.FromSeconds(3))
{
Pump();
_ = row.IconSource; // A later realization/binding re-reads the same VM's icon property.
Thread.Sleep(1);
}
Ensure(newer.IsCompletedSuccessfully && newer.Result is null && row.IconSource is null && service.Counts.Queued == 1,
"被队列丢弃的请求标记未重置,同一条目重新实现绑定后没有重试图标请求。");
release.Set();
watch.Restart();
while (!row.HasIcon && watch.Elapsed < TimeSpan.FromSeconds(3))
{
Pump();
Thread.Sleep(1);
}
Ensure(row.IconSource is { IsFrozen: true }, "同一条目被丢弃的图标请求重试后仍永久显示 glyph。");
Ensure(blocking.IsCompletedSuccessfully && newer.IsCompletedSuccessfully && newer.Result is null,
"重新绑定后的最新请求没有替换旧排队请求。");
});
}
[Test]
public static void SearchResultIconsAreLazyAndNotifyTheUiWithoutBlockingIt()
{
@@ -138,6 +138,12 @@ public partial class App : Application
IsExiting = true;
try
{
// Finish a last keystroke/clear without synchronously writing on the dispatcher.
if (commandPaletteWindow is not null)
{
try { await commandPaletteWindow.FlushRememberedQueryAsync().WaitAsync(TimeSpan.FromSeconds(2)); }
catch (TimeoutException) { }
}
await FileSearchRuntime.StopSharedAsync();
await ShutdownChatRuntimeAsync();
}
@@ -0,0 +1,131 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- Keep this menu independent of the application menu template: its shadow effect
paints beyond rounded corners and is clipped by the ContextMenu popup. -->
<Style x:Key="QuickSearchMenuItemStyle" TargetType="MenuItem">
<Setter Property="Foreground" Value="#414156"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="FontSize" Value="12"/>
<Setter Property="MinHeight" Value="32"/>
<Setter Property="Padding" Value="10,7"/>
<Setter Property="Margin" Value="0,1"/>
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="SnapsToDevicePixels" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="MenuItem">
<Grid>
<Border x:Name="ItemSurface" Background="{TemplateBinding Background}"
CornerRadius="8" Padding="{TemplateBinding Padding}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid x:Name="IconSlot" Width="16" Margin="0,0,8,0">
<ContentPresenter x:Name="IconPresenter" ContentSource="Icon" VerticalAlignment="Center"/>
<TextBlock x:Name="CheckMark" Text="✓" VerticalAlignment="Center" Visibility="Collapsed"/>
</Grid>
<ContentPresenter Grid.Column="1" ContentSource="Header" RecognizesAccessKey="True" VerticalAlignment="Center"/>
<TextBlock x:Name="GestureHint" Grid.Column="2" Text="{TemplateBinding InputGestureText}" Margin="16,0,0,0"
Foreground="#9292AC" VerticalAlignment="Center"/>
<TextBlock x:Name="SubmenuArrow" Grid.Column="3" Text="›" FontSize="16"
Margin="10,0,0,0" VerticalAlignment="Center" Visibility="Collapsed"/>
</Grid>
</Border>
<Popup x:Name="PART_Popup" Placement="Right" Focusable="False" AllowsTransparency="True"
IsOpen="{Binding IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}"
PopupAnimation="None">
<Border Background="#FAFAFF" BorderBrush="#C9C9EB" BorderThickness="1"
CornerRadius="12" Padding="6,7" SnapsToDevicePixels="True">
<StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Cycle"/>
</Border>
</Popup>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsHighlighted" Value="True">
<Setter TargetName="ItemSurface" Property="Background" Value="#E9E9FB"/>
<Setter Property="Foreground" Value="#6868BF"/>
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter TargetName="ItemSurface" Property="Background" Value="#E9E9FB"/>
<Setter Property="Foreground" Value="#6868BF"/>
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Opacity" Value="0.45"/>
<Setter Property="Cursor" Value="Arrow"/>
</Trigger>
<Trigger Property="HasItems" Value="True">
<Setter TargetName="SubmenuArrow" Property="Visibility" Value="Visible"/>
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="CheckMark" Property="Visibility" Value="Visible"/>
<Setter TargetName="IconPresenter" Property="Visibility" Value="Collapsed"/>
</Trigger>
<Trigger Property="Icon" Value="{x:Null}">
<Setter TargetName="IconPresenter" Property="Visibility" Value="Collapsed"/>
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="Icon" Value="{x:Null}"/>
<Condition Property="IsCheckable" Value="False"/>
</MultiTrigger.Conditions>
<Setter TargetName="IconSlot" Property="Visibility" Value="Collapsed"/>
</MultiTrigger>
<Trigger Property="InputGestureText" Value="">
<Setter TargetName="GestureHint" Property="Visibility" Value="Collapsed"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="QuickSearchSeparatorStyle" TargetType="Separator">
<Setter Property="Height" Value="1"/>
<Setter Property="Margin" Value="8,5"/>
<Setter Property="Background" Value="#E4E4F3"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Separator">
<Border Height="1" Background="{TemplateBinding Background}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="QuickSearchContextMenuStyle" TargetType="ContextMenu">
<Style.Resources>
<Style TargetType="MenuItem" BasedOn="{StaticResource QuickSearchMenuItemStyle}"/>
<Style TargetType="Separator" BasedOn="{StaticResource QuickSearchSeparatorStyle}"/>
<!-- MenuBase assigns this special resource key to Separator containers. -->
<Style x:Key="{x:Static MenuItem.SeparatorStyleKey}" TargetType="Separator"
BasedOn="{StaticResource QuickSearchSeparatorStyle}"/>
</Style.Resources>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="#C9C9EB"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Padding" Value="6,7"/>
<Setter Property="MinWidth" Value="174"/>
<Setter Property="HasDropShadow" Value="False"/>
<Setter Property="Effect" Value="{x:Null}"/>
<Setter Property="UseLayoutRounding" Value="True"/>
<Setter Property="SnapsToDevicePixels" Value="True"/>
<Setter Property="TextOptions.TextFormattingMode" Value="Display"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContextMenu">
<Border x:Name="MenuSurface" Background="#FAFAFF" BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="12"
Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">
<StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Cycle"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="ContextMenu" BasedOn="{StaticResource QuickSearchContextMenuStyle}"/>
</ResourceDictionary>
@@ -132,8 +132,8 @@ public sealed class ShellFileIconService : IDisposable
{
while (!stopping && queue.Count == 0) Monitor.Wait(gate);
if (stopping) return;
work = queue.First!.Value;
queue.RemoveFirst();
work = queue.Last!.Value;
queue.RemoveLast();
work.Node = null;
}
ImageSource? image = null;