From 87661582e33c3263d40111427e7f0c0aca3373e2 Mon Sep 17 00:00:00 2001 From: sr55 Date: Sat, 15 Jan 2011 19:11:12 +0000 Subject: [PATCH] WinGui: - Switch over to the new queue processor service. Please report any bugs found in the queue system. It may be a bit buggy until all the kinks are worked out git-svn-id: svn://localhost/HandBrake/trunk@3745 b64f7644-9d1e-0410-96f1-a4d463321fa5 --- win/C#/Functions/Main.cs | 11 +- .../HandBrake.ApplicationServices.csproj | 1 - .../Services/Encode.cs | 39 +- .../Services/Interfaces/IQueue.cs | 146 ------- .../Services/Queue.cs | 465 --------------------- .../Services/QueueManager.cs | 22 +- .../Services/QueueProcessor.cs | 2 +- win/C#/frmActivityWindow.cs | 4 +- win/C#/frmMain.cs | 126 +++--- win/C#/frmPreview.cs | 2 +- win/C#/frmQueue.cs | 81 ++-- 11 files changed, 140 insertions(+), 759 deletions(-) delete mode 100644 win/C#/HandBrake.ApplicationServices/Services/Interfaces/IQueue.cs delete mode 100644 win/C#/HandBrake.ApplicationServices/Services/Queue.cs diff --git a/win/C#/Functions/Main.cs b/win/C#/Functions/Main.cs index 8f7cea32..d2d7ff5e 100644 --- a/win/C#/Functions/Main.cs +++ b/win/C#/Functions/Main.cs @@ -421,8 +421,10 @@ namespace Handbrake.Functions /// /// The encode Queue. /// - public static void RecoverQueue(IQueue encodeQueue) + public static void RecoverQueue(IQueueProcessor encodeQueue) { + string appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\"); + DialogResult result = DialogResult.None; List queueFiles = CheckQueueRecovery(); if (queueFiles.Count == 1) @@ -442,18 +444,17 @@ namespace Handbrake.Functions { foreach (string file in queueFiles) { - encodeQueue.LoadQueueFromFile(file); // Start Recovery + encodeQueue.QueueManager.RestoreQueue(appDataPath + file); // Start Recovery } } else { if (IsMultiInstance) return; // Don't tamper with the files if we are multi instance - string tempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\"); foreach (string file in queueFiles) { - if (File.Exists(Path.Combine(tempPath, file))) - File.Delete(Path.Combine(tempPath, file)); + if (File.Exists(Path.Combine(appDataPath, file))) + File.Delete(Path.Combine(appDataPath, file)); } } } diff --git a/win/C#/HandBrake.ApplicationServices/HandBrake.ApplicationServices.csproj b/win/C#/HandBrake.ApplicationServices/HandBrake.ApplicationServices.csproj index 8938827b..0801065c 100644 --- a/win/C#/HandBrake.ApplicationServices/HandBrake.ApplicationServices.csproj +++ b/win/C#/HandBrake.ApplicationServices/HandBrake.ApplicationServices.csproj @@ -123,7 +123,6 @@ - diff --git a/win/C#/HandBrake.ApplicationServices/Services/Encode.cs b/win/C#/HandBrake.ApplicationServices/Services/Encode.cs index e2046da9..bc5220e1 100644 --- a/win/C#/HandBrake.ApplicationServices/Services/Encode.cs +++ b/win/C#/HandBrake.ApplicationServices/Services/Encode.cs @@ -131,9 +131,9 @@ namespace HandBrake.ApplicationServices.Services { try { - QueueTask QueueTask = encodeQueueTask as QueueTask; + QueueTask queueTask = encodeQueueTask; - if (QueueTask == null) + if (queueTask == null) { throw new ArgumentNullException("QueueTask was null"); } @@ -147,14 +147,14 @@ namespace HandBrake.ApplicationServices.Services if (enableLogging) { - if (!SetupLogging(QueueTask)) + try { - if (this.EncodeCompleted != null) - this.EncodeCompleted( - this, - new EncodeCompletedEventArgs(false, null, "Unable to Start Encode Logging process.")); - - return; + SetupLogging(queueTask); + } + catch (Exception) + { + IsEncoding = false; + throw; } } @@ -164,7 +164,7 @@ namespace HandBrake.ApplicationServices.Services } string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe"); - ProcessStartInfo cliStart = new ProcessStartInfo(handbrakeCLIPath, QueueTask.Query) + ProcessStartInfo cliStart = new ProcessStartInfo(handbrakeCLIPath, queueTask.Query) { RedirectStandardOutput = true, RedirectStandardError = enableLogging ? true : false, @@ -346,9 +346,7 @@ namespace HandBrake.ApplicationServices.Services private void HbProcessExited(object sender, EventArgs e) { IsEncoding = false; - if (this.EncodeCompleted != null) - this.EncodeCompleted(this, new EncodeCompletedEventArgs(true, null, string.Empty)); - + if (windowsSeven.IsWindowsSeven) { windowsSeven.SetTaskBarProgressToNoProgress(); @@ -371,6 +369,9 @@ namespace HandBrake.ApplicationServices.Services { // This exception doesn't warrent user interaction, but it should be logged (TODO) } + + if (this.EncodeCompleted != null) + this.EncodeCompleted(this, new EncodeCompletedEventArgs(true, null, string.Empty)); } /// @@ -429,10 +430,7 @@ namespace HandBrake.ApplicationServices.Services /// /// The encode QueueTask. /// - /// - /// The setup logging. - /// - private bool SetupLogging(QueueTask encodeQueueTask) + private void SetupLogging(QueueTask encodeQueueTask) { string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs"; string logFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId)); @@ -450,18 +448,15 @@ namespace HandBrake.ApplicationServices.Services fileWriter.WriteLine(Logging.CreateCliLogHeader(encodeQueueTask)); logBuffer.AppendLine(Logging.CreateCliLogHeader(encodeQueueTask)); - - return true; } - catch (Exception exc) + catch (Exception) { if (fileWriter != null) { fileWriter.Close(); fileWriter.Dispose(); } - - return false; + throw; } } diff --git a/win/C#/HandBrake.ApplicationServices/Services/Interfaces/IQueue.cs b/win/C#/HandBrake.ApplicationServices/Services/Interfaces/IQueue.cs deleted file mode 100644 index ed649fd3..00000000 --- a/win/C#/HandBrake.ApplicationServices/Services/Interfaces/IQueue.cs +++ /dev/null @@ -1,146 +0,0 @@ -/* IQueue.cs $ - This file is part of the HandBrake source code. - Homepage: . - It may be used under the terms of the GNU General Public License. */ - -namespace HandBrake.ApplicationServices.Services.Interfaces -{ - using System; - using System.Collections.ObjectModel; - - using HandBrake.ApplicationServices.Model; - - /// - /// The IQueue Interface - /// - public interface IQueue : IEncode - { - /// - /// Fires when the Queue has started - /// - event EventHandler QueueStarted; - - /// - /// Fires when a job is Added, Removed or Re-Ordered. - /// Should be used for triggering an update of the Queue Window. - /// - event EventHandler QueueListChanged; - - /// - /// Fires when a pause to the encode queue has been requested. - /// - event EventHandler QueuePauseRequested; - - /// - /// Fires when the entire encode queue has completed. - /// - event EventHandler QueueCompleted; - - /// - /// Gets or sets the last encode that was processed. - /// - /// - QueueTask LastEncode { get; set; } - - /// - /// Gets a value indicating whether Request Pause - /// - bool Paused { get; } - - /// - /// Gets the current state of the encode queue. - /// - ReadOnlyCollection CurrentQueue { get; } - - /// - /// Gets the number of items in the queue. - /// - int Count { get; } - - /// - /// Adds an item to the queue. - /// - /// - /// The query that will be passed to the HandBrake CLI. - /// - /// - /// The title. - /// - /// - /// The location of the source video. - /// - /// - /// The location where the encoded video will be. - /// - /// - /// Custom job - /// - void Add(string query, int title, string source, string destination, bool customJob); - - /// - /// Removes an item from the queue. - /// - /// The zero-based location of the job in the queue. - void Remove(int index); - - /// - /// Retrieve a job from the queue - /// - /// the job id - /// A job for the given index or blank job object - QueueTask GetJob(int index); - - /// - /// Moves an item up one position in the queue. - /// - /// The zero-based location of the job in the queue. - void MoveUp(int index); - - /// - /// Moves an item down one position in the queue. - /// - /// The zero-based location of the job in the queue. - void MoveDown(int index); - - /// - /// Writes the current state of the queue to a file. - /// - /// The location of the file to write the queue to. - void WriteQueueStateToFile(string file); - - /// - /// Writes the current state of the queue in the form of a batch (.bat) file. - /// - /// - /// The location of the file to write the batch file to. - /// - /// - /// The write batch script to file. - /// - bool WriteBatchScriptToFile(string file); - - /// - /// Reads a serialized XML file that represents a queue of encoding jobs. - /// - /// The location of the file to read the queue from. - void LoadQueueFromFile(string file); - - /// - /// Checks the current queue for an existing instance of the specified destination. - /// - /// The destination of the encode. - /// Whether or not the supplied destination is already in the queue. - bool CheckForDestinationDuplicate(string destination); - - /// - /// Starts encoding the first job in the queue and continues encoding until all jobs - /// have been encoded. - /// - void Start(); - - /// - /// Requests a pause of the encode queue. - /// - void Pause(); - } -} \ No newline at end of file diff --git a/win/C#/HandBrake.ApplicationServices/Services/Queue.cs b/win/C#/HandBrake.ApplicationServices/Services/Queue.cs deleted file mode 100644 index 937e37a7..00000000 --- a/win/C#/HandBrake.ApplicationServices/Services/Queue.cs +++ /dev/null @@ -1,465 +0,0 @@ -/* Queue.cs $ - This file is part of the HandBrake source code. - Homepage: . - It may be used under the terms of the GNU General Public License. */ - -namespace HandBrake.ApplicationServices.Services -{ - using System; - using System.Collections.Generic; - using System.Collections.ObjectModel; - using System.Diagnostics; - using System.IO; - using System.Linq; - using System.Threading; - using System.Windows.Forms; - using System.Xml.Serialization; - - using HandBrake.ApplicationServices.Functions; - using HandBrake.ApplicationServices.Model; - using HandBrake.ApplicationServices.Services.Interfaces; - - /// - /// The HandBrake Queue - /// - public class Queue : Encode, IQueue - { - /// - /// The Queue Job List - /// - private readonly List queue = new List(); - - /// - /// An XML Serializer - /// - private static XmlSerializer serializer; - - /// - /// The Next Job ID - /// - private int nextJobId; - - #region Events - /// - /// Fires when the Queue has started - /// - public event EventHandler QueueStarted; - - /// - /// Fires when a job is Added, Removed or Re-Ordered. - /// Should be used for triggering an update of the Queue Window. - /// - public event EventHandler QueueListChanged; - - /// - /// Fires when a pause to the encode queue has been requested. - /// - public event EventHandler QueuePauseRequested; - - /// - /// Fires when the entire encode queue has completed. - /// - public event EventHandler QueueCompleted; - #endregion - - #region Properties - /// - /// Gets or sets the last encode that was processed. - /// - /// - public QueueTask LastEncode { get; set; } - - /// - /// Gets a value indicating whether Request Pause - /// - public bool Paused { get; private set; } - - /// - /// Gets the current state of the encode queue. - /// - public ReadOnlyCollection CurrentQueue - { - get { return this.queue.AsReadOnly(); } - } - - /// - /// Gets the number of items in the queue. - /// - public int Count - { - get { return this.queue.Count; } - } - #endregion - - #region Queue - - /// - /// Gets and removes the next job in the queue. - /// - /// The job that was removed from the queue. - private QueueTask GetNextJob() - { - QueueTask job = this.queue[0]; - this.LastEncode = job; - this.Remove(0); // Remove the item which we are about to pass out. - - this.SaveQueue(); - - return job; - } - - /// - /// Adds an item to the queue. - /// - /// - /// The query that will be passed to the HandBrake CLI. - /// - /// - /// The title. - /// - /// - /// The location of the source video. - /// - /// - /// The location where the encoded video will be. - /// - /// - /// Custom job - /// - public void Add(string query, int title, string source, string destination, bool customJob) - { - QueueTask newJob = new QueueTask - { - Id = this.nextJobId++, - Title = title, - Query = query, - Source = source, - Destination = destination, - CustomQuery = customJob - }; - - this.queue.Add(newJob); - this.SaveQueue(); - - if (this.QueueListChanged != null) - this.QueueListChanged(this, new EventArgs()); - } - - /// - /// Removes an item from the queue. - /// - /// The zero-based location of the job in the queue. - public void Remove(int index) - { - this.queue.RemoveAt(index); - this.SaveQueue(); - - if (this.QueueListChanged != null) - this.QueueListChanged(this, new EventArgs()); - } - - /// - /// Retrieve a job from the queue - /// - /// the job id - /// A job for the given index or blank job object - public QueueTask GetJob(int index) - { - if (this.queue.Count >= (index + 1)) - return this.queue[index]; - - return new QueueTask(); - } - - /// - /// Moves an item up one position in the queue. - /// - /// The zero-based location of the job in the queue. - public void MoveUp(int index) - { - if (index > 0) - { - QueueTask item = queue[index]; - - queue.RemoveAt(index); - queue.Insert((index - 1), item); - } - - this.SaveQueue(); // Update the queue recovery file - - if (this.QueueListChanged != null) - this.QueueListChanged(this, new EventArgs()); - } - - /// - /// Moves an item down one position in the queue. - /// - /// The zero-based location of the job in the queue. - public void MoveDown(int index) - { - if (index < this.queue.Count - 1) - { - QueueTask item = this.queue[index]; - - this.queue.RemoveAt(index); - this.queue.Insert((index + 1), item); - } - - this.SaveQueue(); // Update the queue recovery file - - if (this.QueueListChanged != null) - this.QueueListChanged(this, new EventArgs()); - } - - /// - /// Save any updates to the main queue file. - /// - public void SaveQueue() - { - string file = Init.InstanceId == 0 - ? "hb_queue_recovery.xml" - : string.Format("hb_queue_recovery{0}.xml", Init.InstanceId); - this.WriteQueueStateToFile(file); - } - - /// - /// Writes the current state of the queue to a file. - /// - /// The location of the file to write the queue to. - public void WriteQueueStateToFile(string file) - { - string appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\"); - string tempPath = file.Contains("hb_queue_recovery") ? appDataPath + file : file; - - try - { - using (FileStream strm = new FileStream(tempPath, FileMode.Create, FileAccess.Write)) - { - if (serializer == null) - serializer = new XmlSerializer(typeof(List)); - serializer.Serialize(strm, queue); - strm.Close(); - strm.Dispose(); - } - } - catch (Exception) - { - return; - } - } - - /// - /// Writes the current state of the queue in the form of a batch (.bat) file. - /// - /// - /// The location of the file to write the batch file to. - /// - /// - /// The write batch script to file. - /// - public bool WriteBatchScriptToFile(string file) - { - string queries = string.Empty; - foreach (QueueTask queueItem in this.queue) - { - string qItem = queueItem.Query; - string fullQuery = '"' + Application.StartupPath + "\\HandBrakeCLI.exe" + '"' + qItem; - - if (queries == string.Empty) - queries = queries + fullQuery; - else - queries = queries + " && " + fullQuery; - } - string strCmdLine = queries; - - if (file != string.Empty) - { - try - { - // Create a StreamWriter and open the file, Write the batch file query to the file and - // Close the stream - using (StreamWriter line = new StreamWriter(file)) - { - line.WriteLine(strCmdLine); - } - - return true; - } - catch (Exception exc) - { - throw new Exception("Unable to write to the file. Please make sure that the location has the correct permissions for file writing.", exc); - } - } - return false; - } - - /// - /// Reads a serialized XML file that represents a queue of encoding jobs. - /// - /// The location of the file to read the queue from. - public void LoadQueueFromFile(string file) - { - string appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\"); - string tempPath = file.Contains("hb_queue_recovery") ? appDataPath + file : file; - - if (File.Exists(tempPath)) - { - using (FileStream strm = new FileStream(tempPath, FileMode.Open, FileAccess.Read)) - { - if (strm.Length != 0) - { - if (serializer == null) - serializer = new XmlSerializer(typeof(List)); - - List list = serializer.Deserialize(strm) as List; - - if (list != null) - foreach (QueueTask item in list) - this.queue.Add(item); - - if (!file.Contains("hb_queue_recovery")) - this.SaveQueue(); - - if (this.QueueListChanged != null) - this.QueueListChanged(this, new EventArgs()); - } - } - } - } - - /// - /// Checks the current queue for an existing instance of the specified destination. - /// - /// The destination of the encode. - /// Whether or not the supplied destination is already in the queue. - public bool CheckForDestinationDuplicate(string destination) - { - return this.queue.Any(checkItem => checkItem.Destination.Contains(destination.Replace("\\\\", "\\"))); - } - - #endregion - - #region Encoding - - /// - /// Starts encoding the first job in the queue and continues encoding until all jobs - /// have been encoded. - /// - public void Start() - { - if (this.Count != 0) - { - if (this.Paused) - this.Paused = false; - else - { - this.Paused = false; - try - { - Thread theQueue = new Thread(this.StartQueue) { IsBackground = true }; - theQueue.Start(); - - if (this.QueueStarted != null) - this.QueueStarted(this, new EventArgs()); - } - catch (Exception exc) - { - throw new Exception("Unable to Start Queue", exc); - } - } - } - } - - /// - /// Requests a pause of the encode queue. - /// - public void Pause() - { - this.Paused = true; - - if (this.QueuePauseRequested != null) - this.QueuePauseRequested(this, new EventArgs()); - } - - /// - /// Run through all the jobs on the queue. - /// - /// Object State - private void StartQueue(object state) - { - // Run through each item on the queue - while (this.Count != 0) - { - QueueTask encJob = this.GetNextJob(); - this.SaveQueue(); // Update the queue recovery file - - Start(encJob, true); - - if (HbProcess == null) - { - return; - } - HbProcess.WaitForExit(); - - this.CopyLog(this.LastEncode.Destination); - - HbProcess.Close(); - HbProcess.Dispose(); - - // Growl - if (Init.GrowlEncode) - GrowlCommunicator.Notify("Encode Completed", - "Put down that cocktail...\nyour Handbrake encode is done."); - - while (this.Paused) // Need to find a better way of doing this. - { - Thread.Sleep(2000); - } - } - this.LastEncode = new QueueTask(); - - if (this.QueueCompleted != null) - this.QueueCompleted(this, new EventArgs()); - - // After the encode is done, we may want to shutdown, suspend etc. - Finish(); - } - - /// - /// Perform an action after an encode. e.g a shutdown, standby, restart etc. - /// - private void Finish() - { - // Growl - if (Init.GrowlQueue) - GrowlCommunicator.Notify("Queue Completed", "Put down that cocktail...\nyour Handbrake queue is done."); - - // Do something whent he encode ends. - switch (Init.CompletionOption) - { - case "Shutdown": - Process.Start("Shutdown", "-s -t 60"); - break; - case "Log Off": - Win32.ExitWindowsEx(0, 0); - break; - case "Suspend": - Application.SetSuspendState(PowerState.Suspend, true, true); - break; - case "Hibernate": - Application.SetSuspendState(PowerState.Hibernate, true, true); - break; - case "Lock System": - Win32.LockWorkStation(); - break; - case "Quit HandBrake": - Application.Exit(); - break; - default: - break; - } - } - - #endregion - } -} \ No newline at end of file diff --git a/win/C#/HandBrake.ApplicationServices/Services/QueueManager.cs b/win/C#/HandBrake.ApplicationServices/Services/QueueManager.cs index 5edbf39b..f244e015 100644 --- a/win/C#/HandBrake.ApplicationServices/Services/QueueManager.cs +++ b/win/C#/HandBrake.ApplicationServices/Services/QueueManager.cs @@ -22,6 +22,7 @@ /* * TODO * - Rewrite the batch script generator. + * - QueueTask, switch everything to use the Task property, which is a model of all settings. */ #region Private Variables @@ -163,9 +164,7 @@ { lock (QueueLock) { - // Tag the job with an ID - job.Id = lastJobId++; - queue.Add(job); + queue.Remove(job); InvokeQueueChanged(EventArgs.Empty); } } @@ -185,7 +184,7 @@ this.LastProcessedJob = job; this.Remove(job); // Remove the item which we are about to pass out. - return job; + return job; } return null; @@ -236,15 +235,12 @@ string appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\"); string tempPath = !string.IsNullOrEmpty(exportPath) ? exportPath : appDataPath + string.Format(this.queueFile, string.Empty); - if (File.Exists(tempPath)) + using (FileStream strm = new FileStream(tempPath, FileMode.Create, FileAccess.Write)) { - using (FileStream strm = new FileStream(tempPath, FileMode.Create, FileAccess.Write)) - { - XmlSerializer serializer = new XmlSerializer(typeof(List)); - serializer.Serialize(strm, queue); - strm.Close(); - strm.Dispose(); - } + XmlSerializer serializer = new XmlSerializer(typeof(List)); + serializer.Serialize(strm, queue); + strm.Close(); + strm.Dispose(); } } @@ -286,7 +282,7 @@ /// Whether or not the supplied destination is already in the queue. public bool CheckForDestinationPathDuplicates(string destination) { - return this.queue.Any(checkItem => checkItem.Task.Destination.Contains(destination.Replace("\\\\", "\\"))); + return this.queue.Any(checkItem => checkItem.Destination.Contains(destination.Replace("\\\\", "\\"))); } /// diff --git a/win/C#/HandBrake.ApplicationServices/Services/QueueProcessor.cs b/win/C#/HandBrake.ApplicationServices/Services/QueueProcessor.cs index 16252716..ff865e2e 100644 --- a/win/C#/HandBrake.ApplicationServices/Services/QueueProcessor.cs +++ b/win/C#/HandBrake.ApplicationServices/Services/QueueProcessor.cs @@ -249,7 +249,7 @@ namespace HandBrake.ApplicationServices.Services case "Shutdown": Process.Start("Shutdown", "-s -t 60"); break; - case "Log Off": + case "Log off": Win32.ExitWindowsEx(0, 0); break; case "Suspend": diff --git a/win/C#/frmActivityWindow.cs b/win/C#/frmActivityWindow.cs index ba606d5d..de25ef95 100644 --- a/win/C#/frmActivityWindow.cs +++ b/win/C#/frmActivityWindow.cs @@ -30,7 +30,7 @@ namespace Handbrake /// /// The Encode Object /// - private readonly IQueue encode; + private readonly IEncode encode; /// /// The Scan Object @@ -68,7 +68,7 @@ namespace Handbrake /// /// The scan. /// - public frmActivityWindow(IQueue encode, IScan scan) + public frmActivityWindow(IEncode encode, IScan scan) { InitializeComponent(); diff --git a/win/C#/frmMain.cs b/win/C#/frmMain.cs index 0b02d13a..1c4ccb22 100644 --- a/win/C#/frmMain.cs +++ b/win/C#/frmMain.cs @@ -40,7 +40,7 @@ namespace Handbrake public partial class frmMain : Form { // Objects which may be used by one or more other objects ************* - private IQueue encodeQueue = new Queue(); + private IQueueProcessor queueProcessor = new QueueProcessor(Program.InstanceId); private PresetsHandler presetHandler = new PresetsHandler(); // Windows ************************************************************ @@ -153,7 +153,7 @@ namespace Handbrake treeView_presets.ExpandAll(); lbl_encode.Text = string.Empty; drop_mode.SelectedIndex = 0; - queueWindow = new frmQueue(encodeQueue, this); // Prepare the Queue + queueWindow = new frmQueue(this.queueProcessor, this); // Prepare the Queue if (!Settings.Default.QueryEditorTab) tabs_panel.TabPages.RemoveAt(7); // Remove the query editor tab if the user does not want it enabled. if (Settings.Default.tooltipEnable) @@ -182,7 +182,7 @@ namespace Handbrake // Event Handlers and Queue Recovery events(); - Main.RecoverQueue(encodeQueue); + Main.RecoverQueue(this.queueProcessor); // If have a file passed in via command arguemtents, check it's a file and try scanning it. if (args.Length >= 1 && (File.Exists(args[0]) || Directory.Exists(args[0]))) @@ -231,79 +231,79 @@ namespace Handbrake RegisterPresetEventHandler(); // Handle Window Resize - if (Properties.Settings.Default.MainWindowMinimize) - this.Resize += new EventHandler(frmMain_Resize); + if (Settings.Default.MainWindowMinimize) + this.Resize += this.frmMain_Resize; // Handle Encode Start / Finish / Pause - encodeQueue.EncodeStarted += new EventHandler(encodeStarted); - encodeQueue.EncodeCompleted += encodeEnded; + this.queueProcessor.EncodeService.EncodeStarted += this.encodeStarted; + this.queueProcessor.EncodeService.EncodeCompleted += encodeEnded; // Scan Started and Completed Events SourceScan.ScanStatusChanged += this.SourceScanScanStatusChanged; SourceScan.ScanCompleted += this.SourceScanScanCompleted; // Handle a file being draged onto the GUI. - this.DragEnter += new DragEventHandler(frmMain_DragEnter); - this.DragDrop += new DragEventHandler(frmMain_DragDrop); + this.DragEnter += frmMain_DragEnter; + this.DragDrop += this.frmMain_DragDrop; } // Change the preset label to custom when a user changes a setting. Don't want to give the impression that users can change settings and still be using a preset private void RegisterPresetEventHandler() { // Output Settings - drop_format.SelectedIndexChanged += new EventHandler(changePresetLabel); - check_largeFile.CheckedChanged += new EventHandler(changePresetLabel); - check_iPodAtom.CheckedChanged += new EventHandler(changePresetLabel); - check_optimiseMP4.CheckedChanged += new EventHandler(changePresetLabel); + drop_format.SelectedIndexChanged += this.changePresetLabel; + check_largeFile.CheckedChanged += this.changePresetLabel; + check_iPodAtom.CheckedChanged += this.changePresetLabel; + check_optimiseMP4.CheckedChanged += this.changePresetLabel; // Picture Settings - PictureSettings.PictureSettingsChanged += new EventHandler(changePresetLabel); + PictureSettings.PictureSettingsChanged += this.changePresetLabel; // Filter Settings - Filters.FilterSettingsChanged += new EventHandler(changePresetLabel); + Filters.FilterSettingsChanged += this.changePresetLabel; // Video Tab - drp_videoEncoder.SelectedIndexChanged += new EventHandler(changePresetLabel); - check_2PassEncode.CheckedChanged += new EventHandler(changePresetLabel); - check_turbo.CheckedChanged += new EventHandler(changePresetLabel); - text_filesize.TextChanged += new EventHandler(changePresetLabel); - text_bitrate.TextChanged += new EventHandler(changePresetLabel); - slider_videoQuality.ValueChanged += new EventHandler(changePresetLabel); + drp_videoEncoder.SelectedIndexChanged += this.changePresetLabel; + check_2PassEncode.CheckedChanged += this.changePresetLabel; + check_turbo.CheckedChanged += this.changePresetLabel; + text_filesize.TextChanged += this.changePresetLabel; + text_bitrate.TextChanged += this.changePresetLabel; + slider_videoQuality.ValueChanged += this.changePresetLabel; // Audio Panel - AudioSettings.AudioListChanged += new EventHandler(changePresetLabel); + AudioSettings.AudioListChanged += this.changePresetLabel; // Advanced Tab - x264Panel.rtf_x264Query.TextChanged += new EventHandler(changePresetLabel); + x264Panel.rtf_x264Query.TextChanged += this.changePresetLabel; } private void UnRegisterPresetEventHandler() { // Output Settings - drop_format.SelectedIndexChanged -= new EventHandler(changePresetLabel); - check_largeFile.CheckedChanged -= new EventHandler(changePresetLabel); - check_iPodAtom.CheckedChanged -= new EventHandler(changePresetLabel); - check_optimiseMP4.CheckedChanged -= new EventHandler(changePresetLabel); + drop_format.SelectedIndexChanged -= this.changePresetLabel; + check_largeFile.CheckedChanged -= this.changePresetLabel; + check_iPodAtom.CheckedChanged -= this.changePresetLabel; + check_optimiseMP4.CheckedChanged -= this.changePresetLabel; // Picture Settings - PictureSettings.PictureSettingsChanged -= new EventHandler(changePresetLabel); + PictureSettings.PictureSettingsChanged -= this.changePresetLabel; // Filter Settings - Filters.FilterSettingsChanged -= new EventHandler(changePresetLabel); + Filters.FilterSettingsChanged -= this.changePresetLabel; // Video Tab - drp_videoEncoder.SelectedIndexChanged -= new EventHandler(changePresetLabel); - check_2PassEncode.CheckedChanged -= new EventHandler(changePresetLabel); - check_turbo.CheckedChanged -= new EventHandler(changePresetLabel); - text_filesize.TextChanged -= new EventHandler(changePresetLabel); - text_bitrate.TextChanged -= new EventHandler(changePresetLabel); - slider_videoQuality.ValueChanged -= new EventHandler(changePresetLabel); + drp_videoEncoder.SelectedIndexChanged -= this.changePresetLabel; + check_2PassEncode.CheckedChanged -= this.changePresetLabel; + check_turbo.CheckedChanged -= this.changePresetLabel; + text_filesize.TextChanged -= this.changePresetLabel; + text_bitrate.TextChanged -= this.changePresetLabel; + slider_videoQuality.ValueChanged -= this.changePresetLabel; // Audio Panel - AudioSettings.AudioListChanged -= new EventHandler(changePresetLabel); + AudioSettings.AudioListChanged -= this.changePresetLabel; // Advanced Tab - x264Panel.rtf_x264Query.TextChanged -= new EventHandler(changePresetLabel); + x264Panel.rtf_x264Query.TextChanged -= this.changePresetLabel; } private void changePresetLabel(object sender, EventArgs e) @@ -340,12 +340,12 @@ namespace Handbrake private void encodeStarted(object sender, EventArgs e) { SetEncodeStarted(); - encodeQueue.EncodeStatusChanged += EncodeQueue_EncodeStatusChanged; + this.queueProcessor.EncodeService.EncodeStatusChanged += EncodeQueue_EncodeStatusChanged; } private void encodeEnded(object sender, EventArgs e) { - encodeQueue.EncodeStatusChanged -= EncodeQueue_EncodeStatusChanged; + this.queueProcessor.EncodeService.EncodeStatusChanged -= EncodeQueue_EncodeStatusChanged; SetEncodeFinished(); } #endregion @@ -1047,12 +1047,12 @@ namespace Handbrake if (result == DialogResult.Yes) { // Pause The Queue - encodeQueue.Pause(); + this.queueProcessor.Pause(); if (Settings.Default.showCliForInGuiEncodeStatus) - encodeQueue.SafelyStop(); + this.queueProcessor.EncodeService.SafelyStop(); else - encodeQueue.Stop(); + this.queueProcessor.EncodeService.Stop(); } } else @@ -1061,7 +1061,7 @@ namespace Handbrake string jobSourcePath = !string.IsNullOrEmpty(rtf_query.Text) ? Main.GetSourceFromQuery(rtf_query.Text) : sourcePath; string jobDestination = !string.IsNullOrEmpty(rtf_query.Text) ? Main.GetDestinationFromQuery(rtf_query.Text) : text_destination.Text; - if (encodeQueue.Count != 0 || (!string.IsNullOrEmpty(jobSourcePath) && !string.IsNullOrEmpty(jobDestination))) + if (this.queueProcessor.QueueManager.Count != 0 || (!string.IsNullOrEmpty(jobSourcePath) && !string.IsNullOrEmpty(jobDestination))) { string generatedQuery = QueryGenerator.GenerateFullQuery(this); string specifiedQuery = rtf_query.Text != string.Empty @@ -1116,15 +1116,23 @@ namespace Handbrake if (overwrite == DialogResult.Yes) { - if (encodeQueue.Count == 0) - encodeQueue.Add(query, this.GetTitle(), jobSourcePath, jobDestination, (rtf_query.Text != string.Empty)); + QueueTask task = new QueueTask(query) + { + Title = this.GetTitle(), + Source = jobSourcePath, + Destination = jobDestination, + CustomQuery = (this.rtf_query.Text != string.Empty) + }; + + if (this.queueProcessor.QueueManager.Count == 0) + this.queueProcessor.QueueManager.Add(task); queueWindow.SetQueue(); - if (encodeQueue.Count > 1) + if (this.queueProcessor.QueueManager.Count > 1) queueWindow.Show(false); SetEncodeStarted(); // Encode is running, so setup the GUI appropriately - encodeQueue.Start(); // Start The Queue Encoding Process + this.queueProcessor.Start(); // Start The Queue Encoding Process } this.Focus(); @@ -1229,7 +1237,7 @@ namespace Handbrake } // Make sure we don't have a duplciate on the queue. - if (encodeQueue.CheckForDestinationDuplicate(jobDestination)) + if (this.queueProcessor.QueueManager.CheckForDestinationPathDuplicates(jobDestination)) { if (showError) { @@ -1252,9 +1260,16 @@ namespace Handbrake } // Add the job. - encodeQueue.Add(query, this.GetTitle(), jobSourcePath, jobDestination, (rtf_query.Text != string.Empty)); + QueueTask task = new QueueTask(query) + { + Title = this.GetTitle(), + Source = jobSourcePath, + Destination = jobDestination, + CustomQuery = (this.rtf_query.Text != string.Empty) + }; + this.queueProcessor.QueueManager.Add(task); - lbl_encode.Text = encodeQueue.Count + " encode(s) pending in the queue"; + lbl_encode.Text = this.queueProcessor.QueueManager.Count + " encode(s) pending in the queue"; return true; } @@ -1318,7 +1333,7 @@ namespace Handbrake private void btn_ActivityWindow_Click(object sender, EventArgs e) { if (this.activityWindow == null || !this.activityWindow.IsHandleCreated) - this.activityWindow = new frmActivityWindow(encodeQueue, SourceScan); + this.activityWindow = new frmActivityWindow(this.queueProcessor.EncodeService, SourceScan); this.activityWindow.Show(); this.activityWindow.Activate(); @@ -2398,7 +2413,7 @@ namespace Handbrake lbl_encode.Visible = true; ProgressBarStatus.Value = 0; ProgressBarStatus.Visible = true; - lbl_encode.Text = "Encoding with " + encodeQueue.Count + " encode(s) pending"; + lbl_encode.Text = "Encoding with " + this.queueProcessor.QueueManager.Count + " encode(s) pending"; btn_start.Text = "Stop"; btn_start.ToolTipText = "Stop the encoding process."; btn_start.Image = Properties.Resources.stop; @@ -2433,7 +2448,7 @@ namespace Handbrake e.CurrentFrameRate, e.AverageFrameRate, e.EstimatedTimeLeft, - encodeQueue.Count); + this.queueProcessor.QueueManager.Count); ProgressBarStatus.Value = (int)Math.Round(e.PercentComplete); } @@ -2583,7 +2598,7 @@ namespace Handbrake try { // If currently encoding, the queue isn't paused, and there are queue items to process, prompt to confirm close. - if (encodeQueue.IsEncoding) + if (this.queueProcessor.EncodeService.IsEncoding) { DialogResult result = MessageBox.Show( @@ -2598,7 +2613,8 @@ namespace Handbrake return; } - encodeQueue.Stop(); + this.queueProcessor.Pause(); + this.queueProcessor.EncodeService.Stop(); } if (SourceScan.IsScanning) diff --git a/win/C#/frmPreview.cs b/win/C#/frmPreview.cs index 9fb1d7a4..10bd1cf4 100644 --- a/win/C#/frmPreview.cs +++ b/win/C#/frmPreview.cs @@ -43,7 +43,7 @@ namespace Handbrake /// /// The encode queue /// - private readonly IQueue encodeQueue = new Queue(); + private readonly IEncode encodeQueue = new Encode(); /// /// What is currently playing diff --git a/win/C#/frmQueue.cs b/win/C#/frmQueue.cs index dab46a3f..88dc40c1 100644 --- a/win/C#/frmQueue.cs +++ b/win/C#/frmQueue.cs @@ -10,6 +10,7 @@ namespace Handbrake using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; + using System.Linq; using System.Windows.Forms; using Functions; @@ -33,7 +34,7 @@ namespace Handbrake /// /// An instance of the Queue service /// - private readonly IQueue queue; + private readonly IQueueProcessor queue; /// /// A reference to the main application window @@ -49,20 +50,20 @@ namespace Handbrake /// /// The main window. /// - public frmQueue(IQueue q, frmMain mw) + public frmQueue(IQueueProcessor q, frmMain mw) { InitializeComponent(); this.mainWindow = mw; this.queue = q; - queue.EncodeStarted += new EventHandler(QueueOnEncodeStart); - queue.QueueCompleted += new EventHandler(QueueOnQueueFinished); - queue.QueuePauseRequested += new EventHandler(QueueOnPaused); - queue.QueueListChanged += new EventHandler(queue_QueueListChanged); + queue.EncodeService.EncodeStarted += this.QueueOnEncodeStart; + queue.QueueCompleted += this.QueueOnQueueFinished; + queue.QueuePaused += this.QueueOnPaused; + queue.QueueManager.QueueChanged += new EventHandler(queue_QueueListChanged); - queue.EncodeStarted += new EventHandler(queue_EncodeStarted); - queue.EncodeCompleted += queue_EncodeEnded; + queue.EncodeService.EncodeStarted += this.queue_EncodeStarted; + queue.EncodeService.EncodeCompleted += this.queue_EncodeEnded; drp_completeOption.Text = Properties.Settings.Default.CompletionOption; } @@ -92,7 +93,7 @@ namespace Handbrake /// private void queue_EncodeEnded(object sender, EventArgs e) { - queue.EncodeStatusChanged -= EncodeQueue_EncodeStatusChanged; + queue.EncodeService.EncodeStatusChanged -= EncodeQueue_EncodeStatusChanged; ResetEncodeText(); } @@ -108,7 +109,7 @@ namespace Handbrake private void queue_EncodeStarted(object sender, EventArgs e) { this.SetCurrentEncodeInformation(); - queue.EncodeStatusChanged += EncodeQueue_EncodeStatusChanged; + queue.EncodeService.EncodeStatusChanged += EncodeQueue_EncodeStatusChanged; } /// @@ -215,7 +216,7 @@ namespace Handbrake /// the EventArgs private void BtnEncodeClick(object sender, EventArgs e) { - if (queue.Paused) + if (!queue.IsProcessing) { SetUiEncodeStarted(); } @@ -318,11 +319,11 @@ namespace Handbrake } list_queue.Items.Clear(); - ReadOnlyCollection theQueue = queue.CurrentQueue; + ReadOnlyCollection theQueue = queue.QueueManager.Queue; foreach (QueueTask queueItem in theQueue) { string qItem = queueItem.Query; - QueryParser parsed = Functions.QueryParser.Parse(qItem); + QueryParser parsed = QueryParser.Parse(qItem); // Get the DVD Title string title = parsed.Title == 0 ? "Auto" : parsed.Title.ToString(); @@ -338,8 +339,7 @@ namespace Handbrake chapters = chapters + " - " + parsed.ChapterFinish; } - ListViewItem item = new ListViewItem(); - item.Text = title; // Title + ListViewItem item = new ListViewItem { Tag = queueItem, Text = title }; item.SubItems.Add(chapters); // Chapters item.SubItems.Add(queueItem.Source); // Source item.SubItems.Add(queueItem.Destination); // Destination @@ -387,7 +387,7 @@ namespace Handbrake BeginInvoke(new UpdateHandler(SetCurrentEncodeInformation)); } - QueryParser parsed = QueryParser.Parse(queue.LastEncode.Query); + QueryParser parsed = QueryParser.Parse(queue.QueueManager.LastProcessedJob.Query); // Get title and chapters string title = parsed.Title == 0 ? "Auto" : parsed.Title.ToString(); @@ -414,8 +414,8 @@ namespace Handbrake // found query is a global varible lbl_encodeStatus.Text = "Encoding ..."; - lbl_source.Text = queue.LastEncode.Source + "(Title: " + title + " Chapters: " + chapterlbl + ")"; - lbl_dest.Text = queue.LastEncode.Destination; + lbl_source.Text = queue.QueueManager.LastProcessedJob.Source + "(Title: " + title + " Chapters: " + chapterlbl + ")"; + lbl_dest.Text = queue.QueueManager.LastProcessedJob.Destination; lbl_encodeOptions.Text = "Video: " + parsed.VideoEncoder + " Audio: " + audio + Environment.NewLine + "x264 Options: " + parsed.H264Query; } @@ -472,9 +472,9 @@ namespace Handbrake { lock (list_queue) { - int index = list_queue.SelectedIndices[0]; - mainWindow.RecievingJob(queue.GetJob(index)); - queue.Remove(index); + QueueTask index = list_queue.SelectedItems[0].Tag as QueueTask; + mainWindow.RecievingJob(index); + queue.QueueManager.Remove(index); RedrawQueue(); } } @@ -529,7 +529,7 @@ namespace Handbrake // Move up each selected item foreach (int selectedIndex in selectedIndices) - queue.MoveUp(selectedIndex); + queue.QueueManager.MoveUp(selectedIndex); // Keep the selected item(s) selected, now moved up one index foreach (int selectedIndex in selectedIndices) @@ -559,7 +559,7 @@ namespace Handbrake // Move down each selected item foreach (int selectedIndex in selectedIndices) - queue.MoveDown(selectedIndex); + queue.QueueManager.MoveDown(selectedIndex); // Keep the selected item(s) selected, now moved down one index foreach (int selectedIndex in selectedIndices) @@ -578,23 +578,13 @@ namespace Handbrake // If there are selected items if (list_queue.SelectedIndices.Count > 0) { - // Save the selected indices to select them after the move - List selectedIndices = new List(list_queue.SelectedIndices.Count); - foreach (int selectedIndex in list_queue.SelectedIndices) - selectedIndices.Add(selectedIndex); - - int firstSelectedIndex = selectedIndices[0]; - - // Reverse the list to delete the items from last to first (preserves indices) - selectedIndices.Reverse(); - // Remove each selected item - foreach (int selectedIndex in selectedIndices) - queue.Remove(selectedIndex); + foreach (ListViewItem selectedIndex in this.list_queue.SelectedItems) + queue.QueueManager.Remove((QueueTask)selectedIndex.Tag); - // Select the item where the first deleted item was previously - if (firstSelectedIndex < list_queue.Items.Count) - list_queue.Items[firstSelectedIndex].Selected = true; + // Select the first item after deletion. + if (list_queue.Items.Count > 0) + list_queue.Items[0].Selected = true; } list_queue.Select(); // Activate the control to show the selected items @@ -617,7 +607,7 @@ namespace Handbrake SaveFile.Filter = "Batch|.bat"; SaveFile.ShowDialog(); if (SaveFile.FileName != String.Empty) - queue.WriteBatchScriptToFile(SaveFile.FileName); + queue.QueueManager.WriteBatchScriptToFile(SaveFile.FileName); } /// @@ -635,7 +625,7 @@ namespace Handbrake SaveFile.Filter = "HandBrake Queue|*.queue"; SaveFile.ShowDialog(); if (SaveFile.FileName != String.Empty) - queue.WriteQueueStateToFile(SaveFile.FileName); + queue.QueueManager.BackupQueue(SaveFile.FileName); } /// @@ -652,7 +642,7 @@ namespace Handbrake OpenFile.FileName = string.Empty; OpenFile.ShowDialog(); if (OpenFile.FileName != String.Empty) - queue.LoadQueueFromFile(OpenFile.FileName); + queue.QueueManager.RestoreQueue(OpenFile.FileName); } /// @@ -666,14 +656,9 @@ namespace Handbrake /// private void MnuReaddClick(object sender, EventArgs e) { - if (queue.LastEncode != null && !queue.LastEncode.IsEmpty) + if (queue.QueueManager.LastProcessedJob != null && !queue.QueueManager.LastProcessedJob.IsEmpty) { - queue.Add( - queue.LastEncode.Query, - queue.LastEncode.Title, - queue.LastEncode.Source, - queue.LastEncode.Destination, - queue.LastEncode.CustomQuery); + queue.QueueManager.Add(queue.QueueManager.LastProcessedJob); } } -- 2.11.0