OSDN Git Service

WinGui:
[handbrake-jp/handbrake-jp-git.git] / win / C# / Functions / Main.cs
index acca7e7..d2e136a 100644 (file)
@@ -11,13 +11,16 @@ using System.Diagnostics;
 using System.Text.RegularExpressions;\r
 using System.Collections.Generic;\r
 using System.Xml.Serialization;\r
+using System.Threading;\r
+using Handbrake.EncodeQueue;\r
+using System.Net;\r
 \r
 namespace Handbrake.Functions\r
 {\r
-    class Main\r
+    static class Main\r
     {\r
         // Private Variables\r
-        private static readonly XmlSerializer ser = new XmlSerializer(typeof(List<Queue.QueueItem>));\r
+        private static readonly XmlSerializer ser = new XmlSerializer(typeof(List<Job>));\r
 \r
         /// <summary>\r
         /// Calculate the duration of the selected title and chapters\r
@@ -52,62 +55,6 @@ namespace Handbrake.Functions
         }\r
 \r
         /// <summary>\r
-        /// Calculate the non-anamorphic resoltuion of the source\r
-        /// </summary>\r
-        /// <param name="width"></param>\r
-        /// <param name="top"></param>\r
-        /// <param name="bottom"></param>\r
-        /// <param name="left"></param>\r
-        /// <param name="right"></param>\r
-        /// <param name="selectedTitle"></param>\r
-        /// <returns></returns>\r
-        public static int cacluateNonAnamorphicHeight(int width, decimal top, decimal bottom, decimal left, decimal right, Parsing.Title selectedTitle)\r
-        {\r
-            float aspect = selectedTitle.AspectRatio;\r
-            int aw = 0;\r
-            int ah = 0;\r
-            if (aspect.ToString() == "1.78")\r
-            {\r
-                aw = 16;\r
-                ah = 9;\r
-            }\r
-            else if (aspect.ToString() == "1.33")\r
-            {\r
-                aw = 4;\r
-                ah = 3;\r
-            }\r
-\r
-            if (aw != 0)\r
-            {\r
-                double a = width * selectedTitle.Resolution.Width * ah * (selectedTitle.Resolution.Height - (double)top - (double)bottom);\r
-                double b = selectedTitle.Resolution.Height * aw * (selectedTitle.Resolution.Width - (double)left - (double)right);\r
-\r
-                double y = a / b;\r
-\r
-                // If it's not Mod 16, make it mod 16\r
-                if ((y % 16) != 0)\r
-                {\r
-                    double mod16 = y % 16;\r
-                    if (mod16 >= 8)\r
-                    {\r
-                        mod16 = 16 - mod16;\r
-                        y = y + mod16;\r
-                    }\r
-                    else\r
-                    {\r
-                        y = y - mod16;\r
-                    }\r
-                }\r
-\r
-                //16 * (421 / 16)\r
-                //double z = ( 16 * (( y + 8 ) / 16 ) );\r
-                int x = int.Parse(y.ToString());\r
-                return x;\r
-            }\r
-            return 0;\r
-        }\r
-\r
-        /// <summary>\r
         /// Select the longest title in the DVD title dropdown menu on frmMain\r
         /// </summary>\r
         public static Parsing.Title selectLongestTitle(ComboBox drp_dvdtitle)\r
@@ -215,10 +162,13 @@ namespace Handbrake.Functions
 \r
                 // Add the appropriate file extension\r
                 if (format == 0)\r
-                    destination_filename += ".mp4";\r
+                {\r
+                    if (Properties.Settings.Default.useM4v)\r
+                        destination_filename += ".m4v";\r
+                    else\r
+                        destination_filename += ".mp4";\r
+                }\r
                 else if (format == 1)\r
-                    destination_filename += ".m4v";\r
-                else if (format == 2)\r
                     destination_filename += ".mkv";\r
 \r
                 // Now work out the path where the file will be stored.\r
@@ -243,37 +193,6 @@ namespace Handbrake.Functions
         }\r
 \r
         /// <summary>\r
