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

XFEWarframe

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

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

namespace XFEWarframe.Desktop.Editing;

/// <summary>Native controls for the server's typed field descriptions; contains no save logic.</summary>
public sealed class EditorForm : StackPanel
{
    public IReadOnlyList<EditorField>? Fields
    {
        get => (IReadOnlyList<EditorField>?)GetValue(FieldsProperty);
        set => SetValue(FieldsProperty, value);
    }
    public static readonly DependencyProperty FieldsProperty = DependencyProperty.Register(nameof(Fields), typeof(IReadOnlyList<EditorField>), typeof(EditorForm), new PropertyMetadata(null, (sender, _) => ((EditorForm)sender).Rebuild()));
    public bool EnableSearch
    {
        get => (bool)GetValue(EnableSearchProperty);
        set => SetValue(EnableSearchProperty, value);
    }
    public static readonly DependencyProperty EnableSearchProperty = DependencyProperty.Register(nameof(EnableSearch), typeof(bool), typeof(EditorForm), new PropertyMetadata(true, (sender, _) => ((EditorForm)sender).Rebuild()));
    public EditorForm() => Spacing = 6;
    private void Rebuild()
    {
        Children.Clear();
        var fields = Fields ?? [];
        var cards = CreateCards(fields);
        if (EnableSearch && fields.Count >= 8)
        {
            var search = new AutoSuggestBox { DisplayMemberPath = nameof(EditorField.Label), PlaceholderText = UiText.Translate("搜索设置") };
            Suggestions.SetCandidates(search, fields);
            search.TextChanged += (_, _) =>
            {
                for (var i = 0; i < fields.Count; i++) cards[i].Visibility =
                    fields[i].Label.Contains(search.Text, StringComparison.OrdinalIgnoreCase) || fields[i].Key.Contains(search.Text, StringComparison.OrdinalIgnoreCase) ? Visibility.Visible : Visibility.Collapsed;
            };
            Children.Add(search);
        }
        foreach (var card in cards) Children.Add(card);
    }

