OSDN Git Service

WinGui:
[handbrake-jp/handbrake-jp-git.git] / win / C# / frmMain.cs
index 91e3970..a5b131b 100644 (file)
@@ -12,27 +12,35 @@ namespace Handbrake
     using System.Drawing;\r
     using System.Globalization;\r
     using System.IO;\r
-    using System.Reflection;\r
     using System.Threading;\r
     using System.Windows.Forms;\r
     using Functions;\r
+\r
+    using HandBrake.ApplicationServices.Functions;\r
+    using HandBrake.ApplicationServices.Model;\r
+    using HandBrake.ApplicationServices.Parsing;\r
+    using HandBrake.ApplicationServices.Services;\r
+    using HandBrake.ApplicationServices.Services.Interfaces;\r
+\r
     using Model;\r
-    using Parsing;\r
     using Presets;\r
     using Properties;\r
-    using Services;\r
 \r
+    using Main = Handbrake.Functions.Main;\r
+\r
+    /// <summary>\r
+    /// The Main Window\r
+    /// </summary>\r
     public partial class frmMain : Form\r
     {\r
         // Objects which may be used by one or more other objects *************\r
-        private Queue encodeQueue = new Queue();\r
+        private IQueue encodeQueue = new Queue();\r
         private PresetsHandler presetHandler = new PresetsHandler();\r
 \r
         // Windows ************************************************************\r
         private frmQueue queueWindow;\r
         private frmPreview qtpreview;\r
-        private frmActivityWindow ActivityWindow;\r
-        private frmSplashScreen splash = new frmSplashScreen();\r
+        private frmActivityWindow activityWindow;\r
 \r
         // Globals: Mainly used for tracking. *********************************\r
         public Title selectedTitle;\r
@@ -40,11 +48,10 @@ namespace Handbrake
         private SourceType selectedSourceType;\r
         private string dvdDrivePath;\r
         private string dvdDriveLabel;\r
-        private Preset CurrentlySelectedPreset;\r
+        private Preset currentlySelectedPreset;\r
         private DVD currentSource;\r
-        private ScanService SourceScan = new ScanService();\r
+        private IScan SourceScan = new ScanService();\r
         private List<DriveInformation> drives;\r
-        private Thread encodeMonitor;\r
 \r
         // Delegates **********************************************************\r
         private delegate void UpdateWindowHandler();\r
@@ -76,78 +83,64 @@ namespace Handbrake
 \r
         #region Application Startup\r
 \r
-        public frmMain()\r
+        /// <summary>\r
+        /// Initializes a new instance of the <see cref="frmMain"/> class.\r
+        /// </summary>\r
+        /// <param name="args">\r
+        /// The arguments passed in on application startup.\r
+        /// </param>\r
+        public frmMain(string[] args)\r
         {\r
-            // Load and setup the splash screen in this thread\r
-            splash.Show(this);\r
-            Label lblStatus = new Label { Size = new Size(150, 20), Location = new Point(182, 102) };\r
-            splash.Controls.Add(lblStatus);\r
-\r
             InitializeComponent();\r
 \r
             // Update the users config file with the CLI version data.\r
-            UpdateSplashStatus(lblStatus, "Checking CLI Version Data ...");\r
             Main.SetCliVersionData();\r
-            Main.CheckForValidCliVersion();\r
 \r
             if (Settings.Default.hb_version.Contains("svn"))\r
             {\r
-                Version v = Assembly.GetExecutingAssembly().GetName().Version;\r
-                this.Text += " " + v.ToString(4);\r
+                this.Text += " " + Settings.Default.hb_version;\r
             }\r
 \r
-            // Show the form, but leave disabled until preloading is complete then show the main form)\r
-            this.Enabled = false;\r
-            this.Show();\r
-            Application.DoEvents(); // Forces frmMain to draw\r
-\r
             // Check for new versions, if update checking is enabled\r
-            if (Properties.Settings.Default.updateStatus)\r
+            if (Settings.Default.updateStatus)\r
             {\r
-                DateTime now = DateTime.Now;\r
-                DateTime lastCheck = Properties.Settings.Default.lastUpdateCheckDate;\r
-                TimeSpan elapsed = now.Subtract(lastCheck);\r
-                if (elapsed.TotalDays > Properties.Settings.Default.daysBetweenUpdateCheck)\r
+                if (DateTime.Now.Subtract(Settings.Default.lastUpdateCheckDate).TotalDays > Properties.Settings.Default.daysBetweenUpdateCheck)\r
                 {\r
-                    UpdateSplashStatus(lblStatus, "Checking for updates ...");\r
                     Main.BeginCheckForUpdates(new AsyncCallback(UpdateCheckDone), false);\r
                 }\r
             }\r
 \r
             // Clear the log files in the background\r
-            if (Properties.Settings.Default.clearOldLogs)\r
+            if (Settings.Default.clearOldLogs)\r
             {\r
-                UpdateSplashStatus(lblStatus, "Clearing Old Log Files ..");\r
                 Thread clearLog = new Thread(Main.ClearOldLogs);\r
                 clearLog.Start();\r
             }\r
 \r
             // Setup the GUI components\r
-            UpdateSplashStatus(lblStatus, "Setting up the GUI ...");\r
             LoadPresetPanel(); // Load the Preset Panel\r
             treeView_presets.ExpandAll();\r
             lbl_encode.Text = string.Empty;\r
             drop_mode.SelectedIndex = 0;\r
             queueWindow = new frmQueue(encodeQueue, this); // Prepare the Queue\r
-            if (!Properties.Settings.Default.QueryEditorTab)\r
+            if (!Settings.Default.QueryEditorTab)\r
                 tabs_panel.TabPages.RemoveAt(7); // Remove the query editor tab if the user does not want it enabled.\r
-            if (Properties.Settings.Default.tooltipEnable)\r
+            if (Settings.Default.tooltipEnable)\r
                 ToolTip.Active = true;\r
 \r
             // Load the user's default settings or Normal Preset\r
-            if (Properties.Settings.Default.defaultPreset != string.Empty && presetHandler.GetPreset(Properties.Settings.Default.defaultPreset) != null)\r
+            if (Settings.Default.defaultPreset != string.Empty && presetHandler.GetPreset(Properties.Settings.Default.defaultPreset) != null)\r
             {\r
-                string query = presetHandler.GetPreset(Properties.Settings.Default.defaultPreset).Query;\r
+                string query = presetHandler.GetPreset(Settings.Default.defaultPreset).Query;\r
                 if (query != null)\r
                 {\r
                     x264Panel.Reset2Defaults();\r
 \r
                     QueryParser presetQuery = QueryParser.Parse(query);\r
-                    PresetLoader.LoadPreset(this, presetQuery, Properties.Settings.Default.defaultPreset,\r
-                                            presetHandler.GetPreset(Properties.Settings.Default.defaultPreset).PictureSettings);\r
+                    PresetLoader.LoadPreset(this, presetQuery, Settings.Default.defaultPreset);\r
 \r
-                    x264Panel.X264_StandardizeOptString();\r
-                    x264Panel.X264_SetCurrentSettingsInPanel();\r
+                    x264Panel.StandardizeOptString();\r
+                    x264Panel.SetCurrentSettingsInPanel();\r
                 }\r
             }\r
             else\r
@@ -156,17 +149,21 @@ namespace Handbrake
             // Register with Growl (if not using Growl for the encoding completion action, this wont hurt anything)\r
             GrowlCommunicator.Register();\r
 \r
-            // Finished Loading\r
-            UpdateSplashStatus(lblStatus, "Loading Complete.");\r
-            splash.Close();\r
-            splash.Dispose();\r
-            this.Enabled = true;\r
-\r
             // Event Handlers and Queue Recovery\r
             events();\r
-            queueRecovery();\r
+            Main.RecoverQueue(encodeQueue);\r
+\r
+            // If have a file passed in via command arguemtents, check it's a file and try scanning it.\r
+            if (args.Length >= 1 && (File.Exists(args[0]) || Directory.Exists(args[0])))\r
+            {\r
+                this.StartScan(args[0], 0);\r
+            }\r
         }\r
 \r
+        /// <summary>\r
+        /// When the update check is done, process the results.\r
+        /// </summary>\r
+        /// <param name="result">IAsyncResult result</param>\r
         private void UpdateCheckDone(IAsyncResult result)\r
         {\r
             if (InvokeRequired)\r
@@ -194,34 +191,6 @@ namespace Handbrake
             }\r
         }\r
 \r