-        /// Checks for updates and returns true if an update is available.\r
-        /// </summary>\r
-        /// <param name="debug">Turns on debug mode. Don't use on program startup</param>\r
-        /// <returns>Boolean True = Update available</returns>\r
-        public static Boolean updateCheck(Boolean debug)\r
-        {\r
-            try\r
-            {\r
-                AppcastReader rssRead = new AppcastReader();\r
-                rssRead.getInfo(); // Initializes the class.\r
-                string build = rssRead.build();\r
-\r
-                int latest = int.Parse(build);\r
-                int current = Properties.Settings.Default.hb_build;\r
-                int skip = Properties.Settings.Default.skipversion;\r
-\r
-                if (latest == skip)\r
-                    return false;\r
-\r
-                Boolean update = (latest > current);\r
-                return update;\r
-            }\r
-            catch (Exception exc)\r
-            {\r
-                if (debug)\r
-                    MessageBox.Show("Unable to check for updates, Please try again later. \n" + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
-                return false;\r
-            }\r
-        }\r
-\r
-        /// <summary>\r
         /// Get's HandBrakes version data from the CLI.\r
         /// </summary>\r
         /// <returns>Arraylist of Version Data. 0 = hb_version 1 = hb_build</returns>\r
@@ -296,14 +215,13 @@ namespace Handbrake.Functions
             try\r
             {\r
                 cliProcess.Start();\r
-                cliProcess.Kill();\r
                 // Retrieve standard output and report back to parent thread until the process is complete\r
                 TextReader stdOutput = cliProcess.StandardError;\r
 \r
                 while (!cliProcess.HasExited)\r
                 {\r
                     line = stdOutput.ReadLine() ?? "";\r
-                    Match m = Regex.Match(line, @"HandBrake ([0-9\.]*)*(svn[0-9]*[M]*)* \([0-9]*\)");\r
+                    Match m = Regex.Match(line, @"HandBrake ([0-9.]*)(svn[0-9M]*) \([0-9]*\)");\r
 \r
                     if (m.Success)\r
                     {\r
@@ -314,8 +232,11 @@ namespace Handbrake.Functions
                         Properties.Settings.Default.hb_version = arr[0];\r
                     }\r
                     if (cliProcess.TotalProcessorTime.Seconds > 10) // Don't wait longer than 10 seconds.\r
-                        killCLI();\r
-\r
+                    {\r
+                        Process cli = Process.GetProcessById(cliProcess.Id);\r
+                        if (!cli.HasExited)\r
+                            cli.Kill();\r
+                    }\r
                 }\r
             }\r
             catch (Exception e)\r
@@ -325,26 +246,6 @@ namespace Handbrake.Functions
         }\r
 \r
         /// <summary>\r
-        /// Search through the running processes on the system and kill HandBrakeCLI\r
-        /// </summary>\r
-        private static void killCLI()\r
-        {\r
-            string AppName = "HandBrakeCLI";\r
-            AppName = AppName.ToUpper();\r
-\r
-            Process[] prs = Process.GetProcesses();\r
-            foreach (Process proces in prs)\r
-            {\r
-                if (proces.ProcessName.ToUpper() == AppName)\r
-                {\r
-                    proces.Refresh();\r
-                    if (!proces.HasExited)\r
-                        proces.Kill();\r
-                }\r
-            }\r
-        }\r
-\r
-        /// <summary>\r
         /// Check if the queue recovery file contains records.\r
         /// If it does, it means the last queue did not complete before HandBrake closed.\r
         /// So, return a boolean if true. \r
@@ -358,7 +259,7 @@ namespace Handbrake.Functions
                 {\r
                     using (FileStream strm = new FileStream(tempPath, FileMode.Open, FileAccess.Read))\r
                     {\r
-                        List<Queue.QueueItem> list = ser.Deserialize(strm) as List<Queue.QueueItem>;\r
+                        List<Job> list = ser.Deserialize(strm) as List<Job>;\r
                         if (list != null)\r
                             if (list.Count != 0)\r
                                 return true;\r
@@ -372,5 +273,159 @@ namespace Handbrake.Functions
             }\r
         }\r
 \r
