From ee294958088a96ca232a1334eea6542dd7e30d60 Mon Sep 17 00:00:00 2001 From: sr55 Date: Sat, 23 May 2009 14:57:00 +0000 Subject: WinGui:WinGui: - Stop button, now allows the CLI to cleanly exit by sending ctrl-c rather than killing the process. git-svn-id: svn://svn.handbrake.fr/HandBrake/trunk@2444 b64f7644-9d1e-0410-96f1-a4d463321fa5 --- win/C#/Controls/AudioPanel.cs | 2 - win/C#/Functions/Encode.cs | 218 --------------------------- win/C#/Functions/Main.cs | 5 +- win/C#/HandBrakeCS.csproj | 8 +- win/C#/Queue/QueueHandler.cs | 333 ------------------------------------------ win/C#/Queue/QueueItem.cs | 31 ---- win/C#/frmActivityWindow.cs | 5 +- win/C#/frmMain.cs | 13 +- win/C#/frmPreview.cs | 3 +- win/C#/frmQueue.cs | 11 +- 10 files changed, 27 insertions(+), 602 deletions(-) delete mode 100644 win/C#/Functions/Encode.cs delete mode 100644 win/C#/Queue/QueueHandler.cs delete mode 100644 win/C#/Queue/QueueItem.cs diff --git a/win/C#/Controls/AudioPanel.cs b/win/C#/Controls/AudioPanel.cs index 4b44cffed..f65710670 100644 --- a/win/C#/Controls/AudioPanel.cs +++ b/win/C#/Controls/AudioPanel.cs @@ -383,7 +383,5 @@ namespace Handbrake.Controls AudioTrackGroup.Text = "Selected Track: None (Click \"Add Track\" to add)"; } - - } } diff --git a/win/C#/Functions/Encode.cs b/win/C#/Functions/Encode.cs deleted file mode 100644 index 8d93b780c..000000000 --- a/win/C#/Functions/Encode.cs +++ /dev/null @@ -1,218 +0,0 @@ -/* Encode.cs $ - - This file is part of the HandBrake source code. - Homepage: . - It may be used under the terms of the GNU General Public License. */ - -using System; -using System.Diagnostics; -using System.Windows.Forms; -using System.IO; -using System.Runtime.InteropServices; - -namespace Handbrake.Functions -{ - public class Encode - { - // DLL Imports - [DllImport("user32.dll")] - private static extern void LockWorkStation(); - [DllImport("user32.dll")] - private static extern int ExitWindowsEx(int uFlags, int dwReason); - - /// - /// Execute a HandBrakeCLI process. - /// - /// The CLI Query - public Process runCli(string query) - { - Process hbProc = new Process(); - try - { - string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe"); - string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs"; - string logPath = Path.Combine(logDir, "last_encode_log.txt"); - string strCmdLine = String.Format(@" CMD /c """"{0}"" {1} 2>""{2}"" """, handbrakeCLIPath, query, logPath); - - ProcessStartInfo cliStart = new ProcessStartInfo("CMD.exe", strCmdLine); - if (Properties.Settings.Default.enocdeStatusInGui == "Checked") - { - cliStart.RedirectStandardOutput = true; - cliStart.UseShellExecute = false; - } - if (Properties.Settings.Default.cli_minimized == "Checked") - cliStart.WindowStyle = ProcessWindowStyle.Minimized; - - Process[] before = Process.GetProcesses(); // Get a list of running processes before starting. - hbProc = Process.Start(cliStart); - processID = Main.getCliProcess(before); - isEncoding = true; - currentQuery = query; - - // Set the process Priority - Process hbCliProcess = null; - if (processID != -1) - hbCliProcess = Process.GetProcessById(processID); - - if (hbCliProcess != null) - switch (Properties.Settings.Default.processPriority) - { - case "Realtime": - hbCliProcess.PriorityClass = ProcessPriorityClass.RealTime; - break; - case "High": - hbCliProcess.PriorityClass = ProcessPriorityClass.High; - break; - case "Above Normal": - hbCliProcess.PriorityClass = ProcessPriorityClass.AboveNormal; - break; - case "Normal": - hbCliProcess.PriorityClass = ProcessPriorityClass.Normal; - break; - case "Low": - hbCliProcess.PriorityClass = ProcessPriorityClass.Idle; - break; - default: - hbCliProcess.PriorityClass = ProcessPriorityClass.BelowNormal; - break; - } - } - catch (Exception exc) - { - MessageBox.Show("An error occured in runCli()\n Error Information: \n\n" + exc); - } - - return hbProc; - } - - /// - /// Kill the CLI process - /// - public void closeCLI() - { - Process[] prs = Process.GetProcesses(); - foreach (Process process in prs) - { - if (process.Id == processID) - { - process.Refresh(); - if (!process.HasExited) - process.Kill(); - - process.WaitForExit(); - } - } - } - - /// - /// Perform an action after an encode. e.g a shutdown, standby, restart etc. - /// - public void afterEncodeAction() - { - isEncoding = false; - currentQuery = String.Empty; - // Do something whent he encode ends. - switch (Properties.Settings.Default.CompletionOption) - { - case "Shutdown": - Process.Start("Shutdown", "-s -t 60"); - break; - case "Log Off": - 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": - LockWorkStation(); - break; - case "Quit HandBrake": - Application.Exit(); - break; - default: - break; - } - } - - /// - /// Append the CLI query to the start of the log file. - /// - /// - public void addCLIQueryToLog(string query) - { - string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs"; - string logPath = Path.Combine(logDir, "last_encode_log.txt"); - - StreamReader reader = new StreamReader(File.Open(logPath, FileMode.Open, FileAccess.Read)); - String log = reader.ReadToEnd(); - reader.Close(); - - StreamWriter writer = new StreamWriter(File.Create(logPath)); - - writer.Write("### CLI Query: " + query + "\n\n"); - writer.Write("#########################################\n\n"); - writer.WriteLine(log); - writer.Flush(); - writer.Close(); - } - - /// - /// Save a copy of the log to the users desired location or a default location - /// if this feature is enabled in options. - /// - /// - public void copyLog(string destination) - { - try - { - string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs"; - string tempLogFile = Path.Combine(logDir, "last_encode_log.txt"); - - string encodeDestinationPath = Path.GetDirectoryName(destination); - String[] destName = destination.Split('\\'); - string destinationFile = destName[destName.Length - 1]; - string encodeLogFile = DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + " " + destinationFile + ".txt"; - - // Make sure the log directory exists. - if (!Directory.Exists(logDir)) - Directory.CreateDirectory(logDir); - - // Copy the Log to HandBrakes log folder in the users applciation data folder. - File.Copy(tempLogFile, Path.Combine(logDir, encodeLogFile)); - - // Save a copy of the log file in the same location as the enocde. - if (Properties.Settings.Default.saveLogWithVideo == "Checked") - File.Copy(tempLogFile, Path.Combine(encodeDestinationPath, encodeLogFile)); - - // Save a copy of the log file to a user specified location - if (Directory.Exists(Properties.Settings.Default.saveLogPath)) - if (Properties.Settings.Default.saveLogPath != String.Empty && Properties.Settings.Default.saveLogToSpecifiedPath == "Checked") - File.Copy(tempLogFile, Path.Combine(Properties.Settings.Default.saveLogPath, encodeLogFile)); - } - catch (Exception exc) - { - MessageBox.Show("Something went a bit wrong trying to copy your log file.\nError Information:\n\n" + exc, "Error", - MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - - /// - /// Returns whether HandBrake is currently encoding or not. - /// - public Boolean isEncoding { get; set; } - - /// - /// Returns the currently encoding query string - /// - public String currentQuery { get; set; } - - /// - /// Get the process ID of the current encode. - /// - public int processID { get; set; } - - } -} diff --git a/win/C#/Functions/Main.cs b/win/C#/Functions/Main.cs index a95f5e144..be46465d4 100644 --- a/win/C#/Functions/Main.cs +++ b/win/C#/Functions/Main.cs @@ -12,13 +12,14 @@ using System.Text.RegularExpressions; using System.Collections.Generic; using System.Xml.Serialization; using System.Threading; +using Handbrake.EncodeQueue; namespace Handbrake.Functions { static class Main { // Private Variables - private static readonly XmlSerializer ser = new XmlSerializer(typeof(List)); + private static readonly XmlSerializer ser = new XmlSerializer(typeof(List)); /// /// Calculate the duration of the selected title and chapters @@ -358,7 +359,7 @@ namespace Handbrake.Functions { using (FileStream strm = new FileStream(tempPath, FileMode.Open, FileAccess.Read)) { - List list = ser.Deserialize(strm) as List; + List list = ser.Deserialize(strm) as List; if (list != null) if (list.Count != 0) return true; diff --git a/win/C#/HandBrakeCS.csproj b/win/C#/HandBrakeCS.csproj index 7155e3114..b082ce6ab 100644 --- a/win/C#/HandBrakeCS.csproj +++ b/win/C#/HandBrakeCS.csproj @@ -205,11 +205,13 @@ frmTestWindow.cs + - + + - + @@ -313,7 +315,7 @@ frmSplashScreen.cs - + diff --git a/win/C#/Queue/QueueHandler.cs b/win/C#/Queue/QueueHandler.cs deleted file mode 100644 index 2473b3868..000000000 --- a/win/C#/Queue/QueueHandler.cs +++ /dev/null @@ -1,333 +0,0 @@ -/* QueueHandler.cs $ - - This file is part of the HandBrake source code. - Homepage: . - It may be used under the terms of the GNU General Public License. */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Windows.Forms; -using System.Xml.Serialization; -using System.Threading; -using System.Diagnostics; -using Handbrake.Functions; - -namespace Handbrake.Queue -{ - public class QueueHandler - { - Encode encodeHandler = new Encode(); - private static XmlSerializer ser = new XmlSerializer(typeof(List)); - List queue = new List(); - int id; // Unique identifer number for each job - - #region Queue Handling - public List getQueue() - { - return queue; - } - - /// - /// Get's the next CLI query for encoding - /// - /// String - private string getNextItemForEncoding() - { - QueueItem job = queue[0]; - String query = job.Query; - lastQueueItem = job; - remove(0); // Remove the item which we are about to pass out. - return query; - } - - /// - /// Get the last query that was returned by getNextItemForEncoding() - /// - /// - public QueueItem lastQueueItem { get; set; } - - /// - /// Add's a new item to the queue - /// - /// String - /// - /// - public void add(string query, string source, string destination) - { - QueueItem newJob = new QueueItem { Id = id, Query = query, Source = source, Destination = destination }; - id++; - - queue.Add(newJob); - } - - /// - /// Check to see if a destination path is already on the queue - /// - /// Destination path - /// Boolean True/False. True = Path Exists - public Boolean checkDestinationPath(string destination) - { - foreach (QueueItem checkItem in queue) - { - if (checkItem.Destination.Contains(destination.Replace("\\\\", "\\"))) - return true; - } - return false; - } - - /// - /// Removes an item from the queue. - /// - /// Index - /// Bolean true if successful - public void remove(int index) - { - queue.RemoveAt(index); - } - - /// - /// Returns how many items are in the queue - /// - /// Int - public int count() - { - return queue.Count; - } - - /// - /// Move an item with an index x, up in the queue - /// - /// Int - public void moveUp(int index) - { - if (index > 0) - { - QueueItem item = queue[index]; - - queue.RemoveAt(index); - queue.Insert((index - 1), item); - } - } - - /// - /// Move an item with an index x, down in the queue - /// - /// Int - public void moveDown(int index) - { - if (index < queue.Count - 1) - { - QueueItem item = queue[index]; - - queue.RemoveAt(index); - queue.Insert((index + 1), item); - } - } - - /// - /// Writes the current queue to disk. hb_queue_recovery.xml - /// This function is called after getNextItemForEncoding() - /// - public void write2disk(string file) - { - string tempPath = file == "hb_queue_recovery.xml" ? Path.Combine(Path.GetTempPath(), "hb_queue_recovery.xml") : file; - - try - { - using (FileStream strm = new FileStream(tempPath, FileMode.Create, FileAccess.Write)) - { - ser.Serialize(strm, queue); - strm.Close(); - strm.Dispose(); - } - } - catch (Exception) - { - // Any Errors will be out of diskspace/permissions problems. - // Don't report them as they'll annoy the user. - } - } - - /// - /// Writes the current queue to disk to the location specified in file - /// - /// - public void writeBatchScript(string file) - { - string queries = ""; - foreach (QueueItem queue_item in queue) - { - string q_item = queue_item.Query; - string fullQuery = '"' + Application.StartupPath + "\\HandBrakeCLI.exe" + '"' + q_item; - - if (queries == string.Empty) - queries = queries + fullQuery; - else - queries = queries + " && " + fullQuery; - } - string strCmdLine = queries; - - if (file != "") - { - try - { - // Create a StreamWriter and open the file, Write the batch file query to the file and - // Close the stream - StreamWriter line = new StreamWriter(file); - line.WriteLine(strCmdLine); - line.Close(); - - MessageBox.Show("Your batch script has been sucessfully saved.", "Status", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); - } - catch (Exception) - { - MessageBox.Show("Unable to write to the file. Please make sure that the location has the correct permissions for file writing.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); - } - - } - } - - /// - /// Recover the queue from hb_queue_recovery.xml - /// - public void recoverQueue(string file) - { - string tempPath; - if (file == "hb_queue_recovery.xml") - tempPath = Path.Combine(Path.GetTempPath(), "hb_queue_recovery.xml"); - else - tempPath = file; - - if (File.Exists(tempPath)) - { - using (FileStream strm = new FileStream(tempPath, FileMode.Open, FileAccess.Read)) - { - if (strm.Length != 0) - { - List list = ser.Deserialize(strm) as List; - - if (list != null) - foreach (QueueItem item in list) - queue.Add(item); - - if (file != "hb_queue_recovery.xml") - write2disk("hb_queue_recovery.xml"); - } - } - } - } - #endregion - - #region Encoding - - public Boolean isEncodeStarted { get; private set; } - public Boolean isPaused { get; private set; } - public Boolean isEncoding { get; private set; } - public Process hbProc { get; set; } - - public void startEncode() - { - Thread theQueue; - if (this.count() != 0) - { - if (isPaused) - isPaused = false; - else - { - isPaused = false; - try - { - theQueue = new Thread(startProc) { IsBackground = true }; - theQueue.Start(); - } - catch (Exception exc) - { - MessageBox.Show(exc.ToString()); - } - } - } - } - public void pauseEncode() - { - isPaused = true; - EncodePaused(null); - } - public void endEncode() - { - encodeHandler.closeCLI(); - } - - private void startProc(object state) - { - try - { - // Run through each item on the queue - while (this.count() != 0) - { - string query = getNextItemForEncoding(); - write2disk("hb_queue_recovery.xml"); // Update the queue recovery file - - hbProc = encodeHandler.runCli(query); - EncodeStarted(null); - hbProc.WaitForExit(); - - encodeHandler.addCLIQueryToLog(query); - encodeHandler.copyLog(lastQueueItem.Destination); - - hbProc.Close(); - hbProc.Dispose(); - EncodeFinished(null); - - while (isPaused) // Need to find a better way of doing this. - { - Thread.Sleep(10000); - } - } - EncodeQueueFinished(null); - - // After the encode is done, we may want to shutdown, suspend etc. - encodeHandler.afterEncodeAction(); - } - catch (Exception exc) - { - throw new Exception(exc.ToString()); - } - } - #endregion - - #region Events - public event EventHandler OnEncodeStart; - public event EventHandler OnPaused; - public event EventHandler OnEncodeEnded; - public event EventHandler OnQueueFinished; - - // Invoke the Changed event; called whenever encodestatus changes: - protected virtual void EncodeStarted(EventArgs e) - { - if (OnEncodeStart != null) - OnEncodeStart(this, e); - - isEncoding = true; - } - protected virtual void EncodePaused(EventArgs e) - { - if (OnPaused != null) - OnPaused(this, e); - } - protected virtual void EncodeFinished(EventArgs e) - { - if (OnEncodeEnded != null) - OnEncodeEnded(this, e); - - isEncoding = false; - } - protected virtual void EncodeQueueFinished(EventArgs e) - { - if (OnQueueFinished != null) - OnQueueFinished(this, e); - } - #endregion - - } -} diff --git a/win/C#/Queue/QueueItem.cs b/win/C#/Queue/QueueItem.cs deleted file mode 100644 index 386fef239..000000000 --- a/win/C#/Queue/QueueItem.cs +++ /dev/null @@ -1,31 +0,0 @@ -/* QueueItem.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.Queue -{ - public class QueueItem - { - /// - /// Get or Set the job id. - /// - public int Id { get; set; } - - /// - /// Get or Set the query string. - /// - public string Query { get; set; } - - /// - /// Get or set the source file of encoding - /// - public string Source { get; set; } - - /// - /// Get or set the destination for the file to be encoded. - /// - public string Destination { get; set; } - } -} \ No newline at end of file diff --git a/win/C#/frmActivityWindow.cs b/win/C#/frmActivityWindow.cs index dc979f28e..981ed2f34 100644 --- a/win/C#/frmActivityWindow.cs +++ b/win/C#/frmActivityWindow.cs @@ -9,6 +9,7 @@ using System.Windows.Forms; using System.IO; using System.Threading; using System.Runtime.InteropServices; +using Handbrake.EncodeQueue; using Microsoft.Win32; @@ -19,7 +20,7 @@ namespace Handbrake delegate void SetTextCallback(string text); String read_file; Thread monitor; - Queue.QueueHandler encodeQueue; + QueueHandler encodeQueue; int position; // Position in the arraylist reached by the current log output in the rtf box. string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs"; private frmMain mainWin; @@ -27,7 +28,7 @@ namespace Handbrake /// /// This window should be used to display the RAW output of the handbrake CLI which is produced during an encode. /// - public frmActivityWindow(string file, Queue.QueueHandler eh, frmMain mw) + public frmActivityWindow(string file, QueueHandler eh, frmMain mw) { InitializeComponent(); diff --git a/win/C#/frmMain.cs b/win/C#/frmMain.cs index cc28130ac..15c3e5588 100644 --- a/win/C#/frmMain.cs +++ b/win/C#/frmMain.cs @@ -11,9 +11,9 @@ using System.Windows.Forms; using System.IO; using System.Diagnostics; using System.Threading; +using Handbrake.EncodeQueue; using Handbrake.Functions; using Handbrake.Presets; -using Handbrake.Queue; using Handbrake.Parsing; namespace Handbrake @@ -218,7 +218,7 @@ namespace Handbrake // Experimental HBProc Process Monitoring. if (Properties.Settings.Default.enocdeStatusInGui == "Checked") { - HBProcess = encodeQueue.hbProc; + HBProcess = encodeQueue.encodeProcess.hbProcProcess; Thread EncodeMon = new Thread(encodeMonitorThread); EncodeMon.Start(); } @@ -584,13 +584,16 @@ namespace Handbrake { if (btn_start.Text == "Stop") { - DialogResult result = MessageBox.Show("Are you sure you wish to cancel the encode? Please note that this may break the encoded file. \nTo safely cancel your encode, press ctrl-c on your keyboard in the CLI window. This *may* allow you to preview your encoded content.", "Cancel Encode?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); + DialogResult result = MessageBox.Show("Are you sure you wish to cancel the encode?", "Cancel Encode?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { // Pause The Queue - encodeQueue.pauseEncode(); - encodeQueue.endEncode(); + encodeQueue.pauseEncodeQueue(); + + // Allow the CLI to exit cleanly + Win32.SetForegroundWindow(encodeQueue.encodeProcess.processHandle); + SendKeys.Send("^C"); // Update the GUI setEncodeFinished(); diff --git a/win/C#/frmPreview.cs b/win/C#/frmPreview.cs index 946f04947..7ea472772 100644 --- a/win/C#/frmPreview.cs +++ b/win/C#/frmPreview.cs @@ -5,6 +5,7 @@ using System.Diagnostics; using System.Runtime.InteropServices; using System.IO; using AxQTOControlLib; +using Handbrake.EncodeQueue; using Handbrake.Functions; using QTOControlLib; using QTOLibrary; @@ -88,7 +89,7 @@ namespace Handbrake MessageBox.Show(this, "Handbrake is already encoding a video!", "Status", MessageBoxButtons.OK, MessageBoxIcon.Warning); else { - hbProc = process.runCli((string)state); + hbProc = process.runCli((string)state).hbProcProcess; hbProc.WaitForExit(); hbProc = null; encodeCompleted(); diff --git a/win/C#/frmQueue.cs b/win/C#/frmQueue.cs index 39f548236..88da988ba 100644 --- a/win/C#/frmQueue.cs +++ b/win/C#/frmQueue.cs @@ -8,15 +8,16 @@ using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; +using Handbrake.EncodeQueue; namespace Handbrake { public partial class frmQueue : Form { private delegate void UpdateHandler(); - Queue.QueueHandler queue; + QueueHandler queue; - public frmQueue(Queue.QueueHandler q) + public frmQueue(QueueHandler q) { InitializeComponent(); @@ -84,7 +85,7 @@ namespace Handbrake } private void btn_pause_Click(object sender, EventArgs e) { - queue.pauseEncode(); + queue.pauseEncodeQueue(); setUIEncodeFinished(); resetQueue(); MessageBox.Show("No further items on the queue will start. The current encode process will continue until it is finished. \nClick 'Encode' when you wish to continue encoding the queue.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); @@ -139,8 +140,8 @@ namespace Handbrake } list_queue.Items.Clear(); - List theQueue = queue.getQueue(); - foreach (Queue.QueueItem queue_item in theQueue) + List theQueue = queue.getQueue(); + foreach (QueueItem queue_item in theQueue) { string q_item = queue_item.Query; Functions.QueryParser parsed = Functions.QueryParser.Parse(q_item); -- cgit v1.2.3