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

XFEWarframe

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

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

namespace XFEWarframe.Desktop.Editing;

/// <summary>Opt-in native input verification, using an isolated server and disposable local field models.</summary>
internal static class SuggestionVerification
{
    internal static async Task VerifyAsync(FrameworkElement root, SuggestionProvider catalog)
    {
        var field = new EditorField(new JObject { ["key"] = "choice", ["label"] = "Choice verification", ["type"] = "choice", ["value"] = null,
            ["options"] = new JArray(new JObject { ["value"] = null, ["label"] = "Automatic" },
                new JObject { ["value"] = "/A", ["label"] = "Same name" }, new JObject { ["value"] = "/B", ["label"] = "Same name" }) });
        var card = EditorForm.CreateCards([field]).Single();
        var choice = (AutoSuggestBox)card.Content;
        var remote = new AutoSuggestBox { DisplayMemberPath = "Label" };
        var catalogInput = new AutoSuggestBox { DisplayMemberPath = "Label" };
        Suggestions.SetProvider(catalogInput, catalog);
        var stack = new StackPanel { Spacing = 12, MinWidth = 420 };
        stack.Children.Add(card); stack.Children.Add(remote); stack.Children.Add(catalogInput);
        var dialog = new ContentDialog { XamlRoot = root.XamlRoot, Title = "AutoSuggest verification", Content = stack, CloseButtonText = "Close" };
        var showing = dialog.ShowAsync().AsTask();
        try
        {
            await UntilAsync(() => dialog.IsLoaded && choice.IsLoaded && catalogInput.IsLoaded, "Native suggestion inputs did not load.");
            dialog.UpdateLayout(); choice.Focus(FocusState.Programmatic);
            await TypeAsync(choice, "no-match");
            if (!field.Changed || !field.HasUnresolvedChoice || Suggestions.GetSelectedItem(choice) is not null) throw new InvalidOperationException("Unmatched text retained a valid selection.");
            try { field.Serialize(); throw new InvalidOperationException("Invalid text was serialized as the nullable automatic choice."); }
            catch (InvalidOperationException ex) when (ex.Message.Contains("请选择列表中的选项", StringComparison.Ordinal)) { }
            await TypeAsync(choice, "Same name");
            if (!choice.IsSuggestionListOpen) throw new InvalidOperationException("Matching suggestions were not shown in the native popup.");
            await SubmitAsync(choice);
            if (Suggestions.GetSelectedItem(choice) is not null) throw new InvalidOperationException("An ambiguous label selected the wrong item.");
            await TypeAsync(choice, "/B"); await SubmitAsync(choice);
            if (field.Serialize().ToString() != "/B" || choice.Text != "Same name") throw new InvalidOperationException("Exact path selection did not preserve its identity.");
            await TypeAsync(choice, "Automatic"); await SubmitAsync(choice);
            if (field.Serialize().Type != JTokenType.Null || field.HasUnresolvedChoice) throw new InvalidOperationException("The valid nullable choice could not be restored.");

            var oldResult = new TaskCompletionSource<IReadOnlyList<object>>(TaskCreationOptions.RunContinuationsAsynchronously);
            var oldStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
            Suggestions.SetProvider(remote, new(async query =>
            {
                if (query == "old") { oldStarted.TrySetResult(); return await oldResult.Task; }
                return [new SearchSuggestion(query)];
            }));
            remote.Focus(FocusState.Programmatic);
            await TypeAsync(remote, "old", waitResults: false); await oldStarted.Task.WaitAsync(TimeSpan.FromSeconds(5));
            await TypeAsync(remote, "new");
            oldResult.SetResult([new SearchSuggestion("old")]); await Task.Delay(30);
            if (Results(remote).Cast<SearchSuggestion>().Single().Label != "new") throw new InvalidOperationException("A stale response replaced current suggestions.");
            Suggestions.SetContext(remote, "another-account");
            if (Results(remote).Any()) throw new InvalidOperationException("Account/category changes retained old candidates.");
            Suggestions.SetProvider(remote, new(_ => Task.FromException<IReadOnlyList<object>>(new InvalidOperationException("Isolated lookup failure"))));
            await TypeAsync(remote, "failure");
            if (Results(remote).Any() || Suggestions.GetSearchError(remote).Length == 0) throw new InvalidOperationException("Failed lookups retained stale options or hid the failure.");

            catalogInput.Focus(FocusState.Programmatic);
            const string type = "/Lotus/Powersuits/Excalibur/Excalibur";
            await TypeAsync(catalogInput, type);
            if (!Results(catalogInput).Cast<SearchSuggestion>().Any(x => x.Key == type)) throw new InvalidOperationException("Native catalog suggestions did not query the real API.");
            await SubmitAsync(catalogInput);
            if (Suggestions.GetSelectedItem(catalogInput) is not SearchSuggestion selected || selected.Key != type) throw new InvalidOperationException("Catalog suggestion submission lost the item path.");
        }
        finally { dialog.Hide(); await showing; }
    }
    private static IEnumerable<object> Results(AutoSuggestBox input) => (input.ItemsSource as IEnumerable)?.Cast<object>() ?? [];
    internal static async Task SubmitAsync(AutoSuggestBox input)
    {
        input.UpdateLayout();
        var button = DialogVerification.Children<Button>(input).Single(x => x.Name == "QueryButton");
        var submitted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
        void Submitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args) => submitted.TrySetResult();
        input.QuerySubmitted += Submitted;
        try { ((IInvokeProvider)new ButtonAutomationPeer(button).GetPattern(PatternInterface.Invoke)).Invoke(); await submitted.Task.WaitAsync(TimeSpan.FromSeconds(5)); }
        finally { input.QuerySubmitted -= Submitted; }
    }
    internal static async Task TypeAsync(AutoSuggestBox input, string text, bool waitResults = true)
    {
        // Native focus/popup transitions can still be queued after Focus returns. Let them
        // complete before writing the template part, while keeping stale-provider tests concurrent.
        await Task.Delay(150);
        input.UpdateLayout();
        var textBox = DialogVerification.Children<TextBox>(input).Single(x => x.Name == "TextBox");
        var change = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
        var events = new List<string>();
        void Changed(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
        {
            events.Add($"{args.Reason}:{sender.Text}");
            if (sender.Text == text && args.Reason != AutoSuggestionBoxTextChangeReason.SuggestionChosen) change.TrySetResult();
        }
        input.TextChanged += Changed;
        try
        {
            textBox.Text = text;
            await change.Task.WaitAsync(TimeSpan.FromSeconds(5));
        }
        catch (TimeoutException ex)
        {
            throw new InvalidOperationException($"Native suggestion text event timed out: input={input.Text}, textBox={textBox.Text}, loaded={input.IsLoaded}/{textBox.IsLoaded}, visible={input.XamlRoot?.IsHostVisible}, enabled={input.IsEnabled}/{textBox.IsEnabled}, currentPart={DialogVerification.Children<TextBox>(input).Contains(textBox)}, events={string.Join(";", events)}", ex);
        }
        finally { input.TextChanged -= Changed; }
        if (waitResults) await UntilAsync(() => !Suggestions.GetIsSearching(input), "The candidate lookup did not complete.");
    }
    private static async Task UntilAsync(Func<bool> ready, string error)
    {
        for (var i = 0; i < 500 && !ready(); i++) await Task.Delay(10);
        if (!ready()) throw new InvalidOperationException(error);
    }
}