+        /// <summary>\r
+        /// Get the Process ID of HandBrakeCLI for the current instance.\r
+        /// </summary>\r
+        /// <param name="before">List of processes before the new process was started</param>\r
+        /// <returns>Int - Process ID</returns>\r
+        public static int getCliProcess(Process[] before)\r
+        {\r
+            // This is a bit of a cludge. Maybe someone has a better idea on how to impliment this.\r
+            // Since we used CMD to start HandBrakeCLI, we don't get the process ID from hbProc.\r
+            // Instead we take the processes before and after, and get the ID of HandBrakeCLI.exe\r
+            // avoiding any previous instances of HandBrakeCLI.exe in before.\r
+            // Kill the current process.\r
+\r
+            Process[] hbProcesses = Process.GetProcessesByName("HandBrakeCLI");\r
+\r
+            // Another hack. We maybe need to wait a few seconds for HandBrakeCLI to launch\r
+            if (hbProcesses.Length == 0)\r
+            {\r
+                Thread.Sleep(2000);\r
+                hbProcesses = Process.GetProcessesByName("HandBrakeCLI");\r
+            }\r
+\r
+            Process hbProcess = null;\r
+            if (hbProcesses.Length > 0)\r
+                foreach (Process process in hbProcesses)\r
+                {\r
+                    Boolean found = false;\r
+                    // Check if the current CLI instance was running before we started the current one\r
+                    foreach (Process bprocess in before)\r
+                    {\r
+                        if (process.Id == bprocess.Id)\r
+                            found = true;\r
+                    }\r
+\r
+                    // If it wasn't running before, we found the process we want.\r
+                    if (!found)\r
+                    {\r
+                        hbProcess = process;\r
+                        break;\r
+                    }\r
+                }\r
+            if (hbProcess != null)\r
+                return hbProcess.Id;\r
+\r
+            return -1;\r
+        }\r
+\r
+        /// <summary>\r
+        ///  Clear all the encode log files.\r
+        /// </summary>\r
+        public static void clearLogs()\r
+        {\r
+            string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";\r
+            if (Directory.Exists(logDir))\r
+            {\r
+                DirectoryInfo info = new DirectoryInfo(logDir);\r
+                FileInfo[] logFiles = info.GetFiles("*.txt");\r
+                foreach (FileInfo file in logFiles)\r
+                {\r
+                    if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") && !file.Name.Contains("tmp_appReadable_log.txt"))\r
+                    {\r
+                        File.Delete(file.FullName);\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+        /// <summary>\r
+        /// Begins checking for an update to HandBrake.\r
+        /// </summary>\r
+        /// <param name="callback">The method that will be called when the check is finished.</param>\r
+        /// <param name="debug">Whether or not to execute this in debug mode.</param>\r
+        public static void BeginCheckForUpdates(AsyncCallback callback, bool debug)\r
+        {\r
+            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate\r
+            {\r
+                try\r
+                {\r
+                    // Is this a stable or unstable build?\r
+                    string url = Properties.Settings.Default.hb_build.ToString().EndsWith("1") ? Properties.Settings.Default.appcast_unstable : Properties.Settings.Default.appcast;\r
+\r
+                    // Initialize variables\r
+                    WebRequest request = WebRequest.Create(url);\r
+                    WebResponse response = request.GetResponse();\r
+                    AppcastReader reader = new AppcastReader();\r
+\r
+                    // Get the data, convert it to a string, and parse it into the AppcastReader\r
+                    reader.getInfo(new StreamReader(response.GetResponseStream()).ReadToEnd());\r
+\r
+                    // Further parse the information\r
+                    string build = reader.build;\r
+\r
+                    int latest = int.Parse(build);\r
+                    int current = Properties.Settings.Default.hb_build;\r
+                    int skip = Properties.Settings.Default.skipversion;\r
+\r
+                    // If the user wanted to skip this version, don't report the update\r
+                    if (latest == skip)\r
+                    {\r
+                        UpdateCheckInformation info = new UpdateCheckInformation() { NewVersionAvailable = false, BuildInformation = null };\r
+                        callback(new UpdateCheckResult(debug, info));\r
+                        return;\r
+                    }\r
+\r
+                    // Set when the last update was\r
+                    Properties.Settings.Default.lastUpdateCheckDate = DateTime.Now;\r
+                    Properties.Settings.Default.Save();\r
+\r
+                    UpdateCheckInformation info2 = new UpdateCheckInformation() { NewVersionAvailable = latest > current, BuildInformation = reader };\r
+                    callback(new UpdateCheckResult(debug, info2));\r
+                }\r
+                catch (Exception exc)\r
+                {\r
+                    callback(new UpdateCheckResult(debug, new UpdateCheckInformation() { Error = exc }));\r
+                }\r
+            }));\r
+        }\r
+\r
+        /// <summary>\r
+        /// \r
+        /// </summary>\r
+        /// <param name="result"></param>\r
+        /// <returns></returns>\r
+        public static UpdateCheckInformation EndCheckForUpdates(IAsyncResult result)\r
+        {\r
+            UpdateCheckResult checkResult = (UpdateCheckResult)result;\r
+            return checkResult.Result;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Used in EndUpdateCheck() for update checking and the IAsyncResult design pattern.\r
+        /// </summary>\r
+        private class UpdateCheckResult : IAsyncResult\r
+        {\r
+            public UpdateCheckResult(object asyncState, UpdateCheckInformation info)\r
+            {\r
+                AsyncState = asyncState;\r
+                Result = info;\r
+            }\r
+\r
+            /// <summary>\r
+            /// Gets whether the check was executed in debug mode.\r
+            /// </summary>\r
+            public object AsyncState { get; private set; }\r
+\r
+            /// <summary>\r
+            /// Gets the result of the update check.\r
+            /// </summary>\r
+            public UpdateCheckInformation Result { get; private set; }\r
+\r
+            public WaitHandle AsyncWaitHandle { get { throw new NotImplementedException(); } }\r
+            public bool CompletedSynchronously { get { throw new NotImplementedException(); } }\r
+            public bool IsCompleted { get { throw new NotImplementedException(); } }\r
+        }\r
     }\r
 }\r