OSDN Git Service

WinGui:
[handbrake-jp/handbrake-jp-git.git] / win / C# / Functions / Main.cs
index cb82a4b..f78d38a 100644 (file)
@@ -8,16 +8,20 @@ namespace Handbrake.Functions
     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.Linq;\r
+    using System.Security.Cryptography;\r
     using System.Text;\r
     using System.Text.RegularExpressions;\r
-    using System.Threading;\r
     using System.Windows.Forms;\r
     using System.Xml.Serialization;\r
+\r
+    using HandBrake.Framework.Services;\r
+    using HandBrake.Framework.Services.Interfaces;\r
+    using HandBrake.ApplicationServices.Model;\r
+    using HandBrake.ApplicationServices.Parsing;\r
+    using HandBrake.ApplicationServices.Services.Interfaces;\r
     using Model;\r
-    using Parsing;\r
 \r
     /// <summary>\r
     /// Useful functions which various screens can use.\r
@@ -25,9 +29,14 @@ namespace Handbrake.Functions
     public static class Main\r
     {\r
         /// <summary>\r
+        /// The Error Service\r
+        /// </summary>\r
+        private static readonly IErrorService errorService = new ErrorService();\r
+\r
+        /// <summary>\r
         /// The XML Serializer\r
         /// </summary>\r
-        private static readonly XmlSerializer Ser = new XmlSerializer(typeof(List<Job>));\r
+        private static readonly XmlSerializer Ser = new XmlSerializer(typeof(List<QueueTask>));\r
 \r
         /// <summary>\r
         /// Calculate the duration of the selected title and chapters\r
@@ -61,6 +70,10 @@ namespace Handbrake.Functions
         /// <summary>\r
         /// Set's up the DataGridView on the Chapters tab (frmMain)\r
         /// </summary>\r
+        /// <param name="title">\r
+        /// The currently selected title object.\r
+        /// This will be used to get chapter names if they exist.\r
+        /// </param>\r
         /// <param name="dataChpt">\r
         /// The DataGridView Control\r
         /// </param>\r
@@ -70,7 +83,7 @@ namespace Handbrake.Functions
         /// <returns>\r
         /// The chapter naming.\r
         /// </returns>\r
-        public static DataGridView ChapterNaming(DataGridView dataChpt, string chapterEnd)\r
+        public static DataGridView ChapterNaming(Title title, DataGridView dataChpt, string chapterEnd)\r
         {\r
             int i = 0, finish = 0;\r
 \r
@@ -79,9 +92,18 @@ namespace Handbrake.Functions
 \r
             while (i < finish)\r
             {\r
+                string chapterName = string.Empty;\r
+                if (title != null)\r
+                {\r
+                    if (title.Chapters.Count <= i && title.Chapters[i] != null)\r
+                    {\r
+                        chapterName = title.Chapters[i].ChapterName;\r
+                    }\r
+                }\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[1].Value = string.IsNullOrEmpty(chapterName) ? "Chapter " + (i + 1) : chapterName;\r
                 dataChpt.Rows[n].Cells[0].ValueType = typeof(int);\r
                 dataChpt.Rows[n].Cells[1].ValueType = typeof(string);\r
                 i++;\r
@@ -136,6 +158,38 @@ namespace Handbrake.Functions
         }\r
 \r
         /// <summary>\r
+        /// Create a CSV file with the data from the Main Window Chapters tab\r
+        /// </summary>\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
+                string csv = string.Empty;\r
+\r
+                foreach (DataGridViewRow row in mainWindow.data_chpt.Rows)\r
+                {\r
+                    csv += row.Cells[0].Value.ToString();\r
+                    csv += ",";\r
+                    csv += row.Cells[1].Value.ToString().Replace(",", "\\,");\r
+                    csv += Environment.NewLine;\r
+                }\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
+                ShowExceptiowWindow("Unable to save Chapter Makrers file! \nChapter marker names will NOT be saved in your encode", exc.ToString());\r
+                return false;\r
+            }\r
+        }\r
+\r
+        /// <summary>\r
         /// Function which generates the filename and path automatically based on \r
         /// the Source Name, DVD title and DVD Chapters\r
         /// </summary>\r
