OSDN Git Service

WinGui:
[handbrake-jp/handbrake-jp-git.git] / win / C# / EncodeQueue / Encode.cs
index 29d8bf8..2d788b7 100644 (file)
 /*  Encode.cs $\r
-       \r
-          This file is part of the HandBrake source code.\r
-          Homepage: <http://handbrake.fr>.\r
-          It may be used under the terms of the GNU General Public License. */\r
-\r
-using System;\r
-using System.Diagnostics;\r
-using System.Windows.Forms;\r
-using System.IO;\r
-using Handbrake.Functions;\r
+    This file is part of the HandBrake source code.\r
+    Homepage: <http://handbrake.fr/>.\r
+    It may be used under the terms of the GNU General Public License. */\r
 \r
 namespace Handbrake.EncodeQueue\r
 {\r
+    using System;\r
+    using System.Diagnostics;\r
+    using System.IO;\r
+    using System.Windows.Forms;\r
+    using Functions;\r
+    using Properties;\r
+\r
+    /// <summary>\r
+    /// Class which handles the CLI\r
+    /// </summary>\r
     public class Encode\r
     {\r
-        public Process hbProcess { get; set; }\r
-        public int processID { get; set; }\r
-        public IntPtr processHandle { get; set; }\r
-        public Boolean isEncoding { get; set; }\r
-        public String currentQuery { get; set; }\r
+        /// <summary>\r
+        /// Fires when a new CLI Job starts\r
+        /// </summary>\r
+        public event EventHandler EncodeStarted;\r
+\r
+        /// <summary>\r
+        /// Fires when a CLI job finishes.\r
+        /// </summary>\r
+        public event EventHandler EncodeEnded;\r
+\r
+        /// <summary>\r
+        /// Gets or sets The HB Process\r
+        /// </summary>\r
+        public Process HbProcess { get; set; }\r
+\r
+        /// <summary>\r
+        /// Gets or sets The Process Handle\r
+        /// </summary>\r
+        public IntPtr ProcessHandle { get; set; }\r
+\r
+        /// <summary>\r
+        /// Gets or sets a value indicating whether HandBrakeCLI.exe is running\r
+        /// </summary>\r
+        public bool IsEncoding { get; set; }\r
+\r
+        /// <summary>\r
+        /// Gets or sets the Process ID\r
+        /// </summary>\r
+        private int ProcessID { get; set; }\r
+\r
+        /// <summary>\r
+        /// Create a preview sample video\r
+        /// </summary>\r
+        /// <param name="query">\r
+        /// The CLI Query\r
+        /// </param>\r
+        public void CreatePreviewSample(string query)\r
+        {\r
+            this.Run(query);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Kill the CLI process\r
+        /// </summary>\r
+        public void Stop()\r
+        {\r
+            if (this.HbProcess != null)\r
+                this.HbProcess.Kill();\r
+\r
+            Process[] list = Process.GetProcessesByName("HandBrakeCLI");\r
+            foreach (Process process in list)\r
+                process.Kill();\r
+\r
+            this.IsEncoding = false;\r
+\r
+            if (this.EncodeEnded != null)\r
+                this.EncodeEnded(this, new EventArgs());\r
+        }\r
+\r
+        /// <summary>\r
+        /// Attempt to Safely kill a DirectRun() CLI\r
+        /// NOTE: This will not work with a MinGW CLI\r
+        /// Note: http://www.cygwin.com/ml/cygwin/2006-03/msg00330.html\r
+        /// </summary>\r
+        public void SafelyClose()\r
+        {\r
+            if ((int) this.ProcessHandle == 0)\r
+                return;\r
+\r
+            // Allow the CLI to exit cleanly\r
+            Win32.SetForegroundWindow((int) this.ProcessHandle);\r
+            SendKeys.Send("^C");\r
+\r
+            // HbProcess.StandardInput.AutoFlush = true;\r
+            // HbProcess.StandardInput.WriteLine("^C");\r
+        }\r
 \r
         /// <summary>\r
         /// Execute a HandBrakeCLI process.\r
         /// </summary>\r
-        /// <param name="query">The CLI Query</param>\r
-        public void runCli(string query)\r
+        /// <param name="query">\r
+        /// The CLI Query\r
+        /// </param>\r
+        protected void Run(string query)\r
         {\r
             try\r
             {\r
+                if (this.EncodeStarted != null)\r
+                    this.EncodeStarted(this, new EventArgs());\r
+\r
+                this.IsEncoding = true;\r
+\r
                 string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");\r
-                string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";\r
-                string logPath = Path.Combine(logDir, "last_encode_log.txt");\r
-                string strCmdLine = String.Format(@" CMD /c """"{0}"" {1} 2>""{2}"" """, handbrakeCLIPath, query, logPath);\r
+                string logPath =\r
+                    Path.Combine(\r
+                        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs", \r
+                        "last_encode_log.txt");\r
+                string strCmdLine = String.Format(@" /C """"{0}"" {1} 2>""{2}"" """, handbrakeCLIPath, query, logPath);\r
+                var cliStart = new ProcessStartInfo("CMD.exe", strCmdLine);\r
 \r
-                ProcessStartInfo cliStart = new ProcessStartInfo("CMD.exe", strCmdLine);\r
-                if (Properties.Settings.Default.enocdeStatusInGui)\r
+                if (Settings.Default.enocdeStatusInGui)\r
                 {\r
                     cliStart.RedirectStandardOutput = true;\r
                     cliStart.UseShellExecute = false;\r
-\r
+                    if (!Settings.Default.showCliForInGuiEncodeStatus)\r
+                        cliStart.CreateNoWindow = true;\r
                 }\r
-                if (Properties.Settings.Default.cli_minimized)\r
+                if (Settings.Default.cli_minimized)\r
                     cliStart.WindowStyle = ProcessWindowStyle.Minimized;\r
 \r
                 Process[] before = Process.GetProcesses(); // Get a list of running processes before starting.\r
-                hbProcess = Process.Start(cliStart);\r
-                processID = Main.getCliProcess(before);\r
-                isEncoding = true;\r
-                currentQuery = query;\r
-                if (hbProcess != null)\r
-                    processHandle = hbProcess.MainWindowHandle; // Set the process Handle\r
+                this.HbProcess = Process.Start(cliStart);\r
+                this.ProcessID = Main.GetCliProcess(before);\r
+\r
+                if (this.HbProcess != null)\r
+                    this.ProcessHandle = this.HbProcess.MainWindowHandle; // Set the process Handle\r
 \r
                 // Set the process Priority\r
                 Process hbCliProcess = null;\r
-                if (processID != -1)\r
-                    hbCliProcess = Process.GetProcessById(processID);\r
+                if (this.ProcessID != -1)\r
+                    hbCliProcess = Process.GetProcessById(this.ProcessID);\r
 \r
                 if (hbCliProcess != null)\r
-                    switch (Properties.Settings.Default.processPriority)\r
+                    switch (Settings.Default.processPriority)\r
                     {\r
                         case "Realtime":\r
                             hbCliProcess.PriorityClass = ProcessPriorityClass.RealTime;\r
@@ -81,28 +164,106 @@ namespace Handbrake.EncodeQueue
             }\r
             catch (Exception exc)\r
             {\r
-                MessageBox.Show("It would appear that HandBrakeCLI has not started correctly. You should take a look at the Activity log as it may indicate the reason why.\n\n   Detailed Error Information: error occured in runCli()\n\n" + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
+                MessageBox.Show(\r
+                    "It would appear that HandBrakeCLI has not started correctly. You should take a look at the Activity log as it may indicate the reason why.\n\nDetailed Error Information: error occured in runCli()\n\n" +\r
+                    exc, \r
+                    "Error", \r
+                    MessageBoxButtons.OK, \r
+                    MessageBoxIcon.Error);\r
             }\r
-\r
         }\r
 \r
         /// <summary>\r
-        /// Kill the CLI process\r
+        /// Function to run the CLI directly rather than via CMD\r
+        /// TODO: Code to handle the Log data has yet to be written.\r
+        /// TODO: Code to handle the % / ETA info has to be written.\r
         /// </summary>\r
-        public void closeCLI()\r
+        /// <param name="query">\r
+        /// The query.\r
+        /// </param>\r
+        protected void DirectRun(string query)\r
         {\r
-            hbProcess.Kill();\r
+            try\r
+            {\r
+                if (this.EncodeStarted != null)\r
+                    this.EncodeStarted(this, new EventArgs());\r
+\r
+                this.IsEncoding = true;\r
+\r
+                // Setup the job\r
+                string handbrakeCLIPath = Path.Combine(Environment.CurrentDirectory, "HandBrakeCLI.exe");\r
+                var hbProc = new Process\r
+                                 {\r
+                                     StartInfo =\r
+                                         {\r
+                                             FileName = handbrakeCLIPath, \r
+                                             Arguments = query, \r
+                                             UseShellExecute = false, \r
+                                             RedirectStandardOutput = true, \r
+                                             RedirectStandardError = true, \r
+                                             RedirectStandardInput = true, \r
+                                             CreateNoWindow = false, \r
+                                             WindowStyle = ProcessWindowStyle.Minimized\r
+                                         }\r
+                                 };\r
+\r
+                // Setup the redirects\r
+                hbProc.ErrorDataReceived += new DataReceivedEventHandler(HbProcErrorDataReceived);\r
+                hbProc.OutputDataReceived += new DataReceivedEventHandler(HbProcOutputDataReceived);\r
+\r
+                // Start the process\r
+                hbProc.Start();\r
+\r
+                // Set the Process Priority\r
+                switch (Settings.Default.processPriority)\r
+                {\r
+                    case "Realtime":\r
+                        hbProc.PriorityClass = ProcessPriorityClass.RealTime;\r
+                        break;\r
+                    case "High":\r
+                        hbProc.PriorityClass = ProcessPriorityClass.High;\r
+                        break;\r
+                    case "Above Normal":\r
+                        hbProc.PriorityClass = ProcessPriorityClass.AboveNormal;\r
+                        break;\r
+                    case "Normal":\r
+                        hbProc.PriorityClass = ProcessPriorityClass.Normal;\r
+                        break;\r
+                    case "Low":\r
+                        hbProc.PriorityClass = ProcessPriorityClass.Idle;\r
+                        break;\r
+                    default:\r
+                        hbProc.PriorityClass = ProcessPriorityClass.BelowNormal;\r
+                        break;\r
+                }\r
+\r
+                // Set the class items\r
+                this.HbProcess = hbProc;\r
+                this.ProcessID = hbProc.Id;\r
+                this.ProcessHandle = hbProc.Handle;\r
+            }\r
+            catch (Exception exc)\r
+            {\r
+                Console.WriteLine(exc);\r
+            }\r
         }\r
 \r
         /// <summary>\r
         /// Perform an action after an encode. e.g a shutdown, standby, restart etc.\r
         /// </summary>\r
-        public void afterEncodeAction()\r
+        protected void Finish()\r
         {\r
-            isEncoding = false;\r
-            currentQuery = String.Empty;\r
+            if (this.EncodeEnded != null)\r
+                this.EncodeEnded(this, new EventArgs());\r
+\r
+            this.IsEncoding = false;\r
+\r
+            // Growl\r
+            if (Settings.Default.growlQueue)\r
+                GrowlCommunicator.Notify("Queue Completed", "Put down that cocktail...\nyour Handbrake queue is done.");\r
+\r
             // Do something whent he encode ends.\r
-            switch (Properties.Settings.Default.CompletionOption)\r
+            switch (Settings.Default.CompletionOption)\r
             {\r
                 case "Shutdown":\r
                     Process.Start("Shutdown", "-s -t 60");\r
@@ -128,43 +289,58 @@ namespace Handbrake.EncodeQueue
         }\r
 \r
         /// <summary>\r
-        /// Append the CLI query to the start of the log file.\r
+        /// Add the CLI Query to the Log File.\r
         /// </summary>\r
-        /// <param name="query"></param>\r
-        public void addCLIQueryToLog(string query)\r
+        /// <param name="encJob">\r
+        /// The Encode Job Object\r
+        /// </param>\r
+        protected void AddCLIQueryToLog(Job encJob)\r
         {\r
-            string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";\r
-            string logPath = Path.Combine(logDir, "last_encode_log.txt");\r
+            try\r
+            {\r
+                string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +\r
+                                "\\HandBrake\\logs";\r
+                string logPath = Path.Combine(logDir, "last_encode_log.txt");\r
 \r
-            StreamReader reader = new StreamReader(File.Open(logPath, FileMode.Open, FileAccess.Read));\r
-            String log = reader.ReadToEnd();\r
-            reader.Close();\r
+                var reader =\r
+                    new StreamReader(File.Open(logPath, FileMode.Open, FileAccess.Read, FileShare.Read));\r
+                string log = reader.ReadToEnd();\r
+                reader.Close();\r
 \r
-            StreamWriter writer = new StreamWriter(File.Create(logPath));\r
+                var writer = new StreamWriter(File.Create(logPath));\r
 \r
-            writer.Write("### CLI Query: " + query + "\n\n");\r
-            writer.Write("#########################################\n\n");\r
-            writer.WriteLine(log);\r
-            writer.Flush();\r
-            writer.Close();\r
+                writer.Write("### CLI Query: " + encJob.Query + "\n\n");\r
+                writer.Write("### User Query: " + encJob.CustomQuery + "\n\n");\r
+                writer.Write("#########################################\n\n");\r
+                writer.WriteLine(log);\r
+                writer.Flush();\r
+                writer.Close();\r
+            }\r
+            catch (Exception)\r
+            {\r
+                return;\r
+            }\r
         }\r
 \r
         /// <summary>\r
         /// Save a copy of the log to the users desired location or a default location\r
         /// if this feature is enabled in options.\r
         /// </summary>\r
-        /// <param name="destination"></param>\r
-        public void copyLog(string destination)\r
+        /// <param name="destination">\r
+        /// The Destination File Path\r
+        /// </param>\r
+        protected void CopyLog(string destination)\r
         {\r
             try\r
             {\r
-                string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";\r
+                string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +\r
+                                "\\HandBrake\\logs";\r
                 string tempLogFile = Path.Combine(logDir, "last_encode_log.txt");\r
 \r
                 string encodeDestinationPath = Path.GetDirectoryName(destination);\r
-                String[] destName = destination.Split('\\');\r
-                string destinationFile = destName[destName.Length - 1];\r
-                string encodeLogFile = DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + " " + destinationFile + ".txt";\r
+                string destinationFile = Path.GetFileName(destination);\r
+                string encodeLogFile = destinationFile + " " +\r
+                                       DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + ".txt";\r
 \r
                 // Make sure the log directory exists.\r
                 if (!Directory.Exists(logDir))\r
@@ -174,20 +350,52 @@ namespace Handbrake.EncodeQueue
                 File.Copy(tempLogFile, Path.Combine(logDir, encodeLogFile));\r
 \r
                 // Save a copy of the log file in the same location as the enocde.\r
-                if (Properties.Settings.Default.saveLogWithVideo)\r
+                if (Settings.Default.saveLogWithVideo)\r
                     File.Copy(tempLogFile, Path.Combine(encodeDestinationPath, encodeLogFile));\r
 \r
                 // Save a copy of the log file to a user specified location\r
-                if (Directory.Exists(Properties.Settings.Default.saveLogPath))\r
-                    if (Properties.Settings.Default.saveLogPath != String.Empty && Properties.Settings.Default.saveLogToSpecifiedPath)\r
-                        File.Copy(tempLogFile, Path.Combine(Properties.Settings.Default.saveLogPath, encodeLogFile));\r
+                if (Directory.Exists(Settings.Default.saveLogPath))\r
+                    if (Settings.Default.saveLogPath != String.Empty && Settings.Default.saveLogToSpecifiedPath)\r
+                        File.Copy(tempLogFile, Path.Combine(Settings.Default.saveLogPath, encodeLogFile));\r
             }\r
             catch (Exception exc)\r
             {\r
-                MessageBox.Show("Something went a bit wrong trying to copy your log file.\nError Information:\n\n" + exc, "Error",\r
-                                MessageBoxButtons.OK, MessageBoxIcon.Error);\r
+                MessageBox.Show(\r
+                    "Something went a bit wrong trying to copy your log file.\nError Information:\n\n" + exc, \r
+                    "Error", \r
+                    MessageBoxButtons.OK, \r
+                    MessageBoxIcon.Error);\r
             }\r
         }\r
 \r
+        /// <summary>\r
+        /// Recieve the Standard Error information and process it\r
+        /// </summary>\r
+        /// <param name="sender">\r
+        /// The Sender Object\r
+        /// </param>\r
+        /// <param name="e">\r
+        /// DataReceived EventArgs\r
+        /// </param>\r
+        private static void HbProcErrorDataReceived(object sender, DataReceivedEventArgs e)\r
+        {\r
+            // TODO: Recieve the Log data and process it\r
+            throw new NotImplementedException();\r
+        }\r
+\r
+        /// <summary>\r
+        /// Standard Input Data Recieved from the CLI\r
+        /// </summary>\r
+        /// <param name="sender">\r
+        /// The Sender Object\r
+        /// </param>\r
+        /// <param name="e">\r
+        /// DataReceived EventArgs\r
+        /// </param>\r
+        private static void HbProcOutputDataReceived(object sender, DataReceivedEventArgs e)\r
+        {\r
+            // TODO: Recieve the %, ETA, FPS etc and process it\r
+            throw new NotImplementedException();\r
+        }\r
     }\r
 }
\ No newline at end of file