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

XFEWarframe

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

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Windows.Input;
using CommunityToolkit.Mvvm.Input;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using XFEExtension.NetCore.WinUIHelper.Interface.Services;
using XFEExtension.NetCore.WinUIHelper.Utilities;

namespace XFEWarframe.Desktop.Editing;

/// <summary>Shows an on-demand form through the application's XFE dialog service.</summary>
public sealed class FormDialogButton : Button
{
    public static Func<ContentDialog, Task<ContentDialogResult>>? ShowDialogAsync { get; set; }
    public static readonly DependencyProperty FormProperty = DependencyProperty.Register(nameof(Form), typeof(UIElement), typeof(FormDialogButton), new PropertyMetadata(null));
    public UIElement? Form { get => (UIElement?)GetValue(FormProperty); set => SetValue(FormProperty, value); }
    public static readonly DependencyProperty DialogTitleProperty = DependencyProperty.Register(nameof(DialogTitle), typeof(string), typeof(FormDialogButton), new PropertyMetadata(""));
    public string DialogTitle { get => (string)GetValue(DialogTitleProperty); set => SetValue(DialogTitleProperty, value); }
    public static readonly DependencyProperty PrimaryTextProperty = DependencyProperty.Register(nameof(PrimaryText), typeof(string), typeof(FormDialogButton), new PropertyMetadata("", Changed));
    public string PrimaryText { get => (string)GetValue(PrimaryTextProperty); set => SetValue(PrimaryTextProperty, value); }
    public static readonly DependencyProperty SecondaryTextProperty = DependencyProperty.Register(nameof(SecondaryText), typeof(string), typeof(FormDialogButton), new PropertyMetadata("", Changed));
    public string SecondaryText { get => (string)GetValue(SecondaryTextProperty); set => SetValue(SecondaryTextProperty, value); }
    public static readonly DependencyProperty PrepareCommandProperty = DependencyProperty.Register(nameof(PrepareCommand), typeof(ICommand), typeof(FormDialogButton), new PropertyMetadata(null));
    public ICommand? PrepareCommand { get => (ICommand?)GetValue(PrepareCommandProperty); set => SetValue(PrepareCommandProperty, value); }
    public static readonly DependencyProperty PrimaryCommandProperty = DependencyProperty.Register(nameof(PrimaryCommand), typeof(ICommand), typeof(FormDialogButton), new PropertyMetadata(null));
    public ICommand? PrimaryCommand { get => (ICommand?)GetValue(PrimaryCommandProperty); set => SetValue(PrimaryCommandProperty, value); }
    public static readonly DependencyProperty SecondaryCommandProperty = DependencyProperty.Register(nameof(SecondaryCommand), typeof(ICommand), typeof(FormDialogButton), new PropertyMetadata(null));
    public ICommand? SecondaryCommand { get => (ICommand?)GetValue(SecondaryCommandProperty); set => SetValue(SecondaryCommandProperty, value); }
    public static readonly DependencyProperty CanceledCommandProperty = DependencyProperty.Register(nameof(CanceledCommand), typeof(ICommand), typeof(FormDialogButton), new PropertyMetadata(null));
    public ICommand? CanceledCommand { get => (ICommand?)GetValue(CanceledCommandProperty); set => SetValue(CanceledCommandProperty, value); }
    public static readonly DependencyProperty ErrorTextProperty = DependencyProperty.Register(nameof(ErrorText), typeof(string), typeof(FormDialogButton), new PropertyMetadata(null));
    public string? ErrorText { get => (string?)GetValue(ErrorTextProperty); set => SetValue(ErrorTextProperty, value); }
    public static readonly DependencyProperty CanSubmitProperty = DependencyProperty.Register(nameof(CanSubmit), typeof(bool), typeof(FormDialogButton), new PropertyMetadata(true, Changed));
    public bool CanSubmit { get => (bool)GetValue(CanSubmitProperty); set => SetValue(CanSubmitProperty, value); }
    public static readonly DependencyProperty CanSubmitSecondaryProperty = DependencyProperty.Register(nameof(CanSubmitSecondary), typeof(bool), typeof(FormDialogButton), new PropertyMetadata(true, Changed));
    public bool CanSubmitSecondary { get => (bool)GetValue(CanSubmitSecondaryProperty); set => SetValue(CanSubmitSecondaryProperty, value); }
    public static readonly DependencyProperty IsWorkingProperty = DependencyProperty.Register(nameof(IsWorking), typeof(bool), typeof(FormDialogButton), new PropertyMetadata(false, Changed));
    public bool IsWorking { get => (bool)GetValue(IsWorkingProperty); set => SetValue(IsWorkingProperty, value); }
    public static readonly DependencyProperty ReadyProperty = DependencyProperty.Register(nameof(Ready), typeof(bool), typeof(FormDialogButton), new PropertyMetadata(true));
    public bool Ready { get => (bool)GetValue(ReadyProperty); set => SetValue(ReadyProperty, value); }
    public event EventHandler? Validating;
    public ContentDialog? ActiveDialog { get; private set; }
    private bool opening;
    private static void Changed(DependencyObject sender, DependencyPropertyChangedEventArgs args)
    {
        if (sender is FormDialogButton button && button.ActiveDialog is { } dialog)
        {
            dialog.IsPrimaryButtonEnabled = button.CanSubmit && !button.IsWorking;
            dialog.IsSecondaryButtonEnabled = button.CanSubmitSecondary && !button.IsWorking;
            dialog.PrimaryButtonText = button.PrimaryText; dialog.SecondaryButtonText = button.SecondaryText;
            dialog.DefaultButton = PreferredButton(button.PrimaryText, button.SecondaryText);
            if (button.Form is not null) button.Form.IsHitTestVisible = !button.IsWorking;
        }
    }
    public FormDialogButton() => Click += async (_, _) =>
    {
        try { await OpenAsync(); }
        catch (OperationCanceledException) { }
        catch (Exception ex) { ServiceManager.GetGlobalService<IMessageService>()?.ShowMessage(ex.Message, UiText.Translate("操作未完成"), InfoBarSeverity.Error); }
    };

