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

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
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);
    }
}