using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Security.Cryptography;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
using XFEToolBox.Core.Tools;
namespace QuickTools.Validation;
internal static partial class Program
{
private static readonly List<object> verifiedPackages = [];
private static async Task ValidateActualPackage(string package, ToolPackageManifest manifest, Type service)
{
string hash = Convert.ToHexString(SHA256.HashData(await File.ReadAllBytesAsync(package)));
var launch = (Task)service.GetMethod("BuildPackageAndRunAsync")!.Invoke(null,
[package, manifest.Id, manifest.Version, hash, false, CancellationToken.None, null])!;
await launch.WaitAsync(TimeSpan.FromMinutes(4));
object result = launch.GetType().GetProperty("Result")!.GetValue(launch)!;
Ensure((bool)result.GetType().GetProperty("Success")!.GetValue(result)!, (string)result.GetType().GetProperty("Message")!.GetValue(result)!);
int pid = (int)result.GetType().GetProperty("ProcessId")!.GetValue(result)!;
using var process = Process.GetProcessById(pid);
try
{
var timer = Stopwatch.StartNew();
do { await Task.Delay(100); process.Refresh(); }
while (!process.HasExited && process.MainWindowHandle == 0 && timer.Elapsed < TimeSpan.FromSeconds(15));
Ensure(!process.HasExited && process.MainWindowHandle != 0, "Exact package did not open a window");
Ensure(process.MainWindowTitle == manifest.Name, "Unexpected runtime window: " + process.MainWindowTitle);
string executable = process.MainModule!.FileName;
Ensure(Path.GetFileName(executable).StartsWith("XFEToolRuntime_", StringComparison.Ordinal), "Unexpected test process");
// Load the actual production-compiled package assembly, not the host's
// component library. Exercise its real entry and button handlers with
// isolated fixtures while the independently launched tool remains live.
var assembly = Assembly.LoadFrom(Path.ChangeExtension(executable, ".dll"));
await ValidateCompiledEntry(assembly, manifest);
process.Refresh(); Ensure(!process.HasExited, "Independent package exited during validation");
verifiedPackages.Add(new { id = manifest.Id, version = manifest.Version, sha256 = hash, opened = true, functional = true,
evidence = "Production .xfetool launch + exact compiled entry/button handlers; isolated fixtures", pid });
}
finally
{
// This handle refers only to the process launched above, never a user's existing tool.
if (!process.HasExited)
{
process.CloseMainWindow();
try { await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(10)); }
catch (TimeoutException) { process.Kill(); await process.WaitForExitAsync(); }
}
}
}
private static async Task ValidateCompiledEntry(Assembly assembly, ToolPackageManifest manifest)
{
const string ns = "XFEToolBox.Tools.QuickSuite.";
string fixtures = Path.Combine(root, "actual-package-fixtures", manifest.Id); Directory.CreateDirectory(fixtures);
assembly.GetType(ns + "QuickToolPaths", true)!.GetField("ValidationDataRoot", BindingFlags.NonPublic | BindingFlags.Static)!.SetValue(null, fixtures);
var entry = (FrameworkElement)Activator.CreateInstance(assembly.GetType(manifest.Entry.ViewClass, true)!)!;
var window = FixtureWindow(new Border { Child = new ContentControl { Content = entry } });
window.Show(); await Pump(window);
var page = (FrameworkElement)Descendants(entry).Single(x => x.GetType().FullName == ns + "QuickToolPage");
Ensure(page.GetType().Assembly == assembly, "Package fell back to the old host page");
TextBox Box(string name) => Descendants(page).OfType<TextBox>().Single(b => b.Name == name);
async Task ClickActual(string title)
{
var button = Descendants(page).OfType<Button>().Single(b => Equals(b.Content, title));
Ensure(button.IsEnabled, "Disabled button: " + title);
button.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); await WaitActual();
}
async Task WaitActual()
{
var timer = Stopwatch.StartNew();
while ((bool)page.GetType().GetField("busy", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(page)!)
{ Ensure(timer.Elapsed < TimeSpan.FromSeconds(30), "Package operation timeout"); await Task.Delay(20); }
await Pump(window);
string state = ((TextBlock)page.GetType().GetField("status", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(page)!).Text;
Ensure(!state.StartsWith("未完成"), state);
Ensure(state != "正在处理…", "A finished operation must not display a busy status");
}
try
{
window.Show(); await Pump(window);
Ensure(entry.ActualWidth > 0 && entry.ActualHeight > 0, "Missing package layout");
foreach (var button in Descendants(page).OfType<Button>().Where(b => b.Content is string))
Ensure(button.Style is not null && button.Template is not null, "Unthemed package button: " + button.Content);
switch (manifest.Id)
{
case "xfestudio.quick-calculator":
Ensure(Descendants(page).OfType<Button>().Count(b => b.Parent is System.Windows.Controls.Primitives.UniformGrid) == 24, "Missing keypad");
foreach (string key in new[] { "C", "7", "×", "6", "=" }) await ClickActual(key);
Equal("42", Box("CalculationResult").Text);
await ClickActual("%"); Equal("0.42", Box("CalculationResult").Text);
Box("ExpressionInput").Text = "sqrt(256)+6*7"; await ClickActual("="); Equal("58", Box("CalculationResult").Text);
break;
case "xfestudio.clipboard-plus":
Box("ClipboardText").Text = "Exact package isolated fixture 中文"; await ClickActual("保存为固定片段");
Box("ClipboardSearch").Text = "Exact package isolated";
var clips = Descendants(page).OfType<ListBox>().Single(b => b.Name == "ClipboardEntries"); Equal(1, clips.Items.Count);
clips.SelectedIndex = 0; await Pump(window); Equal("Exact package isolated fixture 中文", Box("ClipboardText").Text);
await ClickActual("删除选中"); Equal(0, clips.Items.Count);
break;
case "xfestudio.screen-assistant":
Drop(Descendants(page).OfType<Grid>().Single(b => b.Name == "ScreenCanvas"), Path.Combine(root, "ocr-fixture.png")); await WaitActual();
await ClickActual("识别当前图片"); Ensure(Box("ScreenResult").Text.Contains("HELLO") && Box("ScreenResult").Text.Contains("12345"), "Package OCR failed");
break;
case "xfestudio.port-inspector":
using (var listener = new TcpListener(IPAddress.Loopback, 0))
{
listener.Start(); Box("PortInput").Text = ((IPEndPoint)listener.LocalEndpoint).Port.ToString(); await ClickActual("查询 / 刷新");
var rows = Descendants(page).OfType<DataGrid>().Single(b => b.Name == "PortResults"); Ensure(rows.Items.Count > 0, "No test endpoint"); rows.SelectedIndex = 0; await Pump(window);
Ensure(Box("PortDetails").Text.Contains(Environment.ProcessId.ToString()) && Box("PortDetails").Text.Contains(Environment.ProcessPath!), "Wrong process/path details");
}
break;
case "xfestudio.developer-text":
Box("TextInput").Text = "{\"name\":\"中文\",\"n\":42}"; await ClickActual("美化 JSON"); Ensure(Box("TextResult").Text.Contains("中文") && Box("TextResult").Text.Contains("\n"), "JSON not formatted");
await ClickActual("压缩 JSON"); Equal("{\"name\":\"中文\",\"n\":42}", Box("TextResult").Text);
break;
case "xfestudio.batch-renamer":
string file = Path.Combine(fixtures, "rename me.txt"); File.WriteAllText(file, "Exact package fixture");
Drop(Descendants(page).OfType<Border>().Single(b => b.ReadLocalValue(UIElement.AllowDropProperty) is true), file); await WaitActual();
Box("RenamePrefix").Text = "new_"; await ClickActual("生成预览");
Equal(1, Descendants(page).OfType<DataGrid>().Single(b => b.Name == "RenamePreview").Items.Count);
var confirmation = page.GetType().GetProperty("Confirmation")!; var previous = confirmation.GetValue(null);
try
{
confirmation.SetValue(null, (Func<string, string, Window?, bool>)((_, _, _) => true));
await ClickActual("执行重命名"); Ensure(File.Exists(Path.Combine(fixtures, "new_rename me.txt")), "Package rename failed");
await ClickActual("撤销本次操作"); Ensure(File.Exists(file) && File.ReadAllText(file) == "Exact package fixture", "Package undo failed");
}
finally { confirmation.SetValue(null, previous); }
break;
case "xfestudio.qr-tool":
Box("QrInput").Text = "Exact package 中文 😀"; await ClickActual("生成二维码");
var image = Descendants(page).OfType<Image>().Single(i => i.Source is BitmapSource);
Equal("Exact package 中文 😀", XFEToolBox.QuickTools.QrService.Decode((BitmapSource)image.Source));
Drop(Descendants(page).OfType<Border>().Single(b => b.ReadLocalValue(UIElement.AllowDropProperty) is true), Path.Combine(root, "qr-fixture.png")); await WaitActual();
Ensure(Box("QrResult").Text.Contains("example.invalid"), "Package QR decode failed");
break;
case "xfestudio.system-shortcuts":
await ClickActual("刷新输出设备"); Ensure(Descendants(page).OfType<ComboBox>().Single(b => b.Name == "OutputDevices").Items.Count > 0, "No audio devices");
await ClickActual("查看本机 IP"); Ensure(Box("LocalAddresses").Text.Length > 0, "No IP state");
var system = assembly.GetType(ns + "SystemActions", true)!; nint hwnd = new WindowInteropHelper(window).Handle;
try { system.GetMethod("SetTopmost")!.Invoke(null, [hwnd, true]); Ensure((bool)system.GetMethod("IsTopmost")!.Invoke(null, [hwnd])!, "Owned window topmost failed"); }
finally { system.GetMethod("SetTopmost")!.Invoke(null, [hwnd, false]); }
break;
default: throw new InvalidOperationException("Unverified package ID");
}
SaveVisual(entry, Path.Combine(root, "actual-package-" + manifest.Id + ".png"));
}
finally
{
window.Close();
foreach (string resource in new[] { "ClipboardHistory", "AwakeLease" })
((IDisposable)assembly.GetType(ns + resource, true)!.GetProperty("Shared")!.GetValue(null)!).Dispose();
}
}
}
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Security.Cryptography;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
using XFEToolBox.Core.Tools;
namespace QuickTools.Validation;
internal static partial class Program
{
private static readonly List<object> verifiedPackages = [];
private static async Task ValidateActualPackage(string package, ToolPackageManifest manifest, Type service)
{
string hash = Convert.ToHexString(SHA256.HashData(await File.ReadAllBytesAsync(package)));
var launch = (Task)service.GetMethod("BuildPackageAndRunAsync")!.Invoke(null,
[package, manifest.Id, manifest.Version, hash, false, CancellationToken.None, null])!;
await launch.WaitAsync(TimeSpan.FromMinutes(4));
object result = launch.GetType().GetProperty("Result")!.GetValue(launch)!;
Ensure((bool)result.GetType().GetProperty("Success")!.GetValue(result)!, (string)result.GetType().GetProperty("Message")!.GetValue(result)!);
int pid = (int)result.GetType().GetProperty("ProcessId")!.GetValue(result)!;
using var process = Process.GetProcessById(pid);
try
{
var timer = Stopwatch.StartNew();
do { await Task.Delay(100); process.Refresh(); }
while (!process.HasExited && process.MainWindowHandle == 0 && timer.Elapsed < TimeSpan.FromSeconds(15));
Ensure(!process.HasExited && process.MainWindowHandle != 0, "Exact package did not open a window");
Ensure(process.MainWindowTitle == manifest.Name, "Unexpected runtime window: " + process.MainWindowTitle);
string executable = process.MainModule!.FileName;
Ensure(Path.GetFileName(executable).StartsWith("XFEToolRuntime_", StringComparison.Ordinal), "Unexpected test process");
// Load the actual production-compiled package assembly, not the host's
// component library. Exercise its real entry and button handlers with
// isolated fixtures while the independently launched tool remains live.
var assembly = Assembly.LoadFrom(Path.ChangeExtension(executable, ".dll"));
await ValidateCompiledEntry(assembly, manifest);
process.Refresh(); Ensure(!process.HasExited, "Independent package exited during validation");
verifiedPackages.Add(new { id = manifest.Id, version = manifest.Version, sha256 = hash, opened = true, functional = true,
evidence = "Production .xfetool launch + exact compiled entry/button handlers; isolated fixtures", pid });
}
finally
{
// This handle refers only to the process launched above, never a user's existing tool.
if (!process.HasExited)
{
process.CloseMainWindow();
try { await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(10)); }
catch (TimeoutException) { process.Kill(); await process.WaitForExitAsync(); }
}
}
}
private static async Task ValidateCompiledEntry(Assembly assembly, ToolPackageManifest manifest)
{
const string ns = "XFEToolBox.Tools.QuickSuite.";
string fixtures = Path.Combine(root, "actual-package-fixtures", manifest.Id); Directory.CreateDirectory(fixtures);
assembly.GetType(ns + "QuickToolPaths", true)!.GetField("ValidationDataRoot", BindingFlags.NonPublic | BindingFlags.Static)!.SetValue(null, fixtures);
var entry = (FrameworkElement)Activator.CreateInstance(assembly.GetType(manifest.Entry.ViewClass, true)!)!;
var window = FixtureWindow(new Border { Child = new ContentControl { Content = entry } });
window.Show(); await Pump(window);
var page = (FrameworkElement)Descendants(entry).Single(x => x.GetType().FullName == ns + "QuickToolPage");
Ensure(page.GetType().Assembly == assembly, "Package fell back to the old host page");
TextBox Box(string name) => Descendants(page).OfType<TextBox>().Single(b => b.Name == name);
async Task ClickActual(string title)
{
var button = Descendants(page).OfType<Button>().Single(b => Equals(b.Content, title));
Ensure(button.IsEnabled, "Disabled button: " + title);
button.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); await WaitActual();
}
async Task WaitActual()
{
var timer = Stopwatch.StartNew();
while ((bool)page.GetType().GetField("busy", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(page)!)
{ Ensure(timer.Elapsed < TimeSpan.FromSeconds(30), "Package operation timeout"); await Task.Delay(20); }
await Pump(window);
string state = ((TextBlock)page.GetType().GetField("status", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(page)!).Text;
Ensure(!state.StartsWith("未完成"), state);
Ensure(state != "正在处理…", "A finished operation must not display a busy status");
}
try
{
window.Show(); await Pump(window);
Ensure(entry.ActualWidth > 0 && entry.ActualHeight > 0, "Missing package layout");
foreach (var button in Descendants(page).OfType<Button>().Where(b => b.Content is string))
Ensure(button.Style is not null && button.Template is not null, "Unthemed package button: " + button.Content);
switch (manifest.Id)
{
case "xfestudio.quick-calculator":
Ensure(Descendants(page).OfType<Button>().Count(b => b.Parent is System.Windows.Controls.Primitives.UniformGrid) == 24, "Missing keypad");
foreach (string key in new[] { "C", "7", "×", "6", "=" }) await ClickActual(key);
Equal("42", Box("CalculationResult").Text);
await ClickActual("%"); Equal("0.42", Box("CalculationResult").Text);
Box("ExpressionInput").Text = "sqrt(256)+6*7"; await ClickActual("="); Equal("58", Box("CalculationResult").Text);
break;
case "xfestudio.clipboard-plus":
Box("ClipboardText").Text = "Exact package isolated fixture 中文"; await ClickActual("保存为固定片段");
Box("ClipboardSearch").Text = "Exact package isolated";
var clips = Descendants(page).OfType<ListBox>().Single(b => b.Name == "ClipboardEntries"); Equal(1, clips.Items.Count);
clips.SelectedIndex = 0; await Pump(window); Equal("Exact package isolated fixture 中文", Box("ClipboardText").Text);
await ClickActual("删除选中"); Equal(0, clips.Items.Count);
break;
case "xfestudio.screen-assistant":
Drop(Descendants(page).OfType<Grid>().Single(b => b.Name == "ScreenCanvas"), Path.Combine(root, "ocr-fixture.png")); await WaitActual();
await ClickActual("识别当前图片"); Ensure(Box("ScreenResult").Text.Contains("HELLO") && Box("ScreenResult").Text.Contains("12345"), "Package OCR failed");
break;
case "xfestudio.port-inspector":
using (var listener = new TcpListener(IPAddress.Loopback, 0))
{
listener.Start(); Box("PortInput").Text = ((IPEndPoint)listener.LocalEndpoint).Port.ToString(); await ClickActual("查询 / 刷新");
var rows = Descendants(page).OfType<DataGrid>().Single(b => b.Name == "PortResults"); Ensure(rows.Items.Count > 0, "No test endpoint"); rows.SelectedIndex = 0; await Pump(window);
Ensure(Box("PortDetails").Text.Contains(Environment.ProcessId.ToString()) && Box("PortDetails").Text.Contains(Environment.ProcessPath!), "Wrong process/path details");
}
break;
case "xfestudio.developer-text":
Box("TextInput").Text = "{\"name\":\"中文\",\"n\":42}"; await ClickActual("美化 JSON"); Ensure(Box("TextResult").Text.Contains("中文") && Box("TextResult").Text.Contains("\n"), "JSON not formatted");
await ClickActual("压缩 JSON"); Equal("{\"name\":\"中文\",\"n\":42}", Box("TextResult").Text);
break;
case "xfestudio.batch-renamer":
string file = Path.Combine(fixtures, "rename me.txt"); File.WriteAllText(file, "Exact package fixture");
Drop(Descendants(page).OfType<Border>().Single(b => b.ReadLocalValue(UIElement.AllowDropProperty) is true), file); await WaitActual();
Box("RenamePrefix").Text = "new_"; await ClickActual("生成预览");
Equal(1, Descendants(page).OfType<DataGrid>().Single(b => b.Name == "RenamePreview").Items.Count);
var confirmation = page.GetType().GetProperty("Confirmation")!; var previous = confirmation.GetValue(null);
try
{
confirmation.SetValue(null, (Func<string, string, Window?, bool>)((_, _, _) => true));
await ClickActual("执行重命名"); Ensure(File.Exists(Path.Combine(fixtures, "new_rename me.txt")), "Package rename failed");
await ClickActual("撤销本次操作"); Ensure(File.Exists(file) && File.ReadAllText(file) == "Exact package fixture", "Package undo failed");
}
finally { confirmation.SetValue(null, previous); }
break;
case "xfestudio.qr-tool":
Box("QrInput").Text = "Exact package 中文 😀"; await ClickActual("生成二维码");
var image = Descendants(page).OfType<Image>().Single(i => i.Source is BitmapSource);
Equal("Exact package 中文 😀", XFEToolBox.QuickTools.QrService.Decode((BitmapSource)image.Source));
Drop(Descendants(page).OfType<Border>().Single(b => b.ReadLocalValue(UIElement.AllowDropProperty) is true), Path.Combine(root, "qr-fixture.png")); await WaitActual();
Ensure(Box("QrResult").Text.Contains("example.invalid"), "Package QR decode failed");
break;
case "xfestudio.system-shortcuts":
await ClickActual("刷新输出设备"); Ensure(Descendants(page).OfType<ComboBox>().Single(b => b.Name == "OutputDevices").Items.Count > 0, "No audio devices");
await ClickActual("查看本机 IP"); Ensure(Box("LocalAddresses").Text.Length > 0, "No IP state");
var system = assembly.GetType(ns + "SystemActions", true)!; nint hwnd = new WindowInteropHelper(window).Handle;
try { system.GetMethod("SetTopmost")!.Invoke(null, [hwnd, true]); Ensure((bool)system.GetMethod("IsTopmost")!.Invoke(null, [hwnd])!, "Owned window topmost failed"); }
finally { system.GetMethod("SetTopmost")!.Invoke(null, [hwnd, false]); }
break;
default: throw new InvalidOperationException("Unverified package ID");
}
SaveVisual(entry, Path.Combine(root, "actual-package-" + manifest.Id + ".png"));
}
finally
{
window.Close();
foreach (string resource in new[] { "ClipboardHistory", "AwakeLease" })
((IDisposable)assembly.GetType(ns + resource, true)!.GetProperty("Shared")!.GetValue(null)!).Dispose();
}
}
}