    public async Task OpenAsync()
    {
        if (opening) return;
        opening = true;
        try
        {
            await ExecuteAsync(PrepareCommand);
            if (!Ready || Form is null) return;
            var show = ShowDialogAsync ?? throw new InvalidOperationException("Dialog service is not initialized.");
            do
            {
                var error = new InfoBar { Severity = InfoBarSeverity.Error, IsClosable = false, Message = ErrorText ?? "", IsOpen = !string.IsNullOrEmpty(ErrorText) };
                var panel = new StackPanel { Spacing = 12 };
                var scroll = new ScrollViewer { Content = Form, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled, MaxHeight = Math.Max(200, (XamlRoot?.Size.Height ?? 800) - 240) };
                panel.Children.Add(error); panel.Children.Add(scroll);
                var dialog = new ContentDialog { Title = DialogTitle, Content = panel, PrimaryButtonText = PrimaryText, SecondaryButtonText = SecondaryText,
                    CloseButtonText = UiText.Translate(PrimaryText.Length + SecondaryText.Length > 0 ? "取消" : "关闭"), DefaultButton = PreferredButton(PrimaryText, SecondaryText),
                    IsPrimaryButtonEnabled = CanSubmit && !IsWorking, IsSecondaryButtonEnabled = CanSubmitSecondary && !IsWorking };
                dialog.Resources["ContentDialogMaxWidth"] = 760d;
                void Validate(ContentDialogButtonClickEventArgs args)
                {
                    try { Validating?.Invoke(this, EventArgs.Empty); error.IsOpen = false; }
                    catch (Exception ex) { args.Cancel = true; error.Message = ex.Message; error.IsOpen = true; }
                }
                dialog.PrimaryButtonClick += (_, args) => Validate(args);
                dialog.SecondaryButtonClick += (_, args) => Validate(args);
                ActiveDialog = dialog;
                ContentDialogResult result;
                try { result = await show(dialog); }
                finally { scroll.Content = null; dialog.Content = null; ActiveDialog = null; }
                // Release the XFE dialog gate before a command opens its destructive-action confirmation.
                if (result == ContentDialogResult.Primary) await ExecuteAsync(PrimaryCommand);
                else if (result == ContentDialogResult.Secondary) await ExecuteAsync(SecondaryCommand);
                else { await ExecuteAsync(CanceledCommand); break; }
                // A rejected save retains the user's draft and shows the server's error in the form.
            } while (!string.IsNullOrEmpty(ErrorText));
        }
        finally { opening = false; }
    }
    private static ContentDialogButton PreferredButton(string primary, string secondary) =>
        primary.Length > 0 ? ContentDialogButton.Primary : secondary.Length > 0 ? ContentDialogButton.Secondary : ContentDialogButton.Close;
    private static async Task ExecuteAsync(ICommand? command)
    {
        if (command?.CanExecute(null) != true) return;
        if (command is IAsyncRelayCommand asyncCommand) await asyncCommand.ExecuteAsync(null);
        else command.Execute(null);
    }
}