OSDN Git Service

LinGui: make Help->Guide work on windows/mingw
[handbrake-jp/handbrake-jp-git.git] / win / C# / Functions / Main.cs
index 1fba55e..d7380b2 100644 (file)
-/*  Common.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.Collections;\r
-using System.Text;\r
-using System.Windows.Forms;\r
-using System.Globalization;\r
-using System.IO;\r
-using System.Drawing;\r
-using System.Diagnostics;\r
-using System.Text.RegularExpressions;\r
+/*  Main.cs $\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.Functions\r
 {\r
-    class Main\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics;\r
+    using System.Globalization;\r
+    using System.IO;\r
+    using System.Net;\r
+    using System.Text;\r
+    using System.Text.RegularExpressions;\r
+    using System.Threading;\r
+    using System.Windows.Forms;\r
+    using System.Xml.Serialization;\r
+    using Model;\r
+    using Parsing;\r
+\r
+    /// <summary>\r
+    /// Useful functions which various screens can use.\r
+    /// </summary>\r
+    public static class Main\r
     {\r
         /// <summary>\r
-        /// Take in a File destination and change it's file extension to a new Extension\r
+        /// The XML Serializer\r
         /// </summary>\r
-        /// <param name="destination"></param>\r
-        /// <param name="newExtension"></param>\r
-        /// <returns>String of the new file path and extension</returns>\r
-        public string setExtension(string destination, string newExtension)\r
-        {\r
-            destination.Replace(".mp4", newExtension);\r
-            destination.Replace(".m4v", newExtension);\r
-            destination.Replace(".mkv", newExtension);\r
-            destination.Replace(".avi", newExtension);\r
-            destination.Replace(".ogm", newExtension);\r
-\r
-            return destination;\r
-        }\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
         /// </summary>\r
-        public TimeSpan calculateDuration(string chapter_start, string chapter_end, Parsing.Title selectedTitle)\r
+        /// <param name="chapterStart">\r
+        /// The chapter Start.\r
+        /// </param>\r
+        /// <param name="chapterEnd">\r
+        /// The chapter End.\r
+        /// </param>\r
+        /// <param name="selectedTitle">\r
+        /// The selected Title.\r
+        /// </param>\r
+        /// <returns>\r
+        /// The calculated duration.\r
+        /// </returns>\r
+        public static TimeSpan CalculateDuration(int chapterStart, int chapterEnd, Title selectedTitle)\r
         {\r
-            TimeSpan Duration = TimeSpan.FromSeconds(0.0);\r
-\r
-            // Get the durations between the 2 chapter points and add them together.\r
-            if (chapter_start != "Auto" && chapter_end != "Auto")\r
+            TimeSpan duration = TimeSpan.FromSeconds(0.0);\r
+            chapterStart++;\r
+            chapterEnd++;\r
+            if (chapterStart != 0 && chapterEnd != 0 && chapterEnd <= selectedTitle.Chapters.Count)\r
             {\r
-                int start_chapter, end_chapter = 0;\r
-                int.TryParse(chapter_start, out start_chapter);\r
-                int.TryParse(chapter_end, out end_chapter);\r
-\r
-                int position = start_chapter - 1;\r
-\r
-                if (start_chapter <= end_chapter)\r
-                {\r
-                    if (end_chapter > selectedTitle.Chapters.Count)\r
-                        end_chapter = selectedTitle.Chapters.Count;\r
-\r
-                    while (position != end_chapter)\r
-                    {\r
-                        TimeSpan dur = selectedTitle.Chapters[position].Duration;\r
-                        Duration = Duration + dur;\r
-                        position++;\r
-                    }\r
-                }\r
+                for (int i = chapterStart; i <= chapterEnd; i++)\r
+                    duration += selectedTitle.Chapters[i - 1].Duration;\r
             }\r
-            return Duration;\r
+\r
+            return duration;\r
         }\r
 \r
         /// <summary>\r
-        /// Calculate the non-anamorphic resoltuion of the source\r
+        /// Set's up the DataGridView on the Chapters tab (frmMain)\r
         /// </summary>\r
-        /// <param name="width"></param>\r
-        /// <returns></returns>\r
-        public int cacluateNonAnamorphicHeight(int width, decimal top, decimal bottom, decimal left, decimal right, Parsing.Title selectedTitle)\r
+        /// <param name="dataChpt">\r
+        /// The DataGridView Control\r
+        /// </param>\r
+        /// <param name="chapterEnd">\r
+        /// The chapter End.\r
+        /// </param>\r
+        /// <returns>\r
+        /// The chapter naming.\r
+        /// </returns>\r
+        public static DataGridView ChapterNaming(DataGridView dataChpt, string chapterEnd)\r
         {\r
-            float aspect = selectedTitle.AspectRatio;\r
-            int aw;\r
-            int ah;\r
-            if (aspect.ToString() == "1.78")\r
-            {\r
-                aw = 16;\r
-                ah = 9;\r
-            }\r
-            else\r
-            {\r
-                aw = 4;\r
-                ah = 3;\r
-            }\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
+            int i = 0, finish = 0;\r
 \r
-            double y = a / b;\r
+            if (chapterEnd != "Auto")\r
+                int.TryParse(chapterEnd, out finish);\r
 \r
-            // If it's not Mod 16, make it mod 16\r
-            if ((y % 16) != 0)\r
+            while (i < finish)\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
+                int n = dataChpt.Rows.Add();\r
+                dataChpt.Rows[n].Cells[0].Value = i + 1;\r
+                dataChpt.Rows[n].Cells[1].Value = "Chapter " + (i + 1);\r
+                dataChpt.Rows[n].Cells[0].ValueType = typeof(int);\r
+                dataChpt.Rows[n].Cells[1].ValueType = typeof(string);\r
+                i++;\r
             }\r
 \r
-            //16 * (421 / 16)\r
-            //double z = ( 16 * (( y + 8 ) / 16 ) );\r
-            int x = int.Parse(y.ToString());\r
-            return x;\r
+            return dataChpt;\r
         }\r
 \r
         /// <summary>\r
-        /// Select the longest title in the DVD title dropdown menu on frmMain\r
+        /// Import a CSV file which contains Chapter Names\r
         /// </summary>\r
-        public Handbrake.Parsing.Title selectLongestTitle(ComboBox drp_dvdtitle)\r
+        /// <param name="dataChpt">\r
+        /// The DataGridView Control\r
+        /// </param>\r
+        /// <param name="filename">\r
+        /// The filepath and name\r
+        /// </param>\r
+        /// <returns>A Populated DataGridView</returns>\r
+        public static DataGridView ImportChapterNames(DataGridView dataChpt, string filename)\r
         {\r
-            int current_largest = 0;\r
-            Handbrake.Parsing.Title title2Select;\r
-\r
-            // Check if there are titles in the DVD title dropdown menu and make sure, it's not just "Automatic"\r
-            if (drp_dvdtitle.Items[0].ToString() != "Automatic")\r
-                title2Select = (Handbrake.Parsing.Title)drp_dvdtitle.Items[0];\r
-            else\r
-                title2Select = null;\r
-\r
-            // So, If there are titles in the DVD Title dropdown menu, lets select the longest.\r
-            if (title2Select != null)\r
+            IDictionary<int, string> chapterMap = new Dictionary<int, string>();\r
+            try\r
             {\r
-                foreach (Handbrake.Parsing.Title x in drp_dvdtitle.Items)\r
+                StreamReader sr = new StreamReader(filename);\r
+                string csv = sr.ReadLine();\r
+                while (csv != null)\r
                 {\r
-                    string title = x.ToString();\r
-                    if (title != "Automatic")\r
+                    if (csv.Trim() != string.Empty)\r
                     {\r
-                        string[] y = title.Split(' ');\r
-                        string time = y[1].Replace("(", "").Replace(")", "");\r
-                        string[] z = time.Split(':');\r
-\r
-                        int hours = int.Parse(z[0]) * 60 * 60;\r
-                        int minutes = int.Parse(z[1]) * 60;\r
-                        int seconds = int.Parse(z[2]);\r
-                        int total_sec = hours + minutes + seconds;\r
-\r
-                        if (current_largest == 0)\r
-                        {\r
-                            current_largest = hours + minutes + seconds;\r
-                            title2Select = x;\r
-                        }\r
-                        else\r
-                        {\r
-                            if (total_sec > current_largest)\r
-                            {\r
-                                current_largest = total_sec;\r
-                                title2Select = x;\r
-                            }\r
-                        }\r
+                        csv = csv.Replace("\\,", "<!comma!>");\r
+                        string[] contents = csv.Split(',');\r
+                        int chapter;\r
+                        int.TryParse(contents[0], out chapter);\r
+                        chapterMap.Add(chapter, contents[1].Replace("<!comma!>", ","));\r
                     }\r
+                    csv = sr.ReadLine();\r
                 }\r
             }\r
-            return title2Select;\r
+            catch (Exception)\r
+            {\r
+                return null;\r
+            }\r
+\r
+            foreach (DataGridViewRow item in dataChpt.Rows)\r
+            {\r
+                string name;\r
+                chapterMap.TryGetValue((int)item.Cells[0].Value, out name);\r
+                item.Cells[1].Value = name ?? "Chapter " + item.Cells[0].Value;\r
+            }\r
+\r
+            return dataChpt;\r
         }\r
 \r
         /// <summary>\r
-        /// Set's up the DataGridView on the Chapters tab (frmMain)\r
+        /// Create a CSV file with the data from the Main Window Chapters tab\r
         /// </summary>\r
-        /// <param name="mainWindow"></param>\r
-        public DataGridView chapterNaming(DataGridView data_chpt, string chapter_start, string chapter_end)\r
+        /// <param name="mainWindow">Main Window</param>\r
+        /// <param name="filePathName">Path to save the csv file</param>\r
+        /// <returns>True if successful </returns>\r
+        public static bool SaveChapterMarkersToCsv(frmMain mainWindow, string filePathName)\r
         {\r
             try\r
             {\r
-                int i = 0;\r
-                int rowCount = 0;\r
-                int start = 0;\r
-                int finish = 0;\r
-                if (chapter_end != "Auto")\r
-                    finish = int.Parse(chapter_end);\r
-\r
-                if (chapter_start != "Auto")\r
-                    start = int.Parse(chapter_start);\r
+                string csv = string.Empty;\r
 \r
-                rowCount = finish - (start - 1);\r
-\r
-                while (i < rowCount)\r
+                foreach (DataGridViewRow row in mainWindow.data_chpt.Rows)\r
                 {\r
-                    DataGridViewRow row = new DataGridViewRow();\r
-\r
-                    data_chpt.Rows.Insert(i, row);\r
-                    data_chpt.Rows[i].Cells[0].Value = (i + 1);\r
-                    data_chpt.Rows[i].Cells[1].Value = "Chapter " + (i + 1);\r
-                    i++;\r
+                    csv += row.Cells[0].Value.ToString();\r
+                    csv += ",";\r
+                    csv += row.Cells[1].Value.ToString().Replace(",", "\\,");\r
+                    csv += Environment.NewLine;\r
                 }\r
-                return data_chpt;\r
+                StreamWriter file = new StreamWriter(filePathName);\r
+                file.Write(csv);\r
+                file.Close();\r
+                file.Dispose();\r
+                return true;\r
             }\r
             catch (Exception exc)\r
             {\r
-                MessageBox.Show("chapterNaming() Error has occured: \n" + exc.ToString());\r
-                return null;\r
+                frmExceptionWindow exceptionWindow = new frmExceptionWindow();\r
+                exceptionWindow.Setup("Unable to save Chapter Makrers file! \nChapter marker names will NOT be saved in your encode", exc.ToString());\r
+                exceptionWindow.ShowDialog();\r
+                return false;\r
             }\r
         }\r
 \r
@@ -206,165 +173,193 @@ namespace Handbrake.Functions
         /// Function which generates the filename and path automatically based on \r
         /// the Source Name, DVD title and DVD Chapters\r
         /// </summary>\r
-        /// <param name="mainWindow"></param>\r
-        public string autoName(ComboBox drp_dvdtitle, string chapter_start, string chatper_end, string source, string dest, int format)\r
+        /// <param name="mainWindow">\r
+        /// The main Window.\r
+        /// </param>\r
+        /// <returns>\r
+        /// The Generated FileName\r
+        /// </returns>\r
+        public static string AutoName(frmMain mainWindow)\r
         {\r
+            string autoNamePath = string.Empty;\r
+            if (mainWindow.drp_dvdtitle.Text != "Automatic")\r
+            {\r
+                // Get the Source Name \r
+                string sourceName = mainWindow.SourceName;\r
 \r
-            string AutoNamePath = string.Empty;\r
+                // Remove any illeagal characters from the source name\r
+                foreach (char character in Path.GetInvalidFileNameChars())\r
+                {\r
+                    if (autoNamePath != null)\r
+                    {\r
+                        sourceName = sourceName.Replace(character.ToString(), string.Empty);\r
+                    }\r
+                }\r
 \r
-            if (drp_dvdtitle.Text != "Automatic")\r
-            {\r
-                // Todo: This code is a tad messy. Clean it up at some point.\r
-                // Get the Source Name\r
-                string[] sourceName = source.Split('\\');\r
-                source = sourceName[sourceName.Length - 1].Replace(".iso", "").Replace(".mpg", "").Replace(".ts", "").Replace(".ps", "");\r
+                if (Properties.Settings.Default.AutoNameRemoveUnderscore)\r
+                    sourceName = sourceName.Replace("_", " ");\r
+\r
+                if (Properties.Settings.Default.AutoNameTitleCase)\r
+                    sourceName = TitleCase(sourceName);\r
 \r
                 // Get the Selected Title Number\r
-                string title = drp_dvdtitle.Text;\r
-                string[] titlesplit = title.Split(' ');\r
-                title = titlesplit[0];\r
+                string[] titlesplit = mainWindow.drp_dvdtitle.Text.Split(' ');\r
+                string dvdTitle = titlesplit[0].Replace("Automatic", string.Empty);\r
 \r
                 // Get the Chapter Start and Chapter End Numbers\r
-                string cs = chapter_start;\r
-                string cf = chatper_end;\r
-\r
-                // Just incase the above are set to their default Automatic values, set the varible to ""\r
-                if (title == "Automatic")\r
-                    title = "";\r
-                if (cs == "Auto")\r
-                    cs = "";\r
-                if (cf == "Auto")\r
-                    cf = "";\r
-\r
-                // If both CS and CF are populated, set the dash varible\r
-                string dash = "";\r
-                if (cf != "Auto")\r
-                    dash = "-";\r
+                string chapterStart = mainWindow.drop_chapterStart.Text.Replace("Auto", string.Empty);\r
+                string chapterFinish = mainWindow.drop_chapterFinish.Text.Replace("Auto", string.Empty);\r
+                string combinedChapterTag = chapterStart;\r
+                if (chapterFinish != chapterStart && chapterFinish != string.Empty)\r
+                    combinedChapterTag = chapterStart + "-" + chapterFinish;\r
 \r
                 // Get the destination filename.\r
-                string destination_filename = "";\r
-                if (Properties.Settings.Default.autoNameFormat != "")\r
+                string destinationFilename;\r
+                if (Properties.Settings.Default.autoNameFormat != string.Empty)\r
                 {\r
-                    destination_filename = Properties.Settings.Default.autoNameFormat;\r
-                    destination_filename = destination_filename.Replace("{source}", source).Replace("{title}", title).Replace("{chapters}", cs + dash + cf);\r
+                    destinationFilename = Properties.Settings.Default.autoNameFormat;\r
+                    destinationFilename =\r
+                        destinationFilename.Replace("{source}", sourceName).Replace("{title}", dvdTitle).Replace(\r
+                            "{chapters}", combinedChapterTag);\r
                 }\r
                 else\r
-                    destination_filename = source + "_T" + title + "_C" + cs + dash + cf;\r
+                    destinationFilename = sourceName + "_T" + dvdTitle + "_C" + combinedChapterTag;\r
 \r
-                // If the text box is blank\r
-                if (!dest.Contains("\\"))\r
+                // Add the appropriate file extension\r
+                if (mainWindow.drop_format.SelectedIndex == 0)\r
                 {\r
-                    string filePath = "";\r
-                    if (Properties.Settings.Default.autoNamePath.Trim() != "")\r
-                    {\r
-                        if (Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location")\r
-                            filePath = Properties.Settings.Default.autoNamePath + "\\";\r
-                    }\r
+                    if (Properties.Settings.Default.useM4v || mainWindow.Check_ChapterMarkers.Checked ||\r
+                        mainWindow.AudioSettings.RequiresM4V() || mainWindow.Subtitles.RequiresM4V())\r
+                        destinationFilename += ".m4v";\r
+                    else\r
+                        destinationFilename += ".mp4";\r
+                }\r
+                else if (mainWindow.drop_format.SelectedIndex == 1)\r
+                    destinationFilename += ".mkv";\r
 \r
-                    if (format == 0)\r
-                        AutoNamePath = filePath + destination_filename + ".mp4";\r
-                    else if (format == 1)\r
-                        AutoNamePath = filePath + destination_filename + ".m4v";\r
-                    else if (format == 2)\r
-                        AutoNamePath = filePath + destination_filename + ".mkv";\r
-                    else if (format == 3)\r
-                        AutoNamePath = filePath + destination_filename + ".avi";\r
-                    else if (format == 4)\r
-                        AutoNamePath = filePath + destination_filename + ".ogm";\r
+                // Now work out the path where the file will be stored.\r
+                // First case: If the destination box doesn't already contain a path, make one.\r
+                if (!mainWindow.text_destination.Text.Contains(Path.DirectorySeparatorChar.ToString()))\r
+                {\r
+                    // If there is an auto name path, use it...\r
+                    if (Properties.Settings.Default.autoNamePath.Trim() != string.Empty &&\r
+                        Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location")\r
+                        autoNamePath = Path.Combine(Properties.Settings.Default.autoNamePath, destinationFilename);\r
+                    else // ...otherwise, output to the source directory\r
+                        autoNamePath = null;\r
                 }\r
-                else // If the text box already has a path and file\r
+                else // Otherwise, use the path that is already there.\r
                 {\r
-                    string destination = AutoNamePath;\r
-                    string[] destName = dest.Split('\\');\r
-                    string[] extension = dest.Split('.');\r
-                    string ext = extension[extension.Length - 1];\r
-\r
-                    destName[destName.Length - 1] = destination_filename + "." + ext;\r
+                    // Use the path and change the file extension to match the previous destination\r
+                    autoNamePath = Path.Combine(Path.GetDirectoryName(mainWindow.text_destination.Text),\r
+                                                destinationFilename);\r
 \r
-                    string fullDest = "";\r
-                    foreach (string part in destName)\r
-                    {\r
-                        if (fullDest != "")\r
-                            fullDest = fullDest + "\\" + part;\r
-                        else\r
-                            fullDest = fullDest + part;\r
-                    }\r
-                    return fullDest;\r
+                    if (Path.HasExtension(mainWindow.text_destination.Text))\r
+                        autoNamePath = Path.ChangeExtension(autoNamePath,\r
+                                                            Path.GetExtension(mainWindow.text_destination.Text));\r
                 }\r
             }\r
-            return AutoNamePath;\r
+\r
+            return autoNamePath;\r
         }\r
 \r
         /// <summary>\r
-        /// Checks for updates and returns true if an update is available.\r
+        /// Get's HandBrakes version data from the CLI.\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 Boolean updateCheck(Boolean debug)\r
+        public static void SetCliVersionData()\r
         {\r
+            string line;\r
+\r
+            // 0 = SVN Build / Version\r
+            // 1 = Build Date\r
+            DateTime lastModified = File.GetLastWriteTime("HandBrakeCLI.exe");\r
+\r
+            if (Properties.Settings.Default.cliLastModified == lastModified && Properties.Settings.Default.hb_build != 0)\r
+                return;\r
+\r
+            Properties.Settings.Default.cliLastModified = lastModified;\r
+\r
+            Process cliProcess = new Process();\r
+            ProcessStartInfo handBrakeCli = new ProcessStartInfo("HandBrakeCLI.exe", " -u -v0")\r
+                                                {\r
+                                                    UseShellExecute = false,\r
+                                                    RedirectStandardError = true,\r
+                                                    RedirectStandardOutput = true,\r
+                                                    CreateNoWindow = true\r
+                                                };\r
+            cliProcess.StartInfo = handBrakeCli;\r
+\r
             try\r
             {\r
-                Functions.AppcastReader rssRead = new Functions.AppcastReader();\r
-                rssRead.getInfo(); // Initializes the class.\r
-                string build = rssRead.build();\r
+                cliProcess.Start();\r
 \r
-                int latest = int.Parse(build);\r
-                int current = Properties.Settings.Default.hb_build;\r
-                int skip = Properties.Settings.Default.skipversion;\r
+                // Retrieve standard output and report back to parent thread until the process is complete\r
+                TextReader stdOutput = cliProcess.StandardError;\r
 \r
-                if (latest == skip)\r
-                    return false;\r
-                else\r
+                while (!cliProcess.HasExited)\r
                 {\r
-                    Boolean update = (latest > current);\r
-                    return update;\r
+                    line = stdOutput.ReadLine() ?? string.Empty;\r
+                    Match m = Regex.Match(line, @"HandBrake ([svnM0-9.]*) \([0-9]*\)");\r
+                    Match platform = Regex.Match(line, @"- ([A-Za-z0-9\s ]*) -");\r
+\r
+                    if (m.Success)\r
+                    {\r
+                        string data = line.Replace("(", string.Empty).Replace(")", string.Empty).Replace("HandBrake ", string.Empty);\r
+                        string[] arr = data.Split(' ');\r
+\r
+                        Properties.Settings.Default.hb_build = int.Parse(arr[1]);\r
+                        Properties.Settings.Default.hb_version = arr[0];\r
+                    }\r
+\r
+                    if (platform.Success)\r
+                    {\r
+                        Properties.Settings.Default.hb_platform = platform.Value.Replace("-", string.Empty).Trim();\r
+                    }\r
+\r
+                    if (cliProcess.TotalProcessorTime.Seconds > 10) // Don't wait longer than 10 seconds.\r
+                    {\r
+                        Process cli = Process.GetProcessById(cliProcess.Id);\r
+                        if (!cli.HasExited)\r
+                        {\r
+                            cli.Kill();\r
+                        }\r
+                    }\r
                 }\r
+\r
+                Properties.Settings.Default.Save();\r
             }\r
-            catch (Exception exc)\r
+            catch (Exception e)\r
             {\r
-                if (debug == true)\r
-                    MessageBox.Show("Unable to check for updates, Please try again later. \n" + exc.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
-                return false;\r
+                frmExceptionWindow exceptionWindow = new frmExceptionWindow();\r
+                exceptionWindow.Setup("Unable to retrieve version information from the CLI.", e.ToString());\r
+                exceptionWindow.ShowDialog();\r
             }\r
         }\r
 \r
         /// <summary>\r
-        /// Get's HandBrakes version data from the CLI.\r
+        /// Check to make sure that the user has an up to date version of the CLI installed.\r
         /// </summary>\r
-        /// <returns>Arraylist of Version Data. 0 = hb_version 1 = hb_build</returns>\r
-        public ArrayList getCliVersionData()\r
+        public static void CheckForValidCliVersion()\r
         {\r
-            ArrayList cliVersionData = new ArrayList();\r
-            // 0 = SVN Build / Version\r
-            // 1 = Build Date\r
-\r
-            Process cliProcess = new Process();\r
-            ProcessStartInfo handBrakeCLI = new ProcessStartInfo("HandBrakeCLI.exe", " -u");\r
-            handBrakeCLI.UseShellExecute = false;\r
-            handBrakeCLI.RedirectStandardError = true;\r
-            handBrakeCLI.RedirectStandardOutput = true;\r
-            handBrakeCLI.CreateNoWindow = true;\r
-            cliProcess.StartInfo = handBrakeCLI;\r
-            cliProcess.Start();\r
-\r
-            // Retrieve standard output and report back to parent thread until the process is complete\r
-            String line;\r
-            TextReader stdOutput = cliProcess.StandardError;\r
-\r
-            while (!cliProcess.HasExited)\r
+            // Make sure we have a recent version for svn builds\r
+            string version = Properties.Settings.Default.hb_version;\r
+            if (version.Contains("svn"))\r
             {\r
-                line = stdOutput.ReadLine();\r
-                Match m = Regex.Match(line, @"HandBrake [0-9\.]*svn[0-9]*[M]* \([0-9]*\)");\r
-                if (m.Success != false)\r
+                version = version.Replace("svn", string.Empty).Trim();\r
+                int build;\r
+                int.TryParse(version, out build);\r
+                if (build < Properties.Settings.Default.hb_min_cli)\r
                 {\r
-                    string data = line.Replace("(", "").Replace(")", "").Replace("HandBrake ", "");\r
-                    string[] arr = data.Split(' ');\r
-                    cliVersionData.Add(arr[0]);\r
-                    cliVersionData.Add(arr[1]);\r
-                    return cliVersionData;\r
+                    MessageBox.Show(\r
+                        "It appears you are trying to use a CLI executable that is too old for this version of the HandBrake GUI.\n" +\r
+                        "Please update the HandBrakeCLI.exe to a newer build.\n\n" +\r
+                        "HandBrake build Detected: " + Properties.Settings.Default.hb_version,\r
+                        "Error",\r
+                        MessageBoxButtons.OK,\r
+                        MessageBoxIcon.Error);\r
+                    return;\r
                 }\r
             }\r
-            return null;\r
         }\r
 \r
         /// <summary>\r
@@ -372,34 +367,469 @@ namespace Handbrake.Functions
         /// If it does, it means the last queue did not complete before HandBrake closed.\r
         /// So, return a boolean if true. \r
         /// </summary>\r
-        public Boolean check_queue_recovery()\r
+        /// <returns>\r
+        /// True if there is a queue to recover.\r
+        /// </returns>\r
+        public static bool CheckQueueRecovery()\r
         {\r
             try\r
             {\r
-                string tempPath = Path.Combine(Path.GetTempPath(), "hb_queue_recovery.dat");\r
-                using (StreamReader reader = new StreamReader(tempPath))\r
+                string tempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\hb_queue_recovery.xml");\r
+                if (File.Exists(tempPath))\r
                 {\r
-                    string queue_item = reader.ReadLine();\r
-                    if (queue_item == null)\r
+                    using (FileStream strm = new FileStream(tempPath, FileMode.Open, FileAccess.Read))\r
                     {\r
-                        reader.Close();\r
-                        reader.Dispose();\r
-                        return false;\r
+                        List<Job> list = Ser.Deserialize(strm) as List<Job>;\r
+                        if (list != null)\r
+                            if (list.Count != 0)\r
+                                return true;\r
                     }\r
-                    else // There exists an item in the recovery queue file, so try and recovr it.\r
+                }\r
+                return false;\r
+            }\r
+            catch (Exception)\r
+            {\r
+                return false; // Keep quiet about the error.\r
+            }\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
+            DateTime startTime = DateTime.Now;\r
+            TimeSpan duration;\r
+\r
+            Process[] hbProcesses = Process.GetProcessesByName("HandBrakeCLI");\r
+            while (hbProcesses.Length == 0)\r
+            {\r
+                hbProcesses = Process.GetProcessesByName("HandBrakeCLI");\r
+                duration = DateTime.Now - startTime;\r
+                if (duration.Seconds > 5 && hbProcesses.Length == 0)\r
+                    // Make sure we don't wait forever if the process doesn't start\r
+                    return -1;\r
+            }\r
+\r
+            Process hbProcess = null;\r
+            foreach (Process process in hbProcesses)\r
+            {\r
+                bool 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") &&\r
+                        !file.Name.Contains("tmp_appReadable_log.txt"))\r
+                        File.Delete(file.FullName);\r
+                }\r
+            }\r
+        }\r
+\r
+        /// <summary>\r
+        /// Clear old log files x days in the past\r
+        /// </summary>\r
+        public static void ClearOldLogs()\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
+\r
+                foreach (FileInfo file in logFiles)\r
+                {\r
+                    if (file.LastWriteTime < DateTime.Now.AddDays(-30))\r
                     {\r
-                        reader.Close();\r
-                        reader.Dispose();\r
-                        return true;\r
+                        if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") &&\r
+                            !file.Name.Contains("tmp_appReadable_log.txt"))\r
+                            File.Delete(file.FullName);\r
                     }\r
                 }\r
             }\r
-            catch (Exception)\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 =\r
+                                                                          Properties.Settings.Default.hb_build.ToString()\r
+                                                                              .EndsWith("1")\r
+                                                                              ? Properties.Settings.Default.\r
+                                                                                    appcast_unstable\r
+                                                                              : 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(\r
+                                                                          new StreamReader(response.GetResponseStream())\r
+                                                                              .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 =\r
+                                                                              new UpdateCheckInformation\r
+                                                                                  {\r
+                                                                                      NewVersionAvailable = false,\r
+                                                                                      BuildInformation = null\r
+                                                                                  };\r
+                                                                          callback(new UpdateCheckResult(debug, info));\r
+                                                                          return;\r
+                                                                      }\r
+\r
+                                                                      // Set when the last update was\r
+                                                                      Properties.Settings.Default.lastUpdateCheckDate =\r
+                                                                          DateTime.Now;\r
+                                                                      Properties.Settings.Default.Save();\r
+\r
+                                                                      UpdateCheckInformation info2 =\r
+                                                                          new UpdateCheckInformation\r
+                                                                              {\r
+                                                                                  NewVersionAvailable = latest > current,\r
+                                                                                  BuildInformation = reader\r
+                                                                              };\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
+        /// End Check for Updates\r
+        /// </summary>\r
+        /// <param name="result">\r
+        /// The result.\r
+        /// </param>\r
+        /// <returns>\r
+        /// Update Check information\r
+        /// </returns>\r
+        public static UpdateCheckInformation EndCheckForUpdates(IAsyncResult result)\r
+        {\r
+            UpdateCheckResult checkResult = (UpdateCheckResult)result;\r
+            return checkResult.Result;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Map languages and their iso639_2 value into a IDictionary\r
+        /// </summary>\r
+        /// <returns>A Dictionary containing the language and iso code</returns>\r
+        public static IDictionary<string, string> MapLanguages()\r
+        {\r
+            IDictionary<string, string> languageMap = new Dictionary<string, string>\r
+                                                          {\r
+                                                              {"Any", "und"}, \r
+                                                              {"Afar", "aar"}, \r
+                                                              {"Abkhazian", "abk"}, \r
+                                                              {"Afrikaans", "afr"}, \r
+                                                              {"Akan", "aka"}, \r
+                                                              {"Albanian", "sqi"}, \r
+                                                              {"Amharic", "amh"}, \r
+                                                              {"Arabic", "ara"}, \r
+                                                              {"Aragonese", "arg"}, \r
+                                                              {"Armenian", "hye"}, \r
+                                                              {"Assamese", "asm"}, \r
+                                                              {"Avaric", "ava"}, \r
+                                                              {"Avestan", "ave"}, \r
+                                                              {"Aymara", "aym"}, \r
+                                                              {"Azerbaijani", "aze"}, \r
+                                                              {"Bashkir", "bak"}, \r
+                                                              {"Bambara", "bam"}, \r
+                                                              {"Basque", "eus"}, \r
+                                                              {"Belarusian", "bel"}, \r
+                                                              {"Bengali", "ben"}, \r
+                                                              {"Bihari", "bih"}, \r
+                                                              {"Bislama", "bis"}, \r
+                                                              {"Bosnian", "bos"}, \r
+                                                              {"Breton", "bre"}, \r
+                                                              {"Bulgarian", "bul"}, \r
+                                                              {"Burmese", "mya"}, \r
+                                                              {"Catalan", "cat"}, \r
+                                                              {"Chamorro", "cha"}, \r
+                                                              {"Chechen", "che"}, \r
+                                                              {"Chinese", "zho"}, \r
+                                                              {"Church Slavic", "chu"}, \r
+                                                              {"Chuvash", "chv"}, \r
+                                                              {"Cornish", "cor"}, \r
+                                                              {"Corsican", "cos"}, \r
+                                                              {"Cree", "cre"}, \r
+                                                              {"Czech", "ces"}, \r
+                                                              {"Dansk", "dan"}, \r
+                                                              {"Divehi", "div"}, \r
+                                                              {"Nederlands", "nld"}, \r
+                                                              {"Dzongkha", "dzo"}, \r
+                                                              {"English", "eng"}, \r
+                                                              {"Esperanto", "epo"}, \r
+                                                              {"Estonian", "est"}, \r
+                                                              {"Ewe", "ewe"}, \r
+                                                              {"Faroese", "fao"}, \r
+                                                              {"Fijian", "fij"}, \r
+                                                              {"Suomi", "fin"}, \r
+                                                              {"Francais", "fra"}, \r
+                                                              {"Western Frisian", "fry"}, \r
+                                                              {"Fulah", "ful"}, \r
+                                                              {"Georgian", "kat"}, \r
+                                                              {"Deutsch", "deu"}, \r
+                                                              {"Gaelic (Scots)", "gla"}, \r
+                                                              {"Irish", "gle"}, \r
+                                                              {"Galician", "glg"}, \r
+                                                              {"Manx", "glv"}, \r
+                                                              {"Greek Modern", "ell"}, \r
+                                                              {"Guarani", "grn"}, \r
+                                                              {"Gujarati", "guj"}, \r
+                                                              {"Haitian", "hat"}, \r
+                                                              {"Hausa", "hau"}, \r
+                                                              {"Hebrew", "heb"}, \r
+                                                              {"Herero", "her"}, \r
+                                                              {"Hindi", "hin"}, \r
+                                                              {"Hiri Motu", "hmo"}, \r
+                                                              {"Magyar", "hun"}, \r
+                                                              {"Igbo", "ibo"}, \r
+                                                              {"Islenska", "isl"}, \r
+                                                              {"Ido", "ido"}, \r
+                                                              {"Sichuan Yi", "iii"}, \r
+                                                              {"Inuktitut", "iku"}, \r
+                                                              {"Interlingue", "ile"}, \r
+                                                              {"Interlingua", "ina"}, \r
+                                                              {"Indonesian", "ind"}, \r
+                                                              {"Inupiaq", "ipk"}, \r
+                                                              {"Italiano", "ita"}, \r
+                                                              {"Javanese", "jav"}, \r
+                                                              {"Japanese", "jpn"}, \r
+                                                              {"Kalaallisut", "kal"}, \r
+                                                              {"Kannada", "kan"}, \r
+                                                              {"Kashmiri", "kas"}, \r
+                                                              {"Kanuri", "kau"}, \r
+                                                              {"Kazakh", "kaz"}, \r
+                                                              {"Central Khmer", "khm"}, \r
+                                                              {"Kikuyu", "kik"}, \r
+                                                              {"Kinyarwanda", "kin"}, \r
+                                                              {"Kirghiz", "kir"}, \r
+                                                              {"Komi", "kom"}, \r
+                                                              {"Kongo", "kon"}, \r
+                                                              {"Korean", "kor"}, \r
+                                                              {"Kuanyama", "kua"}, \r
+                                                              {"Kurdish", "kur"}, \r
+                                                              {"Lao", "lao"}, \r
+                                                              {"Latin", "lat"}, \r
+                                                              {"Latvian", "lav"}, \r
+                                                              {"Limburgan", "lim"}, \r
+                                                              {"Lingala", "lin"}, \r
+                                                              {"Lithuanian", "lit"}, \r
+                                                              {"Luxembourgish", "ltz"}, \r
+                                                              {"Luba-Katanga", "lub"}, \r
+                                                              {"Ganda", "lug"}, \r
+                                                              {"Macedonian", "mkd"}, \r
+                                                              {"Marshallese", "mah"}, \r
+                                                              {"Malayalam", "mal"}, \r
+                                                              {"Maori", "mri"}, \r
+                                                              {"Marathi", "mar"}, \r
+                                                              {"Malay", "msa"}, \r
+                                                              {"Malagasy", "mlg"}, \r
+                                                              {"Maltese", "mlt"}, \r
+                                                              {"Moldavian", "mol"}, \r
+                                                              {"Mongolian", "mon"}, \r
+                                                              {"Nauru", "nau"}, \r
+                                                              {"Navajo", "nav"}, \r
+                                                              {"Ndebele, South", "nbl"}, \r
+                                                              {"Ndebele, North", "nde"}, \r
+                                                              {"Ndonga", "ndo"}, \r
+                                                              {"Nepali", "nep"}, \r
+                                                              {"Norwegian Nynorsk", "nno"}, \r
+                                                              {"Norwegian Bokmål", "nob"}, \r
+                                                              {"Norsk", "nor"}, \r
+                                                              {"Chichewa; Nyanja", "nya"}, \r
+                                                              {"Occitan", "oci"}, \r
+                                                              {"Ojibwa", "oji"}, \r
+                                                              {"Oriya", "ori"}, \r
+                                                              {"Oromo", "orm"}, \r
+                                                              {"Ossetian", "oss"}, \r
+                                                              {"Panjabi", "pan"}, \r
+                                                              {"Persian", "fas"}, \r
+                                                              {"Pali", "pli"}, \r
+                                                              {"Polish", "pol"}, \r
+                                                              {"Portugues", "por"}, \r
+                                                              {"Pushto", "pus"}, \r
+                                                              {"Quechua", "que"}, \r
+                                                              {"Romansh", "roh"}, \r
+                                                              {"Romanian", "ron"}, \r
+                                                              {"Rundi", "run"}, \r
+                                                              {"Russian", "rus"}, \r
+                                                              {"Sango", "sag"}, \r
+                                                              {"Sanskrit", "san"}, \r
+                                                              {"Serbian", "srp"}, \r
+                                                              {"Hrvatski", "hrv"}, \r
+                                                              {"Sinhala", "sin"}, \r
+                                                              {"Slovak", "slk"}, \r
+                                                              {"Slovenian", "slv"}, \r
+                                                              {"Northern Sami", "sme"}, \r
+                                                              {"Samoan", "smo"}, \r
+                                                              {"Shona", "sna"}, \r
+                                                              {"Sindhi", "snd"}, \r
+                                                              {"Somali", "som"}, \r
+                                                              {"Sotho Southern", "sot"}, \r
+                                                              {"Espanol", "spa"}, \r
+                                                              {"Sardinian", "srd"}, \r
+                                                              {"Swati", "ssw"}, \r
+                                                              {"Sundanese", "sun"}, \r
+                                                              {"Swahili", "swa"}, \r
+                                                              {"Svenska", "swe"}, \r
+                                                              {"Tahitian", "tah"}, \r
+                                                              {"Tamil", "tam"}, \r
+                                                              {"Tatar", "tat"}, \r
+                                                              {"Telugu", "tel"}, \r
+                                                              {"Tajik", "tgk"}, \r
+                                                              {"Tagalog", "tgl"}, \r
+                                                              {"Thai", "tha"}, \r
+                                                              {"Tibetan", "bod"}, \r
+                                                              {"Tigrinya", "tir"}, \r
+                                                              {"Tonga", "ton"}, \r
+                                                              {"Tswana", "tsn"}, \r
+                                                              {"Tsonga", "tso"}, \r
+                                                              {"Turkmen", "tuk"}, \r
+                                                              {"Turkish", "tur"}, \r
+                                                              {"Twi", "twi"}, \r
+                                                              {"Uighur", "uig"}, \r
+                                                              {"Ukrainian", "ukr"}, \r
+                                                              {"Urdu", "urd"}, \r
+                                                              {"Uzbek", "uzb"}, \r
+                                                              {"Venda", "ven"}, \r
+                                                              {"Vietnamese", "vie"}, \r
+                                                              {"Volapük", "vol"}, \r
+                                                              {"Welsh", "cym"}, \r
+                                                              {"Walloon", "wln"}, \r
+                                                              {"Wolof", "wol"}, \r
+                                                              {"Xhosa", "xho"}, \r
+                                                              {"Yiddish", "yid"}, \r
+                                                              {"Yoruba", "yor"}, \r
+                                                              {"Zhuang", "zha"}, \r
+                                                              {"Zulu", "zul"}\r
+                                                          };\r
+            return languageMap;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Get a list of available DVD drives which are ready and contain DVD content.\r
+        /// </summary>\r
+        /// <returns>A List of Drives with their details</returns>\r
+        public static List<DriveInformation> GetDrives()\r
+        {\r
+            List<DriveInformation> drives = new List<DriveInformation>();\r
+            DriveInfo[] theCollectionOfDrives = DriveInfo.GetDrives();\r
+            int id = 0;\r
+            foreach (DriveInfo curDrive in theCollectionOfDrives)\r
             {\r
-                // Keep quiet about the error.\r
-                return false;\r
+                if (curDrive.DriveType == DriveType.CDRom && curDrive.IsReady &&\r
+                    File.Exists(curDrive.RootDirectory + "VIDEO_TS\\VIDEO_TS.IFO"))\r
+                {\r
+                    drives.Add(new DriveInformation\r
+                                   {\r
+                                       Id = id,\r
+                                       VolumeLabel = curDrive.VolumeLabel,\r
+                                       RootDirectory = curDrive.RootDirectory + "VIDEO_TS"\r
+                                   });\r
+                    id++;\r
+                }\r
             }\r
+            return drives;\r
         }\r
 \r
+        /// <summary>\r
+        /// Change a string to Title Case/\r
+        /// </summary>\r
+        /// <param name="input">\r
+        /// The input.\r
+        /// </param>\r
+        /// <returns>\r
+        /// A string in title case.\r
+        /// </returns>\r
+        public static string TitleCase(string input)\r
+        {\r
+            string[] tokens = input.Split(' ');\r
+            StringBuilder sb = new StringBuilder(input.Length);\r
+            foreach (string s in tokens)\r
+            {\r
+                sb.Append(s[0].ToString().ToUpper());\r
+                sb.Append(s.Substring(1).ToLower());\r
+                sb.Append(" ");\r
+            }\r
+\r
+            return sb.ToString().Trim();\r
+        }\r
+\r
+        /// <summary>\r
+        /// Show the Exception Window\r
+        /// </summary>\r
+        /// <param name="shortError">\r
+        /// The short error.\r
+        /// </param>\r
+        /// <param name="longError">\r
+        /// The long error.\r
+        /// </param>\r
+        public static void ShowExceptiowWindow(string shortError, string longError)\r
+        {\r
+            frmExceptionWindow exceptionWindow = new frmExceptionWindow();\r
+            exceptionWindow.Setup(shortError, longError);\r
+            exceptionWindow.Show();\r
+        }\r
     }\r
 }
\ No newline at end of file