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

XFEWarframe

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

公开
关注 0 Fork 0 Star 0
UTF-8
using Windows.ApplicationModel.DataTransfer;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Automation;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Imaging;
using Newtonsoft.Json.Linq;
using XFEWarframe.Client;
using XFEWarframe.Loadouts;
using XFEWarframe.Client.Runtime;

namespace XFEWarframe.Desktop.Editing;

/// <summary>A reusable native card collection and slot board for every equipment type and desktop role.</summary>
public sealed class ModLoadoutView : Grid
{
    private const string DragFormat = "XFEWarframe.OwnedMod.v1";
    private readonly string instance = Guid.NewGuid().ToString("N");
    private readonly EquipmentEditorModel owner;
    private readonly ModLoadout layout;
    private readonly EquipmentTab tab;
    private readonly Grid board = new() { ColumnSpacing = 20 };
    private int boardMode = -1;
    private bool layoutQueued;
    private int cacheGeneration;
    private int collectionGeneration;
    private bool detached;
    private bool countedCache;
    private readonly Task<ModSearchIndex> searchIndex;
    private CancellationTokenSource? searchLifetime;
    private readonly ProgressRing searchProgress = new() { Width = 32, Height = 32, Visibility = Visibility.Collapsed };
    private readonly InfoBar notice = new() { IsClosable = true };
    private readonly GridView collection = new() { SelectionMode = ListViewSelectionMode.Single, IsItemClickEnabled = true,
        HorizontalAlignment = HorizontalAlignment.Stretch, CanDragItems = false, Padding = new Thickness(0, 0, 4, 0) };
    private readonly AutoSuggestBox search = new() { PlaceholderText = UiText.Translate("搜索名称、效果或元素(多个关键词以空格分隔)"), MinWidth = 160, QueryIcon = new SymbolIcon(Symbol.Find) };
    private readonly SelectorBar filters = new();
    private readonly Dictionary<int, Button> slotButtons = [];
    private EquipmentAction? active;
    private string filter = "all";
    private int? selectedSlot;
    private int page;
    private readonly TextBlock count = new() { VerticalAlignment = VerticalAlignment.Center, Opacity = .7 };
    private readonly Button previous = new() { Content = UiText.Translate("上一页") }, next = new() { Content = UiText.Translate("下一页") };
    private readonly Button cache = new() { Content = UiText.Translate("缓存原版卡面…") };
    private readonly TextBlock cached = new() { Opacity = .7, VerticalAlignment = VerticalAlignment.Center };
    private readonly List<Control> inputs = [];
    private CancellationTokenSource? cacheLifetime;
    public SelectorBar Configurations { get; } = new();
    public EquipmentAction? ActiveAction => active;
    public Task SearchCompletion { get; private set; } = Task.CompletedTask;
    public IReadOnlyDictionary<int, string> Selection => layout.Slots.ToDictionary(x => x.Index, x => active?.Fields.FirstOrDefault(f => f.Key == "mod" + x.Index)?.Value.ToString() ?? "");

