Use function to delegate the progress task

This commit is contained in:
Jack251970 2025-01-10 19:13:19 +08:00
parent ed7265d244
commit 297d191412
5 changed files with 76 additions and 81 deletions

View file

@ -1,22 +0,0 @@
using System.Threading.Tasks;
namespace Flow.Launcher.Plugin;
/// <summary>
/// Interface for progress box
/// </summary>
public interface IProgressBoxEx
{
/// <summary>
/// Show progress box.
/// </summary>
/// <param name="progress">
/// Progress value. Should be between 0 and 100. When progress is 100, the progress box will be closed.
/// </param>
public void ReportProgress(double progress);
/// <summary>
/// Close progress box.
/// </summary>
public Task CloseAsync();
}

View file

@ -322,8 +322,13 @@ namespace Flow.Launcher.Plugin
/// If there is issue when showing the message box, it will return null.
/// </summary>
/// <param name="caption">The caption of the message box.</param>
/// <param name="reportProgressAsync">
/// Time-consuming task function, whose input is the action to report progress.
/// The input of the action is the progress value which is a double value between 0 and 100.
/// If there are any exceptions, this action will be null.
/// </param>
/// <param name="forceClosed">When user closes the progress box manually by button or esc key, this action will be called.</param>
/// <returns>A progress box interface.</returns>
public IProgressBoxEx ShowProgressBox(string caption, Action forceClosed = null);
public Task ShowProgressBoxAsync(string caption, Func<Action<double>, Task> reportProgressAsync, Action forceClosed = null);
}
}

View file

@ -3,11 +3,10 @@ using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Flow.Launcher.Infrastructure.Logger;
using Flow.Launcher.Plugin;
namespace Flow.Launcher
{
public partial class ProgressBoxEx : Window, IProgressBoxEx
public partial class ProgressBoxEx : Window
{
private readonly Action _forceClosed;
@ -17,31 +16,48 @@ namespace Flow.Launcher
InitializeComponent();
}
public static IProgressBoxEx Show(string caption, Action forceClosed = null)
public static async Task ShowAsync(string caption, Func<Action<double>, Task> reportProgressAsync, Action forceClosed = null)
{
if (!Application.Current.Dispatcher.CheckAccess())
{
return Application.Current.Dispatcher.Invoke(() => Show(caption, forceClosed));
}
ProgressBoxEx prgBox = null;
try
{
var prgBox = new ProgressBoxEx(forceClosed)
if (!Application.Current.Dispatcher.CheckAccess())
{
Title = caption
};
prgBox.TitleTextBlock.Text = caption;
prgBox.Show();
return prgBox;
await Application.Current.Dispatcher.InvokeAsync(() =>
{
prgBox = new ProgressBoxEx(forceClosed)
{
Title = caption
};
prgBox.TitleTextBlock.Text = caption;
prgBox.Show();
});
}
await reportProgressAsync(prgBox.ReportProgress).ConfigureAwait(false);
}
catch (Exception e)
{
Log.Error($"|ProgressBoxEx.Show|An error occurred: {e.Message}");
return null;
await reportProgressAsync(null).ConfigureAwait(false);
}
finally
{
if (!Application.Current.Dispatcher.CheckAccess())
{
await Application.Current.Dispatcher.InvokeAsync(async () =>
{
if (prgBox != null)
{
await prgBox.CloseAsync();
}
});
}
}
}
public void ReportProgress(double progress)
private void ReportProgress(double progress)
{
if (!Application.Current.Dispatcher.CheckAccess())
{
@ -64,7 +80,7 @@ namespace Flow.Launcher
}
}
public async Task CloseAsync()
private async Task CloseAsync()
{
if (!Application.Current.Dispatcher.CheckAccess())
{

View file

@ -324,7 +324,7 @@ namespace Flow.Launcher
public MessageBoxResult ShowMsgBox(string messageBoxText, string caption = "", MessageBoxButton button = MessageBoxButton.OK, MessageBoxImage icon = MessageBoxImage.None, MessageBoxResult defaultResult = MessageBoxResult.OK) =>
MessageBoxEx.Show(messageBoxText, caption, button, icon, defaultResult);
public IProgressBoxEx ShowProgressBox(string caption, Action forceClosed = null) => ProgressBoxEx.Show(caption, forceClosed);
public Task ShowProgressBoxAsync(string caption, Func<Action<double>, Task> reportProgressAsync, Action forceClosed = null) => ProgressBoxEx.ShowAsync(caption, reportProgressAsync, forceClosed);
#endregion

View file

@ -144,7 +144,6 @@ namespace Flow.Launcher.Plugin.PluginsManager
var filePath = Path.Combine(Path.GetTempPath(), downloadFilename);
IProgressBoxEx prgBox = null;
var downloadCancelled = false;
try
{
@ -162,42 +161,45 @@ namespace Flow.Launcher.Plugin.PluginsManager
var canReportProgress = totalBytes != -1;
var prgBoxTitle = $"{Context.API.GetTranslation("plugin_pluginsmanager_downloading_plugin")} {plugin.Name}";
if (canReportProgress &&
(prgBox = Context.API.ShowProgressBox(prgBoxTitle, () =>
{
if (prgBox != null)
if (canReportProgress)
{
await Context.API.ShowProgressBoxAsync(prgBoxTitle,
async (reportProgress) =>
{
if (reportProgress == null)
{
// cannot use progress box
await Http.DownloadAsync(plugin.UrlDownload, filePath).ConfigureAwait(false);
}
else
{
await using var contentStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
await using var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true);
var buffer = new byte[8192];
long totalRead = 0;
int read;
while ((read = await contentStream.ReadAsync(buffer).ConfigureAwait(false)) > 0)
{
await fileStream.WriteAsync(buffer.AsMemory(0, read)).ConfigureAwait(false);
totalRead += read;
var progressValue = totalRead * 100 / totalBytes;
// check if user cancelled download before reporting progress
if (downloadCancelled)
return;
else
reportProgress(progressValue);
}
}
},
() =>
{
cts.Cancel();
downloadCancelled = true;
}
})) != null)
{
await using var contentStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
await using var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true);
var buffer = new byte[8192];
long totalRead = 0;
int read;
while ((read = await contentStream.ReadAsync(buffer).ConfigureAwait(false)) > 0)
{
await fileStream.WriteAsync(buffer.AsMemory(0, read)).ConfigureAwait(false);
totalRead += read;
var progressValue = totalRead * 100 / totalBytes;
// check if user cancelled download before reporting progress
if (downloadCancelled)
return;
else
prgBox.ReportProgress(progressValue);
}
// check if user cancelled download before closing progress box
if (downloadCancelled)
return;
else
await prgBox?.CloseAsync();
});
}
else
{
@ -217,9 +219,6 @@ namespace Flow.Launcher.Plugin.PluginsManager
}
catch (HttpRequestException e)
{
// force close progress box
await prgBox?.CloseAsync();
// show error message
Context.API.ShowMsgError(
string.Format(Context.API.GetTranslation("plugin_pluginsmanager_downloading_plugin"), plugin.Name),
@ -230,9 +229,6 @@ namespace Flow.Launcher.Plugin.PluginsManager
}
catch (Exception e)
{
// force close progress box
await prgBox?.CloseAsync();
// show error message
Context.API.ShowMsgError(Context.API.GetTranslation("plugin_pluginsmanager_install_error_title"),
string.Format(Context.API.GetTranslation("plugin_pluginsmanager_install_error_subtitle"),