using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Text.Json; using System.Windows; using System.Windows.Controls; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Threading; using XFEToolBox.QuickTools; namespace QuickTools.Validation; internal static partial class Program { private static string root = ""; private static readonly List results = []; private static readonly List dispatcherErrors = []; private static int passed, failed; private static readonly string[] Folders = ["ClipboardPlus", "ScreenAssistant", "QuickCalculator", "PortInspector", "DeveloperText", "BatchRenamer", "QrTool", "SystemShortcuts"]; [STAThread] private static int Main(string[] args) { if (args.Contains("--catalog") || args.Contains("--launch-package") || args.Contains("--publish-verified")) return ReleaseOperations(args).GetAwaiter().GetResult(); if (args.Contains("--port-child")) { using var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); Console.WriteLine(((IPEndPoint)listener.LocalEndpoint).Port); Console.Out.Flush(); Thread.Sleep(TimeSpan.FromMinutes(2)); return 0; } root = Path.GetFullPath(args.FirstOrDefault(a => !a.StartsWith("--")) ?? Path.Combine("artifacts", "quick-tools", DateTime.Now.ToString("yyyyMMdd-HHmmss"))); Directory.CreateDirectory(root); QuickToolPaths.ValidationDataRoot = Path.Combine(root, "isolated-user-data"); XFEToolBox.Tools.QuickSuite.QuickToolPaths.ValidationDataRoot = Path.Combine(root, "isolated-entry-data"); var app = new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown }; app.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("/XFEToolBox.WpfCore;component/Resources/Style/ToolThemeResources.xaml", UriKind.Relative) }); app.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("/XFEToolBox;component/Resources/Style/MainStyle.xaml", UriKind.Relative) }); app.DispatcherUnhandledException += (_, e) => { dispatcherErrors.Add(e.Exception); e.Handled = true; }; var bindingErrors = new StringWriter(); PresentationTraceSources.DataBindingSource.Listeners.Add(new TextWriterTraceListener(bindingErrors)); PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Error; app.Dispatcher.InvokeAsync(async () => { try { await ValidateServices(); await ValidatePages(); await ValidateRedesign(); await ValidateManifestEntries(); await ValidateLauncher(); if (args.Contains("--package")) await PackageTools(); if (args.Contains("--icons")) GenerateIcons(); await Test("No dispatcher or binding exceptions", () => { Ensure(dispatcherErrors.Count == 0, string.Join("\n", dispatcherErrors)); Ensure(bindingErrors.ToString().Length == 0, bindingErrors.ToString()); }); } catch (Exception e) { failed++; Console.Error.WriteLine(e); } finally { ClipboardHistory.Shared.Dispose(); File.WriteAllText(Path.Combine(root, "results.json"), JsonSerializer.Serialize(new { passed, failed, results }, new JsonSerializerOptions { WriteIndented = true })); if (args.Contains("--package")) File.WriteAllText(Path.Combine(root, "verification.json"), JsonSerializer.Serialize(new { automatedFailures = failed, tools = verifiedPackages }, ReleaseJson)); Console.WriteLine($"RESULT: {passed} passed, {failed} failed. Artifacts: {root}"); app.Shutdown(); } }); app.Run(); return failed == 0 ? 0 : 1; } private static Task Test(string name, Action action) => Test(name, () => { action(); return Task.CompletedTask; }); private static async Task Test(string name, Func action) { var timer = Stopwatch.StartNew(); try { await action(); passed++; results.Add(new { name, pass = true, milliseconds = timer.ElapsedMilliseconds }); Console.WriteLine($"PASS {name} ({timer.ElapsedMilliseconds} ms)"); } catch (Exception e) { failed++; results.Add(new { name, pass = false, error = e.ToString() }); Console.WriteLine($"FAIL {name}: {e}"); } } private static void Ensure(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); } private static void Equal(T expected, T actual) => Ensure(EqualityComparer.Default.Equals(expected, actual), $"Expected {expected}; got {actual}"); private static void Throws(Action action) where T : Exception { try { action(); } catch (T) { return; } throw new InvalidOperationException($"Expected {typeof(T).Name}"); } private static async Task ValidateServices() { await Test("Calculator grammar / precedence / safe rejection", () => { foreach (var (expression, result) in new[] { ("1920/1080", "1.77777777777778"), ("2+3*4", "14"), ("2^3^2", "512"), ("-2^2", "-4"), ("2^-3", "0.125"), ("sqrt(256)+abs(-3)", "19"), ("17%5", "2"), ("1e3×2÷5", "400"), ("sin(pi/2)", "1") }) Equal(result, Calculator.Calculate(expression)); foreach (string invalid in new[] { "", "1/0", "1%0", "sqrt(-1)", "1e999", "System.IO.File.Delete(\"x\")", "(1+2", "1abc", new string('(', 70) + "1" + new string(')', 70), new string('-', 100) + "1" }) Throws(() => Calculator.Calculate(invalid)); }); await Test("Unit / arbitrary-base / dates", () => { Equal("1024 MiB", Calculator.ConvertUnit("1 GiB to MiB")); Equal("3.048 m", Calculator.ConvertUnit("10 ft to m")); Equal("0 C", Calculator.ConvertUnit("32 F to C")); Equal("1000 MB", Calculator.ConvertUnit("1 GB to MB")); Throws(() => Calculator.ConvertUnit("1 kg to m")); Throws(() => Calculator.ConvertUnit("-274 C to K")); Equal("255", Calculator.ConvertBase("FF", 16, 10)); Equal("-11111111", Calculator.ConvertBase("-255", 10, 2)); Equal("18446744073709551616", Calculator.ConvertBase("10000000000000000", 16, 10)); Throws(() => Calculator.ConvertBase("2", 2, 10)); Ensure(Calculator.Timestamp("0").StartsWith("UTC 1970-01-01 00:00:00.000 +00:00"), "Unix epoch"); Ensure(Calculator.Timestamp("2000-01-01T00:00:00Z").Contains("946684800"), "Timestamp conversion"); Ensure(Calculator.DateDifference("2026-10-14T00:00:00+08:00", "2026-10-15T00:00:00+08:00").StartsWith("1 天"), "Date difference"); }); await Test("Developer encodings / JSON / regex / diff", () => { const string input = "测试 😀 + & \"\"\n"; foreach (var (encode, decode) in new[] { ("Base64 编码", "Base64 解码"), ("URL 编码", "URL 解码"), ("Unicode 转义", "Unicode 还原"), ("HTML 编码", "HTML 解码") }) Equal(input, TextActions.Apply(decode, TextActions.Apply(encode, input))); Equal("{\"text\":\"中文\",\"n\":3}", TextActions.Apply("JSON 压缩", TextActions.Apply("JSON 格式化", "{\"text\":\"中文\",\"n\":3}"))); Throws(() => TextActions.Apply("JSON 格式化", "{bad}")); Throws(() => TextActions.Apply("Base64 解码", "not base64!")); Throws(() => TextActions.Apply("Base64 解码", "/w==")); Equal("a" + Environment.NewLine + "b", TextActions.Apply("行去重", "a\r\nb\na")); Ensure(Guid.TryParse(TextActions.Apply("生成 GUID", ""), out _), "GUID"); Ensure(TextActions.Match(@"(\d+)", "abc 123 def").Contains("分组 1: 123"), "Regex groups"); Ensure(TextActions.Match("", new string('a', 20000)).Contains("仅展示前 200"), "Regex bounded results"); Throws(() => TextActions.Match("(a+)+$", new string('a', 10000) + "!")); string diff = TextActions.Diff("a\nb", "a\nc"); Ensure(diff.Contains("- b") && diff.Contains("+ c"), "Diff"); Throws(() => TextActions.Apply("SHA256", new string('a', 1048577))); }); await Test("Streaming hashes", async () => { string path = Path.Combine(root, "hash fixture.txt"); await File.WriteAllTextAsync(path, "abc", new UTF8Encoding(false)); string hash = await TextActions.FileHashes(path); Ensure(hash.Contains("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad") && hash.Contains("900150983cd24fb0d6963f7d28e17f72"), "SHA256 / MD5 bytes"); }); await Test("Rename preview / execute / undo / case-only", () => { string dir = Path.Combine(root, "rename-roundtrip"); Directory.CreateDirectory(dir); string[] paths = [Path.Combine(dir, "a test.txt"), Path.Combine(dir, "中文.txt")]; foreach (string p in paths) File.WriteAllText(p, "content:" + p); string[] before = paths.Select(File.ReadAllText).ToArray(); var plan = RenameService.Preview(paths, new(Prefix: "前缀_", Suffix: "_后缀", Numbered: true, Start: 7, Digits: 2)); Equal(2, plan.Length); Ensure(paths.All(File.Exists) && plan.All(p => !File.Exists(p.Target)), "Preview must not mutate"); var journal = RenameService.Execute(plan, Path.Combine(dir, "journal")); Ensure(plan.All(p => File.Exists(p.Target) && !File.Exists(p.Source)), "Renamed paths"); for (int i = 0; i < plan.Length; i++) Equal(before[i], File.ReadAllText(plan[i].Target)); RenameService.Undo(journal, Path.Combine(dir, "journal")); Ensure(paths.All(File.Exists), "Undo names"); var upper = RenameService.Preview([paths[0]], new(Find: "a", Replace: "A")); var upperJournal = RenameService.Execute(upper, Path.Combine(dir, "journal")); Ensure(Directory.EnumerateFiles(dir).Select(Path.GetFileName).Contains("A test.txt", StringComparer.Ordinal), "Case-only rename"); RenameService.Undo(upperJournal, Path.Combine(dir, "journal")); }); await Test("Rename collision / modified source / duplicate / rollback protection", () => { string dir = Path.Combine(root, "rename-safety"); Directory.CreateDirectory(dir); string a = Path.Combine(dir, "a.txt"), b = Path.Combine(dir, "b.txt"); File.WriteAllText(a, "source"); File.WriteAllText(b, "destination"); Throws(() => RenameService.Preview([a], new(Find: "a", Replace: "b"))); Equal("destination", File.ReadAllText(b)); foreach (string invalid in new[] { "CON.txt", "LPT1.txt", "COM².foo", "name.", "name ", "../x", "x:y" }) Throws(() => RenameService.ValidateName(invalid)); var plan = RenameService.Preview([a], new(Prefix: "new_")); File.AppendAllText(a, "changed"); Throws(() => RenameService.Execute(plan, Path.Combine(dir, "journal"))); plan = RenameService.Preview([a], new(Prefix: "new_")); Throws(() => RenameService.Execute([plan[0], plan[0]], Path.Combine(dir, "journal"))); var batch = RenameService.Preview([a, b], new(Prefix: "new_")); using (var locked = new FileStream(b, FileMode.Open, FileAccess.Read, FileShare.Read)) Throws(() => RenameService.Execute(batch, Path.Combine(dir, "journal"))); Ensure(File.Exists(a) && File.Exists(b) && batch.All(p => !File.Exists(p.Target)), "Partial failure rollback"); Ensure(Directory.GetFiles(Path.Combine(dir, "journal"), "*.rolledback.json").Length == 1, "Recovery journal"); }); await Test("Clipboard opt-in / limits / exclusions / encrypted persistence", () => { string dir = Path.Combine(root, "clipboard-fixtures"); using var history = new ClipboardHistory(dir); Ensure(!history.Enabled && history.Entries.Count == 0, "Must be opt-in; no initial clipboard read"); Ensure(ClipboardHistory.IsExcluded("KeePassXC", history.ExcludedProcesses), "Default exclusions"); Ensure(ClipboardHistory.IsExcluded("TEST", "test.exe, example.exe"), "Case-insensitive process exclusions"); history.Add("PRIVATE_FIXTURE_ONLY", "fixture", true); history.Add("session-only", "fixture"); history.Add("session-only", "fixture"); Equal(2, history.Entries.Count); history.Add(new string('x', 65537), "fixture"); Equal(2, history.Entries.Count); for (int i = 0; i < 120; i++) history.Add("fixture-" + i, "fixture"); Equal(100, history.Entries.Count); Ensure(history.Entries.Any(e => e.Pinned), "Pinned preservation"); Ensure(!Encoding.UTF8.GetString(File.ReadAllBytes(Path.Combine(dir, "pinned-clips.bin"))).Contains("PRIVATE_FIXTURE_ONLY"), "Pins must be encrypted"); using var reloaded = new ClipboardHistory(dir); Equal(1, reloaded.Entries.Count); Equal("PRIVATE_FIXTURE_ONLY", reloaded.Entries[0].Text); Ensure(!reloaded.Enabled, "Opt-in resets across launches"); history.ClearHistory(); Equal(1, history.Entries.Count); history.TogglePin(history.Entries[0]); using var unpinned = new ClipboardHistory(dir); Equal(0, unpinned.Entries.Count); string blocked = Path.Combine(root, "blocked-pin-storage"); File.WriteAllText(blocked, "not a directory"); using var inaccessible = new ClipboardHistory(blocked); Throws(() => inaccessible.Add("should not be falsely pinned", "fixture", true)); Equal(0, inaccessible.Entries.Count); }); await Test("QR UTF8 / rotation / PNG roundtrip / no overwrite", () => { const string text = "https://example.invalid/?text=中文😀&n=1"; var bitmap = QrService.Encode(text); Equal(text, QrService.Decode(bitmap)); Ensure(bitmap.IsFrozen, "Frozen bitmap"); var rotated = new TransformedBitmap(bitmap, new RotateTransform(90)); Equal(text, QrService.Decode(rotated)); string path = Path.Combine(root, "qr-fixture.png"); QrService.Save(bitmap, path); var loaded = QrService.Load(path); Equal(bitmap.PixelWidth, loaded.PixelWidth); Equal(text, QrService.Decode(loaded)); Throws(() => QrService.Save(bitmap, path)); Throws(() => QrService.Encode(new string('x', 2001))); var blank = DrawFixture("", 120, 100); Throws(() => QrService.Decode(blank)); }); await Test("Screen pixels / crop / color / DPI mapping", () => { var image = BitmapSource.Create(200, 100, 96, 96, PixelFormats.Bgra32, null, Enumerable.Repeat(new byte[] { 0x33, 0x22, 0x11, 0xFF }, 20000).SelectMany(x => x).ToArray(), 800); image.Freeze(); Equal(new Int32Rect(20, 10, 80, 40), ScreenTools.PixelBounds(new Rect(10, 5, 40, 20), new Size(100, 50), image)); Equal(new Int32Rect(0, 0, 200, 100), ScreenTools.PixelBounds(new Rect(-20, -20, 200, 120), new Size(100, 50), image)); Equal("#112233 · RGB(17, 34, 51)", ScreenTools.ColorAt(image, 10, 10)); var crop = ScreenTools.Crop(image, new(20, 10, 80, 40)); Equal(80, crop.PixelWidth); Ensure(crop.IsFrozen, "Frozen crop"); }); await Test("Actual Windows OCR on synthetic text", async () => { string[] languages = ScreenTools.OcrLanguages(); Console.WriteLine("OCR languages: " + string.Join(", ", languages)); Ensure(languages.Length > 0, "No installed OCR language; recognition remains unverified"); var image = DrawFixture("HELLO 12345", 700, 180); QrService.Save(image, Path.Combine(root, "ocr-fixture.png")); string text = await ScreenTools.Recognize(image); Ensure(text.Contains("HELLO", StringComparison.OrdinalIgnoreCase) && text.Contains("12345"), "OCR result: " + text); }); await Test("Actual TCP/UDP IPv4+IPv6 ownership", async () => { foreach (var address in new[] { IPAddress.Loopback, IPAddress.IPv6Loopback }) { using var tcp = new TcpListener(address, 0); tcp.Start(); using var udp = new UdpClient(new IPEndPoint(address, 0)); int tcpPort = ((IPEndPoint)tcp.LocalEndpoint).Port, udpPort = ((IPEndPoint)udp.Client.LocalEndPoint!).Port; var rows = await Task.Run(() => PortInspector.Query()); string suffix = address.AddressFamily == AddressFamily.InterNetwork ? "4" : "6"; var found = rows.Single(r => r.Port == tcpPort && r.Protocol == "TCP" + suffix && r.Process.Pid == Environment.ProcessId); Ensure(found.State == "监听" && File.Exists(found.Process.Path), "TCP details / path"); Ensure(rows.Any(r => r.Port == udpPort && r.Protocol == "UDP" + suffix && r.Process.Pid == Environment.ProcessId), "UDP owner"); Ensure(PortInspector.Query(tcpPort).All(r => r.Port == tcpPort), "Port filter"); } Throws(() => PortInspector.Query(65536)); Throws(() => PortInspector.Terminate(PortInspector.ReadProcess(Environment.ProcessId))); }); await Test("Terminate owned fixture only / PID and path identity protection", async () => { var start = new ProcessStartInfo(Environment.ProcessPath!) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true }; start.ArgumentList.Add("--port-child"); using var child = Process.Start(start)!; try { string line = await child.StandardOutput.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(15)) ?? ""; int port = int.Parse(line); var owner = PortInspector.Query(port).Single(r => r.Process.Pid == child.Id).Process; Throws(() => PortInspector.Terminate(owner with { StartedUtcTicks = owner.StartedUtcTicks + 1 })); Throws(() => PortInspector.Terminate(owner with { Path = "not-the-process.exe" })); Ensure(!child.HasExited, "Rejected identity must not kill"); PortInspector.Terminate(owner); await child.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(10)); var release = Stopwatch.StartNew(); while (PortInspector.Query(port).Any(r => r.Process.Pid == child.Id)) { Ensure(release.Elapsed < TimeSpan.FromSeconds(10), "Owned port did not release within 10 seconds"); await Task.Delay(100); } Console.WriteLine($"Owned child exited; endpoint table removed in {release.ElapsedMilliseconds} ms"); using var rebind = new TcpListener(IPAddress.Loopback, port); rebind.Start(); } finally { if (!child.HasExited) { child.Kill(); await child.WaitForExitAsync(); } } }); await Test("Quick commands / preserve text / invalid inputs", () => { Equal("42", QuickQuery.Execute("=6*7").Single().CopyText); Equal("1024 MiB", QuickQuery.Execute("unit 1 GiB to MiB").Single().CopyText); const string original = " spaced text\n"; Equal(Convert.ToBase64String(Encoding.UTF8.GetBytes(original)), QuickQuery.Execute("base64 " + original).Single().CopyText); Equal(QuickToolKind.Qr, QuickQuery.Execute("qr fixture").Single().Tool!.Value); Ensure(QuickQuery.Execute("port -1").Single().CopyText is null, "Bad port not executable"); Ensure(QuickQuery.IsQuery("json {\"private\":true}") && !QuickQuery.IsQuery("my file.txt"), "Query classification"); }); await Test("System read-only APIs and test-owned window topmost", async () => { var devices = SystemActions.OutputDevices(); Ensure(devices.All(d => d.Id.Length > 0 && d.Name.Length > 0), "Audio endpoint metadata"); Console.WriteLine($"Audio: {devices.Length} active playback endpoints (no defaults changed)"); _ = SystemActions.LocalAddresses(); using var lease = new AwakeLease(); Throws(() => lease.Start(0)); var window = FixtureWindow(new TextBlock { Text = "Topmost test" }); try { window.Show(); await Pump(window); nint hwnd = new WindowInteropHelper(window).Handle; SystemActions.SetTopmost(hwnd, true); Ensure(SystemActions.IsTopmost(hwnd), "Topmost on"); SystemActions.SetTopmost(hwnd, false); Ensure(!SystemActions.IsTopmost(hwnd), "Topmost off"); } finally { window.Close(); } Throws(() => SystemActions.SetTopmost(0, true)); Throws(() => SystemActions.PasteTo(0)); }); } private static async Task ValidatePages() { foreach (var kind in Enum.GetValues()) { await Test("WPF page layout / themed controls / " + kind, async () => { var page = new QuickToolPage(kind, new(kind == QuickToolKind.Qr ? "UI fixture 中文" : kind == QuickToolKind.Text ? "{\"n\":42}" : null)); var window = FixtureWindow(page); try { window.Show(); await Pump(window); Ensure(page.ActualWidth > 0 && page.ActualHeight > 0, "Page layout"); foreach (var button in Descendants(page).OfType