-        // Startup Functions   \r
-        private void queueRecovery()\r
-        {\r
-            if (Main.CheckQueueRecovery())\r
-            {\r
-                DialogResult result =\r
-                    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
-                if (result == DialogResult.Yes)\r
-                    encodeQueue.LoadQueueFromFile("hb_queue_recovery.xml"); // Start Recovery\r
-                else\r
-                {\r
-                    // Remove the Queue recovery file if the user doesn't want to recovery the last queue.\r
-                    string queuePath = Path.Combine(Path.GetTempPath(), "hb_queue_recovery.xml");\r
-                    if (File.Exists(queuePath))\r
-                        File.Delete(queuePath);\r
-                }\r
-            }\r
-        }\r
-\r
-        private void UpdateSplashStatus(Label status, string text)\r
-        {\r
-            status.Text = text;\r
-            Application.DoEvents();\r
-        }\r
-\r
         #endregion\r
 \r
         #region Events\r
@@ -237,7 +206,6 @@ namespace Handbrake
                 this.Resize += new EventHandler(frmMain_Resize);\r
 \r
             // Handle Encode Start / Finish / Pause\r
-            encodeQueue.QueuePauseRequested += new EventHandler(encodePaused);\r
             encodeQueue.EncodeStarted += new EventHandler(encodeStarted);\r
             encodeQueue.EncodeEnded += new EventHandler(encodeEnded);\r
 \r
@@ -308,7 +276,7 @@ namespace Handbrake
         private void changePresetLabel(object sender, EventArgs e)\r
         {\r
             labelPreset.Text = "Output Settings (Preset: Custom)";\r
-            CurrentlySelectedPreset = null;\r
+            this.currentlySelectedPreset = null;\r
         }\r
 \r
         private static void frmMain_DragEnter(object sender, DragEventArgs e)\r