@@ -150,8 +204,9 @@ namespace Handbrake.Functions
             string autoNamePath = string.Empty;\r
             if (mainWindow.drp_dvdtitle.Text != "Automatic")\r
             {\r
-                // Get the Source Name \r
-                string sourceName = mainWindow.SourceName;\r
+                // Get the Source Name and remove any invalid characters\r
+\r
+                string sourceName = Path.GetInvalidFileNameChars().Aggregate(Path.GetFileNameWithoutExtension(mainWindow.SourceName), (current, character) => current.Replace(character.ToString(), string.Empty));\r
 \r
                 if (Properties.Settings.Default.AutoNameRemoveUnderscore)\r
                     sourceName = sourceName.Replace("_", " ");\r
@@ -175,9 +230,9 @@ namespace Handbrake.Functions
                 if (Properties.Settings.Default.autoNameFormat != string.Empty)\r
                 {\r
                     destinationFilename = Properties.Settings.Default.autoNameFormat;\r
-                    destinationFilename =\r
-                        destinationFilename.Replace("{source}", sourceName).Replace("{title}", dvdTitle).Replace(\r
-                            "{chapters}", combinedChapterTag);\r
+                    destinationFilename = destinationFilename.Replace("{source}", sourceName)\r
+                                                             .Replace("{title}", dvdTitle)\r
+                                                             .Replace("{chapters}", combinedChapterTag);\r
                 }\r
                 else\r
                     destinationFilename = sourceName + "_T" + dvdTitle + "_C" + combinedChapterTag;\r
@@ -185,11 +240,10 @@ namespace Handbrake.Functions
                 // Add the appropriate file extension\r
                 if (mainWindow.drop_format.SelectedIndex == 0)\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
+                    destinationFilename += Properties.Settings.Default.useM4v == 0 || Properties.Settings.Default.useM4v == 2 || mainWindow.Check_ChapterMarkers.Checked ||\r
+                                           mainWindow.AudioSettings.RequiresM4V() || mainWindow.Subtitles.RequiresM4V()\r
+                                               ? ".m4v"\r
+                                               : ".mp4";\r
                 }\r
                 else if (mainWindow.drop_format.SelectedIndex == 1)\r
                     destinationFilename += ".mkv";\r
@@ -199,9 +253,19 @@ namespace Handbrake.Functions
                 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
+                    if (Properties.Settings.Default.autoNamePath.Trim() == "{source_path}" && !string.IsNullOrEmpty(mainWindow.sourcePath))\r
+                    {\r
+                        autoNamePath = Path.Combine(Path.GetDirectoryName(mainWindow.sourcePath), destinationFilename);\r
+                        if (autoNamePath == mainWindow.sourcePath)\r
+                        {\r
+                            // Append out_ to files that already exist or is the source file\r
+                            autoNamePath = Path.Combine(Path.GetDirectoryName(mainWindow.sourcePath), "output_" + destinationFilename);\r
+                        }\r
+                    }\r
+                    else if (Properties.Settings.Default.autoNamePath.Trim() != string.Empty && Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location")\r
+                    {\r
                         autoNamePath = Path.Combine(Properties.Settings.Default.autoNamePath, destinationFilename);\r
+                    }\r
                     else // ...otherwise, output to the source directory\r
                         autoNamePath = null;\r
                 }\r
@@ -211,15 +275,8 @@ namespace Handbrake.Functions
                     autoNamePath = Path.Combine(Path.GetDirectoryName(mainWindow.text_destination.Text), destinationFilename);\r
 \r
                     if (Path.HasExtension(mainWindow.text_destination.Text))\r
-                        autoNamePath = Path.ChangeExtension(autoNamePath, Path.GetExtension(mainWindow.text_destination.Text));\r
-                }\r
-            }\r
-\r
-            foreach (char character in Path.GetInvalidFileNameChars())\r
-            {\r
-                if (autoNamePath != null)\r
-                {\r
-                    autoNamePath = autoNamePath.Replace(character.ToString(), string.Empty);\r
+                        autoNamePath = Path.ChangeExtension(autoNamePath,\r
+                                                            Path.GetExtension(mainWindow.text_destination.Text));\r
                 }\r
             }\r
 \r
@@ -235,13 +292,22 @@ namespace Handbrake.Functions
 \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
+            // Get the SHA1 Hash of HandBrakeCLI\r
+            byte[] hash;\r
+            using (Stream stream = File.OpenRead(Path.Combine(Application.StartupPath, "HandBrakeCLI.exe")))\r
+            {\r
+                hash = SHA1.Create().ComputeHash(stream);\r
+            }\r
+            string base64Hash = Convert.ToBase64String(hash);\r
+         \r
+            // Compare the hash with the last known hash. If it's the same, return.\r
+            if (Properties.Settings.Default.CliExeHash == base64Hash)\r
+            {\r
                 return;\r
+            }\r
 \r
