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

XFEWarframe

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

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media.Imaging;
using XFEWarframe.Client;

namespace XFEWarframe.Desktop.Editing;

internal static class GameAssetImageVerification
{
    internal static async Task VerifyAsync(Panel host)
    {
        var resource = "/Lotus/Interface/XFEVerification/" + Guid.NewGuid().ToString("N") + ".png";
        var cacheKey = VisualAssetCache.Key("icon", resource);
        var missingKey = VisualAssetCache.Key("verification-missing", Guid.NewGuid().ToString("N"));
        string? fixture = null;
        var wrongThread = 0;
        // Catch swallowed first-chance failures too: missing images must not make
        // a wrong-thread dependency-property read look like a successful fallback.
        EventHandler<FirstChanceExceptionEventArgs> capture = (_, args) =>
        {
            if (args.Exception is COMException { HResult: unchecked((int)0x8001010E) }) Interlocked.Increment(ref wrongThread);
        };
        AppDomain.CurrentDomain.FirstChanceException += capture;
        var control = new GameAssetImage { Width = 1, Height = 1 };
        try
        {
            host.Children.Add(control);
            host.UpdateLayout();
            async Task ResolveAsync(Action request)
            {
                var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
                var onUiThread = false;
                EventHandler completed = (_, _) => { onUiThread = control.DispatcherQueue.HasThreadAccess; completion.TrySetResult(); };
                control.ImageResolved += completed;
                try
                {
                    request();
                    try { await completion.Task.WaitAsync(TimeSpan.FromSeconds(5)); }
                    catch (TimeoutException ex)
                    {
                        throw new InvalidOperationException($"Image loading stalled: controlLoaded={control.IsLoaded}, hostLoaded={host.IsLoaded}, source={control.Source?.GetType().Name ?? "none"}, cached={control.IsCached}, wrongThread={Volatile.Read(ref wrongThread)}.", ex);
                    }
                    if (!onUiThread) throw new InvalidOperationException("Image completion was raised away from the WinUI dispatcher.");
                    if (Volatile.Read(ref wrongThread) != 0) throw new InvalidOperationException("Image loading accessed a WinUI object from a worker thread (0x8001010E).");
                }
                finally { control.ImageResolved -= completed; }
            }

            await ResolveAsync(() => control.CacheKey = missingKey);
            if (control.IsCached || control.Source is not null) throw new InvalidOperationException("A missing image did not retain its placeholder.");
            fixture = await Task.Run(() => VisualAssetCache.StoreAsync(cacheKey, PngImages.CropRgba([30, 90, 160, 255], 1, 1, 0, 0, 1, 1)));
            await ResolveAsync(() => control.CacheKey = cacheKey);
            if (!control.IsCached || control.Source is not WriteableBitmap || control.PixelWidth != 1 || control.PixelHeight != 1)
                throw new InvalidOperationException("The cached PNG was not decoded by the actual WinUI image control.");

            await ResolveAsync(() => { control.Resource = resource; control.CacheKey = ""; });
            if (!control.IsCached || control.Source is not WriteableBitmap || control.PixelWidth != 1 || control.PixelHeight != 1)
                throw new InvalidOperationException("The cached resource icon did not load through WinUI.");

            await ResolveAsync(() => { control.CacheKey = cacheKey; control.CacheKey = missingKey; });
            if (control.IsCached || control.Source is not null) throw new InvalidOperationException("An obsolete image request replaced the current placeholder.");

            var manifestArgument = Environment.GetCommandLineArgs().SingleOrDefault(x => x.StartsWith("--verify-native-card-manifest=", StringComparison.Ordinal));
            if (manifestArgument is not null)
            {
                var manifest = manifestArgument["--verify-native-card-manifest=".Length..];
                var nativeCards = await Task.Run(() =>
                {
                    using var document = System.Text.Json.JsonDocument.Parse(File.ReadAllText(manifest));
                    return document.RootElement.EnumerateArray().Select(x => (Key: x.GetProperty("Key").GetString()!, Type: x.GetProperty("Type").GetString()!)).ToArray();
                });
                var results = new List<object>();
                foreach (var family in new[] { "/Pistol/WeaponDamageAmountMod", "/Sets/Umbra/", "/Expert/PrimedWeaponCritDamageMod", "Randomized", "InfestationKing", "CosmeticEnhancers" })
                {
                    var card = nativeCards.FirstOrDefault(x => x.Type.Contains(family, StringComparison.Ordinal));
                    if (card.Key is null) throw new InvalidDataException("Native offline sample is missing: " + family);
                    var size = await Task.Run(async () =>
                    {
                        var path = VisualAssetCache.Find(card.Key) ?? throw new InvalidDataException("Native card was not cached: " + card.Type);
                        var png = await File.ReadAllBytesAsync(path); PngImages.Validate(png);
                        return (Width: System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(16, 4)), Height: System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(20, 4)));
                    });
                    await ResolveAsync(() => control.CacheKey = card.Key);
                    if (!control.IsCached || control.Source is not WriteableBitmap || control.PixelWidth != size.Width || control.PixelHeight != size.Height || size.Width < 100 || size.Height < 60)
                        throw new InvalidOperationException("A real native card did not load offline through WinUI: " + card.Type);
                    results.Add(new { card.Key, card.Type, width = control.PixelWidth, height = control.PixelHeight, cached = control.IsCached });
                }
                var report = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(manifest))!, "winui-native-cache-" + System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".json");
                await File.WriteAllTextAsync(report, System.Text.Json.JsonSerializer.Serialize(new { passed = true, mode = "offline-cached-originals-through-WinUI", samples = results }, new System.Text.Json.JsonSerializerOptions { WriteIndented = true }));
            }
        }
        finally
        {
            AppDomain.CurrentDomain.FirstChanceException -= capture;
            host.Children.Remove(control);
            if (fixture is not null) File.Delete(fixture); // Only the uniquely named fixture created above.
        }
    }
}