@@ -339,25 +307,14 @@ namespace Handbrake
         private void encodeStarted(object sender, EventArgs e)\r
         {\r
             SetEncodeStarted();\r
-\r
-            // Experimental HBProc Process Monitoring.\r
-            if (Properties.Settings.Default.enocdeStatusInGui)\r
-            {\r
-                encodeMonitor = new Thread(EncodeMonitorThread);\r
-                encodeMonitor.Start();\r
-            }\r
+            encodeQueue.EncodeStatusChanged += EncodeQueue_EncodeStatusChanged;\r
         }\r
 \r
         private void encodeEnded(object sender, EventArgs e)\r
         {\r
+            encodeQueue.EncodeStatusChanged -= EncodeQueue_EncodeStatusChanged;\r
             SetEncodeFinished();\r
         }\r
-\r
-        private void encodePaused(object sender, EventArgs e)\r
-        {\r
-            SetEncodeFinished();\r
-        }\r
-\r
         #endregion\r
 \r
         // User Interface Menus / Tool Strips *********************************\r
@@ -421,8 +378,7 @@ namespace Handbrake
         /// </param>\r
         private void mnu_encodeLog_Click(object sender, EventArgs e)\r
         {\r
-            frmActivityWindow dvdInfoWindow = new frmActivityWindow(encodeQueue, SourceScan);\r
-            dvdInfoWindow.Show();\r
+            this.btn_ActivityWindow_Click(this, null);\r
         }\r
 \r
         /// <summary>\r
@@ -535,9 +491,13 @@ namespace Handbrake
         /// </param>\r
         private void btn_new_preset_Click(object sender, EventArgs e)\r
         {\r
-            Form preset = new frmAddPreset(this, QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null),\r
-                                           presetHandler);\r
-            preset.ShowDialog();\r
+            Form preset = new frmAddPreset(this, presetHandler);\r
+            if (preset.ShowDialog() == DialogResult.OK)\r
+            {\r
+                TreeNode presetTreeview = new TreeNode(presetHandler.LastPresetAdded.Name) { ForeColor = Color.Black };\r
+                treeView_presets.Nodes.Add(presetTreeview);\r
+                presetHandler.LastPresetAdded = null;\r
+            }\r
         }\r
 \r
         #endregion\r
@@ -570,7 +530,7 @@ namespace Handbrake
         private void mnu_UpdateCheck_Click(object sender, EventArgs e)\r
         {\r
             lbl_updateCheck.Visible = true;\r
-            Main.BeginCheckForUpdates(new AsyncCallback(updateCheckDoneMenu), false);\r
+            Main.BeginCheckForUpdates(new AsyncCallback(this.UpdateCheckDoneMenu), false);\r
         }\r
 \r
         /// <summary>\r
@@ -647,6 +607,7 @@ namespace Handbrake
         /// </param>\r
         private void pmnu_saveChanges_Click(object sender, EventArgs e)\r
         {\r
+            // TODO this requires a re-think since the Query Editor has changed.\r
             DialogResult result =\r
                 MessageBox.Show(\r
                     "Do you wish to include picture settings when updating the preset: " +\r
@@ -654,10 +615,10 @@ namespace Handbrake
                     MessageBoxIcon.Question);\r
             if (result == DialogResult.Yes)\r
                 presetHandler.Update(treeView_presets.SelectedNode.Text,\r
-                                     QueryGenerator.GenerateTabbedComponentsQuery(this), true);\r
+                                     QueryGenerator.GenerateQueryForPreset(this, QueryPictureSettingsMode.SourceMaximum, true, 0, 0), true);\r
             else if (result == DialogResult.No)\r
                 presetHandler.Update(treeView_presets.SelectedNode.Text,\r
-                                     QueryGenerator.GenerateTabbedComponentsQuery(this), false);\r
+                                     QueryGenerator.GenerateQueryForPreset(this, QueryPictureSettingsMode.SourceMaximum, true, 0, 0), false);\r
         }\r
 \r
         /// <summary>\r
@@ -714,8 +675,13 @@ namespace Handbrake
         /// </param>\r
         private void btn_addPreset_Click(object sender, EventArgs e)\r
         {\r
-            Form preset = new frmAddPreset(this, QueryGenerator.GenerateTabbedComponentsQuery(this), presetHandler);\r
-            preset.ShowDialog();\r
+            Form preset = new frmAddPreset(this, presetHandler);\r
+            if (preset.ShowDialog() == DialogResult.OK)\r
+            {\r
+                TreeNode presetTreeview = new TreeNode(presetHandler.LastPresetAdded.Name) { ForeColor = Color.Black };\r
+                treeView_presets.Nodes.Add(presetTreeview);\r
+                presetHandler.LastPresetAdded = null;\r
+            }\r
         }\r
 \r
         /// <summary>\r
@@ -861,7 +827,6 @@ namespace Handbrake
                 if (preset != null)\r
                 {\r
                     string query = presetHandler.GetPreset(presetName).Query;\r
-                    bool loadPictureSettings = presetHandler.GetPreset(presetName).PictureSettings;\r
 \r
                     if (query != null)\r
                     {\r
@@ -872,14 +837,14 @@ namespace Handbrake
                         QueryParser presetQuery = QueryParser.Parse(query);\r
 \r
                         // Now load the preset\r
-                        PresetLoader.LoadPreset(this, presetQuery, presetName, loadPictureSettings);\r
+                        PresetLoader.LoadPreset(this, presetQuery, presetName);\r
 \r
                         // The x264 widgets will need updated, so do this now:\r
-                        x264Panel.X264_StandardizeOptString();\r
-                        x264Panel.X264_SetCurrentSettingsInPanel();\r
+                        x264Panel.StandardizeOptString();\r
+                        x264Panel.SetCurrentSettingsInPanel();\r
 \r
                         // Finally, let this window have a copy of the preset settings.\r
-                        CurrentlySelectedPreset = preset;\r
+                        this.currentlySelectedPreset = preset;\r
                         PictureSettings.SetPresetCropWarningLabel(preset);\r
                     }\r
                 }\r