    public ModLoadoutView(EquipmentEditorModel owner, EquipmentTab tab, string? configuration = null)
    {
        this.owner = owner; this.tab = tab; layout = owner.Modding ?? throw new ArgumentException("Equipment has no modding data.");
        searchIndex = Task.Run(() => new ModSearchIndex(layout.Cards));
        RowSpacing = 16;
        RowDefinitions.Add(new() { Height = GridLength.Auto }); RowDefinitions.Add(new() { Height = GridLength.Auto });
        RowDefinitions.Add(new() { Height = GridLength.Auto }); RowDefinitions.Add(new() { Height = new GridLength(1, GridUnitType.Star) });
        RowDefinitions.Add(new() { Height = GridLength.Auto }); RowDefinitions.Add(new() { Height = GridLength.Auto });
        var toolbar = new Grid { ColumnSpacing = 12 }; toolbar.ColumnDefinitions.Add(new() { Width = new GridLength(1, GridUnitType.Star) }); toolbar.ColumnDefinitions.Add(new() { Width = GridLength.Auto });
        AutomationProperties.SetAutomationId(Configurations, "equipment-mod-configs");
        var configurationScroll = new ScrollViewer { Content = Configurations, HorizontalScrollMode = ScrollMode.Enabled, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
            VerticalScrollMode = ScrollMode.Disabled, VerticalScrollBarVisibility = ScrollBarVisibility.Disabled };
        toolbar.Children.Add(configurationScroll);
        toolbar.RowDefinitions.Add(new() { Height = GridLength.Auto }); toolbar.RowDefinitions.Add(new() { Height = GridLength.Auto }); toolbar.RowSpacing = 8;
        var commands = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 };
        var rename = new Button { Content = UiText.Translate("配装名称…") }; rename.Click += async (_, _) => await RenameAsync();
        var reset = new Button { Content = UiText.Translate("重置输入") }; reset.Click += (_, _) => { if (active is not null) { foreach (var f in active.Fields) f.Reset(); RenderBoard(); RefreshCollection(); } };
        var save = new Button { Content = UiText.Translate("保存配装"), Style = (Style)Application.Current.Resources["OrbitAccentButtonStyle"] };
        inputs.AddRange([Configurations, rename, reset, search, filters, collection]);
        commands.Children.Add(rename); commands.Children.Add(reset); commands.Children.Add(save); Grid.SetColumn(commands, 1); toolbar.Children.Add(commands); Children.Add(toolbar);
        var boardScroll = new ScrollViewer { Content = board, MaxHeight = 400, HorizontalScrollMode = ScrollMode.Disabled,
            HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled, VerticalScrollBarVisibility = ScrollBarVisibility.Auto };
        Grid.SetRow(boardScroll, 1); Children.Add(boardScroll);
        board.SizeChanged += (_, e) =>
        {
            var mode = e.NewSize.Width >= 1100 ? 2 : e.NewSize.Width >= 820 ? 1 : 0;
            if (mode == boardMode) return; boardMode = mode;
            if (layoutQueued) return; layoutQueued = true;
            DispatcherQueue.TryEnqueue(() => { layoutQueued = false; RenderBoard(); });
        };
        var collectionToolbar = new Grid { ColumnSpacing = 16 }; collectionToolbar.ColumnDefinitions.Add(new() { Width = new GridLength(1, GridUnitType.Star) }); collectionToolbar.ColumnDefinitions.Add(new() { Width = GridLength.Auto });
        collectionToolbar.RowDefinitions.Add(new() { Height = GridLength.Auto }); collectionToolbar.RowDefinitions.Add(new() { Height = GridLength.Auto }); collectionToolbar.RowSpacing = 4;
        AutomationProperties.SetAutomationId(search, "mod-collection-search");
        search.DisplayMemberPath = nameof(EditorOption.Label);
        Suggestions.SetProvider(search, new SuggestionProvider(async (query, cancellation) =>
        {
            var selectedFilter = filter;
            var index = await searchIndex.WaitAsync(cancellation);
            return await Task.Run<IReadOnlyList<object>>(() => index.Search(query, cancellation).Where(x => MatchesFilter(x, selectedFilter))
                .Take(25).Select(x => (object)new EditorOption(new JValue(x.Key), x.Name)).ToArray(), cancellation);
        }));
        ToolTipService.SetToolTip(search, UiText.Translate("搜索病毒会包含病毒、冰和毒;其他复合元素也包含其组成元素。多个关键词须同时匹配。"));
        search.TextChanged += (_, args) => { if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput) { page = 0; RefreshCollection(); } };
        search.SuggestionChosen += (_, args) => { if (args.SelectedItem is EditorOption option) { search.Text = option.Label; page = 0; RefreshCollection(); } };
        search.QuerySubmitted += (_, _) => { page = 0; RefreshCollection(); };
        collectionToolbar.Children.Add(search);
        foreach (var (key, title) in new[] { ("all", "全部"), ("normal", "MOD"), ("special", "光环与姿态"), ("exilus", "特殊功能"), ("arcane", "赋能") }) filters.Items.Add(new SelectorBarItem { Text = UiText.Translate(title), Tag = key });
        filters.SelectionChanged += (_, _) => { filter = filters.SelectedItem?.Tag as string ?? "all"; page = 0; RefreshCollection(); };
        filters.SelectedItem = filters.Items[0]; Grid.SetColumn(filters, 1); collectionToolbar.Children.Add(filters); Grid.SetRow(collectionToolbar, 2); Children.Add(collectionToolbar);
        collection.ItemsPanel = (ItemsPanelTemplate)Microsoft.UI.Xaml.Markup.XamlReader.Load("<ItemsPanelTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><ItemsWrapGrid Orientation=\"Horizontal\" ItemWidth=\"210\" ItemHeight=\"116\"/></ItemsPanelTemplate>");
        AutomationProperties.SetAutomationId(collection, "mod-collection"); collection.AllowDrop = true;
        collection.DragOver += (_, e) => { if (e.DataView.Contains(DragFormat)) { e.AcceptedOperation = DataPackageOperation.Move; e.DragUIOverride.Caption = UiText.Translate("卸下 MOD"); } };
        collection.Drop += async (_, e) => await DropAsync(e, null);
        collection.ItemClick += (_, e) => { if (e.ClickedItem is FrameworkElement { Tag: ModCard card } && selectedSlot is { } slot) Install(card.Key, slot); };
        Grid.SetRow(collection, 3); Children.Add(collection);
        Grid.SetRow(searchProgress, 3); Children.Add(searchProgress);
        var footer = new Grid { ColumnSpacing = 12, RowSpacing = 8 }; footer.ColumnDefinitions.Add(new() { Width = new GridLength(1, GridUnitType.Star) }); footer.ColumnDefinitions.Add(new() { Width = GridLength.Auto });
        footer.RowDefinitions.Add(new() { Height = GridLength.Auto }); footer.RowDefinitions.Add(new() { Height = GridLength.Auto });
        var status = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 16 }; status.Children.Add(count); status.Children.Add(cached); footer.Children.Add(status);
        var paging = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 }; paging.Children.Add(cache); paging.Children.Add(previous); paging.Children.Add(next); Grid.SetColumn(paging, 1); footer.Children.Add(paging);
        AutomationProperties.SetAutomationId(cache, "mod-cache-original-cards"); cache.Click += async (_, _) => await CacheAsync();
        Loaded += (_, _) => { detached = false; RefreshCollection(); };
        Unloaded += (_, _) => { detached = true; collectionGeneration++; cacheGeneration++; searchLifetime?.Cancel(); cacheLifetime?.Cancel(); };
        previous.Click += (_, _) => { page--; RefreshCollection(); }; next.Click += (_, _) => { page++; RefreshCollection(); };
        Grid.SetRow(footer, 4); Children.Add(footer); Grid.SetRow(notice, 5); Children.Add(notice);
        bool? narrowLayout = null;
        SizeChanged += (_, e) =>
        {
            var narrow = e.NewSize.Width < 680; if (narrow == narrowLayout) return; narrowLayout = narrow;
            foreach (var (grid, content) in new[] { (toolbar, (FrameworkElement)commands), (collectionToolbar, filters), (footer, paging) })
            {
                Grid.SetRow(content, narrow ? 1 : 0); Grid.SetColumn(content, narrow ? 0 : 1); Grid.SetColumnSpan(content, narrow ? 2 : 1);
                content.HorizontalAlignment = HorizontalAlignment.Right;
                grid.ColumnDefinitions[1].Width = narrow ? new GridLength(0) : GridLength.Auto;
            }
            Grid.SetColumnSpan(configurationScroll, narrow ? 2 : 1);
            Grid.SetColumnSpan(search, narrow ? 2 : 1); Grid.SetColumnSpan(status, narrow ? 2 : 1);
        };
        foreach (var action in tab.Actions) Configurations.Items.Add(new SelectorBarItem { Text = action.Label, Tag = action });
        Configurations.SelectionChanged += (_, _) =>
        {
            active = Configurations.SelectedItem?.Tag as EquipmentAction; selectedSlot = null;
            if (active is null) return;
            AutomationProperties.SetAutomationId(save, "equipment-save-" + active.Key); AutomationProperties.SetAutomationId(reset, "equipment-reset-" + active.Key);
            save.Command = owner.SaveCommand; save.CommandParameter = active; // Native command also governs permission/conflict/busy state.
            RenderBoard(); RefreshCollection();
        };
        Configurations.SelectedItem = Configurations.Items.FirstOrDefault(x => ((EquipmentAction)x.Tag).Key == configuration) ?? Configurations.Items.FirstOrDefault();
        UpdateState();
    }
    private bool CanEdit => !owner.IsBusy && !owner.HasConflict && ReferenceEquals(owner.Modding, layout) && owner.Tabs.Contains(tab) && active is not null && owner.Actions.Contains(active);
    public void UpdateState() { foreach (var control in inputs) control.IsEnabled = CanEdit; foreach (var control in slotButtons.Values) control.IsEnabled = CanEdit; cache.IsEnabled = !owner.IsBusy && cacheLifetime is null; }
    private bool MatchesFilter(ModCard card, string selectedFilter) => selectedFilter switch
    {
        "arcane" => card.Family == "ARCANE", "special" => card.Family is "AURA" or "STANCE",
        "exilus" => card.CompatibleSlots.Any(i => layout.Slots.Any(s => s.Index == i && s.Kind == ModSlotKind.Exilus)),
        "normal" => card.Family is not ("AURA" or "STANCE" or "ARCANE"), _ => true
    };

    private void RenderBoard()
    {
        board.Children.Clear(); board.RowDefinitions.Clear(); board.ColumnDefinitions.Clear(); slotButtons.Clear(); var draft = Selection; var state = ModLoadoutRules.Capacity(layout, draft);
        board.RowSpacing = 12;
        for (var i = 0; i < 3; i++) board.RowDefinitions.Add(new() { Height = GridLength.Auto });
        if (boardMode == 2) board.ColumnDefinitions.Add(new() { Width = new GridLength(170) });
        board.ColumnDefinitions.Add(new() { Width = new GridLength(1, GridUnitType.Star) });
        if (boardMode > 0 && layout.Slots.Any(x => x.Kind == ModSlotKind.Arcane)) board.ColumnDefinitions.Add(new() { Width = new GridLength(150) });
        // Each layout owns its elements. A cleared panel may retain native ownership even
        // when Parent is already null, so rebuilding must not reparent a retained control.
        var capacity = new TextBlock { FontSize = 18, TextWrapping = TextWrapping.Wrap,
            Text = UiText.Translate("容量") + $"  {state.Remaining} / {state.Maximum}" + (state.Known ? "" : "\n" + UiText.Translate("默认极性尚未提取,容量为估算")) };
        var status = new StackPanel { Spacing = 16 }; status.Children.Add(capacity);
        status.Children.Add(new TextBlock { Text = UiText.Translate("拖动卡片安装或交换。拖回下方库存卸下,也可右键卸下。"), TextWrapping = TextWrapping.Wrap, Opacity = .7 });
        var clear = new Button { Content = UiText.Translate("全部卸下"), IsEnabled = CanEdit }; clear.Click += (_, _) => { if (!CanEdit) return; foreach (var slot in layout.Slots) Write(slot.Index, ""); RenderBoard(); RefreshCollection(); }; status.Children.Add(clear);
        if (boardMode != 2) { status.Orientation = Orientation.Horizontal; status.Spacing = 24; ((TextBlock)status.Children[1]).Visibility = Visibility.Collapsed; Grid.SetColumnSpan(status, board.ColumnDefinitions.Count); }
        board.Children.Add(status);
        var center = new StackPanel { Spacing = 12 }; var special = new Grid { ColumnSpacing = 12, MaxWidth = 440, HorizontalAlignment = HorizontalAlignment.Stretch };
        foreach (var slot in layout.Slots.Where(x => x.Kind is ModSlotKind.Aura or ModSlotKind.Stance or ModSlotKind.Exilus))
        { special.ColumnDefinitions.Add(new() { Width = new GridLength(1, GridUnitType.Star) }); var button = Slot(slot, draft); Grid.SetColumn(button, special.Children.Count); special.Children.Add(button); }
        if (special.Children.Count > 0) center.Children.Add(special);
        var normals = new Grid { ColumnSpacing = 12, RowSpacing = 12 };
        var normalColumns = layout.Slots.Count(x => x.Kind == ModSlotKind.Normal) == 10 ? 5 : 4;
        for (var i = 0; i < normalColumns; i++) normals.ColumnDefinitions.Add(new() { Width = new GridLength(1, GridUnitType.Star) });
        normals.RowDefinitions.Add(new() { Height = GridLength.Auto }); normals.RowDefinitions.Add(new() { Height = GridLength.Auto });
        foreach (var slot in layout.Slots.Where(x => x.Kind == ModSlotKind.Normal)) { var button = Slot(slot, draft); Grid.SetColumn(button, slot.Index % normalColumns); Grid.SetRow(button, slot.Index / normalColumns); normals.Children.Add(button); }
        center.Children.Add(normals); Grid.SetColumn(center, boardMode == 2 ? 1 : 0); Grid.SetRow(center, boardMode == 2 ? 0 : 1); board.Children.Add(center);
        var arcanes = new Grid { ColumnSpacing = 12, RowSpacing = 12 };
        foreach (var slot in layout.Slots.Where(x => x.Kind == ModSlotKind.Arcane))
        {
            var button = Slot(slot, draft);
            if (boardMode > 0) { arcanes.RowDefinitions.Add(new() { Height = GridLength.Auto }); Grid.SetRow(button, arcanes.Children.Count); }
            else { arcanes.ColumnDefinitions.Add(new() { Width = new GridLength(1, GridUnitType.Star) }); Grid.SetColumn(button, arcanes.Children.Count); }
            arcanes.Children.Add(button);
        }
        if (arcanes.Children.Count > 0) { Grid.SetColumn(arcanes, boardMode > 0 ? board.ColumnDefinitions.Count - 1 : 0); Grid.SetRow(arcanes, boardMode == 2 ? 0 : boardMode == 1 ? 1 : 2); board.Children.Add(arcanes); }
        UpdateState();
    }
    private Button Slot(ModSlot slot, IReadOnlyDictionary<int, string> draft)
    {
        var key = draft.GetValueOrDefault(slot.Index) ?? ""; var card = layout.Cards.FirstOrDefault(x => x.Key == key);
        var button = new Button { Padding = new Thickness(4), HorizontalAlignment = HorizontalAlignment.Stretch, MinWidth = 0, MinHeight = 90,
            AllowDrop = true, CanDrag = key.Length > 0, Tag = slot.Index };
        AutomationProperties.SetAutomationId(button, "mod-slot-" + slot.Index);
        var title = UiText.Translate(slot.Kind switch { ModSlotKind.Aura => "光环", ModSlotKind.Stance => "姿态", ModSlotKind.Exilus => "特殊功能", ModSlotKind.Arcane => "赋能", _ => "MOD 槽" });
        button.Content = card is not null ? Tile(card, double.NaN, 84, slot.Index) : new TextBlock { Text = key.Length > 0 ? UiText.Translate("存档中的 MOD 尚未识别") : title + (slot.Locked ? " · " + UiText.Translate("未解锁") : ""), TextWrapping = TextWrapping.Wrap, Opacity = .7 };
        ToolTipService.SetToolTip(button, title + " · " + slot.Polarity + (card is not null ? " · " + ModLoadoutRules.EffectiveDrain(slot, card) : ""));
        button.Click += (_, _) => { selectedSlot = slot.Index; Show(UiText.Translate("选择下方卡片安装到此槽位,或拖入卡片。"), false); };
        var flyout = new MenuFlyout(); var remove = new MenuFlyoutItem { Text = UiText.Translate("卸下 MOD"), IsEnabled = key.Length > 0 }; remove.Click += (_, _) => Uninstall(slot.Index); flyout.Items.Add(remove); button.ContextFlyout = flyout;
        button.DragStarting += (_, e) => StartDrag(e, key, slot.Index);
        button.DragOver += (_, e) => { if (e.DataView.Contains(DragFormat) && !slot.Locked) { e.AcceptedOperation = DataPackageOperation.Move; e.DragUIOverride.Caption = UiText.Translate("安装 / 交换 MOD"); } };
        button.Drop += async (_, e) => await DropAsync(e, slot.Index);
        slotButtons[slot.Index] = button; return button;
    }
    private FrameworkElement Tile(ModCard card, double width, double height, int? source = null)
    {
        var tile = new Grid { Width = width, Height = height, Tag = card, CanDrag = true };
        var key = VisualAssetCache.Key("card-compact", card.Type, card.Fingerprint, UiText.Language);
        var image = new GameAssetImage { Width = width, Height = height, CacheKey = key };
        var placeholder = new StackPanel { Spacing = 6, Margin = new Thickness(8), VerticalAlignment = VerticalAlignment.Center };
        placeholder.Children.Add(new TextBlock { Text = card.Name, TextWrapping = TextWrapping.Wrap, MaxLines = 2 });
        placeholder.Children.Add(new TextBlock { Text = UiText.Format("等级 {0} · 消耗 {1}", card.Rank, Math.Abs(card.Drain)), Opacity = .7, FontSize = 12 });
        placeholder.Children.Add(new TextBlock { Text = UiText.Translate("等待原生卡面缓存"), Opacity = .5, FontSize = 11 });
        image.ImageResolved += (_, _) => placeholder.Visibility = image.IsCached ? Visibility.Collapsed : Visibility.Visible;
        tile.Children.Add(image); tile.Children.Add(placeholder);
        AutomationProperties.SetName(tile, card.Name + " · " + card.Rank); AutomationProperties.SetAutomationId(tile, "mod-card-" + card.Key);
        ToolTipService.SetToolTip(tile, card.Name + " · " + UiText.Format("等级 {0} · 消耗 {1}", card.Rank, Math.Abs(card.Drain)));
        tile.DragStarting += (_, e) => { StartDrag(e, card.Key, source); if (!e.Cancel) image.SetDragPreview(e.DragUI); }; return tile;
    }
    public Task SearchAsync(string query)
    {
        search.Text = query; page = 0; RefreshCollection(); return SearchCompletion;
    }
    private void RefreshCollection() => SearchCompletion = RefreshCollectionAsync();
    private async Task RefreshCollectionAsync()
    {
        if (detached) return;
        searchLifetime?.Cancel();
        using var lifetime = new CancellationTokenSource(); searchLifetime = lifetime;
        var observed = ++collectionGeneration; var query = search.Text; var selectedFilter = filter; var requestedPage = page;
        searchProgress.Visibility = Visibility.Visible; searchProgress.IsActive = true;
        previous.IsEnabled = next.IsEnabled = false;
        try
        {
            // Cancel obsolete requests while the user types; normalization, the full
            // inventory scan, filtering and sorting all run away from the UI thread.
            await Task.Delay(100, lifetime.Token);
            var index = await searchIndex.WaitAsync(lifetime.Token);
            var matches = await Task.Run(() => index.Search(query, lifetime.Token).Where(x => MatchesFilter(x, selectedFilter))
                .OrderBy(x => x.Name, StringComparer.CurrentCulture).ThenByDescending(x => x.Rank).ToArray(), lifetime.Token);
            if (observed != collectionGeneration || detached) return;
            page = Math.Clamp(requestedPage, 0, Math.Max(0, (matches.Length - 1) / 60));
            collection.Items.Clear(); foreach (var card in matches.Skip(page * 60).Take(60)) collection.Items.Add(Tile(card, 196, 100));
            count.Text = UiText.Format("共 {0} 张 · 第 {1} / {2} 页", matches.Length, page + 1, Math.Max(1, (matches.Length + 59) / 60));
            previous.IsEnabled = page > 0; next.IsEnabled = (page + 1) * 60 < matches.Length;
            if (!countedCache) { countedCache = true; _ = UpdateCacheCountAsync(); }
        }
        catch (OperationCanceledException) { }
        catch (Exception error) { if (observed == collectionGeneration && !detached) Show(error.Message, true); }
        finally
        {
            if (ReferenceEquals(searchLifetime, lifetime)) searchLifetime = null;
            if (observed == collectionGeneration && !detached) { searchProgress.IsActive = false; searchProgress.Visibility = Visibility.Collapsed; }
        }
    }
    private async Task UpdateCacheCountAsync()
    {
        var observed = ++cacheGeneration;
        var counts = await Task.Run(() => { var entries = layout.Cards.Select(x => VisualAssetCache.Key("card-compact", x.Type, x.Fingerprint, UiText.Language)).Distinct().ToArray(); return (Ready: entries.Count(x => VisualAssetCache.Find(x) is not null), Total: entries.Length); });
        if (observed == cacheGeneration) cached.Text = UiText.Format("原版卡面 {0} / {1}", counts.Ready, counts.Total);
    }
    private void StartDrag(DragStartingEventArgs e, string key, int? source)
    {
        if (key.Length == 0 || !CanEdit) { e.Cancel = true; return; }
        e.Data.SetData(DragFormat, instance + "\n" + active!.Key + "\n" + (source?.ToString() ?? "") + "\n" + key);
        e.AllowedOperations = DataPackageOperation.Move;
    }
    private async Task DropAsync(DragEventArgs e, int? target)
    {
        var deferral = e.GetDeferral();
        try
        {
            if (!CanEdit || !e.DataView.Contains(DragFormat)) return;
            var text = await e.DataView.GetDataAsync(DragFormat) as string; if (text is null || text.Length > 2048) return;
            var parts = text.Split('\n'); if (!CanEdit || parts.Length != 4 || parts[0] != instance || parts[1] != active!.Key) return;
            int? source = int.TryParse(parts[2], out var index) ? index : null;
            if (target is { } slot) Install(parts[3], slot, source);
            else if (source is { } old && Selection.GetValueOrDefault(old) == parts[3]) Uninstall(old);
            e.AcceptedOperation = DataPackageOperation.Move;
        }
        catch (Exception ex) { Show(ex.Message, true); }
        finally { deferral.Complete(); }
    }
    public void Install(string key, int target, int? source = null)
    {
        if (!CanEdit) return;
        try { var next = ModLoadoutRules.Install(layout, Selection, key, target, source); foreach (var value in next) Write(value.Key, value.Value); notice.IsOpen = false; RenderBoard(); RefreshCollection(); }
        catch (InvalidOperationException ex) { Show(ex.Message, true); }
    }
    public void Uninstall(int slot)
    {
        if (!CanEdit || !layout.Slots.Any(x => x.Index == slot)) return;
        Write(slot, ""); RenderBoard(); RefreshCollection();
    }
    private void Write(int slot, string key) { if (active?.Fields.FirstOrDefault(x => x.Key == "mod" + slot) is { } field) field.Value = new JValue(key); }
    private async Task CacheAsync()
    {
        if (cacheLifetime is not null || owner.IsBusy) return;
        using var lifetime = new CancellationTokenSource(); cacheLifetime = lifetime; UpdateState();
        try
        {
            var sessions = await RuntimeDiscovery.FindAllAsync(lifetime.Token);
            if (sessions.Length != 1) throw new InvalidOperationException(UiText.Translate("卡面提取需要一个运行中的新版游戏实例;已有缓存可以直接离线使用。"));
            using var runtime = new RuntimeControlClient(sessions[0]); var state = await runtime.StatusAsync(lifetime.Token);
            if (!Version.TryParse(state.Version, out var version) || version < new Version(1, 4, 7))
                throw new InvalidOperationException(UiText.Translate("自动卡面渲染需要 1.4.7 或更新组件,请在下次启动前修复安装。已有卡面可离线使用。"));
            var cacheStatus = await runtime.CardCacheStatusAsync(lifetime.Token);
            if (!cacheStatus.Available) throw new InvalidOperationException(cacheStatus.Message);
            var cards = layout.Cards.Select(x => new NativeCardIdentity(x.Type, x.Fingerprint)).Distinct().Where(x => VisualAssetCache.Find(VisualAssetCache.Key("card-compact", x.Type, x.Fingerprint, UiText.Language)) is null).ToArray();
            foreach (var batch in NativeCardCacheRequest.Batches(UiText.Language, cards))
            {
                cacheStatus = await runtime.CacheCardsAsync(batch, lifetime.Token);
                if (!cacheStatus.Available) throw new InvalidOperationException(cacheStatus.Message);
                Show(cacheStatus.Message, false);
            }
            // The native renderer builds each requested fingerprint directly. No
            // browsing, scrolling or entering the game's MOD screen is required.
            var previousCount = -1;
            for (var i = 0; cards.Length > 0 && i < Math.Clamp((cards.Length + 19) / 20 * 3 + 30, 60, 600); i++)
            {
                await Task.Delay(1000, lifetime.Token); var status = await runtime.CardCacheStatusAsync(lifetime.Token);
                cacheStatus = status;
                if (!status.Available) throw new InvalidOperationException(status.Message);
                if (status.Pending != previousCount) { previousCount = status.Pending; RefreshCollection(); RenderBoard(); _ = UpdateCacheCountAsync(); }
                if (status.Pending == 0 && status.Writing == 0)
                {
                    break;
                }
            }
            var missing = await Task.Run(() => layout.Cards.Select(x => VisualAssetCache.Key("card-compact", x.Type, x.Fingerprint, UiText.Language))
                .Distinct().Count(key => VisualAssetCache.Find(key) is null), lifetime.Token);
            if (missing > 0) throw new InvalidOperationException(UiText.Format("仍有 {0} 张原版卡面未缓存,请重试自动渲染。", missing) +
                (cacheStatus.Failed > 0 ? "\n" + cacheStatus.Message : ""));
            Show(UiText.Translate("全部原版卡面已缓存,可以离线配装。"), false);
            RefreshCollection(); RenderBoard(); _ = UpdateCacheCountAsync();
        }
        catch (OperationCanceledException) { }
        catch (Exception ex) { Show(ex.Message, true); }
        finally { cacheLifetime = null; UpdateState(); }
    }
    private void Show(string message, bool error) { notice.Severity = error ? InfoBarSeverity.Error : InfoBarSeverity.Informational; notice.Message = UiText.Translate(message); notice.IsOpen = true; }
    private async Task RenameAsync()
    {
        if (owner.IsBusy || owner.HasConflict || active?.Fields.FirstOrDefault(x => x.Key == "name") is not { } field) return;
        var input = new TextBox { Text = field.Value.ToString(), MaxLength = 100 };
        var dialog = new ContentDialog { XamlRoot = XamlRoot, Title = UiText.Translate("配装名称"), Content = input, PrimaryButtonText = UiText.Translate("确定"), CloseButtonText = UiText.Translate("取消"), DefaultButton = ContentDialogButton.Primary };
        var action = active;
        if (await dialog.ShowAsync() == ContentDialogResult.Primary && CanEdit && ReferenceEquals(active, action)) field.Value = new JValue(input.Text.Trim());
    }
}