From 9b802f2c2cb7793079cf3bcef91cd461b634cc43 Mon Sep 17 00:00:00 2001 From: lobinho <354454350+eolobinhooooooooooooooohhoooooo@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:34:56 -0300 Subject: [PATCH] fix(apps): stabilize download batches and progress --- .github/workflows/apps-download-tests.yml | 45 +++++ Optimizer.Tests/AppDownloadProgressTests.cs | 39 ++++ Optimizer.Tests/AppDownloadStateTests.cs | 178 ++++++++++++++++ Optimizer.Tests/Optimizer.Tests.csproj | 22 ++ Optimizer.Tests/README.md | 13 ++ Optimizer.Tests/WebClientProgressTests.cs | 212 ++++++++++++++++++++ Optimizer/AppDownloadProgress.cs | 11 + Optimizer/AppDownloadState.cs | 63 ++++++ Optimizer/Forms/MainForm.Apps.cs | 20 ++ Optimizer/Forms/MainForm.Startup.cs | 9 +- Optimizer/Forms/MainForm.cs | 129 ++++++------ Optimizer/Optimizer.csproj | 4 +- 12 files changed, 669 insertions(+), 76 deletions(-) create mode 100644 .github/workflows/apps-download-tests.yml create mode 100644 Optimizer.Tests/AppDownloadProgressTests.cs create mode 100644 Optimizer.Tests/AppDownloadStateTests.cs create mode 100644 Optimizer.Tests/Optimizer.Tests.csproj create mode 100644 Optimizer.Tests/README.md create mode 100644 Optimizer.Tests/WebClientProgressTests.cs create mode 100644 Optimizer/AppDownloadProgress.cs create mode 100644 Optimizer/AppDownloadState.cs diff --git a/.github/workflows/apps-download-tests.yml b/.github/workflows/apps-download-tests.yml new file mode 100644 index 0000000..0e71f34 --- /dev/null +++ b/.github/workflows/apps-download-tests.yml @@ -0,0 +1,45 @@ +name: Apps download checks + +on: + pull_request: + branches: [master] + paths: + - "Optimizer/AppDownload*.cs" + - "Optimizer/Models/AppInfo.cs" + - "Optimizer/Forms/MainForm*.cs" + - "Optimizer/Optimizer.csproj" + - "Optimizer/packages.config" + - "Optimizer.sln" + - "Optimizer.Tests/**" + - ".github/workflows/apps-download-tests.yml" + push: + branches: [master] + paths: + - "Optimizer/AppDownload*.cs" + - "Optimizer/Models/AppInfo.cs" + - "Optimizer/Forms/MainForm*.cs" + - "Optimizer/Optimizer.csproj" + - "Optimizer/packages.config" + - "Optimizer.sln" + - "Optimizer.Tests/**" + - ".github/workflows/apps-download-tests.yml" + +permissions: + contents: read + +jobs: + test: + runs-on: windows-latest + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-dotnet@v5 + with: + dotnet-version: "8.0.x" + - uses: microsoft/setup-msbuild@v3 + - uses: NuGet/setup-nuget@v4 + - name: Restore application packages + run: nuget restore Optimizer.sln -NonInteractive + - name: Build application + run: msbuild Optimizer.sln /t:Rebuild /m /p:Configuration=Release '/p:Platform=Any CPU' /verbosity:minimal + - name: Run isolated download tests + run: dotnet test Optimizer.Tests/Optimizer.Tests.csproj --configuration Release diff --git a/Optimizer.Tests/AppDownloadProgressTests.cs b/Optimizer.Tests/AppDownloadProgressTests.cs new file mode 100644 index 0000000..ee061e7 --- /dev/null +++ b/Optimizer.Tests/AppDownloadProgressTests.cs @@ -0,0 +1,39 @@ +using Xunit; + +namespace Optimizer.Tests { + public sealed class AppDownloadProgressTests { + [Theory] + [InlineData(0L, -1L)] + [InlineData(1L, -1L)] + [InlineData(33554432L, -1L)] + [InlineData(long.MaxValue, -1L)] + [InlineData(0L, 0L)] + [InlineData(1L, 0L)] + [InlineData(1L, long.MinValue)] + public void MissingOrInvalidLengthIsIndeterminate(long received, long total) + { + Assert.Null(AppDownloadProgress.Percentage(received, total)); + } + + [Theory] + [InlineData(0L, 100L, 0)] + [InlineData(-1L, 100L, 0)] + [InlineData(long.MinValue, 100L, 0)] + [InlineData(1L, 100L, 1)] + [InlineData(1L, 3L, 33)] + [InlineData(50L, 100L, 50)] + [InlineData(99L, 100L, 99)] + [InlineData(100L, 100L, 100)] + [InlineData(101L, 100L, 100)] + [InlineData(long.MaxValue, 1L, 100)] + [InlineData(long.MaxValue, long.MaxValue, 100)] + [InlineData(long.MaxValue - 1, long.MaxValue, 99)] + [InlineData(10737418240L, 21474836480L, 50)] + public void KnownLengthProducesABoundedPercentage(long received, long total, int expected) + { + int? percentage = AppDownloadProgress.Percentage(received, total); + Assert.Equal(expected, percentage); + Assert.InRange(percentage.Value, 0, 100); + } + } +} diff --git a/Optimizer.Tests/AppDownloadStateTests.cs b/Optimizer.Tests/AppDownloadStateTests.cs new file mode 100644 index 0000000..9c59087 --- /dev/null +++ b/Optimizer.Tests/AppDownloadStateTests.cs @@ -0,0 +1,178 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Xunit; + +namespace Optimizer.Tests { + public sealed class AppDownloadStateTests { + static AppInfo App(string title) + { + return new AppInfo { Title = title, Tag = "c" + title, Link = "https://example.invalid/x86", Link64 = "https://example.invalid/x64" }; + } + + static AppDownloadState.Batch Begin(AppDownloadState state) + { + return state.TryBeginDownload(new[] { App("One") }, Path.GetTempPath(), true, false); + } + + [Fact] + public void IdleStateIsNotBusy() + { + AppDownloadState state = new AppDownloadState(); + Assert.False(state.IsBusy); + Assert.False(state.IsLoadingFeed); + Assert.False(state.IsDownloading); + } + + [Fact] + public void FeedLoadBlocksAnotherRefreshAndDownloads() + { + AppDownloadState state = new AppDownloadState(); + Assert.True(state.TryBeginFeedLoad()); + Assert.True(state.IsLoadingFeed); + Assert.True(state.IsBusy); + Assert.False(state.TryBeginFeedLoad()); + Assert.Null(Begin(state)); + Assert.False(state.IsDownloading); + } + + [Fact] + public void FeedCompletionAllowsDownloadsAgain() + { + AppDownloadState state = new AppDownloadState(); + Assert.True(state.TryBeginFeedLoad()); + state.EndFeedLoad(); + Assert.False(state.IsLoadingFeed); + Assert.NotNull(Begin(state)); + } + + [Fact] + public void DownloadBlocksRefreshAndReentry() + { + AppDownloadState state = new AppDownloadState(); + Assert.NotNull(Begin(state)); + Assert.True(state.IsDownloading); + Assert.True(state.IsBusy); + Assert.False(state.TryBeginFeedLoad()); + Assert.Null(Begin(state)); + } + + [Fact] + public void DownloadCompletionRestoresIdleState() + { + AppDownloadState state = new AppDownloadState(); + AppDownloadState.Batch batch = Begin(state); + state.EndDownload(batch); + Assert.False(state.IsBusy); + Assert.True(state.TryBeginFeedLoad()); + } + + [Fact] + public void EmptySelectionDoesNotStartABatch() + { + AppDownloadState state = new AppDownloadState(); + Assert.Null(state.TryBeginDownload(new AppInfo[0], Path.GetTempPath(), true, false)); + Assert.False(state.IsBusy); + Assert.True(state.TryBeginFeedLoad()); + } + + [Fact] + public void InvalidInputsDoNotLeaveTheDownloaderBusy() + { + AppDownloadState state = new AppDownloadState(); + Assert.Throws(() => state.TryBeginDownload(null, Path.GetTempPath(), true, false)); + Assert.Throws(() => state.TryBeginDownload(new[] { App("One") }, string.Empty, true, false)); + Assert.False(state.IsBusy); + Assert.NotNull(Begin(state)); + } + + [Fact] + public void BatchCapturesSelectionAndAppMetadata() + { + AppInfo app = App("One"); + List selected = new List { app }; + AppDownloadState state = new AppDownloadState(); + AppDownloadState.Batch batch = state.TryBeginDownload(selected, Path.GetTempPath(), true, false); + + selected.Clear(); + app.Title = "Changed"; + app.Tag = "Changed"; + app.Link = "Changed"; + app.Link64 = "Changed"; + + AppInfo captured = Assert.Single(batch.Apps); + Assert.Equal("One", captured.Title); + Assert.Equal("cOne", captured.Tag); + Assert.Equal("https://example.invalid/x86", captured.Link); + Assert.Equal("https://example.invalid/x64", captured.Link64); + Assert.NotSame(app, captured); + } + + [Theory] + [InlineData(true, true)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(false, false)] + public void BatchCapturesArchitectureInstallationAndCanonicalFolder(bool prefer64, bool autoInstall) + { + string folder = Path.Combine(Path.GetTempPath(), "Optimizer fixture", "..", "Downloads"); + AppDownloadState.Batch batch = new AppDownloadState().TryBeginDownload(new[] { App("One") }, folder, prefer64, autoInstall); + Assert.Equal(Path.GetFullPath(folder), batch.Folder); + Assert.Equal(prefer64, batch.Prefer64); + Assert.Equal(autoInstall, batch.AutoInstall); + } + + [Fact] + public void BatchSelectionCannotBeExtendedAfterStarting() + { + AppDownloadState.Batch batch = Begin(new AppDownloadState()); + IList apps = Assert.IsAssignableFrom>(batch.Apps); + Assert.Throws(() => apps.Add(App("Two"))); + Assert.Single(batch.Apps); + } + + [Fact] + public void OldCompletionCannotUnlockANewerBatch() + { + AppDownloadState state = new AppDownloadState(); + AppDownloadState.Batch first = Begin(state); + state.EndDownload(first); + AppDownloadState.Batch second = Begin(state); + state.EndDownload(first); + state.EndDownload(null); + + Assert.True(state.IsDownloading); + Assert.False(state.TryBeginFeedLoad()); + state.EndDownload(second); + Assert.False(state.IsBusy); + } + + [Fact] + public void EndingAFeedLoadCannotUnlockAnActiveDownload() + { + AppDownloadState state = new AppDownloadState(); + AppDownloadState.Batch batch = Begin(state); + state.EndFeedLoad(); + Assert.True(state.IsDownloading); + Assert.False(state.TryBeginFeedLoad()); + Assert.Null(Begin(state)); + state.EndDownload(batch); + Assert.False(state.IsBusy); + } + + [Fact] + public void FailedSnapshotEnumerationDoesNotStartAPartialBatch() + { + AppDownloadState state = new AppDownloadState(); + Assert.Throws(() => state.TryBeginDownload(InterruptedSelection(), Path.GetTempPath(), true, false)); + Assert.False(state.IsBusy); + Assert.NotNull(Begin(state)); + } + + static IEnumerable InterruptedSelection() + { + yield return App("One"); + throw new IOException("Fixture selection failure"); + } + } +} diff --git a/Optimizer.Tests/Optimizer.Tests.csproj b/Optimizer.Tests/Optimizer.Tests.csproj new file mode 100644 index 0000000..11841ab --- /dev/null +++ b/Optimizer.Tests/Optimizer.Tests.csproj @@ -0,0 +1,22 @@ + + + net48 + 7.3 + true + false + true + + + + + + all + + + + + + + + + diff --git a/Optimizer.Tests/README.md b/Optimizer.Tests/README.md new file mode 100644 index 0000000..ef178e9 --- /dev/null +++ b/Optimizer.Tests/README.md @@ -0,0 +1,13 @@ +# App download regression tests + +Run on Windows with the .NET Framework 4.8 Developer Pack and .NET SDK 8 or newer: + +```powershell +dotnet test .\Optimizer.Tests\Optimizer.Tests.csproj --configuration Release +``` + +The tests compile the production download-state and progress helpers directly. They do not launch Optimizer, run installers, apply optimizations, or access system configuration. Feed URLs in the state tests use the reserved `.invalid` domain and are never requested. + +Coverage includes unknown or zero content lengths, large byte counts, percentage bounds, exclusive feed/download operations, stable batch inputs, and state recovery after invalid inputs. Loopback-only HTTP tests verify that a real chunked download reports unknown-length progress on a Windows Forms synchronization context, including cancellation and timeout cleanup. Downloaded bytes are inert test data in a temporary folder, never executable content. + +These are helper and HTTP-contract tests, not an end-to-end test of MainForm or the installer workflow. diff --git a/Optimizer.Tests/WebClientProgressTests.cs b/Optimizer.Tests/WebClientProgressTests.cs new file mode 100644 index 0000000..a5a6459 --- /dev/null +++ b/Optimizer.Tests/WebClientProgressTests.cs @@ -0,0 +1,212 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; +using Xunit; + +namespace Optimizer.Tests { + public sealed class WebClientProgressTests { + public enum FixtureOutcome { Complete, Cancel, Timeout } + + [Theory] + [InlineData(FixtureOutcome.Complete)] + [InlineData(FixtureOutcome.Cancel)] + [InlineData(FixtureOutcome.Timeout)] + public async Task ChunkedProgressAndCleanupWorkOnTheUiThread(FixtureOutcome outcome) + { + TaskCompletionSource completed = new TaskCompletionSource(); + Thread thread = new Thread(() => + { + try + { + DownloadOnUiThread(outcome); + completed.SetResult(true); + } + catch (Exception ex) + { + completed.SetException(ex); + } + }); + thread.IsBackground = true; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + + Assert.Same(completed.Task, await Task.WhenAny(completed.Task, Task.Delay(TimeSpan.FromSeconds(25)))); + if (outcome == FixtureOutcome.Timeout) + { + TimeoutException error = await Assert.ThrowsAsync(() => completed.Task); + Assert.Equal("Fixture timeout after progress.", error.Message); + Assert.Empty(error.Data); + } + else + await completed.Task; + } + + static void DownloadOnUiThread(FixtureOutcome outcome) + { + bool cancel = outcome != FixtureOutcome.Complete; + string folder = Path.Combine(Path.GetTempPath(), "OptimizerDownloads-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(folder); + TcpListener listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + int port = ((IPEndPoint)listener.LocalEndpoint).Port; + SynchronizationContext previous = SynchronizationContext.Current; + Exception failure = null; + + try + { + using (ManualResetEventSlim progressObserved = new ManualResetEventSlim()) + using (ManualResetEventSlim releaseResponse = new ManualResetEventSlim()) + using (WindowsFormsSynchronizationContext context = new WindowsFormsSynchronizationContext()) + using (ProgressBar bar = new ProgressBar()) + using (WebClient client = new WebClient { Proxy = null }) + { + SynchronizationContext.SetSynchronizationContext(context); + int uiThread = Thread.CurrentThread.ManagedThreadId; + bool unknownLength = false; + bool wrongThread = false; + bool determinateWithoutLength = false; + bool cancellationRequested = false; + bool cancelledCompletion = false; + Exception progressError = null; + client.DownloadFileCompleted += (sender, e) => cancelledCompletion = e.Cancelled; + client.DownloadProgressChanged += (sender, e) => + { + try + { + wrongThread |= Thread.CurrentThread.ManagedThreadId != uiThread; + int? percentage = AppDownloadProgress.Percentage(e.BytesReceived, e.TotalBytesToReceive); + if (e.TotalBytesToReceive < 0 && e.BytesReceived > 0) + { + unknownLength = true; + determinateWithoutLength |= percentage.HasValue; + progressObserved.Set(); + } + if (percentage.HasValue) bar.Value = percentage.Value; + } + catch (Exception ex) + { + progressError = ex; + progressObserved.Set(); + } + }; + + Task server = ServeChunkedResponse(listener, progressObserved, releaseResponse, cancel); + Task download = null; + try + { + string file = Path.Combine(folder, "fixture.download"); + download = client.DownloadFileTaskAsync(new Uri("http://127.0.0.1:" + port + "/fixture"), file); + Stopwatch timeout = Stopwatch.StartNew(); + while (!download.IsCompleted && timeout.Elapsed < TimeSpan.FromSeconds(10)) + { + Application.DoEvents(); + if (outcome == FixtureOutcome.Timeout && unknownLength) + throw new TimeoutException("Fixture timeout after progress."); + if (cancel && unknownLength && !cancellationRequested) + { + cancellationRequested = true; + client.CancelAsync(); + releaseResponse.Set(); + } + Thread.Sleep(5); + } + + Assert.True(download.IsCompleted, "Loopback download did not complete."); + if (cancel) + { + Assert.True(cancellationRequested); + Assert.True(cancelledCompletion); + Exception error = Record.Exception(() => download.GetAwaiter().GetResult()); + Assert.True(error is OperationCanceledException || error is WebException, "WebClient must report cancellation or its aborted request error."); + } + else + download.GetAwaiter().GetResult(); + Assert.True(WaitForCompletion(server), "Loopback server did not complete."); + server.GetAwaiter().GetResult(); + Assert.True(unknownLength, "The response must exercise progress before its size is known."); + Assert.False(wrongThread); + Assert.False(determinateWithoutLength); + Assert.Null(progressError); + if (!cancel) Assert.Equal(65536, new FileInfo(file).Length); + } + catch (Exception ex) + { + failure = ex; + throw; + } + finally + { + client.CancelAsync(); + listener.Stop(); + releaseResponse.Set(); + bool downloadStopped = WaitForCompletion(download); + bool serverStopped = WaitForCompletion(server); + if (download != null && download.IsFaulted) _ = download.Exception; + if (server.IsFaulted) _ = server.Exception; + if (!downloadStopped || !serverStopped) + { + TimeoutException cleanup = new TimeoutException("Loopback operations did not stop during cleanup."); + if (failure == null) throw cleanup; + failure.Data["CleanupFailure"] = cleanup; + } + } + } + } + catch (Exception ex) + { + failure = ex; + throw; + } + finally + { + SynchronizationContext.SetSynchronizationContext(previous); + listener.Stop(); + try { Directory.Delete(folder, true); } + catch (Exception cleanup) + { + if (failure == null) throw; + failure.Data["FixtureCleanupFailure"] = cleanup; + } + } + } + + static bool WaitForCompletion(Task task) + { + Stopwatch timeout = Stopwatch.StartNew(); + while (task != null && !task.IsCompleted && timeout.Elapsed < TimeSpan.FromSeconds(2)) + { + Application.DoEvents(); + Thread.Sleep(5); + } + return task == null || task.IsCompleted; + } + + static async Task ServeChunkedResponse(TcpListener listener, ManualResetEventSlim progressObserved, ManualResetEventSlim releaseResponse, bool cancel) + { + using (TcpClient connection = await listener.AcceptTcpClientAsync().ConfigureAwait(false)) + using (NetworkStream stream = connection.GetStream()) + using (StreamReader reader = new StreamReader(stream, Encoding.ASCII, false, 1024, true)) + { + string line; + do { line = await reader.ReadLineAsync().ConfigureAwait(false); } + while (!string.IsNullOrEmpty(line)); + + byte[] header = Encoding.ASCII.GetBytes("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n10000\r\n"); + await stream.WriteAsync(header, 0, header.Length).ConfigureAwait(false); + byte[] content = new byte[65536]; + await stream.WriteAsync(content, 0, content.Length).ConfigureAwait(false); + Assert.True(await Task.Run(() => progressObserved.Wait(TimeSpan.FromSeconds(5))).ConfigureAwait(false), "No unknown-length progress event was observed."); + if (cancel) Assert.True(await Task.Run(() => releaseResponse.Wait(TimeSpan.FromSeconds(5))).ConfigureAwait(false), "Cancellation was not requested."); + byte[] end = Encoding.ASCII.GetBytes("\r\n0\r\n\r\n"); + try { await stream.WriteAsync(end, 0, end.Length).ConfigureAwait(false); } + catch (IOException) when (cancel) { } + } + } + } +} diff --git a/Optimizer/AppDownloadProgress.cs b/Optimizer/AppDownloadProgress.cs new file mode 100644 index 0000000..b8d6b7f --- /dev/null +++ b/Optimizer/AppDownloadProgress.cs @@ -0,0 +1,11 @@ +namespace Optimizer { + internal static class AppDownloadProgress { + internal static int? Percentage(long received, long total) + { + if (total <= 0) return null; + if (received <= 0) return 0; + if (received >= total) return 100; + return (int)(100m * received / total); + } + } +} diff --git a/Optimizer/AppDownloadState.cs b/Optimizer/AppDownloadState.cs new file mode 100644 index 0000000..8003a11 --- /dev/null +++ b/Optimizer/AppDownloadState.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace Optimizer { + internal sealed class AppDownloadState { + internal sealed class Batch { + internal IReadOnlyList Apps { get; private set; } + internal string Folder { get; private set; } + internal bool Prefer64 { get; private set; } + internal bool AutoInstall { get; private set; } + + internal Batch(AppInfo[] apps, string folder, bool prefer64, bool autoInstall) + { + Apps = Array.AsReadOnly(apps); + Folder = Path.GetFullPath(folder); + Prefer64 = prefer64; + AutoInstall = autoInstall; + } + } + + Batch _batch; + internal bool IsLoadingFeed { get; private set; } + internal bool IsDownloading { get { return _batch != null; } } + internal bool IsBusy { get { return IsLoadingFeed || IsDownloading; } } + + internal bool TryBeginFeedLoad() + { + if (IsBusy) return false; + IsLoadingFeed = true; + return true; + } + + internal void EndFeedLoad() + { + IsLoadingFeed = false; + } + + internal Batch TryBeginDownload(IEnumerable apps, string folder, bool prefer64, bool autoInstall) + { + if (IsBusy) return null; + if (apps == null) throw new ArgumentNullException(nameof(apps)); + + AppInfo[] selected = apps.Select(app => new AppInfo + { + Title = app.Title, + Tag = app.Tag, + Link = app.Link, + Link64 = app.Link64 + }).ToArray(); + if (selected.Length == 0) return null; + + _batch = new Batch(selected, folder, prefer64, autoInstall); + return _batch; + } + + internal void EndDownload(Batch batch) + { + if (ReferenceEquals(_batch, batch)) _batch = null; + } + } +} diff --git a/Optimizer/Forms/MainForm.Apps.cs b/Optimizer/Forms/MainForm.Apps.cs index 5a32346..d6dd031 100644 --- a/Optimizer/Forms/MainForm.Apps.cs +++ b/Optimizer/Forms/MainForm.Apps.cs @@ -18,6 +18,26 @@ public sealed partial class MainForm { LinkLabel _appsClear; int _appsTileW; bool _appsLayingOut, _appsBulk; + bool _appsFeedAvailable; + readonly AppDownloadState _appDownloads = new AppDownloadState(); + + void UpdateAppDownloaderControls() + { + bool downloading = _appDownloads.IsDownloading; + btnGetFeed.Enabled = !_appDownloads.IsBusy; + btnDownloadApps.Enabled = !_appDownloads.IsBusy && _appsFeedAvailable && AppsFromFeed.Count > 0; + changeDownDirB.Enabled = !downloading; + txtDownloadFolder.ReadOnly = downloading; + c64.Enabled = !downloading; + c32.Enabled = !downloading; + cAutoInstall.Enabled = !downloading; + + if (_appsGroups != null) + foreach (Panel group in _appsGroups) group.Enabled = !downloading; + if (_appsCatToggles != null) + foreach (LinkLabel toggle in _appsCatToggles) toggle.Enabled = !downloading; + if (_appsClear != null) _appsClear.Enabled = !downloading; + } bool UpdateGoToDownloadsButtonState() { diff --git a/Optimizer/Forms/MainForm.Startup.cs b/Optimizer/Forms/MainForm.Startup.cs index 686b663..1d81833 100644 --- a/Optimizer/Forms/MainForm.Startup.cs +++ b/Optimizer/Forms/MainForm.Startup.cs @@ -147,14 +147,14 @@ void ShowHardwareLoading(bool loading) } } - bool _appsLoading; + bool _appsLoading { get { return _appDownloads.IsLoadingFeed; } } FluentLabel _appsLoadingText; BusyBar _appsBusy; /// Downloads the online feed in the background, falling back to the embedded copy. void GetFeedAsync() { - if (_appsLoading) return; + if (!_appDownloads.TryBeginFeedLoad()) return; CaptureUi(); SetAppsLoading(true); @@ -214,9 +214,8 @@ void ApplyFeed(Tuple online) void SetAppsLoading(bool loading) { - _appsLoading = loading; - btnGetFeed.Enabled = !loading; - if (loading) btnDownloadApps.Enabled = false; + if (!loading) _appDownloads.EndFeedLoad(); + UpdateAppDownloaderControls(); if (_appsHost == null) return; if (_appsLoadingText == null) diff --git a/Optimizer/Forms/MainForm.cs b/Optimizer/Forms/MainForm.cs index 3a09b15..2f5fc4a 100644 --- a/Optimizer/Forms/MainForm.cs +++ b/Optimizer/Forms/MainForm.cs @@ -2303,7 +2303,8 @@ private void PopulateEmbeddedFeed() } catch (Exception ex) { - btnDownloadApps.Enabled = false; + _appsFeedAvailable = false; + UpdateAppDownloaderControls(); txtFeedError.Visible = true; LayoutAppsTab(); @@ -2424,7 +2425,8 @@ private void PopulateFeed(string feed, Func openImage) foreach (Control group in feedGroups) group.ResumeLayout(); } - btnDownloadApps.Enabled = true; + _appsFeedAvailable = true; + UpdateAppDownloaderControls(); txtFeedError.Visible = false; OnAppsFeedPopulated(); } @@ -4528,18 +4530,14 @@ private void chkReadOnly_CheckedChanged(object sender, EventArgs e) private void RenderAppDownloaderBusy() { - btnDownloadApps.Enabled = false; - changeDownDirB.Enabled = false; - txtDownloadFolder.ReadOnly = true; + UpdateAppDownloaderControls(); linkWarnings.Visible = false; } private void RenderAppDownloaderFree() { - btnDownloadApps.Enabled = true; - changeDownDirB.Enabled = true; - txtDownloadFolder.ReadOnly = false; + UpdateAppDownloaderControls(); UpdateGoToDownloadsButtonState(); linkWarnings.Visible = !string.IsNullOrEmpty(downloadLog); @@ -4554,70 +4552,73 @@ private void RenderAppDownloaderFree() private async void btnDownloadApps_Click(object sender, EventArgs e) { + if (_appDownloads.IsBusy || !_appsFeedAvailable) return; + if (string.IsNullOrWhiteSpace(txtDownloadFolder.Text) || !Directory.Exists(txtDownloadFolder.Text)) { FluentMessageBox.Show(OptionsHelper.TranslationList["downloadDirInvalid"].ToString(), "Optimizer", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } - RenderAppDownloaderBusy(); - maxCount = 0; + AppInfo[] selectedApps = AppsFromFeed.Where(app => + { + if (app == null || string.IsNullOrEmpty(app.Tag)) return false; + MoonCheck check = appsTab.Controls.Find(app.Tag, true).FirstOrDefault() as MoonCheck; + return check != null && check.Checked; + }).ToArray(); + AppDownloadState.Batch batch = _appDownloads.TryBeginDownload(selectedApps, txtDownloadFolder.Text, c64.Checked, cAutoInstall.Checked); + if (batch == null) return; + + maxCount = batch.Apps.Count; count = 0; downloadLog = string.Empty; try { + RenderAppDownloaderBusy(); List downloadedInstallers = new List(); - foreach (Control c in Utilities.GetSelfAndChildrenRecursive(appsTab)) - { - if (c.Name == "cAutoInstall") continue; - if (c is MoonCheck && ((MoonCheck)c).Checked) maxCount++; - } - - foreach (AppInfo x in AppsFromFeed) + foreach (AppInfo x in batch.Apps) { - if (string.IsNullOrEmpty(x.Tag)) continue; - Control[] matches = appsTab.Controls.Find(x.Tag, true); - if (matches.Length == 0) continue; - - MoonCheck currentCheck = matches[0] as MoonCheck; - if (currentCheck == null || !currentCheck.Checked) continue; - + if (IsDisposed || Disposing) return; appNameTemp = x.Title; string downloadedFile = null; + count++; + progressDownloader.Value = 0; + progressDownloader.Style = ProgressBarStyle.Marquee; + txtDownloadStatus.Text = string.Format("({1}/{2}) - {0} ...", appNameTemp, count, maxCount); - if (c64.Checked) + if (batch.Prefer64) { - count++; if (string.IsNullOrEmpty(x.Link64)) { downloadLog += "• " + x.Title + ":" + Environment.NewLine + OptionsHelper.TranslationList["no64Download"] + Environment.NewLine + Environment.NewLine; - downloadedFile = await DownloadApp(x, false); + downloadedFile = await DownloadApp(x, false, batch.Folder); } else { - downloadedFile = await DownloadApp(x, true); + downloadedFile = await DownloadApp(x, true, batch.Folder); } } else { - count++; if (!string.IsNullOrEmpty(x.Link)) - downloadedFile = await DownloadApp(x, false); + downloadedFile = await DownloadApp(x, false, batch.Folder); else downloadLog += "• " + x.Title + ":" + Environment.NewLine + OptionsHelper.TranslationList["no32Download"] + Environment.NewLine + Environment.NewLine; } + if (IsDisposed || Disposing) return; if (!string.IsNullOrEmpty(downloadedFile) && !downloadedInstallers.Contains(downloadedFile, StringComparer.OrdinalIgnoreCase)) downloadedInstallers.Add(downloadedFile); } - if (cAutoInstall.Checked) + if (batch.AutoInstall) { count = 0; foreach (string installer in downloadedInstallers) { + if (IsDisposed || Disposing) return; string extension = Path.GetExtension(installer); if (!string.Equals(extension, ".exe", StringComparison.OrdinalIgnoreCase) && !string.Equals(extension, ".msi", StringComparison.OrdinalIgnoreCase)) continue; @@ -4651,18 +4652,24 @@ private async void btnDownloadApps_Click(object sender, EventArgs e) } finally { - foreach (Control c in Utilities.GetSelfAndChildrenRecursive(appsTab)) + _appDownloads.EndDownload(batch); + if (!IsDisposed && !Disposing) { - if (c.Name == "cAutoInstall") continue; - MoonCheck check = c as MoonCheck; - if (check != null && check.Checked) check.Checked = false; - } + foreach (Control c in Utilities.GetSelfAndChildrenRecursive(appsTab)) + { + if (c.Name == "cAutoInstall") continue; + MoonCheck check = c as MoonCheck; + if (check != null && check.Checked) check.Checked = false; + } - RenderAppDownloaderFree(); + progressDownloader.Style = ProgressBarStyle.Continuous; + progressDownloader.Value = 0; + RenderAppDownloaderFree(); + } } } - private async Task DownloadApp(AppInfo app, bool pref64) + private async Task DownloadApp(AppInfo app, bool pref64, string downloadFolder) { string temporaryFile = null; try @@ -4678,7 +4685,7 @@ private async Task DownloadApp(AppInfo app, bool pref64) string safeTitle = Utilities.SanitizeFileFolderName(app.Title).Trim(); if (string.IsNullOrWhiteSpace(safeTitle)) throw new InvalidOperationException("The application name cannot be used as a file name."); - string folder = Path.GetFullPath(txtDownloadFolder.Text); + string folder = downloadFolder; string architecture = pref64 ? "-x64" : "-x86"; string destinationFile = Path.GetFullPath(Path.Combine(folder, safeTitle + architecture + extension)); string folderPrefix = folder.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar; @@ -4691,7 +4698,6 @@ private async Task DownloadApp(AppInfo app, bool pref64) downloader.Headers.Add("User-Agent: Other"); downloader.Encoding = Encoding.UTF8; downloader.DownloadProgressChanged += Downloader_DownloadProgressChanged; - downloader.DownloadFileCompleted += Downloader_DownloadFileCompleted; await downloader.DownloadFileTaskAsync(downloadUri, temporaryFile); } @@ -4719,39 +4725,22 @@ private async Task DownloadApp(AppInfo app, bool pref64) } } - private void Downloader_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) - { - this.BeginInvoke((MethodInvoker)delegate - { - //txtDownloadStatus.Text = "Finished"; - }); - } - - int tempProgress; private void Downloader_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { - this.BeginInvoke((MethodInvoker)delegate - { - double bytesIn = double.Parse(e.BytesReceived.ToString()); - double totalBytes = double.Parse(e.TotalBytesToReceive.ToString()); - double percentage = bytesIn / totalBytes * 100; + if (IsDisposed || Disposing || !_appDownloads.IsDownloading) return; - tempProgress = int.Parse(Math.Truncate(percentage).ToString()); - - // if Content-Length header is missing, just show an animation - if (Math.Abs(tempProgress) > 100) - { - txtDownloadStatus.Text = string.Format("({1}/{2}) - {0} ...", appNameTemp, count, maxCount); - progressDownloader.Style = ProgressBarStyle.Marquee; - } - // if not, show actual progress - else - { - txtDownloadStatus.Text = string.Format("({1}/{2}) - {0} - {3} / {4}", appNameTemp, count, maxCount, ByteSize.FromBytes(e.BytesReceived).ToString("MB"), ByteSize.FromBytes(e.TotalBytesToReceive).ToString("MB")); - progressDownloader.Style = ProgressBarStyle.Continuous; - progressDownloader.Value = tempProgress; - } - }); + int? percentage = AppDownloadProgress.Percentage(e.BytesReceived, e.TotalBytesToReceive); + if (!percentage.HasValue) + { + txtDownloadStatus.Text = string.Format("({1}/{2}) - {0} ...", appNameTemp, count, maxCount); + progressDownloader.Style = ProgressBarStyle.Marquee; + } + else + { + txtDownloadStatus.Text = string.Format("({1}/{2}) - {0} - {3} / {4}", appNameTemp, count, maxCount, ByteSize.FromBytes(e.BytesReceived).ToString("MB"), ByteSize.FromBytes(e.TotalBytesToReceive).ToString("MB")); + progressDownloader.Style = ProgressBarStyle.Continuous; + progressDownloader.Value = percentage.Value; + } } private void button5_Click(object sender, EventArgs e) diff --git a/Optimizer/Optimizer.csproj b/Optimizer/Optimizer.csproj index e49c3bb..84c6119 100644 --- a/Optimizer/Optimizer.csproj +++ b/Optimizer/Optimizer.csproj @@ -86,6 +86,8 @@ + + Component @@ -493,4 +495,4 @@ --> - \ No newline at end of file +