-            Properties.Settings.Default.cliLastModified = lastModified;\r
-\r
+            // It's not the same, so start the CLI to get it's version data.\r
             Process cliProcess = new Process();\r
             ProcessStartInfo handBrakeCli = new ProcessStartInfo("HandBrakeCLI.exe", " -u -v0")\r
                                                 {\r
@@ -262,16 +328,19 @@ namespace Handbrake.Functions
                 while (!cliProcess.HasExited)\r
                 {\r
                     line = stdOutput.ReadLine() ?? string.Empty;\r
-                    Match m = Regex.Match(line, @"HandBrake ([svnM0-9.]*) \([0-9]*\)");\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
+                        string version = m.Groups[1].Success ? m.Groups[1].Value : string.Empty;\r
+                        string build = m.Groups[2].Success ? m.Groups[2].Value : string.Empty;\r
 \r
-                        Properties.Settings.Default.hb_build = int.Parse(arr[1]);\r
-                        Properties.Settings.Default.hb_version = arr[0];\r
+                        int buildValue;\r
+                        int.TryParse(build, out buildValue);\r
+\r
+                        Properties.Settings.Default.hb_build = buildValue;\r
+                        Properties.Settings.Default.hb_version = version;\r
                     }\r
 \r
                     if (platform.Success)\r
@@ -289,37 +358,17 @@ namespace Handbrake.Functions
                     }\r
                 }\r
 \r
+                Properties.Settings.Default.CliExeHash = base64Hash;\r
+\r
                 Properties.Settings.Default.Save();\r
             }\r
             catch (Exception e)\r
             {\r
-                MessageBox.Show("Unable to retrieve version information from the CLI. \nError:\n" + e);\r
-            }\r
-        }\r
+                Properties.Settings.Default.hb_build = 0;\r
+                Properties.Settings.Default.CliExeHash = null;\r
+                Properties.Settings.Default.Save();\r
 \r
-        /// <summary>\r
-        /// Check to make sure that the user has an up to date version of the CLI installed.\r
-        /// </summary>\r
-        public static void CheckForValidCliVersion()\r
-        {\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
-                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
-                    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
+                ShowExceptiowWindow("Unable to retrieve version information from the CLI.", e.ToString());\r
             }\r
         }\r
 \r
@@ -331,203 +380,95 @@ namespace Handbrake.Functions
         /// <returns>\r
         /// True if there is a queue to recover.\r
         /// </returns>\r
-        public static bool CheckQueueRecovery()\r
+        public static List<string> CheckQueueRecovery()\r
         {\r
             try\r
             {\r
-                string tempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\hb_queue_recovery.xml");\r
-                if (File.Exists(tempPath))\r
+                string tempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\");\r
+                List<string> queueFiles = new List<string>();\r
+\r
+                DirectoryInfo info = new DirectoryInfo(tempPath);\r
+                FileInfo[] logFiles = info.GetFiles("*.xml");\r
+                foreach (FileInfo file in logFiles)\r
                 {\r
-                    using (FileStream strm = new FileStream(tempPath, FileMode.Open, FileAccess.Read))\r
+                    if (!file.Name.Contains("hb_queue_recovery"))\r
+                        continue;\r
+\r
+                    using (FileStream strm = new FileStream(Path.Combine(file.DirectoryName, file.Name), FileMode.Open, FileAccess.Read))\r
                     {\r
-                        List<Job> list = Ser.Deserialize(strm) as List<Job>;\r
+                        List<QueueTask> list = Ser.Deserialize(strm) as List<QueueTask>;\r
                         if (list != null)\r
+                        {\r
                             if (list.Count != 0)\r
-                                return true;\r
+                            {\r
+                                queueFiles.Add(file.Name);\r
+                            }\r
+                        }\r
                     }\r
                 }\r
-                return false;\r
+\r
+                return queueFiles;\r
             }\r
             catch (Exception)\r
             {\r
-                return false; // Keep quiet about the error.\r
+                return new List<string>(); // Keep quiet about the error.\r
             }\r
         }\r
 \r
         /// <summary>\r
-        /// Get the Process ID of HandBrakeCLI for the current instance.\r
+        /// Recover a queue from file.\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
+        /// <param name="encodeQueue">\r
+        /// The encode Queue.\r
+        /// </param>\r
+        public static void RecoverQueue(IQueueProcessor encodeQueue)\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
+            string appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\");\r
 \r
