OSDN Git Service

WinGui:
[handbrake-jp/handbrake-jp-git.git] / win / C# / frmMain.cs
index 8e7e31d..bfa4054 100644 (file)
@@ -1,8 +1,7 @@
 /*  frmMain.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
+    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\r
 {\r
@@ -13,13 +12,15 @@ 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 EncodeQueue;\r
     using Functions;\r
     using Model;\r
     using Parsing;\r
     using Presets;\r
+    using Properties;\r
+    using Services;\r
 \r
     public partial class frmMain : Form\r
     {\r
@@ -34,12 +35,14 @@ namespace Handbrake
         private frmActivityWindow ActivityWindow;\r
         private Form splash;\r
         public string sourcePath;\r
-        private string lastAction;\r
+        private ActivityLogMode lastAction;\r
         private SourceType selectedSourceType;\r
         private string dvdDrivePath;\r
         private string dvdDriveLabel;\r
         private Preset CurrentlySelectedPreset;\r
         private DVD currentSource;\r
+        private Scan SourceScan = new Scan();\r
+        private List<DriveInformation> drives;\r
 \r
         // Delegates **********************************************************\r
         private delegate void UpdateWindowHandler();\r
@@ -53,17 +56,24 @@ namespace Handbrake
             // Load and setup the splash screen in this thread\r
             splash = new frmSplashScreen();\r
             splash.Show(this);\r
-            Label lblStatus = new Label {Size = new Size(150, 20), Location = new Point(182, 102)};\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
-            lblStatus.Text = "Setting Version Data ...";\r
+            lblStatus.Text = "Checking CLI Version Data ...";\r
             Application.DoEvents();\r
             Main.SetCliVersionData();\r
+            Main.CheckForValidCliVersion();\r
 \r
-            // Show the form, but leave disabled until preloading is complete then show the main form\r
+            if (Settings.Default.hb_version.Contains("svn"))\r
+            {\r
+                Version v = Assembly.GetExecutingAssembly().GetName().Version;\r
+                this.Text += " " + v.ToString(4);\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
@@ -117,7 +127,7 @@ namespace Handbrake
                         x264Panel.Reset2Defaults();\r
 \r
                         QueryParser presetQuery = QueryParser.Parse(query);\r
-                        PresetLoader.LoadPreset(this, presetQuery, Properties.Settings.Default.defaultPreset, \r
+                        PresetLoader.LoadPreset(this, presetQuery, Properties.Settings.Default.defaultPreset,\r
                                                 loadPictureSettings);\r
 \r
                         x264Panel.X264_StandardizeOptString();\r
@@ -171,9 +181,9 @@ namespace Handbrake
             }\r
             catch (Exception ex)\r
             {\r
-                if ((bool) result.AsyncState)\r
+                if ((bool)result.AsyncState)\r
                     MessageBox.Show(\r
-                        "Unable to check for updates, Please try again later.\n\nDetailed Error Information:\n" + ex, \r
+                        "Unable to check for updates, Please try again later.\n\nDetailed Error Information:\n" + ex,\r
                         "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
             }\r
         }\r
@@ -185,7 +195,7 @@ namespace Handbrake
             {\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
+                        "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
@@ -337,7 +347,7 @@ namespace Handbrake
 \r
         private void encodeStarted(object sender, EventArgs e)\r
         {\r
-            lastAction = "encode";\r
+            lastAction = ActivityLogMode.Encode;\r
             SetEncodeStarted();\r
 \r
             // Experimental HBProc Process Monitoring.\r
@@ -385,7 +395,7 @@ namespace Handbrake
 \r
         private void mnu_encodeLog_Click(object sender, EventArgs e)\r
         {\r
-            frmActivityWindow dvdInfoWindow = new frmActivityWindow(lastAction);\r
+            frmActivityWindow dvdInfoWindow = new frmActivityWindow(lastAction, encodeQueue, SourceScan);\r
             dvdInfoWindow.Show();\r
         }\r
 \r
@@ -405,7 +415,7 @@ namespace Handbrake
             LoadPresetPanel();\r
             if (treeView_presets.Nodes.Count == 0)\r
                 MessageBox.Show(\r
-                    "Unable to load the presets.xml file. Please select \"Update Built-in Presets\" from the Presets Menu. \nMake sure you are running the program in Admin mode if running on Vista. See Windows FAQ for details!", \r
+                    "Unable to load the presets.xml file. Please select \"Update Built-in Presets\" from the Presets Menu. \nMake sure you are running the program in Admin mode if running on Vista. See Windows FAQ for details!",\r
                     "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
             else\r
                 MessageBox.Show("Presets have been updated!", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Information);\r
@@ -426,12 +436,12 @@ namespace Handbrake
 \r
         private void mnu_importMacPreset_Click(object sender, EventArgs e)\r
         {\r
-            importPreset();\r
+            ImportPreset();\r
         }\r
 \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
+            Form preset = new frmAddPreset(this, QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null),\r
                                            presetHandler);\r
             preset.ShowDialog();\r
         }\r
@@ -476,16 +486,16 @@ namespace Handbrake
                     updateWindow.ShowDialog();\r
                 }\r
                 else\r
-                    MessageBox.Show("There are no new updates at this time.", "Update Check", MessageBoxButtons.OK, \r
+                    MessageBox.Show("There are no new updates at this time.", "Update Check", MessageBoxButtons.OK,\r
                                     MessageBoxIcon.Information);\r
                 lbl_updateCheck.Visible = false;\r
                 return;\r
             }\r
             catch (Exception ex)\r
             {\r
-                if ((bool) result.AsyncState)\r
+                if ((bool)result.AsyncState)\r
                     MessageBox.Show(\r
-                        "Unable to check for updates, Please try again later.\n\nDetailed Error Information:\n" + ex, \r
+                        "Unable to check for updates, Please try again later.\n\nDetailed Error Information:\n" + ex,\r
                         "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
             }\r
         }\r
@@ -515,7 +525,7 @@ namespace Handbrake
 \r
         private void pmnu_import_Click(object sender, EventArgs e)\r
         {\r
-            importPreset();\r
+            ImportPreset();\r
         }\r
 \r
         private void pmnu_saveChanges_Click(object sender, EventArgs e)\r
@@ -523,13 +533,13 @@ namespace Handbrake
             DialogResult result =\r
                 MessageBox.Show(\r
                     "Do you wish to include picture settings when updating the preset: " +\r
-                    treeView_presets.SelectedNode.Text, "Update Preset", MessageBoxButtons.YesNoCancel, \r
+                    treeView_presets.SelectedNode.Text, "Update Preset", MessageBoxButtons.YesNoCancel,\r
                     MessageBoxIcon.Question);\r
             if (result == DialogResult.Yes)\r
-                presetHandler.Update(treeView_presets.SelectedNode.Text, \r
+                presetHandler.Update(treeView_presets.SelectedNode.Text,\r
                                      QueryGenerator.GenerateTabbedComponentsQuery(this), true);\r
             else if (result == DialogResult.No)\r
-                presetHandler.Update(treeView_presets.SelectedNode.Text, \r
+                presetHandler.Update(treeView_presets.SelectedNode.Text,\r
                                      QueryGenerator.GenerateTabbedComponentsQuery(this), false);\r
         }\r
 \r
@@ -565,7 +575,7 @@ namespace Handbrake
 \r
         private void btn_removePreset_Click(object sender, EventArgs e)\r
         {\r
-            DialogResult result = MessageBox.Show("Are you sure you wish to delete the selected preset?", "Preset", \r
+            DialogResult result = MessageBox.Show("Are you sure you wish to delete the selected preset?", "Preset",\r
                                                   MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
             if (result == DialogResult.Yes)\r
             {\r
@@ -582,7 +592,7 @@ namespace Handbrake
         {\r
             if (treeView_presets.SelectedNode != null)\r
             {\r
-                DialogResult result = MessageBox.Show("Are you sure you wish to set this preset as the default?", \r
+                DialogResult result = MessageBox.Show("Are you sure you wish to set this preset as the default?",\r
                                                       "Preset", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
                 if (result == DialogResult.Yes)\r
                 {\r
@@ -620,7 +630,7 @@ namespace Handbrake
         {\r
             if (e.KeyCode == Keys.Delete)\r
             {\r
-                DialogResult result = MessageBox.Show("Are you sure you wish to delete the selected preset?", "Preset", \r
+                DialogResult result = MessageBox.Show("Are you sure you wish to delete the selected preset?", "Preset",\r
                                                       MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
                 if (result == DialogResult.Yes)\r
                 {\r
@@ -695,7 +705,7 @@ namespace Handbrake
             }\r
         }\r
 \r
-        private void importPreset()\r
+        private void ImportPreset()\r
         {\r
             if (openPreset.ShowDialog() == DialogResult.OK)\r
             {\r
@@ -703,31 +713,27 @@ namespace Handbrake
                 if (presetHandler.CheckIfUserPresetExists(parsed.PresetName + " (Imported)"))\r
                 {\r
                     DialogResult result =\r
-                        MessageBox.Show("This preset appears to already exist. Would you like to overwrite it?", \r
-                                        "Overwrite preset?", \r
+                        MessageBox.Show("This preset appears to already exist. Would you like to overwrite it?",\r
+                                        "Overwrite preset?",\r
                                         MessageBoxButtons.YesNo, MessageBoxIcon.Warning);\r
                     if (result == DialogResult.Yes)\r
                     {\r
                         PresetLoader.LoadPreset(this, parsed, parsed.PresetName, parsed.UsesPictureSettings);\r
-                        presetHandler.Update(parsed.PresetName + " (Imported)", \r
-                                             QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null), \r
+                        presetHandler.Update(parsed.PresetName + " (Imported)",\r
+                                             QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null),\r
                                              parsed.UsesPictureSettings);\r
                     }\r
                 }\r
                 else\r
                 {\r
                     PresetLoader.LoadPreset(this, parsed, parsed.PresetName, parsed.UsesPictureSettings);\r
-                    presetHandler.Add(parsed.PresetName, \r
-                                      QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null), \r
-                                      parsed.UsesPictureSettings);\r
-\r
-                    if (presetHandler.Add(parsed.PresetName + " (Imported)", \r
-                                          QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null), \r
+                    if (presetHandler.Add(parsed.PresetName + " (Imported)",\r
+                                          QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null),\r
                                           parsed.UsesPictureSettings))\r
                     {\r
                         TreeNode preset_treeview = new TreeNode(parsed.PresetName + " (Imported)")\r
                                                        {\r
-                                                          ForeColor = Color.Black\r
+                                                           ForeColor = Color.Black\r
                                                        };\r
                         treeView_presets.Nodes.Add(preset_treeview);\r
                     }\r
@@ -741,7 +747,23 @@ namespace Handbrake
 \r
         private void btn_source_Click(object sender, EventArgs e)\r
         {\r
-            mnu_dvd_drive.Visible = true;\r
+            // Remove old Drive Menu Items.\r
+            List<ToolStripMenuItem> itemsToRemove = new List<ToolStripMenuItem>();\r
+            foreach (var item in btn_source.DropDownItems)\r
+            {\r
+                if (item.GetType() == typeof(ToolStripMenuItem))\r
+                {\r
+                    ToolStripMenuItem menuItem = (ToolStripMenuItem)item;\r
+                    if (menuItem.Name.StartsWith("Drive"))\r
+                    {\r
+                        itemsToRemove.Add(menuItem);\r
+                    }\r
+                }\r
+            }\r
+\r
+            foreach (ToolStripMenuItem item in itemsToRemove)\r
+                btn_source.DropDownItems.Remove(item);\r
+\r
             Thread driveInfoThread = new Thread(SetDriveSelectionMenuItem);\r
             driveInfoThread.Start();\r
         }\r
@@ -755,12 +777,12 @@ namespace Handbrake
                     !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
+                        "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
+                    result = MessageBox.Show("Are you sure you wish to cancel the encode?", "Cancel Encode?",\r
                                              MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
                 }\r
 \r
@@ -805,9 +827,9 @@ namespace Handbrake
                                                               "priority over the GUI, your recently updated settings will not be taken " +\r
                                                               "into account when encoding this job." +\r
                                                               Environment.NewLine + Environment.NewLine +\r
-                                                              "Do you want to replace the manual query with the updated GUI-generated query?", \r
-                                                              "Manual Query does not Match GUI", \r
-                                                              MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk, \r
+                                                              "Do you want to replace the manual query with the updated GUI-generated query?",\r
+                                                              "Manual Query does not Match GUI",\r
+                                                              MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk,\r
                                                               MessageBoxDefaultButton.Button3);\r
 \r
                         switch (result)\r
@@ -836,13 +858,13 @@ namespace Handbrake
                         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
+                                    "The destination file already exists. Are you sure you want to overwrite it?",\r
                                     "Overwrite File?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
 \r
                     if (overwrite == DialogResult.Yes)\r
                     {\r
                         if (encodeQueue.Count == 0)\r
-                            encodeQueue.Add(query, sourcePath, text_destination.Text, (rtf_query.Text != string.Empty));\r
+                            encodeQueue.Add(query, getTitle(), sourcePath, text_destination.Text, (rtf_query.Text != string.Empty));\r
 \r
                         queueWindow.SetQueue();\r
                         if (encodeQueue.Count > 1)\r
@@ -850,15 +872,15 @@ namespace Handbrake
 \r
                         SetEncodeStarted(); // Encode is running, so setup the GUI appropriately\r
                         encodeQueue.Start(); // Start The Queue Encoding Process\r
-                        lastAction = "encode"; // Set the last action to encode - Used for activity window.\r
+                        lastAction = ActivityLogMode.Encode; // Set the last action to encode - Used for activity window.\r
                     }\r
                     if (ActivityWindow != null)\r
-                        ActivityWindow.SetEncodeMode();\r
+                        ActivityWindow.SetMode(ActivityLogMode.Encode);\r
 \r
                     this.Focus();\r
                 }\r
                 else if (string.IsNullOrEmpty(sourcePath) || string.IsNullOrEmpty(text_destination.Text))\r
-                    MessageBox.Show("No source or destination selected.", "Warning", MessageBoxButtons.OK, \r
+                    MessageBox.Show("No source or destination selected.", "Warning", MessageBoxButtons.OK,\r
                                     MessageBoxIcon.Warning);\r
             }\r
         }\r
@@ -866,7 +888,7 @@ namespace Handbrake
         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, \r
+                MessageBox.Show("No source or destination selected.", "Warning", MessageBoxButtons.OK,\r
                                 MessageBoxIcon.Warning);\r
             else\r
             {\r
@@ -878,13 +900,13 @@ namespace Handbrake
                 {\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
+                            "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, sourcePath, text_destination.Text, (rtf_query.Text != string.Empty));\r
+                        encodeQueue.Add(query, getTitle(), sourcePath, text_destination.Text, (rtf_query.Text != string.Empty));\r
                 }\r
                 else\r
-                    encodeQueue.Add(query, sourcePath, text_destination.Text, (rtf_query.Text != string.Empty));\r
+                    encodeQueue.Add(query, getTitle(), sourcePath, text_destination.Text, (rtf_query.Text != string.Empty));\r
 \r
                 lbl_encode.Text = encodeQueue.Count + " encode(s) pending in the queue";\r
 \r
@@ -901,7 +923,7 @@ namespace Handbrake
         private void tb_preview_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, \r
+                MessageBox.Show("No source or destination selected.", "Warning", MessageBoxButtons.OK,\r
                                 MessageBoxIcon.Warning);\r
             else\r
             {\r
@@ -916,7 +938,7 @@ namespace Handbrake
                     qtpreview.Show();\r
                 }\r
                 else\r
-                    MessageBox.Show(qtpreview, "The preview window is already open!", "Warning", MessageBoxButtons.OK, \r
+                    MessageBox.Show(qtpreview, "The preview window is already open!", "Warning", MessageBoxButtons.OK,\r
                                     MessageBoxIcon.Warning);\r
             }\r
         }\r
@@ -924,18 +946,18 @@ namespace Handbrake
         private void btn_ActivityWindow_Click(object sender, EventArgs e)\r
         {\r
             if (ActivityWindow == null || !ActivityWindow.IsHandleCreated)\r
-                ActivityWindow = new frmActivityWindow(lastAction);\r
+                ActivityWindow = new frmActivityWindow(lastAction, encodeQueue, SourceScan);\r
             else\r
                 switch (lastAction)\r
                 {\r
-                    case "scan":\r
-                        ActivityWindow.SetScanMode();\r
+                    case ActivityLogMode.Scan:\r
+                        ActivityWindow.SetMode(ActivityLogMode.Scan);\r
                         break;\r
-                    case "encode":\r
-                        ActivityWindow.SetEncodeMode();\r
+                    case ActivityLogMode.Encode:\r
+                        ActivityWindow.SetMode(ActivityLogMode.Encode);\r
                         break;\r
                     default:\r
-                        ActivityWindow.SetEncodeMode();\r
+                        ActivityWindow.SetMode(ActivityLogMode.Encode);\r
                         break;\r
                 }\r
 \r
@@ -972,6 +994,8 @@ namespace Handbrake
             this.Activate();\r
             this.WindowState = FormWindowState.Normal;\r
             notifyIcon.Visible = false;\r
+\r
+            this.StartScan(null, 2);\r
         }\r
 \r
         #endregion\r
@@ -1003,15 +1027,28 @@ namespace Handbrake
 \r
         private void mnu_dvd_drive_Click(object sender, EventArgs e)\r
         {\r
-            if (this.dvdDrivePath == null) return;\r
-            this.selectedSourceType = SourceType.DvdDrive;\r
-            SelectSource(this.dvdDrivePath);\r
+            ToolStripMenuItem item = sender as ToolStripMenuItem;\r
+            if (item != null)\r
+            {\r
+                string driveId = item.Name.Replace("Drive", string.Empty);\r
+                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
+                    if (this.dvdDrivePath == null) return;\r
+                    this.selectedSourceType = SourceType.DvdDrive;\r
+                    SelectSource(this.dvdDrivePath);\r
+                }\r
+            }\r
         }\r
 \r
         private void SelectSource(string file)\r
         {\r
             Check_ChapterMarkers.Enabled = true;\r
-            lastAction = "scan";\r
+            lastAction = ActivityLogMode.Scan;\r
             sourcePath = string.Empty;\r
 \r
             if (file == string.Empty) // Must have a file or path\r
@@ -1028,7 +1065,7 @@ namespace Handbrake
         {\r
             if ((drp_dvdtitle.Items.Count == 1) && (drp_dvdtitle.Items[0].ToString() == "Automatic"))\r
                 MessageBox.Show(\r
-                    "There are no titles to select. Please load a source file by clicking the 'Source' button above before trying to select a title.", \r
+                    "There are no titles to select. Please load a source file by clicking the 'Source' button above before trying to select a title.",\r
                     "Alert", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);\r
         }\r
 \r
@@ -1041,7 +1078,7 @@ namespace Handbrake
             drop_chapterFinish.Items.Clear();\r
 \r
             // If the dropdown is set to automatic nothing else needs to be done.\r
-            // Otheriwse if its not, title data has to be loased from parsing.\r
+            // Otheriwse if its not, title data has to be loaded from parsing.\r
             if (drp_dvdtitle.Text != "Automatic")\r
             {\r
                 selectedTitle = drp_dvdtitle.SelectedItem as Title;\r
@@ -1078,7 +1115,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);\r
+                AudioSettings.SetTrackList(selectedTitle, CurrentlySelectedPreset);\r
 \r
                 // Populate the Subtitles dropdown\r
                 Subtitles.SetSubtitleTrackAuto(selectedTitle.Subtitles.ToArray());\r
@@ -1096,7 +1133,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 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
@@ -1125,7 +1162,7 @@ namespace Handbrake
             if (drop_mode.SelectedIndex != 0) // Function is not used if we are not in chapters mode.\r
                 return;\r
 \r
-            Control ctl = (Control) sender;\r
+            Control ctl = (Control)sender;\r
             int chapterStart, chapterEnd;\r
             int.TryParse(drop_chapterStart.Text, out chapterStart);\r
             int.TryParse(drop_chapterFinish.Text, out chapterEnd);\r
@@ -1159,8 +1196,8 @@ namespace Handbrake
                             int n = data_chpt.Rows.Add();\r
                             data_chpt.Rows[n].Cells[0].Value = (i + 1);\r
                             data_chpt.Rows[n].Cells[1].Value = "Chapter " + (i + 1);\r
-                            data_chpt.Rows[n].Cells[0].ValueType = typeof (int);\r
-                            data_chpt.Rows[n].Cells[1].ValueType = typeof (string);\r
+                            data_chpt.Rows[n].Cells[0].ValueType = typeof(int);\r
+                            data_chpt.Rows[n].Cells[1].ValueType = typeof(string);\r
                             i++;\r
                         }\r
                     }\r
@@ -1209,7 +1246,7 @@ namespace Handbrake
                 case 2:\r
                     if (selectedTitle != null)\r
                     {\r
-                        duration = duration/selectedTitle.Fps;\r
+                        duration = duration / selectedTitle.Fps;\r
                         lbl_duration.Text = TimeSpan.FromSeconds(duration).ToString();\r
                     }\r
                     else\r
@@ -1258,7 +1295,7 @@ namespace Handbrake
                     if (selectedTitle != null)\r
                     {\r
                         drop_chapterStart.Text = "0";\r
-                        drop_chapterFinish.Text = (selectedTitle.Fps*selectedTitle.Duration.TotalSeconds).ToString();\r
+                        drop_chapterFinish.Text = (selectedTitle.Fps * selectedTitle.Duration.TotalSeconds).ToString();\r
                     }\r
                     return;\r
             }\r
@@ -1287,7 +1324,7 @@ namespace Handbrake
                 {\r
                     case 1:\r
                         if (\r
-                            !Path.GetExtension(DVD_Save.FileName).Equals(".mp4", \r
+                            !Path.GetExtension(DVD_Save.FileName).Equals(".mp4",\r
                                                                          StringComparison.InvariantCultureIgnoreCase))\r
                             if (Properties.Settings.Default.useM4v)\r
                                 DVD_Save.FileName = DVD_Save.FileName.Replace(".mp4", ".m4v").Replace(".mkv", ".m4v");\r
@@ -1296,8 +1333,7 @@ namespace Handbrake
                         break;\r
                     case 2:\r
                         if (\r
-                            !Path.GetExtension(DVD_Save.FileName).Equals(".mkv", \r
-                                                                         StringComparison.InvariantCultureIgnoreCase))\r
+                            !Path.GetExtension(DVD_Save.FileName).Equals(".mkv", StringComparison.InvariantCultureIgnoreCase))\r
                             DVD_Save.FileName = DVD_Save.FileName.Replace(".mp4", ".mkv").Replace(".m4v", ".mkv");\r
                         break;\r
                     default:\r
@@ -1408,29 +1444,13 @@ namespace Handbrake
 \r
                     CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");\r
                     double cqStep = Properties.Settings.Default.x264cqstep;\r
-                    double multiplier = 1.0/cqStep;\r
-                    double value = slider_videoQuality.Value*multiplier;\r
+                    double multiplier = 1.0 / cqStep;\r
+                    double value = slider_videoQuality.Value * multiplier;\r
+\r
+                    slider_videoQuality.Maximum = (int)(51 / Properties.Settings.Default.x264cqstep);\r
 \r
-                    switch (Properties.Settings.Default.x264cqstep.ToString(culture))\r
-                    {\r
-                        case "0.2":\r
-                            slider_videoQuality.Maximum = 255;\r
-                            break;\r
-                        case "0.25":\r
-                            slider_videoQuality.Maximum = 204;\r
-                            break;\r
-                        case "0.5":\r
-                            slider_videoQuality.Maximum = 102;\r
-                            break;\r
-                        case "1":\r
-                            slider_videoQuality.Maximum = 51;\r
-                            break;\r
-                        default:\r
-                            slider_videoQuality.Maximum = 51;\r
-                            break;\r
-                    }\r
                     if (value < slider_videoQuality.Maximum)\r
-                        slider_videoQuality.Value = slider_videoQuality.Maximum - (int) value;\r
+                        slider_videoQuality.Value = slider_videoQuality.Maximum - (int)value;\r
 \r
                     break;\r
                 case "VP3 (Theora)":\r
@@ -1473,38 +1493,21 @@ namespace Handbrake
         {\r
             // Work out the current RF value.\r
             double cqStep = _cachedCqStep;\r
-            double rfValue = 51.0 - slider_videoQuality.Value*cqStep;\r
+            double rfValue = 51.0 - slider_videoQuality.Value * cqStep;\r
 \r
             // Change the maximum value for the slider\r
-            switch (Properties.Settings.Default.x264cqstep.ToString(new CultureInfo("en-US")))\r
-            {\r
-                case "0.2":\r
-                    slider_videoQuality.Maximum = 255;\r
-                    break;\r
-                case "0.25":\r
-                    slider_videoQuality.Maximum = 204;\r
-                    break;\r
-                case "0.5":\r
-                    slider_videoQuality.Maximum = 102;\r
-                    break;\r
-                case "1":\r
-                    slider_videoQuality.Maximum = 51;\r
-                    break;\r
-                default:\r
-                    slider_videoQuality.Maximum = 51;\r
-                    break;\r
-            }\r
+            slider_videoQuality.Maximum = (int)(51 / Properties.Settings.Default.x264cqstep);\r
 \r
             // Reset the CQ slider to RF0\r
             slider_videoQuality.Value = slider_videoQuality.Maximum;\r
 \r
             // Reset the CQ slider back to the previous value as close as possible\r
             double cqStepNew = Properties.Settings.Default.x264cqstep;\r
-            double rfValueCurrent = 51.0 - slider_videoQuality.Value*cqStepNew;\r
+            double rfValueCurrent = 51.0 - slider_videoQuality.Value * cqStepNew;\r
             while (rfValueCurrent < rfValue)\r
             {\r
                 slider_videoQuality.Value--;\r
-                rfValueCurrent = 51.0 - slider_videoQuality.Value*cqStepNew;\r
+                rfValueCurrent = 51.0 - slider_videoQuality.Value * cqStepNew;\r
             }\r
 \r
             // Cache the CQ step for the next calculation\r
@@ -1520,7 +1523,7 @@ namespace Handbrake
                     lbl_SliderValue.Text = "QP:" + (32 - slider_videoQuality.Value);\r
                     break;\r
                 case "H.264 (x264)":\r
-                    double rfValue = 51.0 - slider_videoQuality.Value*cqStep;\r
+                    double rfValue = 51.0 - slider_videoQuality.Value * cqStep;\r
                     rfValue = Math.Round(rfValue, 2);\r
                     lbl_SliderValue.Text = "RF:" + rfValue.ToString(new CultureInfo("en-US"));\r
                     break;\r
@@ -1602,6 +1605,19 @@ namespace Handbrake
             }\r
         }\r
 \r
+        private void btn_export_Click(object sender, EventArgs e)\r
+        {\r
+            SaveFileDialog saveFileDialog = new SaveFileDialog();\r
+            saveFileDialog.Filter = "Csv File|*.csv";\r
+            saveFileDialog.DefaultExt = "csv";\r
+            if (saveFileDialog.ShowDialog() == DialogResult.OK)\r
+            {\r
+                string filename = saveFileDialog.FileName;\r
+\r
+                Main.SaveChapterMarkersToCsv(this, filename);\r
+            }\r
+        }\r
+\r
         private void mnu_resetChapters_Click(object sender, EventArgs e)\r
         {\r
             data_chpt.Rows.Clear();\r
@@ -1630,27 +1646,16 @@ namespace Handbrake
         #region Source Scan\r
 \r
         public bool isScanning { get; set; }\r
-        private Scan SourceScan;\r
 \r
         private void StartScan(string filename, int title)\r
         {\r
             // Setup the GUI components for the scan.\r
             sourcePath = filename;\r
-            foreach (Control ctrl in Controls)\r
-                if (!(ctrl is StatusStrip || ctrl is MenuStrip || ctrl is ToolStrip))\r
-                    ctrl.Enabled = false;\r
 \r
-            lbl_encode.Visible = true;\r
-            lbl_encode.Text = "Scanning ...";\r
-            btn_source.Enabled = false;\r
-            btn_start.Enabled = false;\r
-            btn_showQueue.Enabled = false;\r
-            btn_add2Queue.Enabled = false;\r
-            tb_preview.Enabled = false;\r
-            mnu_killCLI.Visible = true;\r
+            this.DisableGUI();\r
 \r
             if (ActivityWindow != null)\r
-                ActivityWindow.SetScanMode();\r
+                ActivityWindow.SetMode(ActivityLogMode.Scan);\r
 \r
             // Start the Scan\r
             try\r
@@ -1704,13 +1709,24 @@ namespace Handbrake
                 if (currentSource.Titles.Count != 0)\r
                     drp_dvdtitle.Items.AddRange(currentSource.Titles.ToArray());\r
 \r
-                // Now select the longest title\r
-                if (currentSource.Titles.Count != 0)\r
-                    drp_dvdtitle.SelectedItem = Main.SelectLongestTitle(currentSource);\r
+                foreach (Title title in currentSource.Titles)\r
+                {\r
+                    if (title.MainTitle)\r
+                    {\r
+                        drp_dvdtitle.SelectedItem = title;\r
+                    }\r
+                }\r
+\r
+                if (drp_dvdtitle.SelectedItem == null && drp_dvdtitle.Items.Count > 0)\r
+                {\r
+                    drp_dvdtitle.SelectedIndex = 0;\r
+                }\r
 \r
                 // Enable the creation of chapter markers if the file is an image of a dvd.\r
-                if (sourcePath.ToLower().Contains(".iso") || sourcePath.Contains("VIDEO_TS") ||\r
-                    Directory.Exists(Path.Combine(sourcePath, "VIDEO_TS")))\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
                 {\r
@@ -1723,7 +1739,7 @@ namespace Handbrake
                 if (drp_dvdtitle.Items.Count == 0)\r
                 {\r
                     MessageBox.Show(\r
-                        "No Title(s) found. \n\nYour Source may be copy protected, badly mastered or in a format which HandBrake does not support. \nPlease refer to the Documentation and FAQ (see Help Menu).", \r
+                        "No Title(s) found. \n\nYour Source may be copy protected, badly mastered or in a format which HandBrake does not support. \nPlease refer to the Documentation and FAQ (see Help Menu).",\r
                         "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);\r
                     sourcePath = string.Empty;\r
                 }\r
@@ -1734,7 +1750,7 @@ namespace Handbrake
             }\r
             catch (Exception exc)\r
             {\r
-                MessageBox.Show("frmMain.cs - updateUIafterScan " + exc, "Error", MessageBoxButtons.OK, \r
+                MessageBox.Show("frmMain.cs - updateUIafterScan " + exc, "Error", MessageBoxButtons.OK,\r
                                 MessageBoxIcon.Error);\r
                 EnableGUI();\r
             }\r
@@ -1762,25 +1778,31 @@ namespace Handbrake
             }\r
         }\r
 \r
+        private void DisableGUI()\r
+        {\r
+            foreach (Control ctrl in Controls)\r
+                if (!(ctrl is StatusStrip || ctrl is MenuStrip || ctrl is ToolStrip))\r
+                    ctrl.Enabled = false;\r
+\r
+            lbl_encode.Visible = true;\r
+            lbl_encode.Text = "Scanning ...";\r
+            btn_source.Enabled = false;\r
+            btn_start.Enabled = false;\r
+            btn_showQueue.Enabled = false;\r
+            btn_add2Queue.Enabled = false;\r
+            tb_preview.Enabled = false;\r
+            mnu_killCLI.Visible = true;\r
+        }\r
+\r
         private void KillScan()\r
         {\r
-            try\r
-            {\r
-                SourceScan.ScanCompleted -= new EventHandler(SourceScan_ScanCompleted);\r
-                EnableGUI();\r
-                ResetGUI();\r
+            SourceScan.ScanCompleted -= new EventHandler(SourceScan_ScanCompleted);\r
+            EnableGUI();\r
+            ResetGUI();\r
 \r
-                if (SourceScan.ScanProcess() != null)\r
-                    SourceScan.ScanProcess().Kill();\r
+            SourceScan.KillScan();\r
 \r
-                lbl_encode.Text = "Scan Cancelled!";\r
-            }\r
-            catch (Exception ex)\r
-            {\r
-                MessageBox.Show(\r
-                    "Unable to kill HandBrakeCLI.exe \nYou may need to manually kill HandBrakeCLI.exe using the Windows Task Manager if it does not close automatically within the next few minutes. \n\nError Information: \n" +\r
-                    ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
-            }\r
+            lbl_encode.Text = "Scan Cancelled!";\r
         }\r
 \r
         private void ResetGUI()\r
@@ -1809,8 +1831,7 @@ namespace Handbrake
         public void RecievingJob(Job job)\r
         {\r
             string query = job.Query;\r
-            StartScan(job.Source, 0);\r
-\r
+            StartScan(job.Source, job.Title);\r
 \r
             if (query != null)\r
             {\r
@@ -1907,21 +1928,25 @@ namespace Handbrake
                     return;\r
                 }\r
 \r
-                List<DriveInformation> drives = Main.GetDrives();\r
+                drives = Main.GetDrives();\r
 \r
-                if (drives.Count == 0)\r
+                List<ToolStripMenuItem> menuItems = new List<ToolStripMenuItem>();\r
+                foreach (DriveInformation drive in drives)\r
                 {\r
-                    mnu_dvd_drive.Text = "[No DVD Drive Ready]";\r
-                    return;\r
+                    ToolStripMenuItem menuItem = new ToolStripMenuItem();\r
+                    menuItem.Name = drive.ToString();\r
+                    menuItem.Text = drive.RootDirectory + " (" + drive.VolumeLabel + ")";\r
+                    menuItem.Image = Resources.disc_small;\r
+                    menuItem.Click += new EventHandler(mnu_dvd_drive_Click);\r
+                    menuItems.Add(menuItem);\r
                 }\r
 \r
-                this.dvdDrivePath = drives[0].RootDirectory + "VIDEO_TS";\r
-                this.dvdDriveLabel = drives[0].VolumeLabel;\r
-                mnu_dvd_drive.Text = this.dvdDrivePath + " (" + this.dvdDriveLabel + ")";\r
+                foreach (ToolStripMenuItem item in menuItems)\r
+                    btn_source.DropDownItems.Add(item);\r
             }\r
-            catch (Exception)\r
+            catch (Exception exc)\r
             {\r
-                mnu_dvd_drive.Text = "[No DVD Drive Ready / Found]";\r
+                MessageBox.Show("Error in SetDriveSelectionMenuItem" + exc);\r
             }\r
         }\r
 \r
@@ -1932,14 +1957,32 @@ namespace Handbrake
         {\r
             if (presetHandler.CheckIfPresetsAreOutOfDate())\r
                 if (!Properties.Settings.Default.presetNotification)\r
-                    MessageBox.Show(splash, \r
-                                    "HandBrake has determined your built-in presets are out of date... These presets will now be updated.", \r
+                    MessageBox.Show(splash,\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
             presetHandler.GetPresetPanel(ref treeView_presets);\r
             treeView_presets.Update();\r
         }\r
 \r
+        /// <summary>\r
+        /// Get the title from the selected item in the title dropdown.\r
+        /// </summary>\r
+        /// <returns>\r
+        /// The title.\r
+        /// </returns>\r
+        private int getTitle()\r
+        {\r
+            int title = 0;\r
+            if (drp_dvdtitle.SelectedItem != null)\r
+            {\r
+                string[] titleInfo = drp_dvdtitle.SelectedItem.ToString().Split(' ');\r
+                int.TryParse(titleInfo[0], out title);\r
+            }\r
+\r
+            return title;\r
+        }\r
+\r
         #endregion\r
 \r
         #region Overrides\r
@@ -1947,9 +1990,9 @@ namespace Handbrake
         /// <summary>\r
         /// Handle GUI shortcuts\r
         /// </summary>\r
-        /// <param name="msg"></param>\r
-        /// <param name="keyData"></param>\r
-        /// <returns></returns>\r
+        /// <param name="msg">Message</param>\r
+        /// <param name="keyData">Keys</param>\r
+        /// <returns>Bool</returns>\r
         protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\r
         {\r
             if (keyData == (Keys.Control | Keys.S))\r
@@ -1969,18 +2012,31 @@ namespace Handbrake
         /// <summary>\r
         /// If the queue is being processed, prompt the user to confirm application close.\r
         /// </summary>\r
-        /// <param name="e"></param>\r
+        /// <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) && (!encodeQueue.PauseRequested) && (encodeQueue.Count > 0))\r
+            if (encodeQueue.IsEncoding)\r
             {\r
                 DialogResult result =\r
                     MessageBox.Show(\r
-                        "HandBrake has queue items to process. Closing HandBrake will not stop the current encoding, but will stop processing the queue.\n\nDo you want to close HandBrake?", \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
+\r
                 if (result == DialogResult.No)\r
                     e.Cancel = true;\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.KillScan();\r
             }\r
             base.OnFormClosing(e);\r
         }\r
@@ -2017,26 +2073,22 @@ namespace Handbrake
         /// <param name="CurrentFps"></param>\r
         /// <param name="AverageFps"></param>\r
         /// <param name="TimeRemaining"></param>\r
-        private void EncodeOnEncodeProgress(object Sender, int CurrentTask, int TaskCount, float PercentComplete, \r
-                                            float CurrentFps, float AverageFps, TimeSpan TimeRemaining)\r
+        private void EncodeOnEncodeProgress(object Sender, int CurrentTask, int TaskCount, float PercentComplete, float CurrentFps, float AverageFps, TimeSpan TimeRemaining)\r
         {\r
             if (this.InvokeRequired)\r
             {\r
-                this.BeginInvoke(new EncodeProgressEventHandler(EncodeOnEncodeProgress), \r
-                                 new[]\r
-                                     {\r
-                                         Sender, CurrentTask, TaskCount, PercentComplete, CurrentFps, AverageFps, \r
-                                         TimeRemaining\r
-                                     });\r
+                this.BeginInvoke(\r
+                    new EncodeProgressEventHandler(EncodeOnEncodeProgress),\r
+                    new[] { Sender, CurrentTask, TaskCount, PercentComplete, CurrentFps, AverageFps, TimeRemaining });\r
                 return;\r
             }\r
             lbl_encode.Text =\r
-                string.Format("Encode Progress: {0}%,       FPS: {1},       Avg FPS: {2},       Time Remaining: {3} ", \r
-                              PercentComplete, CurrentFps, AverageFps, TimeRemaining);\r
+                string.Format("Encode Progress: {0}%,       FPS: {1},       Avg FPS: {2},       Time Remaining: {3} ", PercentComplete, CurrentFps, AverageFps, TimeRemaining);\r
         }\r
 \r
         #endregion\r
 \r
+\r
         // This is the END of the road ****************************************\r
     }\r
 }
\ No newline at end of file