@@ -917,17 +882,17 @@ namespace Handbrake
                                         MessageBoxButtons.YesNo, MessageBoxIcon.Warning);\r
                     if (result == DialogResult.Yes)\r
                     {\r
-                        PresetLoader.LoadPreset(this, parsed, parsed.PresetName, parsed.UsesPictureSettings);\r
+                        PresetLoader.LoadPreset(this, parsed, parsed.PresetName);\r
                         presetHandler.Update(parsed.PresetName + " (Imported)",\r
-                                             QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null),\r
+                                             QueryGenerator.GenerateFullQuery(this),\r
                                              parsed.UsesPictureSettings);\r
                     }\r
                 }\r
                 else\r
                 {\r
-                    PresetLoader.LoadPreset(this, parsed, parsed.PresetName, parsed.UsesPictureSettings);\r
+                    PresetLoader.LoadPreset(this, parsed, parsed.PresetName);\r
                     if (presetHandler.Add(parsed.PresetName + " (Imported)",\r
-                                          QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null),\r
+                                          QueryGenerator.GenerateFullQuery(this),\r
                                           parsed.UsesPictureSettings))\r
                     {\r
                         TreeNode preset_treeview = new TreeNode(parsed.PresetName + " (Imported)")\r
@@ -948,7 +913,7 @@ namespace Handbrake
             MessageBox.Show("This feature has not been implimented yet.", "Not Implimented", MessageBoxButtons.OK, MessageBoxIcon.Warning);\r
             return;\r
 \r
-            SaveFileDialog savefiledialog = new SaveFileDialog();\r
+            /*SaveFileDialog savefiledialog = new SaveFileDialog();\r
             savefiledialog.Filter = "plist|*.plist";\r
 \r
             if (treeView_presets.SelectedNode != null)\r
@@ -959,7 +924,7 @@ namespace Handbrake
                     Preset preset = presetHandler.GetPreset(treeView_presets.SelectedNode.Text);\r
                     PlistPresetHandler.Export(savefiledialog.FileName, preset);\r
                 }\r
-            }\r
+            }*/\r
         }\r
 \r
         #endregion\r