-            Process[] hbProcesses = Process.GetProcessesByName("HandBrakeCLI");\r
-            while (hbProcesses.Length == 0)\r
+            DialogResult result = DialogResult.None;\r
+            List<string> queueFiles = CheckQueueRecovery();\r
+            if (queueFiles.Count == 1)\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
+                result = MessageBox.Show(\r
+                        "HandBrake has detected unfinished items on the queue from the last time the application was launched. Would you like to recover these?",\r
+                        "Queue Recovery Possible", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
             }\r
-\r
-            Process hbProcess = null;\r
-            foreach (Process process in hbProcesses)\r
+            else if (queueFiles.Count > 1)\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
+                result = MessageBox.Show(\r
+                        "HandBrake has detected multiple unfinished queue files. These will be from multiple instances of HandBrake running. Would you like to recover all unfinished jobs?",\r
+                        "Queue Recovery Possible", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\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
+            if (result == DialogResult.Yes)\r
             {\r
-                DirectoryInfo info = new DirectoryInfo(logDir);\r
-                FileInfo[] logFiles = info.GetFiles("*.txt");\r
-                foreach (FileInfo file in logFiles)\r
+                foreach (string file in queueFiles)\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
+                    encodeQueue.QueueManager.RestoreQueue(appDataPath + file); // Start Recovery\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
+            else\r
             {\r
-                DirectoryInfo info = new DirectoryInfo(logDir);\r
-                FileInfo[] logFiles = info.GetFiles("*.txt");\r
+                if (IsMultiInstance) return; // Don't tamper with the files if we are multi instance\r
 \r
-                foreach (FileInfo file in logFiles)\r
+                foreach (string file in queueFiles)\r
                 {\r
-                    if (file.LastWriteTime < DateTime.Now.AddDays(-30))\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
+                    if (File.Exists(Path.Combine(appDataPath, file)))\r
+                        File.Delete(Path.Combine(appDataPath, file));\r
                 }\r
             }\r
         }\r
 \r
         /// <summary>\r
-        /// Begins checking for an update to HandBrake.\r
+        /// Gets a value indicating whether HandBrake is running in multi instance mode\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
+        /// <returns>True if the UI has another instance running</returns>\r
+        public static bool IsMultiInstance\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
+            get\r
+            {\r
+                return Process.GetProcessesByName("HandBrake").Length > 0 ? true : false;\r
+            }\r
         }\r
 \r
         /// <summary>\r
@@ -729,32 +670,6 @@ namespace Handbrake.Functions
         }\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
-                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
@@ -769,12 +684,69 @@ namespace Handbrake.Functions
             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
+                if (!string.IsNullOrEmpty(s))\r
+                {\r
+                    sb.Append(s[0].ToString().ToUpper());\r
+                    sb.Append(s.Substring(1).ToLower());\r
+                    sb.Append(" ");\r
+                }\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
+            errorService.ShowError(shortError, longError);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Get The Source from the CLI Query\r
+        /// </summary>\r
+        /// <param name="query">Full CLI Query</param>\r
+        /// <returns>The Source Path</returns>\r
+        public static string GetSourceFromQuery(string query)\r
+        {\r
+            int startIndex = query.IndexOf("-i \"");\r
+            if (startIndex != -1)\r
+            {\r
+                string input = query.Substring(startIndex).Replace("-i \"", string.Empty).Trim();\r
+\r
+                int closeIndex = input.IndexOf('"');\r
+\r
+                return closeIndex == -1 ? "Unknown" : input.Substring(0, closeIndex);\r
+            }\r
+\r
+            return "Unknown";\r
+        }\r
+\r
+        /// <summary>\r
+        /// Get the Destination from the CLI Query\r
+        /// </summary>\r
+        /// <param name="query">Full CLI Query</param>\r
+        /// <returns>The Destination path</returns>\r
+        public static string GetDestinationFromQuery(string query)\r
+        {\r
+            int startIndex = query.IndexOf("-o \"");\r
+            if (startIndex != -1)\r
+            {\r
+                string output = query.Substring(startIndex).Replace("-o \"", string.Empty).Trim();\r
+\r
+                int closeIndex = output.IndexOf('"');\r
+\r
+                return closeIndex == -1 ? "Unknown" : output.Substring(0, closeIndex);\r
+            }\r
+\r
+            return "Unknown";\r
+        }\r
     }\r
 }
\ No newline at end of file