    // Create cards without a temporary parent so each is attached to its final host once.
    internal static SettingsCard[] CreateCards(IReadOnlyList<EditorField> fields)
    {
        var cards = new List<SettingsCard>();
        var dependentUpdates = new List<Action>();
        foreach (var field in fields)
        {
            FrameworkElement control;
            switch (field.Kind)
            {
                case "bool":
                    var toggle = new ToggleSwitch { Header = field.Label, IsOn = field.Value.Value<bool>(), OnContent = UiText.Translate("开启"), OffContent = UiText.Translate("关闭") };
                    toggle.Toggled += (_, _) => field.Value = new JValue(toggle.IsOn); control = toggle; break;
                case "choice":
                    var choice = CreateChoiceSearch(field, () => { foreach (var update in dependentUpdates) update(); });
                    control = choice;
                    if (field.Key.StartsWith("ability", StringComparison.Ordinal))
                    {
                        var abilityRow = new Grid { ColumnSpacing = 12, Width = 420 };
                        abilityRow.ColumnDefinitions.Add(new() { Width = new GridLength(36) }); abilityRow.ColumnDefinitions.Add(new() { Width = new GridLength(1, GridUnitType.Star) });
                        var icon = new GameAssetImage { Width = 36, Height = 36, Resource = (Suggestions.GetSelectedItem(choice) as EditorOption)?.Icon ?? "" };
                        AutomationProperties.SetAutomationId(choice, field.Key);
                        choice.RegisterPropertyChangedCallback(Suggestions.SelectedItemProperty, (_, _) => icon.Resource = (Suggestions.GetSelectedItem(choice) as EditorOption)?.Icon ?? "");
                        abilityRow.Children.Add(icon); Grid.SetColumn(choice, 1); abilityRow.Children.Add(choice); control = abilityRow;
                    }
                    break;
                case "strings":
                    var choicesPanel = new StackPanel { Spacing = 8 };
                    choicesPanel.Children.Add(new TextBlock { Text = field.Label, TextWrapping = TextWrapping.Wrap });
                    var list = new StackPanel { Spacing = 6 }; choicesPanel.Children.Add(list);
                    var values = (field.Value as JArray ?? []).Select(x => x.DeepClone()).ToList();
                    void Render()
                    {
                        field.Value = new JArray(values); list.Children.Clear();
                        if (values.Count == 0) list.Children.Add(new TextBlock { Text = UiText.Translate("使用默认轮换"), Opacity = .7 });
                        for (var i = 0; i < values.Count; i++)
                        {
                            var index = i; var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 };
                            row.Children.Add(new TextBlock { Text = $"{i + 1}. " + (field.Options.FirstOrDefault(x => JToken.DeepEquals(x.Value, values[i]))?.Label ?? values[i].ToString()), Width = 200, VerticalAlignment = VerticalAlignment.Center });
                            var up = new Button { Content = UiText.Translate("上移"), IsEnabled = i > 0 }; up.Click += (_, _) => { (values[index - 1], values[index]) = (values[index], values[index - 1]); Render(); };
                            var remove = new Button { Content = UiText.Translate("移除") }; remove.Click += (_, _) => { values.RemoveAt(index); Render(); };
                            row.Children.Add(up); row.Children.Add(remove); list.Children.Add(row);
                        }
                    }
                    var addRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 };
                    var selector = new AutoSuggestBox { DisplayMemberPath = nameof(EditorOption.Label), MinWidth = 260 };
                    Suggestions.SetCandidates(selector, field.Options); Suggestions.SetIsSelectionRequired(selector, true); Suggestions.SetSelectedItem(selector, field.Options.FirstOrDefault());
                    var add = new Button { Content = UiText.Translate("追加任务") }; add.Click += (_, _) => { if (Suggestions.GetSelectedItem(selector) is EditorOption option && values.Count < 30) { values.Add(option.Value.DeepClone()); Render(); } };
                    addRow.Children.Add(selector); addRow.Children.Add(add); choicesPanel.Children.Add(addRow); Render(); control = choicesPanel; break;
                case "stat":
                    var statPanel = new StackPanel { Spacing = 8 };
                    var actual = new ToggleSwitch { Header = field.Label, IsOn = true, OnContent = UiText.Translate("输入实际数值"), OffContent = UiText.Translate("输入品质系数(0–1)") };
                    var statNumber = new NumberBox { SpinButtonPlacementMode = NumberBoxSpinButtonPlacementMode.Compact, HorizontalAlignment = HorizontalAlignment.Stretch };
                    var rangeText = new TextBlock { TextWrapping = TextWrapping.Wrap, Opacity = .7 };
                    var updating = false; double minimum = 0, maximum = 1;
                    void UpdateStat()
                    {
                        var range = field.Ranges.OfType<JObject>().FirstOrDefault(r => ((JObject)r["match"]!).Properties().All(p => fields.Any(f => !f.HasUnresolvedChoice && f.Key == p.Name && JToken.DeepEquals(f.Value, p.Value))));
                        if (range is null) { statNumber.IsEnabled = false; rangeText.Text = UiText.Translate("请选择适用装备、属性和稀有度。"); return; }
                        updating = true;
                        try
                        {
                            minimum = range.Value<double>("min"); maximum = range.Value<double>("max");
                            statNumber.IsEnabled = maximum > minimum;
                            // Reset bounds first to avoid clamping the retained quality while switching attributes.
                            statNumber.Minimum = double.NegativeInfinity; statNumber.Maximum = double.PositiveInfinity;
                            statNumber.Value = actual.IsOn ? minimum + (maximum - minimum) * field.Value.Value<double>() : field.Value.Value<double>();
                            statNumber.Minimum = actual.IsOn ? minimum + (maximum - minimum) * field.Minimum : field.Minimum;
                            statNumber.Maximum = actual.IsOn ? maximum : field.Maximum;
                            statNumber.SmallChange = actual.IsOn ? .1 : .01;
                            rangeText.Text = UiText.Format("实际范围 {0:0.###}–{1:0.###}{2} · 品质 {3:0.######}", minimum, maximum, range.Value<string>("unit"), field.Value.Value<double>());
                        }
                        finally { updating = false; }
                    }
                    statNumber.ValueChanged += (_, _) =>
                    {
                        if (updating) return;
                        field.Value = new JValue(actual.IsOn ? (statNumber.Value - minimum) / (maximum - minimum) : statNumber.Value);
                    };
                    actual.Toggled += (_, _) => UpdateStat(); dependentUpdates.Add(UpdateStat);
                    statPanel.Children.Add(actual); statPanel.Children.Add(statNumber); statPanel.Children.Add(rangeText); control = statPanel; break;
                case "number":
                    var number = new NumberBox { Header = field.Label, Value = field.Value.Value<double>(), Minimum = field.Minimum, Maximum = field.Maximum, SmallChange = field.Step,
                        SpinButtonPlacementMode = NumberBoxSpinButtonPlacementMode.Compact, HorizontalAlignment = HorizontalAlignment.Stretch };
                    number.ValueChanged += (_, _) => field.Value = new JValue(number.Value); control = number; break;
                case "date":
                    var panel = new StackPanel { Spacing = 8 };
                    panel.Children.Add(new TextBlock { Text = field.Label, TextWrapping = TextWrapping.Wrap });
                    var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 };
                    var date = new CalendarDatePicker { PlaceholderText = UiText.Translate("未设置"), Date = field.Value.Value<long>() == 0 ? null : DateTimeOffset.FromUnixTimeMilliseconds(field.Value.Value<long>()).ToLocalTime() };
                    var time = new TimePicker { ClockIdentifier = "24HourClock", Time = date.Date?.TimeOfDay ?? TimeSpan.Zero };
                    void Changed() => field.Value = new JValue(date.Date is DateTimeOffset day ? new DateTimeOffset(day.Date + time.Time, day.Offset).ToUnixTimeMilliseconds() : 0);
                    date.DateChanged += (_, _) => Changed(); time.TimeChanged += (_, _) => Changed();
                    var clear = new Button { Content = UiText.Translate("清空") }; clear.Click += (_, _) => { date.Date = null; Changed(); };
                    row.Children.Add(date); row.Children.Add(time); row.Children.Add(clear); panel.Children.Add(row); control = panel; break;
                default:
                    var text = new TextBox { Header = field.Label, Text = field.Value.Type == JTokenType.Null ? "" : field.Value.ToString(), MaxLength = 1024, HorizontalAlignment = HorizontalAlignment.Stretch };
                    text.TextChanged += (_, _) => field.Value = new JValue(text.Text); control = text; break;
            }
            AutomationProperties.SetName(control, field.Label);
            AutomationProperties.SetAutomationId(control, field.Key);
            var card = new SettingsCard { Header = field.Label, Content = control, Tag = field.Key, HorizontalAlignment = HorizontalAlignment.Stretch };
            switch (control)
            {
                case ToggleSwitch toggle: toggle.Header = null; break;
                case ComboBox combo: combo.Header = null; combo.Width = 260; break;
                case AutoSuggestBox search: search.Header = null; search.Width = field.Key.StartsWith("ability", StringComparison.Ordinal) ? 320 : 260; break;
                case NumberBox number: number.Header = null; number.Width = 180; break;
                case TextBox text: text.Header = null; text.Width = 260; break;
                case StackPanel panel:
                    if (panel.Children.FirstOrDefault() is TextBlock heading && heading.Text == field.Label) panel.Children.Remove(heading);
                    if (panel.Children.FirstOrDefault() is ToggleSwitch mode) mode.Header = null;
                    card.ContentAlignment = ContentAlignment.Vertical;
                    card.HorizontalContentAlignment = HorizontalAlignment.Stretch;
                    break;
            }
            cards.Add(card);
        }
        foreach (var update in dependentUpdates) update();
        return cards.ToArray();
    }

    private static AutoSuggestBox CreateChoiceSearch(EditorField field, Action changed)
    {
        var search = new AutoSuggestBox
        {
            TextMemberPath = nameof(EditorOption.Label),
            PlaceholderText = UiText.Translate(field.Key.StartsWith("ability", StringComparison.Ordinal) ? "输入技能名称搜索" : "输入名称搜索")
        };
        // DisplayMemberPath generates a text template. It must not compete with
        // our icon template when the native suggestion ListView is realized.
        if (field.Options.Any(x => x.Icon.Length > 0))
            search.ItemTemplate = (DataTemplate)Application.Current.Resources["OriginalGameSuggestionTemplate"];
        else search.DisplayMemberPath = nameof(EditorOption.Label);
        Suggestions.SetCandidates(search, field.Options); Suggestions.SetIsSelectionRequired(search, true);
        Suggestions.SetSelectedItem(search, field.HasUnresolvedChoice ? null : field.Options.FirstOrDefault(x => JToken.DeepEquals(x.Value, field.Value)));
        if (field.HasUnresolvedChoice) search.Text = field.ChoiceQuery;
        search.RegisterPropertyChangedCallback(Suggestions.SelectedItemProperty, (_, _) =>
        {
            field.HasUnresolvedChoice = Suggestions.GetSelectedItem(search) is not EditorOption;
            field.Value = Suggestions.GetSelectedItem(search) is EditorOption option ? option.Value.DeepClone() : JValue.CreateNull();
            changed();
        });
        search.RegisterPropertyChangedCallback(AutoSuggestBox.TextProperty, (sender, _) => field.ChoiceQuery = ((AutoSuggestBox)sender).Text);
        return search;
    }
}