diff --git a/Source/LibationFileManager/Configuration.PersistentSettings.cs b/Source/LibationFileManager/Configuration.PersistentSettings.cs index f5ce0adb..cffb3817 100644 --- a/Source/LibationFileManager/Configuration.PersistentSettings.cs +++ b/Source/LibationFileManager/Configuration.PersistentSettings.cs @@ -415,6 +415,21 @@ public partial class Configuration [Description("Save all podcast episodes in a series to the series parent folder?")] public bool SavePodcastsToParentFolder { get => GetNonString(defaultValue: false); set => SetNonString(value); } + [Description("Auto-scroll the download queue to keep active downloads in view.")] + public bool AutoScrollQueue { get => GetNonString(defaultValue: true); set => SetNonString(value); } + + [Description("Maximum number of books to download and decrypt simultaneously. Defaults to the number of logical processors.")] + public int MaxConcurrentDownloads + { + get + { + var value = GetNonString(defaultValue: 0); + // Treat 0 or 1 as "use default" — 1 may have been written by an earlier bug. + return value <= 1 ? Environment.ProcessorCount : value; + } + set => SetNonString(Math.Max(2, value)); + } + [Description("Global download speed limit in bytes per second.")] public long DownloadSpeedLimit { diff --git a/Source/LibationUiBase/ProcessQueue/ProcessQueueViewModel.cs b/Source/LibationUiBase/ProcessQueue/ProcessQueueViewModel.cs index 40ff26fc..2db0e60d 100644 --- a/Source/LibationUiBase/ProcessQueue/ProcessQueueViewModel.cs +++ b/Source/LibationUiBase/ProcessQueue/ProcessQueueViewModel.cs @@ -1,4 +1,4 @@ -using ApplicationServices; +using ApplicationServices; using DataLayer; using FileLiberator; using LibationFileManager; @@ -8,6 +8,7 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; +using System.Threading; using System.Threading.Tasks; namespace LibationUiBase.ProcessQueue; @@ -40,11 +41,19 @@ public class ProcessQueueViewModel : ReactiveObject Queue.QueuedCountChanged += Queue_QueuedCountChanged; Queue.CompletedCountChanged += Queue_CompletedCountChanged; SpeedLimit = Configuration.Instance.DownloadSpeedLimit / 1024m / 1024; + MaxConcurrentDownloads = Configuration.Instance.MaxConcurrentDownloads; + AutoScrollQueue = Configuration.Instance.AutoScrollQueue; + MultiThreadEnabled = true; } public int CompletedCount { get => field; private set { RaiseAndSetIfChanged(ref field, value); RaisePropertyChanged(nameof(AnyCompleted)); } } public int QueuedCount { get => field; private set { this.RaiseAndSetIfChanged(ref field, value); RaisePropertyChanged(nameof(AnyQueued)); } } public int ErrorCount { get => field; private set { RaiseAndSetIfChanged(ref field, value); RaisePropertyChanged(nameof(AnyErrors)); } } + public int MaxConcurrentDownloads { get => field; set { RaiseAndSetIfChanged(ref field, value); Configuration.Instance.MaxConcurrentDownloads = value; } } + public bool AutoScrollQueue { get => field; set { RaiseAndSetIfChanged(ref field, value); Configuration.Instance.AutoScrollQueue = value; } } + public bool MultiThreadEnabled { get => field; set => RaiseAndSetIfChanged(ref field, value); } + + private int EffectiveConcurrentDownloads => MultiThreadEnabled ? Math.Max(2, MaxConcurrentDownloads) : 1; public string? RunningTime { get => field; set => RaiseAndSetIfChanged(ref field, value); } public bool ProgressBarVisible { get => field; set => RaiseAndSetIfChanged(ref field, value); } public bool AnyCompleted => CompletedCount > 0; @@ -69,8 +78,9 @@ public class ProcessQueueViewModel : ReactiveObject : 0; config.DownloadSpeedLimit = (long)(_speedLimit * 1024 * 1024); - if (Queue.Current is ProcessBookViewModel currentBook) - currentBook.Configuration.DownloadSpeedLimit = config.DownloadSpeedLimit; + // Apply to all currently active books + foreach (var activeBook in Queue.Active.OfType()) + activeBook.Configuration.DownloadSpeedLimit = config.DownloadSpeedLimit; SpeedLimitIncrement = _speedLimit > 100 ? 10 : _speedLimit > 10 ? 1 @@ -535,97 +545,123 @@ public class ProcessQueueViewModel : ReactiveObject RunningTime = string.Empty; ProgressBarVisible = true; var startingTime = DateTime.Now; + + // Shared state written from parallel book tasks — protected by _resultLock bool shownLicenseGuidanceMessage = false; bool shownWidevineGuidanceMessage = false; bool shownDiskFullMessage = false; - // Bounds the daily-limit deferral rotation, so a book can never be shuffled to the back forever. - int consecutiveDeferrals = 0; + var _resultLock = new object(); + using var abortCts = new CancellationTokenSource(); + var activeTasks = new HashSet(); - using var counterTimer = new System.Threading.Timer(_ => RunningTime = timeToStr(DateTime.Now - startingTime), null, 0, 500); + using var counterTimer = new Timer(_ => RunningTime = timeToStr(DateTime.Now - startingTime), null, 0, 500); - while (Queue.MoveNext()) + async Task ProcessBookAsync(ProcessBookViewModel book) { - if (Queue.Current is not ProcessBookViewModel nextBook) - { - Serilog.Log.Logger.Information("Current queue item is empty."); - continue; - } + Serilog.Log.Logger.Information("Begin processing queued item: '{item_LibraryBook}'", book.LibraryBook); + ProcessStart?.Invoke(this, book); - // Checked here rather than at queueing time so the queue keeps its contents and the user can - // change the limit mid-run. Deferral keeps a mixed queue moving under "Plus titles only". - var gate = await WaitForDailyLimitAsync(nextBook, consecutiveDeferrals); + var result = await book.ProcessOneAsync(); - if (gate is DailyLimitGate.Defer) - { - consecutiveDeferrals++; - RequeueLast(nextBook); - continue; - } - - consecutiveDeferrals = 0; - - if (gate is DailyLimitGate.Cancelled) - { - Serilog.Log.Logger.Information("Queue was cancelled while waiting on the daily download limit."); - nextBook.Result = ProcessBookResult.Cancelled; - nextBook.Status = ProcessBookStatus.Cancelled; - continue; - } - - Serilog.Log.Logger.Information("Begin processing queued item: '{item_LibraryBook}'", nextBook.LibraryBook); - SpeedLimit = nextBook.Configuration.DownloadSpeedLimit / 1024m / 1024; - ProcessStart?.Invoke(this, nextBook); - var result = await nextBook.ProcessOneAsync(); - - Serilog.Log.Logger.Information("Completed processing queued item: '{item_LibraryBook}' with result: {result}", nextBook.LibraryBook, result); + Serilog.Log.Logger.Information("Completed processing: '{item_LibraryBook}' result: {result}", book.LibraryBook, result); if (result == ProcessBookResult.ValidationFail) - Queue.ClearCurrent(); - else if (result == ProcessBookResult.FailedAbort) - Queue.ClearQueue(); - // Stop the whole queue on first real disk-full write (local or network); do not retry hundreds of titles. - else if (result == ProcessBookResult.DiskFull) { - if (!shownDiskFullMessage) - { - await MessageBoxBase.Show( - DiskFullUserMessage.BuildQueueStoppedBody(), - DiskFullUserMessage.DialogCaption, - MessageBoxButtons.OK, - MessageBoxIcon.Warning); - shownDiskFullMessage = true; - } - Queue.ClearQueue(); + Queue.RemoveActive(book); } - else if (result == ProcessBookResult.FailedSkip) - await nextBook.LibraryBook.UpdateBookStatusAsync(LiberatedStatus.Error); - else if (!shownLicenseGuidanceMessage - && (result == ProcessBookResult.LicenseDeniedPossibleOutage - || (result == ProcessBookResult.LicenseDenied && nextBook.LibraryBook.IsAudiblePlus))) + else { - var body = result == ProcessBookResult.LicenseDeniedPossibleOutage - ? ContentLicenseDeniedUserMessage.BuildDialogBodyForPossibleOutage(nextBook.LibraryBook.Book.TitleWithSubtitle) - : ContentLicenseDeniedUserMessage.BuildDialogBodyForPlusCatalog(nextBook.LibraryBook.Book.TitleWithSubtitle); - await MessageBoxBase.Show( - body, - ContentLicenseDeniedUserMessage.DialogCaption, - MessageBoxButtons.OK, - MessageBoxIcon.Asterisk); - shownLicenseGuidanceMessage = true; - } - else if (!shownWidevineGuidanceMessage && result == ProcessBookResult.WidevineRecommended) - { - await MessageBoxBase.Show( - WidevineRecommendationUserMessage.BuildDialogBody(nextBook.LibraryBook.Book.TitleWithSubtitle), - WidevineRecommendationUserMessage.DialogCaption, - MessageBoxButtons.OK, - MessageBoxIcon.Asterisk); - shownWidevineGuidanceMessage = true; - } - ProcessEnd?.Invoke(this, nextBook); - } - Serilog.Log.Logger.Information("Completed processing queue"); + Queue.MarkCompleted(book); + if (result == ProcessBookResult.FailedAbort) + { + abortCts.Cancel(); + Queue.ClearQueue(); + } + else if (result == ProcessBookResult.DiskFull) + { + abortCts.Cancel(); + Queue.ClearQueue(); + bool show; + lock (_resultLock) { show = !shownDiskFullMessage; shownDiskFullMessage = true; } + if (show) + await MessageBoxBase.Show( + DiskFullUserMessage.BuildQueueStoppedBody(), + DiskFullUserMessage.DialogCaption, + MessageBoxButtons.OK, + MessageBoxIcon.Warning); + } + else if (result == ProcessBookResult.FailedSkip) + { + await book.LibraryBook.UpdateBookStatusAsync(LiberatedStatus.Error); + } + else if (result == ProcessBookResult.LicenseDeniedPossibleOutage + || (result == ProcessBookResult.LicenseDenied && book.LibraryBook.IsAudiblePlus)) + { + bool show; + lock (_resultLock) { show = !shownLicenseGuidanceMessage; shownLicenseGuidanceMessage = true; } + if (show) + { + var body = result == ProcessBookResult.LicenseDeniedPossibleOutage + ? ContentLicenseDeniedUserMessage.BuildDialogBodyForPossibleOutage(book.LibraryBook.Book.TitleWithSubtitle) + : ContentLicenseDeniedUserMessage.BuildDialogBodyForPlusCatalog(book.LibraryBook.Book.TitleWithSubtitle); + await MessageBoxBase.Show( + body, + ContentLicenseDeniedUserMessage.DialogCaption, + MessageBoxButtons.OK, + MessageBoxIcon.Asterisk); + } + } + else if (result == ProcessBookResult.WidevineRecommended) + { + bool show; + lock (_resultLock) { show = !shownWidevineGuidanceMessage; shownWidevineGuidanceMessage = true; } + if (show) + await MessageBoxBase.Show( + WidevineRecommendationUserMessage.BuildDialogBody(book.LibraryBook.Book.TitleWithSubtitle), + WidevineRecommendationUserMessage.DialogCaption, + MessageBoxButtons.OK, + MessageBoxIcon.Asterisk); + } + } + + ProcessEnd?.Invoke(this, book); + } + + while (true) + { + activeTasks.RemoveWhere(t => t.IsCompleted); + + if (abortCts.IsCancellationRequested) + { + await Task.WhenAll(activeTasks); + break; + } + + // If at capacity, wait for a slot to open before trying to dequeue more + if (activeTasks.Count >= EffectiveConcurrentDownloads) + { + await Task.WhenAny(activeTasks); + continue; + } + + if (Queue.TryDequeueNext(out var nextBook)) + { + activeTasks.Add(ProcessBookAsync(nextBook)); + continue; + } + + // Queue is empty; if no tasks are running we are done + if (activeTasks.Count == 0) + break; + + // Items still in flight — wait for one to finish; new items may arrive while waiting + await Task.WhenAny(activeTasks); + } + + await Task.WhenAll(activeTasks); + + Serilog.Log.Logger.Information("Completed processing queue"); Queue_CompletedCountChanged(this, 0); ProgressBarVisible = false; } diff --git a/Source/LibationUiBase/TrackedQueue[T].cs b/Source/LibationUiBase/TrackedQueue[T].cs index 799d80b2..f9e0a3f1 100644 --- a/Source/LibationUiBase/TrackedQueue[T].cs +++ b/Source/LibationUiBase/TrackedQueue[T].cs @@ -1,7 +1,8 @@ -using System; +using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; +using System.Diagnostics.CodeAnalysis; using System.Linq; namespace LibationUiBase; @@ -16,14 +17,14 @@ public enum QueuePosition /* * This data structure is like lifting a metal chain one link at a time. - * Each time you grab and lift a new link (MoveNext call): - * - * 1) you're holding a new link in your hand (Current) - * 2) the remaining chain to be lifted shortens by 1 link (Queued) - * 3) the pile of chain at your feet grows by 1 link (Completed) - * + * Each time you grab and lift a new link (TryDequeueNext call): + * + * 1) you're holding new links in your hand (Active) + * 2) the remaining chain to be lifted shortens (Queued) + * 3) as links are finished, the pile at your feet grows (Completed) + * * The index is the link position from the first link you lifted to the - * last one in the chain. + * last one in the chain. */ public class TrackedQueue : IReadOnlyCollection, IList, INotifyCollectionChanged where T : class { @@ -31,13 +32,16 @@ public class TrackedQueue : IReadOnlyCollection, IList, INotifyCollectionC public event EventHandler? QueuedCountChanged; public event NotifyCollectionChangedEventHandler? CollectionChanged; - public T? Current { get; private set; } + /// Returns the first active item for backward compatibility (e.g. speed limit display). + public T? Current => _active.FirstOrDefault(); + public IReadOnlyList Active => _active; public IReadOnlyList Completed => _completed; private List Queued { get; } = new(); + private readonly List _active = new(); private readonly List _completed = new(); private readonly object lockObject = new(); - private int QueueStartIndex => Completed.Count + (Current is null ? 0 : 1); + private int QueueStartIndex => Completed.Count + _active.Count; public T this[int index] { @@ -45,10 +49,15 @@ public class TrackedQueue : IReadOnlyCollection, IList, INotifyCollectionC { lock (lockObject) { - return index < Completed.Count ? Completed[index] - : index == Completed.Count && Current is not null ? Current - : index < Count ? Queued[index - QueueStartIndex] - : throw new IndexOutOfRangeException(); + if (index < Completed.Count) + return Completed[index]; + int activeOffset = index - Completed.Count; + if (activeOffset < _active.Count) + return _active[activeOffset]; + int queueOffset = index - QueueStartIndex; + if (queueOffset >= 0 && queueOffset < Queued.Count) + return Queued[queueOffset]; + throw new IndexOutOfRangeException(); } } } @@ -69,8 +78,12 @@ public class TrackedQueue : IReadOnlyCollection, IList, INotifyCollectionC lock (lockObject) { int index = _completed.IndexOf(item); - if (index < 0 && item == Current) - index = Completed.Count; + if (index < 0) + { + int activeIdx = _active.IndexOf(item); + if (activeIdx >= 0) + index = Completed.Count + activeIdx; + } if (index < 0) { index = Queued.IndexOf(item); @@ -123,15 +136,72 @@ public class TrackedQueue : IReadOnlyCollection, IList, INotifyCollectionC return false; } - public void ClearCurrent() + /// + /// Pops the next item from the queue into the Active set. + /// Returns false when the queue is empty. + /// + public bool TryDequeueNext([MaybeNullWhen(false)] out T item) { - T? current; + int queuedCount; lock (lockObject) { - current = Current; - Current = null; + if (Queued.Count == 0) + { + item = null; + return false; + } + item = Queued[0]; + Queued.RemoveAt(0); + _active.Add(item); + queuedCount = Queued.Count; } - CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, current, _completed.Count)); + QueuedCountChanged?.Invoke(this, queuedCount); + return true; + } + + /// + /// Moves an active item into Completed when its processing succeeds or fails normally. + /// + public void MarkCompleted(T item) + { + int completedCount; + lock (lockObject) + { + _active.Remove(item); + _completed.Add(item); + completedCount = _completed.Count; + } + CompletedCountChanged?.Invoke(this, completedCount); + } + + /// + /// Removes an active item from the queue display entirely (used for ValidationFail). + /// + public void RemoveActive(T item) + { + int removedIndex; + lock (lockObject) + { + removedIndex = _active.IndexOf(item); + if (removedIndex >= 0) + _active.RemoveAt(removedIndex); + } + if (removedIndex >= 0) + CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, _completed.Count + removedIndex)); + } + + /// Legacy single-item sequential accessor — kept for compatibility. + public void ClearCurrent() + { + T? first; + lock (lockObject) + { + first = _active.FirstOrDefault(); + if (first != null) + _active.Remove(first); + } + if (first != null) + CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, first, _completed.Count)); } public void ClearQueue() @@ -181,28 +251,32 @@ public class TrackedQueue : IReadOnlyCollection, IList, INotifyCollectionC CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move, item, QueueStartIndex + newIndex, QueueStartIndex + oldIndex)); } + /// + /// Legacy sequential MoveNext — completes the first active item and dequeues the next. + /// Only valid when at most one item is active at a time. + /// public bool MoveNext() { + T? oldActive; int completedCount = 0, queuedCount = 0; bool completedChanged = false; try { lock (lockObject) { - if (Current != null) + oldActive = _active.FirstOrDefault(); + if (oldActive != null) { - _completed.Add(Current); + _active.Remove(oldActive); + _completed.Add(oldActive); completedCount = _completed.Count; completedChanged = true; } if (Queued.Count == 0) - { - Current = null; return false; - } - Current = Queued[0]; + var next = Queued[0]; Queued.RemoveAt(0); - + _active.Add(next); queuedCount = Queued.Count; return true; } @@ -231,8 +305,7 @@ public class TrackedQueue : IReadOnlyCollection, IList, INotifyCollectionC { lock (lockObject) { - if (Current is null) return Completed.Concat(Queued); - return Completed.Concat([Current]).Concat(Queued); + return _completed.Concat(_active).Concat(Queued); } } diff --git a/Source/LibationWinForms/ProcessQueue/ProcessQueueControl.Designer.cs b/Source/LibationWinForms/ProcessQueue/ProcessQueueControl.Designer.cs index b5bf91f5..c72a37ae 100644 --- a/Source/LibationWinForms/ProcessQueue/ProcessQueueControl.Designer.cs +++ b/Source/LibationWinForms/ProcessQueue/ProcessQueueControl.Designer.cs @@ -42,6 +42,8 @@ this.tabPage1 = new System.Windows.Forms.TabPage(); this.virtualFlowControl2 = new LibationWinForms.ProcessQueue.VirtualFlowControl(); this.panel1 = new System.Windows.Forms.Panel(); + this.autoScrollChk = new System.Windows.Forms.CheckBox(); + this.multiThreadChk = new System.Windows.Forms.CheckBox(); this.label1 = new System.Windows.Forms.Label(); this.numericUpDown1 = new LibationWinForms.ProcessQueue.NumericUpDownSuffix(); this.btnCleanFinished = new System.Windows.Forms.Button(); @@ -150,35 +152,61 @@ this.virtualFlowControl2.Dock = System.Windows.Forms.DockStyle.Fill; this.virtualFlowControl2.Location = new System.Drawing.Point(3, 3); this.virtualFlowControl2.Name = "virtualFlowControl2"; - this.virtualFlowControl2.Size = new System.Drawing.Size(390, 424); + this.virtualFlowControl2.Size = new System.Drawing.Size(390, 401); this.virtualFlowControl2.TabIndex = 3; // // panel1 // this.panel1.BackColor = System.Drawing.SystemColors.Control; this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.panel1.Controls.Add(this.autoScrollChk); + this.panel1.Controls.Add(this.multiThreadChk); this.panel1.Controls.Add(this.label1); this.panel1.Controls.Add(this.numericUpDown1); this.panel1.Controls.Add(this.btnCleanFinished); this.panel1.Controls.Add(this.cancelAllBtn); this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom; - this.panel1.Location = new System.Drawing.Point(3, 427); + this.panel1.Location = new System.Drawing.Point(3, 403); this.panel1.Name = "panel1"; - this.panel1.Size = new System.Drawing.Size(390, 29); + this.panel1.Size = new System.Drawing.Size(390, 52); this.panel1.TabIndex = 2; - // + // + // autoScrollChk + // + this.autoScrollChk.Anchor = System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Top; + this.autoScrollChk.AutoSize = true; + this.autoScrollChk.Checked = true; + this.autoScrollChk.CheckState = System.Windows.Forms.CheckState.Checked; + this.autoScrollChk.Location = new System.Drawing.Point(82, 5); + this.autoScrollChk.Name = "autoScrollChk"; + this.autoScrollChk.TabIndex = 6; + this.autoScrollChk.Text = "Auto-scroll"; + this.autoScrollChk.UseVisualStyleBackColor = true; + // + // multiThreadChk + // + this.multiThreadChk.Anchor = System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Top; + this.multiThreadChk.AutoSize = true; + this.multiThreadChk.Checked = true; + this.multiThreadChk.CheckState = System.Windows.Forms.CheckState.Checked; + this.multiThreadChk.Location = new System.Drawing.Point(82, 28); + this.multiThreadChk.Name = "multiThreadChk"; + this.multiThreadChk.TabIndex = 7; + this.multiThreadChk.Text = "Parallel downloads"; + this.multiThreadChk.UseVisualStyleBackColor = true; + // // label1 - // + // this.label1.Anchor = System.Windows.Forms.AnchorStyles.Right; this.label1.AutoSize = true; - this.label1.Location = new System.Drawing.Point(148, 6); + this.label1.Location = new System.Drawing.Point(148, 30); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(54, 15); this.label1.TabIndex = 5; this.label1.Text = "DL Limit:"; - // + // // numericUpDown1 - // + // this.numericUpDown1.Anchor = System.Windows.Forms.AnchorStyles.Right; this.numericUpDown1.DecimalPlaces = 1; this.numericUpDown1.Increment = new decimal(new int[] { @@ -186,7 +214,7 @@ 0, 0, 65536}); - this.numericUpDown1.Location = new System.Drawing.Point(208, 2); + this.numericUpDown1.Location = new System.Drawing.Point(208, 26); this.numericUpDown1.Maximum = new decimal(new int[] { 999, 0, @@ -204,24 +232,24 @@ 0, 0}); this.numericUpDown1.ValueChanged += new System.EventHandler(this.numericUpDown1_ValueChanged); - // + // // btnCleanFinished - // - this.btnCleanFinished.Dock = System.Windows.Forms.DockStyle.Right; + // + this.btnCleanFinished.Anchor = System.Windows.Forms.AnchorStyles.Right | System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom; this.btnCleanFinished.Location = new System.Drawing.Point(298, 0); this.btnCleanFinished.Name = "btnCleanFinished"; - this.btnCleanFinished.Size = new System.Drawing.Size(90, 23); + this.btnCleanFinished.Size = new System.Drawing.Size(90, 50); this.btnCleanFinished.TabIndex = 3; this.btnCleanFinished.Text = "Clear Finished"; this.btnCleanFinished.UseVisualStyleBackColor = true; this.btnCleanFinished.Click += new System.EventHandler(this.btnClearFinished_Click); - // + // // cancelAllBtn - // - this.cancelAllBtn.Dock = System.Windows.Forms.DockStyle.Left; + // + this.cancelAllBtn.Anchor = System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom; this.cancelAllBtn.Location = new System.Drawing.Point(0, 0); this.cancelAllBtn.Name = "cancelAllBtn"; - this.cancelAllBtn.Size = new System.Drawing.Size(75, 23); + this.cancelAllBtn.Size = new System.Drawing.Size(78, 50); this.cancelAllBtn.TabIndex = 2; this.cancelAllBtn.Text = "Cancel All"; this.cancelAllBtn.UseVisualStyleBackColor = true; @@ -364,5 +392,7 @@ private System.Windows.Forms.Button logCopyBtn; private NumericUpDownSuffix numericUpDown1; private System.Windows.Forms.Label label1; + private System.Windows.Forms.CheckBox autoScrollChk; + private System.Windows.Forms.CheckBox multiThreadChk; } } diff --git a/Source/LibationWinForms/ProcessQueue/ProcessQueueControl.cs b/Source/LibationWinForms/ProcessQueue/ProcessQueueControl.cs index aabe7d4c..63ad0be1 100644 --- a/Source/LibationWinForms/ProcessQueue/ProcessQueueControl.cs +++ b/Source/LibationWinForms/ProcessQueue/ProcessQueueControl.cs @@ -38,23 +38,21 @@ internal partial class ProcessQueueControl : UserControl ViewModel.PropertyChanged += ProcessQueue_PropertyChanged; ViewModel.LogEntries.CollectionChanged += LogEntries_CollectionChanged; ViewModel.ProcessStart += Book_ProcessStart; + autoScrollChk.CheckedChanged += (s, e) => ViewModel.AutoScrollQueue = autoScrollChk.Checked; + multiThreadChk.CheckedChanged += (s, e) => ViewModel.MultiThreadEnabled = multiThreadChk.Checked; ProcessQueue_PropertyChanged(this, new PropertyChangedEventArgs(null)); } private void Book_ProcessStart(object? sender, ProcessBookViewModel e) { + if (!ViewModel.AutoScrollQueue) return; Invoke(() => { - if (ViewModel.Queue?.IndexOf(e) is int newtBookIndex && newtBookIndex > 0 && itemIsVisible(newtBookIndex - 1)) - { - // Only scroll the new item into view if the previous item is visible. - // This allows users to scroll through the queue without being interrupted. - virtualFlowControl2.ScrollIntoView(newtBookIndex); - } + // Pin the first active download to the top so all parallel in-progress items are visible. + int firstActiveIndex = ViewModel.Queue.Completed.Count; + if (firstActiveIndex < ViewModel.Queue.Count) + virtualFlowControl2.ScrollToTop(firstActiveIndex); }); - - bool itemIsVisible(int newtBookIndex) - => virtualFlowControl2.FirstRealizedIndex <= newtBookIndex && virtualFlowControl2.LastRealizedIndex >= newtBookIndex; } private void LogEntries_CollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) @@ -131,6 +129,10 @@ internal partial class ProcessQueueControl : UserControl numericUpDown1.Increment = ViewModel.SpeedLimitIncrement; numericUpDown1.DecimalPlaces = ViewModel.SpeedLimit >= 10 ? 0 : ViewModel.SpeedLimit >= 1 ? 1 : 2; } + if (e.PropertyName is null or nameof(ViewModel.AutoScrollQueue)) + autoScrollChk.Checked = ViewModel.AutoScrollQueue; + if (e.PropertyName is null or nameof(ViewModel.MultiThreadEnabled)) + multiThreadChk.Checked = ViewModel.MultiThreadEnabled; } /// diff --git a/Source/LibationWinForms/ProcessQueue/VirtualFlowControl.cs b/Source/LibationWinForms/ProcessQueue/VirtualFlowControl.cs index 49f44e20..199b12a5 100644 --- a/Source/LibationWinForms/ProcessQueue/VirtualFlowControl.cs +++ b/Source/LibationWinForms/ProcessQueue/VirtualFlowControl.cs @@ -230,6 +230,17 @@ internal partial class VirtualFlowControl : UserControl } } + /// + /// Scrolls so that is pinned to the top of the view, + /// maximising how many items below it (e.g. parallel active downloads) are visible. + /// + public void ScrollToTop(int index) + { + if (index < 0 || index >= VirtualControlCount) + return; + SetScrollPosition(index * VirtualControlHeight); + } + /// /// Calculated the virtual controls that are in view at the current scroll position and windows size, /// positions to simulate scroll activity, then fires updates the controls with