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

XFEWarframe

【WinUI】基于Warframe游戏本体的公开服务器以及安装器

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Text.Json;
using CommunityToolkit.WinUI.Controls;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Automation;
using Microsoft.UI.Xaml.Controls;
using Newtonsoft.Json.Linq;
using Windows.Foundation;

namespace XFEWarframe.Desktop.Editing;

/// <summary>Hidden, in-process regression checks; no desktop input, game or server is accessed.</summary>
internal static class AbilityEditorVerification
{
    internal static async Task RunAsync(Window window, string reportPath)
    {
        if (!Environment.GetCommandLineArgs().Any(x => x.StartsWith("--profile-root=", StringComparison.Ordinal)))
            throw new InvalidOperationException("Ability UI verification requires an isolated --profile-root.");
        var checks = new List<string>();
        var nativeErrors = new List<string>();
        string? error = null;
        void Unhandled(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs args)
        {
            nativeErrors.Add(args.Message + "\n" + args.Exception);
            args.Handled = true; // Capture deferred template failures only in this isolated test.
        }
        Application.Current.UnhandledException += Unhandled;
        var view = new EquipmentEditorView();
        var originalContent = window.Content;
        var data = new JObject
        {
            ["version"] = "fixture-v1", ["selectedKey"] = "fixture-suit", ["selectedName"] = "Ability fixture",
            ["actions"] = new JArray(Enumerable.Range(0, 6).Select(config => new JObject
            {
                ["key"] = "ability.multiple." + config, ["label"] = "Config " + (char)('A' + config),
                ["fields"] = new JArray(Enumerable.Range(1, 4).SelectMany(slot => Enumerable.Range(1, 3).Select(bank => Field(
                    "ability" + slot + (bank == 1 ? "" : "_" + bank)))))
            }))
        };
        var model = new EquipmentEditorModel(_ => Task.FromResult((JObject)data.DeepClone()), (_, body) =>
        {
            var action = data["actions"]!.Single(x => x.Value<string>("key") == body.Value<string>("action"));
            foreach (var field in action["fields"]!) field["value"] = body["values"]![field.Value<string>("key")!]!.DeepClone();
            return Task.FromResult(new JObject());
        }, _ => Task.FromResult(new EquipmentRevision("fixture-v1", "p1", true)), (_, _) => Task.FromResult(true), _ => { });
        try
        {
            window.Content = view;
            view.Model = model;
            await model.LoadAsync(new("fixture", "Fixture", "Suits", "fixture-suit", "experimental-abilities"));
            foreach (var width in new[] { 1400d, 1024d, 800d })
            {
                Layout(width);
                await Task.Delay(30);
                var configs = DialogVerification.Children<SelectorBar>(view)
                    .Single(x => AutomationProperties.GetAutomationId(x) == "equipment-ability-configs");
                foreach (var config in configs.Items)
                {
                    configs.SelectedItem = config;
                    Layout(width);
                    await Task.Delay(20);
                    var sections = DialogVerification.Children<SettingsExpander>(view).ToArray();
                    foreach (var section in sections) section.IsExpanded = true;
                    Layout(width);
                    await Task.Delay(20);
                    FailOnNativeError();
                    var inputs = DialogVerification.Children<AutoSuggestBox>(view).ToArray();
                    if (sections.Length != 4 || inputs.Length != 12)
                        throw new InvalidOperationException($"Expected four slots and twelve choices, got {sections.Length}/{inputs.Length}.");
                    foreach (var input in inputs)
                    {
                        if (input.ItemTemplate is null || input.DisplayMemberPath.Length > 0 || input.TextMemberPath != nameof(EditorOption.Label))
                            throw new InvalidOperationException("Icon suggestions must use a custom item template and a separate text member path.");
                        var options = Suggestions.GetCandidates(input)!.Cast<EditorOption>().ToArray();
                        input.ItemsSource = options;
                        input.ApplyTemplate();
                        input.IsSuggestionListOpen = true;
                        Layout(width);
                        await Task.Delay(15);
                        FailOnNativeError();
                        var field = model.Actions.Single(x => x.Key == ((EquipmentAction)config.Tag).Key).Fields
                            .Single(x => x.Key == AutomationProperties.GetAutomationId(input));
                        Suggestions.SetSelectedItem(input, options[2]);
                        if (input.Text != options[2].Label || !JToken.DeepEquals(field.Serialize(), options[2].Value))
                            throw new InvalidOperationException("Icon choice lost its display label or stored ability path.");
                        input.IsSuggestionListOpen = false;
                    }
                }
                checks.Add($"{width}px: six configurations, four expanded slots, twelve native icon choices each, selection and serialization");
            }
            var actionToSave = model.Actions.First();
            await model.SaveCommand.ExecuteAsync(actionToSave);
            if (model.HasMessage || model.Actions.First().Fields.Any(x => x.Value.ToString() != "/Fixture/Other"))
                throw new InvalidOperationException("Ability selections did not survive save and rebuilding the view.");
            Layout(1024); await Task.Delay(30); FailOnNativeError();
            checks.Add("Save and rebuild preserve selected ability paths");
            var plainSchema = Field("setting");
            foreach (var option in plainSchema["options"]!) option["icon"] = "";
            var plainField = new EditorField(plainSchema);
            var plainCard = EditorForm.CreateCards([plainField]).Single();
            window.Content = plainCard;
            plainCard.Measure(new Size(800, 200)); plainCard.Arrange(new Rect(0, 0, 800, 200)); plainCard.UpdateLayout();
            var plain = (AutoSuggestBox)plainCard.Content;
            plain.ItemsSource = plainField.Options; plain.IsSuggestionListOpen = true;
            await Task.Delay(30); FailOnNativeError();
            Suggestions.SetSelectedItem(plain, plainField.Options.Last());
            if (plain.ItemTemplate is not null || plain.DisplayMemberPath != nameof(EditorOption.Label) ||
                plain.Text != plainField.Options.Last().Label || plainField.Serialize().ToString() != "/Fixture/Other")
                throw new InvalidOperationException("Text-only settings suggestions regressed.");
            plain.IsSuggestionListOpen = false;
            checks.Add("Text-only setting choices retain labels, selection and native suggestions");
        }
        catch (Exception exception) { error = exception.ToString(); }
        finally
        {
            view.Model = null;
            window.Content = originalContent;
            model.Detach();
            Application.Current.UnhandledException -= Unhandled;
        }
        Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(reportPath))!);
        await File.WriteAllTextAsync(reportPath, JsonSerializer.Serialize(new
        {
            passed = error is null && nativeErrors.Count == 0, checks, error, nativeErrors,
            scope = "Hidden native WinUI controls and fixture model; no desktop input, production API or game interaction."
        }, new JsonSerializerOptions { WriteIndented = true }));
        void FailOnNativeError()
        {
            if (nativeErrors.Count > 0) throw new InvalidOperationException(string.Join("\n", nativeErrors));
        }
        void Layout(double width)
        {
            view.Measure(new Size(width, 900)); view.Arrange(new Rect(0, 0, width, 900)); view.UpdateLayout();
        }
    }

    private static JObject Field(string key) => new()
    {
        ["key"] = key, ["label"] = key, ["type"] = "choice", ["value"] = "/Fixture/Ability",
        ["options"] = new JArray(new JObject { ["value"] = "", ["label"] = "Original" },
            new JObject { ["value"] = "/Fixture/Ability", ["label"] = "Fixture ability", ["icon"] = "/Fixture/Ability.png" },
            new JObject { ["value"] = "/Fixture/Other", ["label"] = "Other ability", ["icon"] = "/Fixture/Other.png" })
    };
}