@@ -1011,47 +976,41 @@ namespace Handbrake
         {\r
             if (btn_start.Text == "Stop")\r
             {\r
-                DialogResult result;\r
-                if (Properties.Settings.Default.enocdeStatusInGui &&\r
-                    !Properties.Settings.Default.showCliForInGuiEncodeStatus)\r
-                {\r
-                    result = MessageBox.Show(\r
-                        "Are you sure you wish to cancel the encode?\n\nPlease note, when 'Enable in-GUI encode status' is enabled, stopping this encode will render the file unplayable. ",\r
-                        "Cancel Encode?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
-                }\r
-                else\r
-                {\r
-                    result = MessageBox.Show("Are you sure you wish to cancel the encode?", "Cancel Encode?",\r
-                                             MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
-                }\r
+                DialogResult result = !Properties.Settings.Default.showCliForInGuiEncodeStatus\r
+                             ? MessageBox.Show(\r
+                                 "Are you sure you wish to cancel the encode?\n\nPlease note: Stopping this encode will render the file unplayable. ",\r
+                                 "Cancel Encode?",\r
+                                 MessageBoxButtons.YesNo,\r
+                                 MessageBoxIcon.Question)\r
+                             : MessageBox.Show(\r
+                                 "Are you sure you wish to cancel the encode?",\r
+                                 "Cancel Encode?",\r
+                                 MessageBoxButtons.YesNo,\r
+                                 MessageBoxIcon.Question);\r
 \r
                 if (result == DialogResult.Yes)\r
                 {\r
                     // Pause The Queue\r
                     encodeQueue.Pause();\r
 \r
-                    if (Properties.Settings.Default.enocdeStatusInGui &&\r
-                        !Properties.Settings.Default.showCliForInGuiEncodeStatus)\r
-                    {\r
-                        encodeQueue.Stop();\r
-                        if (encodeQueue.HbProcess != null)\r
-                            encodeQueue.HbProcess.WaitForExit();\r
-                    }\r
-                    else\r
-                    {\r
+                    if (Settings.Default.showCliForInGuiEncodeStatus)\r
                         encodeQueue.SafelyClose();\r
-                    }\r
+                    else\r
+                        encodeQueue.Stop();\r
                 }\r
             }\r
             else\r
             {\r
-                if (encodeQueue.Count != 0 ||\r
-                    (!string.IsNullOrEmpty(sourcePath) && !string.IsNullOrEmpty(text_destination.Text)))\r
+                // If we have a custom query, then we'll want to figure out what the new source and destination is, otherwise we'll just use the gui components.\r
+                string jobSourcePath = !string.IsNullOrEmpty(rtf_query.Text) ? Main.GetSourceFromQuery(rtf_query.Text) : sourcePath;\r
+                string jobDestination = !string.IsNullOrEmpty(rtf_query.Text) ? Main.GetDestinationFromQuery(rtf_query.Text) : text_destination.Text;\r
+\r
+                if (encodeQueue.Count != 0 || (!string.IsNullOrEmpty(jobSourcePath) && !string.IsNullOrEmpty(jobDestination)))\r
                 {\r
-                    string generatedQuery = QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null);\r
+                    string generatedQuery = QueryGenerator.GenerateFullQuery(this);\r
                     string specifiedQuery = rtf_query.Text != string.Empty\r
                                                 ? rtf_query.Text\r
-                                                : QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null);\r
+                                                : QueryGenerator.GenerateFullQuery(this);\r
                     string query = string.Empty;\r
 \r
                     // Check to make sure the generated query matches the GUI settings\r
@@ -1090,17 +1049,19 @@ namespace Handbrake
                     }\r
 \r
                     DialogResult overwrite = DialogResult.Yes;\r
-                    if (text_destination.Text != string.Empty)\r
-                        if (File.Exists(text_destination.Text))\r
-                            overwrite =\r
-                                MessageBox.Show(\r
-                                    "The destination file already exists. Are you sure you want to overwrite it?",\r
-                                    "Overwrite File?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
+                    if (!string.IsNullOrEmpty(jobDestination) && File.Exists(jobDestination))\r
+                    {\r
+                        overwrite = MessageBox.Show(\r
+                                "The destination file already exists. Are you sure you want to overwrite it?",\r
+                                "Overwrite File?",\r
+                                MessageBoxButtons.YesNo,\r
+                                MessageBoxIcon.Question);\r
+                    }\r
 \r
                     if (overwrite == DialogResult.Yes)\r
                     {\r
                         if (encodeQueue.Count == 0)\r
-                            encodeQueue.Add(query, getTitle(), sourcePath, text_destination.Text, (rtf_query.Text != string.Empty));\r
+                            encodeQueue.Add(query, this.GetTitle(), jobSourcePath, jobDestination, (rtf_query.Text != string.Empty));\r
 \r
                         queueWindow.SetQueue();\r
                         if (encodeQueue.Count > 1)\r
@@ -1129,36 +1090,45 @@ namespace Handbrake
         /// </param>\r
         private void btn_add2Queue_Click(object sender, EventArgs e)\r
         {\r
-            if (string.IsNullOrEmpty(sourcePath) || string.IsNullOrEmpty(text_destination.Text))\r
-                MessageBox.Show("No source or destination selected.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);\r
-            else\r
-            {\r
-                if (!Directory.Exists(Path.GetDirectoryName(text_destination.Text)))\r
-                {\r
-                    MessageBox.Show("Destination Path does not exist.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);\r
-                    return;\r
-                }\r
+            // Get the CLI query or use the query editor if it's not empty.\r
+            string query = QueryGenerator.GenerateFullQuery(this);\r
+            if (!string.IsNullOrEmpty(rtf_query.Text))\r
+                query = rtf_query.Text;\r
 \r
-                string query = QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null);\r
-                if (rtf_query.Text != string.Empty)\r
-                    query = rtf_query.Text;\r
+            // If we have a custom query, then we'll want to figure out what the new source and destination is, otherwise we'll just use the gui components.\r
+            string jobSourcePath = !string.IsNullOrEmpty(rtf_query.Text) ? Main.GetSourceFromQuery(rtf_query.Text) : sourcePath;\r
+            string jobDestination = !string.IsNullOrEmpty(rtf_query.Text) ? Main.GetDestinationFromQuery(rtf_query.Text) : text_destination.Text;\r
 \r
-                if (encodeQueue.CheckForDestinationDuplicate(text_destination.Text))\r
-                {\r
-                    DialogResult result =\r
-                        MessageBox.Show(\r
-                            "There is already a queue item for this destination path. \n\n If you continue, the encode will be overwritten. Do you wish to continue?",\r
-                            "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);\r
-                    if (result == DialogResult.Yes)\r
-                        encodeQueue.Add(query, getTitle(), sourcePath, text_destination.Text, (rtf_query.Text != string.Empty));\r
-                }\r
-                else\r
-                    encodeQueue.Add(query, getTitle(), sourcePath, text_destination.Text, (rtf_query.Text != string.Empty));\r
+            // Make sure we have a Source and Destination.\r
+            if (string.IsNullOrEmpty(jobSourcePath) || string.IsNullOrEmpty(jobDestination))\r
+            {\r
+                MessageBox.Show("No source or destination selected.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);\r
+                return;\r
+            }\r
 \r
-                lbl_encode.Text = encodeQueue.Count + " encode(s) pending in the queue";\r
+            // Make sure the destination path exists.\r
+            if (!Directory.Exists(Path.GetDirectoryName(jobDestination)))\r
+            {\r
+                MessageBox.Show("Destination Path does not exist.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);\r
+                return;\r
+            }\r
 \r
-                queueWindow.Show();\r
+            // Make sure we don't have a duplciate on the queue.\r
+            if (encodeQueue.CheckForDestinationDuplicate(jobDestination))\r
+            {\r
+                DialogResult result =\r
+                    MessageBox.Show(\r
+                        "There is already a queue item for this destination path. \n\n If you continue, the encode will be overwritten. Do you wish to continue?",\r
+                        "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);\r
+                if (result == DialogResult.Yes)\r
+                    encodeQueue.Add(query, this.GetTitle(), jobSourcePath, jobDestination, (rtf_query.Text != string.Empty));\r
             }\r
+            else\r
+                encodeQueue.Add(query, this.GetTitle(), jobSourcePath, jobDestination, (rtf_query.Text != string.Empty));\r
+\r
+            lbl_encode.Text = encodeQueue.Count + " encode(s) pending in the queue";\r
+\r
+            queueWindow.Show();\r
         }\r
 \r
         /// <summary>\r
@@ -1219,11 +1189,11 @@ namespace Handbrake
         /// </param>\r
         private void btn_ActivityWindow_Click(object sender, EventArgs e)\r
         {\r
-            if (ActivityWindow == null || !ActivityWindow.IsHandleCreated)\r
-                ActivityWindow = new frmActivityWindow(encodeQueue, SourceScan);\r
+            if (this.activityWindow == null || !this.activityWindow.IsHandleCreated)\r
+                this.activityWindow = new frmActivityWindow(encodeQueue, SourceScan);\r
 \r
-            ActivityWindow.Show();\r
-            ActivityWindow.Activate();\r
+            this.activityWindow.Show();\r
+            this.activityWindow.Activate();\r
         }\r
 \r
         #endregion\r
@@ -1320,7 +1290,6 @@ namespace Handbrake
                 int id;\r
                 if (int.TryParse(driveId, out id))\r
                 {\r
-\r
                     this.dvdDrivePath = drives[id].RootDirectory;\r
                     this.dvdDriveLabel = drives[id].VolumeLabel;\r
 \r
@@ -1368,7 +1337,7 @@ namespace Handbrake
             {\r
                 selectedTitle = drp_dvdtitle.SelectedItem as Title;\r
                 lbl_duration.Text = selectedTitle.Duration.ToString();\r
-                PictureSettings.CurrentlySelectedPreset = CurrentlySelectedPreset;\r
+                PictureSettings.CurrentlySelectedPreset = this.currentlySelectedPreset;\r
                 PictureSettings.Source = selectedTitle; // Setup Picture Settings Tab Control\r
 \r
                 // Populate the Angles dropdown\r
@@ -1403,7 +1372,7 @@ namespace Handbrake
                     drop_chapterFinish.Text = drop_chapterFinish.Items[drop_chapterFinish.Items.Count - 1].ToString();\r
 \r
                 // Populate the Audio Channels Dropdown\r
-                AudioSettings.SetTrackList(selectedTitle, CurrentlySelectedPreset);\r
+                AudioSettings.SetTrackList(selectedTitle, this.currentlySelectedPreset);\r
 \r
                 // Populate the Subtitles dropdown\r
                 Subtitles.SetSubtitleTrackAuto(selectedTitle.Subtitles.ToArray());\r
@@ -1421,7 +1390,7 @@ namespace Handbrake
                     text_destination.Text = autoPath;\r
                 else\r
                     MessageBox.Show(\r
-                        "You currently have \"Automatically name output files\" enabled for the destination file box, but you do not have a default directory set.\n\nYou should set a \"Default Path\" in HandBrakes preferences. (See 'Tools' menu -> 'Options' -> 'General' Tab -> 'Default Path')",\r
+                        "You currently have \"Automatically name output files\" enabled for the destination file box, but you do not have a valid default directory set.\n\nYou should set a \"Default Path\" in HandBrakes preferences. (See 'Tools' menu -> 'Options' -> 'General' Tab -> 'Default Path')",\r
                         "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);\r
             }\r
 \r
@@ -1750,6 +1719,28 @@ namespace Handbrake
         }\r
 \r
         /// <summary>\r
+        /// When the FrameRate is not Same As Source, show the Max/Constant Mode dropdown\r
+        /// </summary>\r
+        /// <param name="sender">\r
+        /// The sender.\r
+        /// </param>\r
+        /// <param name="e">\r
+        /// The e.\r
+        /// </param>\r
+        private void drp_videoFramerate_SelectedIndexChanged(object sender, EventArgs e)\r
+        {\r
+            if (this.drp_videoFramerate.SelectedIndex == 0)\r
+            {\r
+                this.checkMaximumFramerate.Visible = false;\r
+                this.checkMaximumFramerate.CheckState = CheckState.Unchecked;\r
+            }\r
+            else\r
+            {\r
+                this.checkMaximumFramerate.Visible = true;\r
+            }\r
+        }\r
+\r
+        /// <summary>\r
         /// Set the container format options\r
         /// </summary>\r
         public void setContainerOpts()\r
@@ -1771,7 +1762,7 @@ namespace Handbrake
             }\r
         }\r
 \r
-        private double _cachedCqStep = Properties.Settings.Default.x264cqstep;\r
+        private double cachedCqStep = Properties.Settings.Default.x264cqstep;\r
 \r
         /// <summary>\r
         /// Update the CQ slider for x264 for a new CQ step. This is set from option\r
@@ -1779,7 +1770,7 @@ namespace Handbrake
         public void setQualityFromSlider()\r
         {\r
             // Work out the current RF value.\r
-            double cqStep = _cachedCqStep;\r
+            double cqStep = this.cachedCqStep;\r
             double rfValue = 51.0 - slider_videoQuality.Value * cqStep;\r
 \r
             // Change the maximum value for the slider\r
@@ -1798,7 +1789,7 @@ namespace Handbrake
             }\r
 \r
             // Cache the CQ step for the next calculation\r
-            _cachedCqStep = Properties.Settings.Default.x264cqstep;\r
+            this.cachedCqStep = Properties.Settings.Default.x264cqstep;\r
         }\r
 \r
         private void slider_videoQuality_Scroll(object sender, EventArgs e)\r
@@ -1918,7 +1909,7 @@ namespace Handbrake
         // Query Editor Tab\r
         private void btn_generate_Query_Click(object sender, EventArgs e)\r
         {\r
-            rtf_query.Text = QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null);\r
+            rtf_query.Text = QueryGenerator.GenerateFullQuery(this);\r
         }\r
 \r
         private void btn_clear_Click(object sender, EventArgs e)\r
@@ -2035,17 +2026,19 @@ namespace Handbrake
                     drp_dvdtitle.SelectedIndex = 0;\r
                 }\r
 \r
-                // Enable the creation of chapter markers if the file is an image of a dvd.\r
-                int start, end;\r
-                int.TryParse(drop_chapterStart.Items[0].ToString(), out start);\r
-                int.TryParse(drop_chapterFinish.Items[drop_chapterFinish.Items.Count - 1].ToString(), out end);\r
-                if (end > start)\r
-                    Check_ChapterMarkers.Enabled = true;\r
-                else\r
+                // Enable the creation of chapter markers if the file is an image of a dvd\r
+                if (drop_chapterStart.Items.Count > 0)\r
                 {\r
-                    Check_ChapterMarkers.Enabled = false;\r
-                    Check_ChapterMarkers.Checked = false;\r
-                    data_chpt.Rows.Clear();\r
+                    int start, end;\r
+                    int.TryParse(drop_chapterStart.Items[0].ToString(), out start);\r
+                    int.TryParse(drop_chapterFinish.Items[drop_chapterFinish.Items.Count - 1].ToString(), out end);\r
+                    if (end > start) Check_ChapterMarkers.Enabled = true;\r
+                    else\r
+                    {\r
+                        Check_ChapterMarkers.Enabled = false;\r
+                        Check_ChapterMarkers.Checked = false;\r
+                        data_chpt.Rows.Clear();\r
+                    }\r
                 }\r
 \r
                 // If no titles were found, Display an error message\r
@@ -2175,14 +2168,14 @@ namespace Handbrake
                 QueryParser presetQuery = QueryParser.Parse(query);\r
 \r
                 // Now load the preset\r
-                PresetLoader.LoadPreset(this, presetQuery, "Load Back From Queue", true);\r
+                PresetLoader.LoadPreset(this, presetQuery, "Load Back From Queue");\r
 \r
                 // The x264 widgets will need updated, so do this now:\r
-                x264Panel.X264_StandardizeOptString();\r
-                x264Panel.X264_SetCurrentSettingsInPanel();\r
+                x264Panel.StandardizeOptString();\r
+                x264Panel.SetCurrentSettingsInPanel();\r
 \r
                 // Finally, let this window have a copy of the preset settings.\r
-                CurrentlySelectedPreset = null;\r
+                this.currentlySelectedPreset = null;\r
                 PictureSettings.SetPresetCropWarningLabel(null);\r
             }\r
         }\r
@@ -2251,6 +2244,35 @@ namespace Handbrake
         }\r
 \r
         /// <summary>\r
+        /// Display the Encode Status\r
+        /// </summary>\r
+        /// <param name="sender">\r
+        /// The sender.\r
+        /// </param>\r
+        /// <param name="e">\r
+        /// The e.\r
+        /// </param>\r
+        private void EncodeQueue_EncodeStatusChanged(object sender, HandBrake.ApplicationServices.EncodeProgressEventArgs e)\r
+        {\r
+            if (this.InvokeRequired)\r
+            {\r
+                this.BeginInvoke(new Encode.EncodeProgessStatus(EncodeQueue_EncodeStatusChanged), new[] { sender, e });\r
+                return;\r
+            }\r
+\r
+            lbl_encode.Text =\r
+                string.Format(\r
+                "{0:00.00}%,  FPS: {1:000.0},  Avg FPS: {2:000.0},  Time Remaining: {3},  Encode(s) Pending {4}",\r
+                e.PercentComplete,\r
+                e.CurrentFrameRate,\r
+                e.AverageFrameRate,\r
+                e.EstimatedTimeLeft,\r
+                encodeQueue.Count);\r
+\r
+            ProgressBarStatus.Value = (int)Math.Round(e.PercentComplete);\r
+        }\r
+\r
+        /// <summary>\r
         /// Set the DVD Drive selection in the "Source" Menu\r
         /// </summary>\r
         private void SetDriveSelectionMenuItem()\r
@@ -2293,8 +2315,8 @@ namespace Handbrake
         private void LoadPresetPanel()\r
         {\r
             if (presetHandler.CheckIfPresetsAreOutOfDate())\r
-                if (!Properties.Settings.Default.presetNotification)\r
-                    MessageBox.Show(splash,\r
+                if (!Settings.Default.presetNotification)\r
+                    MessageBox.Show(this,\r
                                     "HandBrake has determined your built-in presets are out of date... These presets will now be updated.",\r
                                     "Preset Update", MessageBoxButtons.OK, MessageBoxIcon.Information);\r
 \r
@@ -2308,7 +2330,7 @@ namespace Handbrake
         /// <returns>\r
         /// The title.\r
         /// </returns>\r
-        private int getTitle()\r
+        private int GetTitle()\r
         {\r
             int title = 0;\r
             if (drp_dvdtitle.SelectedItem != null)\r
@@ -2326,12 +2348,12 @@ namespace Handbrake
         /// <param name="result">\r
         /// The result.\r
         /// </param>\r
-        private void updateCheckDoneMenu(IAsyncResult result)\r
+        private void UpdateCheckDoneMenu(IAsyncResult result)\r
         {\r
             // Make sure it's running on the calling thread\r
             if (InvokeRequired)\r
             {\r
-                Invoke(new MethodInvoker(() => updateCheckDoneMenu(result)));\r
+                Invoke(new MethodInvoker(() => this.UpdateCheckDoneMenu(result)));\r
                 return;\r
             }\r
             UpdateCheckInformation info;\r
@@ -2392,84 +2414,41 @@ namespace Handbrake
         /// <param name="e">FormClosingEventArgs</param>\r
         protected override void OnFormClosing(FormClosingEventArgs e)\r
         {\r
-            // If currently encoding, the queue isn't paused, and there are queue items to process, prompt to confirm close.\r
-            if (encodeQueue.IsEncoding)\r
+            try\r
             {\r
-                DialogResult result =\r
-                    MessageBox.Show(\r
-                        "HandBrake has queue items to process. Closing HandBrake will stop the current encoding.\n\nDo you want to close HandBrake?",\r
-                        "Close HandBrake?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
+                // If currently encoding, the queue isn't paused, and there are queue items to process, prompt to confirm close.\r
+                if (encodeQueue.IsEncoding)\r
+                {\r
+                    DialogResult result =\r
+                        MessageBox.Show(\r
+                            "HandBrake is currently encoding. Closing HandBrake will stop the current encode and will result in an unplayable file.\n\nDo you want to close HandBrake?",\r
+                            "Close HandBrake?",\r
+                            MessageBoxButtons.YesNo,\r
+                            MessageBoxIcon.Question);\r
 \r
-                if (result == DialogResult.No)\r
-                    e.Cancel = true;\r
+                    if (result == DialogResult.No)\r
+                    {\r
+                        e.Cancel = true;\r
+                        return;\r
+                    }\r
 \r
-                // Try to safely close out if we can, or kill the cli if using in-gui status\r
-                if (Settings.Default.enocdeStatusInGui)\r
                     encodeQueue.Stop();\r
-                else\r
-                    encodeQueue.SafelyClose();\r
-            }\r
-\r
-            if (SourceScan.IsScanning)\r
-            {\r
-                SourceScan.ScanCompleted -= new EventHandler(SourceScan_ScanCompleted);\r
-                SourceScan.Stop();\r
-            }\r
-            base.OnFormClosing(e);\r
-        }\r
-\r
-        #endregion\r
-\r
-        #region In-GUI Encode Status\r
-\r
-        /// <summary>\r
-        /// Starts a new thread to monitor and process the CLI encode status\r
-        /// </summary>\r
-        private void EncodeMonitorThread()\r
-        {\r
-            try\r
-            {\r
-                Parser encode = new Parser(encodeQueue.HbProcess.StandardOutput.BaseStream);\r
-                encode.OnEncodeProgress += EncodeOnEncodeProgress;\r
-                while (!encode.EndOfStream)\r
-                    encode.ReadEncodeStatus();\r
+                }\r
 \r
-                SetEncodeFinished();\r
+                if (SourceScan.IsScanning)\r
+                {\r
+                    SourceScan.ScanCompleted -= new EventHandler(SourceScan_ScanCompleted);\r
+                    SourceScan.Stop();\r
+                }\r
             }\r
             catch (Exception exc)\r
             {\r
-                MessageBox.Show(exc.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
+                Main.ShowExceptiowWindow("HandBrake was not able to shutdown properly. You may need to forcefully quit HandBrake CLI from TaskManager if it's still running.", exc.ToString());\r
             }\r
-        }\r
-\r
-        /// <summary>\r
-        /// Displays the Encode status in the GUI\r
-        /// </summary>\r
-        /// <param name="sender">The sender</param>\r
-        /// <param name="currentTask">The current task</param>\r
-        /// <param name="taskCount">Number of tasks</param>\r
-        /// <param name="percentComplete">Percent complete</param>\r
-        /// <param name="currentFps">Current encode speed in fps</param>\r
-        /// <param name="av">Avg encode speed</param>\r
-        /// <param name="timeRemaining">Time Left</param>\r
-        private void EncodeOnEncodeProgress(object sender, int currentTask, int taskCount, float percentComplete, float currentFps, float av, TimeSpan timeRemaining)\r
-        {\r
-            if (this.InvokeRequired)\r
+            finally\r
             {\r
-                this.BeginInvoke(\r
-                    new EncodeProgressEventHandler(EncodeOnEncodeProgress),\r
-                    new[] { sender, currentTask, taskCount, percentComplete, currentFps, av, timeRemaining });\r
-                return;\r
+                base.OnFormClosing(e);\r
             }\r
-            lbl_encode.Text =\r
-                string.Format(\r
-                "{0:00.00}%,    FPS: {1:000.0},    Avg FPS: {2:000.0},    Time Remaining: {3}",\r
-                percentComplete,\r
-                currentFps,\r
-                av,\r
-                timeRemaining);\r
-\r
-            ProgressBarStatus.Value = (int)Math.Round(percentComplete);\r
         }\r
 \r
         #endregion\r