Flow.Launcher/Flow.Launcher/ProgressBoxEx.xaml.cs

121 lines
3.4 KiB
C#
Raw Normal View History

using System;
2025-01-09 08:37:52 +00:00
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
2025-01-09 13:48:13 +00:00
namespace Flow.Launcher
{
public partial class ProgressBoxEx : Window
{
2025-04-13 09:50:44 +00:00
private static readonly string ClassName = nameof(ProgressBoxEx);
2025-02-26 12:11:27 +00:00
private readonly Action _cancelProgress;
2025-02-26 12:11:27 +00:00
private ProgressBoxEx(Action cancelProgress)
{
2025-02-26 12:11:27 +00:00
_cancelProgress = cancelProgress;
InitializeComponent();
}
2025-02-26 12:11:27 +00:00
public static async Task ShowAsync(string caption, Func<Action<double>, Task> reportProgressAsync, Action cancelProgress = null)
{
ProgressBoxEx progressBox = null;
try
{
if (!Application.Current.Dispatcher.CheckAccess())
{
await Application.Current.Dispatcher.InvokeAsync(() =>
{
progressBox = new ProgressBoxEx(cancelProgress)
{
Title = caption
};
progressBox.TitleTextBlock.Text = caption;
progressBox.Show();
});
}
else
{
progressBox = new ProgressBoxEx(cancelProgress)
{
Title = caption
};
progressBox.TitleTextBlock.Text = caption;
progressBox.Show();
}
await reportProgressAsync(progressBox.ReportProgress).ConfigureAwait(false);
}
catch (Exception e)
{
2025-04-13 09:50:44 +00:00
App.API.LogError(ClassName, $"An error occurred: {e.Message}");
await reportProgressAsync(null).ConfigureAwait(false);
}
finally
{
if (!Application.Current.Dispatcher.CheckAccess())
{
2025-01-11 04:38:08 +00:00
await Application.Current.Dispatcher.InvokeAsync(() =>
{
progressBox?.Close();
});
}
else
{
progressBox?.Close();
}
}
}
private void ReportProgress(double progress)
{
if (!Application.Current.Dispatcher.CheckAccess())
{
Application.Current.Dispatcher.Invoke(() => ReportProgress(progress));
return;
}
if (progress < 0)
{
ProgressBar.Value = 0;
}
else if (progress >= 100)
{
ProgressBar.Value = 100;
Close();
}
else
{
ProgressBar.Value = progress;
}
}
private void KeyEsc_OnPress(object sender, ExecutedRoutedEventArgs e)
{
ForceClose();
}
private void Button_Cancel(object sender, RoutedEventArgs e)
{
ForceClose();
}
private void Button_Minimize(object sender, RoutedEventArgs e)
{
WindowState = WindowState.Minimized;
}
private void Button_Background(object sender, RoutedEventArgs e)
{
Hide();
}
private void ForceClose()
{
2025-01-10 05:06:37 +00:00
Close();
2025-02-26 12:11:27 +00:00
_cancelProgress?.Invoke();
}
}
}