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

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using XFEToolBox.Client.Models;
using XFEToolBox.Client.Utilities;
using XFEToolBox.Client.ViewModel.Pages;
using XFEToolBox.Client.Views.Pages;
using XFEToolBox.WpfCore.Controls;
using ActivityKind = XFEToolBox.Client.Models.ActivityKind;

namespace HomeDashboard.Validation;

internal static class Program
{
    [STAThread]
    private static int Main()
    {
        // A separate process is intentional: exercise compiled BAML and real layout in
        // Release/ReadyToRun without starting the app's login, tray or upgrade services.
        var app = new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };
        foreach (var resource in new[]
        {
            "/XFEToolBox.WpfCore;component/Resources/Style/ToolThemeResources.xaml",
            "/XFEToolBox;component/Resources/Style/MainStyle.xaml",
            "/XFEToolBox;component/Resources/Style/AdminManagementStyle.xaml"
        })
            app.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri(resource, UriKind.Relative) });

        var failures = new List<Exception>();
        app.DispatcherUnhandledException += (_, args) =>
        {
            failures.Add(args.Exception);
            args.Handled = true;
        };
        var frame = new Frame { NavigationUIVisibility = System.Windows.Navigation.NavigationUIVisibility.Hidden };
        var window = new Window
        {
            Width = 1000, Height = 700, Left = -10000, Top = -10000,
            ShowActivated = false, ShowInTaskbar = false, Content = frame
        };
        var exitCode = 1;
        app.Dispatcher.InvokeAsync(async () =>
        {
            try
            {
                await ValidateAsync(frame, window, failures);
                exitCode = 0;
            }
            catch (Exception exception) { Console.Error.WriteLine(exception); }
            finally { window.Close(); app.Shutdown(); }
        });
        window.Show();
        app.Run();
        return exitCode;
    }

    private static async Task ValidateAsync(Frame frame, Window window, List<Exception> failures)
    {
        var page = MainPage.Current!;
        var alternate = new Page { Content = new TextBlock { Text = "其他页面" } };
        var carousel = (Carousel)page.FindName("mainCarousel");
        var cover = BitmapSource.Create(1, 1, 96, 96, PixelFormats.Bgra32, null, new byte[] { 220, 160, 160, 255 }, 4);
        cover.Freeze();
        carousel.SetItems([new CarouselImageItem { Title = "离线回归测试", Image = cover }]);
        carousel.IsLoading = false;
        carousel.AutoPlay = false;

        frame.Content = page;
        await LayoutAsync(window, failures);
        frame.Content = alternate;
        await LayoutAsync(window, failures);

        // Real-world trigger: launching a tool on another page creates an activity.
        using var activity = ActivityCenterService.Start("工具包获取回归", ActivityKind.ToolPackage);
        activity.Report(null, "正在准备");
        var navigationTimes = new List<double>();
        for (var index = 0; index < 30; index++)
        {
            activity.Report(index == 0 ? null : index, "运行中");
            var elapsed = Stopwatch.StartNew();
            frame.Content = page;
            await LayoutAsync(window, failures);
            navigationTimes.Add(elapsed.Elapsed.TotalMilliseconds);
            AssertProgress(page, activity.Item, index == 0 ? 0 : index);
            activity.Report(70, "进度更新");
            await LayoutAsync(window, failures);
            AssertProgress(page, activity.Item, 70);
            Ensure(page.ActualWidth > 0 && page.ActualHeight > 0, "主页没有完成布局。");
            frame.Content = alternate;
            await LayoutAsync(window, failures);
        }

        activity.Succeed("已完成");
        using var failed = ActivityCenterService.Start("失败回归");
        failed.Fail("预期失败");
        using var cancelled = ActivityCenterService.Start("取消回归", canCancel: true);
        cancelled.Cancel();
        frame.Content = page;
        await LayoutAsync(window, failures);
        AssertProgress(page, activity.Item, 100);
        AssertProgress(page, failed.Item, 0);
        AssertProgress(page, cancelled.Item, 0);

        foreach (var kind in Enum.GetValues<LauncherItemKind>())
        {
            var card = new LauncherItemViewModel(new LauncherItem
            {
                Kind = kind, TargetId = "fallback-test", Title = "图标回归",
                ExecuteAsync = () => Task.CompletedTask
            });
            Ensure(card.IconSource is BitmapSource { PixelWidth: > 0, PixelHeight: > 0, IsFrozen: true },
                $"{kind} 的内置图标没有实际解码。不能只检查 BitmapImage 对象是否存在。");
        }
        foreach (var kind in Enum.GetValues<RecentUsageKind>())
        {
            var card = new RecentUsageCardViewModel(new RecentUsageEntry
            {
                Kind = kind, TargetId = "fallback-test", Name = "图标回归",
                IconReference = "/Resources/Image/wrench.png"
            });
            Ensure(card.IconSource is BitmapSource { PixelWidth: > 0, IsFrozen: true }, "最近使用图标资源解析失败。");
        }
        Ensure(failures.Count == 0, "Dispatcher 发生未处理异常。");
        Console.WriteLine($"PASS: 30 次往返主页;运行/空进度/成功/失败/取消的实际进度条绑定;内置图标实际解码。导航+布局最大 {navigationTimes.Max():F1} ms。");
    }

    private static async Task LayoutAsync(Window window, List<Exception> failures)
    {
        await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
        window.UpdateLayout();
        await window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
        if (failures.Count > 0) throw new AggregateException("主页渲染抛出异常。", failures);
    }

    private static void AssertProgress(MainPage page, ActivityItem activity, double expected)
    {
        var bar = Descendants(page).OfType<ProgressBar>().SingleOrDefault(control => ReferenceEquals(control.DataContext, activity));
        Ensure(bar is not null, "活动进度条未生成。");
        var binding = BindingOperations.GetBindingExpression(bar!, ProgressBar.ValueProperty);
        Ensure(binding?.ParentBinding.Mode == BindingMode.OneWay && binding.Status == BindingStatus.Active,
            "活动进度只能从服务单向流向界面,不能回写只读属性。");
        Ensure(bar!.Value == expected, $"进度显示错误:期望 {expected},实际 {bar.Value}。");
    }

    private static IEnumerable<DependencyObject> Descendants(DependencyObject root)
    {
        for (var index = 0; index < VisualTreeHelper.GetChildrenCount(root); index++)
        {
            var child = VisualTreeHelper.GetChild(root, index);
            yield return child;
            foreach (var descendant in Descendants(child)) yield return descendant;
        }
    }

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