OSDN Git Service

WinGui:
[handbrake-jp/handbrake-jp-git.git] / win / C# / frmMain.cs
1 /*  frmMain.cs $\r
2         \r
3            This file is part of the HandBrake source code.\r
4            Homepage: <http://handbrake.fr/>.\r
5            It may be used under the terms of the GNU General Public License. */\r
6 \r
7 using System;\r
8 using System.Collections.Generic;\r
9 using System.Drawing;\r
10 using System.Globalization;\r
11 using System.Windows.Forms;\r
12 using System.IO;\r
13 using System.Diagnostics;\r
14 using System.Threading;\r
15 using Handbrake.EncodeQueue;\r
16 using Handbrake.Functions;\r
17 using Handbrake.Presets;\r
18 using Handbrake.Parsing;\r
19 \r
20 namespace Handbrake\r
21 {\r
22     public partial class frmMain : Form\r
23     {\r
24         // Objects which may be used by one or more other objects *************\r
25         EncodeAndQueueHandler encodeQueue = new EncodeAndQueueHandler();\r
26         PresetsHandler presetHandler = new PresetsHandler();\r
27         QueryGenerator queryGen = new QueryGenerator();\r
28 \r
29         // Globals: Mainly used for tracking. *********************************\r
30         public Title selectedTitle;\r
31         private DVD thisDVD;\r
32         private frmQueue queueWindow;\r
33         private frmPreview qtpreview;\r
34         private frmActivityWindow ActivityWindow;\r
35         private Form splash;\r
36         public string sourcePath;\r
37         private string lastAction;\r
38         private SourceType selectedSourceType;\r
39         private string dvdDrivePath;\r
40         private string dvdDriveLabel;\r
41 \r
42         // Delegates **********************************************************\r
43         private delegate void UpdateWindowHandler();\r
44 \r
45         // Applicaiton Startup ************************************************\r
46 \r
47         #region Application Startup\r
48         public frmMain()\r
49         {\r
50             // Load and setup the splash screen in this thread\r
51             splash = new frmSplashScreen();\r
52             splash.Show(this);\r
53             Label lblStatus = new Label { Size = new Size(150, 20), Location = new Point(182, 102) };\r
54             splash.Controls.Add(lblStatus);\r
55 \r
56             InitializeComponent();\r
57 \r
58             // Update the users config file with the CLI version data.\r
59             lblStatus.Text = "Setting Version Data ...";\r
60             Application.DoEvents();\r
61             Main.setCliVersionData();\r
62 \r
63             // Show the form, but leave disabled until preloading is complete then show the main form\r
64             this.Enabled = false;\r
65             this.Show();\r
66             Application.DoEvents(); // Forces frmMain to draw\r
67 \r
68             // Check for new versions, if update checking is enabled\r
69             if (Properties.Settings.Default.updateStatus)\r
70             {\r
71                 DateTime now = DateTime.Now;\r
72                 DateTime lastCheck = Properties.Settings.Default.lastUpdateCheckDate;\r
73                 TimeSpan elapsed = now.Subtract(lastCheck);\r
74                 if (elapsed.TotalDays > Properties.Settings.Default.daysBetweenUpdateCheck)\r
75                 {\r
76                     lblStatus.Text = "Checking for updates ...";\r
77                     Application.DoEvents();\r
78 \r
79                     Main.BeginCheckForUpdates(new AsyncCallback(UpdateCheckDone), false);\r
80                 }\r
81             }\r
82 \r
83             // Setup the GUI components\r
84             lblStatus.Text = "Setting up the GUI ...";\r
85             Application.DoEvents();\r
86             loadPresetPanel();                       // Load the Preset Panel\r
87             treeView_presets.ExpandAll();\r
88             lbl_encode.Text = "";\r
89             queueWindow = new frmQueue(encodeQueue);        // Prepare the Queue\r
90             if (!Properties.Settings.Default.QueryEditorTab)\r
91                 tabs_panel.TabPages.RemoveAt(7); // Remove the query editor tab if the user does not want it enabled.\r
92 \r
93             // Load the user's default settings or Normal Preset\r
94             if (Properties.Settings.Default.defaultPreset != "")\r
95             {\r
96                 if (presetHandler.GetPreset(Properties.Settings.Default.defaultPreset) != null)\r
97                 {\r
98                     string query = presetHandler.GetPreset(Properties.Settings.Default.defaultPreset).Query;\r
99                     Boolean loadPictureSettings = presetHandler.GetPreset(Properties.Settings.Default.defaultPreset).PictureSettings;\r
100 \r
101                     if (query != null)\r
102                     {\r
103                         //Ok, Reset all the H264 widgets before changing the preset\r
104                         x264Panel.reset2Defaults();\r
105 \r
106                         // Send the query from the file to the Query Parser class, then load the preset\r
107                         QueryParser presetQuery = QueryParser.Parse(query);\r
108                         PresetLoader.presetLoader(this, presetQuery, Properties.Settings.Default.defaultPreset, loadPictureSettings);\r
109 \r
110                         // The x264 widgets will need updated, so do this now:\r
111                         x264Panel.X264_StandardizeOptString();\r
112                         x264Panel.X264_SetCurrentSettingsInPanel();\r
113                     }\r
114                 }\r
115                 else\r
116                     loadNormalPreset();\r
117             }\r
118             else\r
119                 loadNormalPreset();\r
120 \r
121             // Enabled GUI tooltip's if Required\r
122             if (Properties.Settings.Default.tooltipEnable)\r
123                 ToolTip.Active = true;\r
124 \r
125             // Register with Growl (if not using Growl for the encoding completion action, this wont hurt anything)\r
126             GrowlCommunicator.Register();\r
127 \r
128             //Finished Loading\r
129             lblStatus.Text = "Loading Complete!";\r
130             Application.DoEvents();\r
131             splash.Close();\r
132             splash.Dispose();\r
133             this.Enabled = true;\r
134 \r
135             // Event Handlers and Queue Recovery\r
136             events();\r
137             queueRecovery();\r
138         }\r
139 \r
140         private void UpdateCheckDone(IAsyncResult result)\r
141         {\r
142             if (InvokeRequired)\r
143             {\r
144                 Invoke(new MethodInvoker(() => UpdateCheckDone(result)));\r
145                 return;\r
146             }\r
147 \r
148             UpdateCheckInformation info;\r
149 \r
150             try\r
151             {\r
152                 info = Main.EndCheckForUpdates(result);\r
153 \r
154                 if (info.NewVersionAvailable)\r
155                 {\r
156                     frmUpdater updateWindow = new frmUpdater(info.BuildInformation);\r
157                     updateWindow.ShowDialog();\r
158                 }\r
159             }\r
160             catch (Exception ex)\r
161             {\r
162                 if ((bool)result.AsyncState)\r
163                     MessageBox.Show("Unable to check for updates, Please try again later.\n\nDetailed Error Information:\n" + ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
164             }\r
165         }\r
166 \r
167         // Startup Functions   \r
168         private void queueRecovery()\r
169         {\r
170             if (Main.checkQueueRecovery())\r
171             {\r
172                 DialogResult result = MessageBox.Show("HandBrake has detected unfinished items on the queue from the last time the application was launched. Would you like to recover these?", "Queue Recovery Possible", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
173 \r
174                 if (result == DialogResult.Yes)\r
175                     encodeQueue.LoadQueueFromFile("hb_queue_recovery.xml"); // Start Recovery\r
176                 else\r
177                 {\r
178                     // Remove the Queue recovery file if the user doesn't want to recovery the last queue.\r
179                     string queuePath = Path.Combine(Path.GetTempPath(), "hb_queue_recovery.xml");\r
180                     if (File.Exists(queuePath))\r
181                         File.Delete(queuePath);\r
182                 }\r
183             }\r
184         }\r
185         #endregion\r
186 \r
187         #region Properties\r
188         public string SourceName\r
189         {\r
190             get\r
191             {\r
192                 if (this.selectedSourceType == SourceType.DvdDrive)\r
193                 {\r
194                     return this.dvdDriveLabel;\r
195                 }\r
196 \r
197                 return Path.GetFileNameWithoutExtension(this.sourcePath);\r
198             }\r
199         }\r
200         #endregion\r
201 \r
202         #region Events\r
203         // Encoding Events for setting up the GUI\r
204         private void events()\r
205         {\r
206             // Handle Widget changes when preset is selected.\r
207             RegisterPresetEventHandler();\r
208 \r
209             // Handle Window Resize\r
210             if (Properties.Settings.Default.MainWindowMinimize)\r
211                 this.Resize += new EventHandler(frmMain_Resize);\r
212 \r
213             // Handle Encode Start / Finish / Pause\r
214             encodeQueue.CurrentJobCompleted += new EventHandler(encodeEnded);\r
215             encodeQueue.QueuePauseRequested += new EventHandler(encodePaused);\r
216             encodeQueue.NewJobStarted += new EventHandler(encodeStarted);\r
217 \r
218             // Handle a file being draged onto the GUI.\r
219             this.DragEnter += new DragEventHandler(frmMain_DragEnter);\r
220             this.DragDrop += new DragEventHandler(frmMain_DragDrop);\r
221         }\r
222 \r
223         // Change the preset label to custom when a user changes a setting. Don't want to give the impression that users can change settings and still be using a preset\r
224         private void RegisterPresetEventHandler()\r
225         {\r
226             // Output Settings\r
227             drop_format.SelectedIndexChanged += new EventHandler(changePresetLabel);\r
228             check_largeFile.CheckedChanged += new EventHandler(changePresetLabel);\r
229             check_iPodAtom.CheckedChanged += new EventHandler(changePresetLabel);\r
230             check_optimiseMP4.CheckedChanged += new EventHandler(changePresetLabel);\r
231 \r
232             // Picture Settings\r
233             //PictureSettings.PictureSettingsChanged += new EventHandler(changePresetLabel);\r
234 \r
235             // Filter Settings\r
236             Filters.FilterSettingsChanged += new EventHandler(changePresetLabel);\r
237 \r
238             // Video Tab\r
239             drp_videoEncoder.SelectedIndexChanged += new EventHandler(changePresetLabel);\r
240             check_2PassEncode.CheckedChanged += new EventHandler(changePresetLabel);\r
241             check_turbo.CheckedChanged += new EventHandler(changePresetLabel);\r
242             text_filesize.TextChanged += new EventHandler(changePresetLabel);\r
243             text_bitrate.TextChanged += new EventHandler(changePresetLabel);\r
244             slider_videoQuality.ValueChanged += new EventHandler(changePresetLabel);\r
245 \r
246             // Audio Panel\r
247             AudioSettings.AudioListChanged += new EventHandler(changePresetLabel);\r
248 \r
249             // Advanced Tab\r
250             x264Panel.rtf_x264Query.TextChanged += new EventHandler(changePresetLabel);\r
251         }\r
252         private void UnRegisterPresetEventHandler()\r
253         {\r
254             // Output Settings \r
255             drop_format.SelectedIndexChanged -= new EventHandler(changePresetLabel);\r
256             check_largeFile.CheckedChanged -= new EventHandler(changePresetLabel);\r
257             check_iPodAtom.CheckedChanged -= new EventHandler(changePresetLabel);\r
258             check_optimiseMP4.CheckedChanged -= new EventHandler(changePresetLabel);\r
259 \r
260             // Picture Settings\r
261             //PictureSettings.PictureSettingsChanged -= new EventHandler(changePresetLabel);\r
262 \r
263             // Filter Settings\r
264             Filters.FilterSettingsChanged -= new EventHandler(changePresetLabel);\r
265 \r
266             // Video Tab\r
267             drp_videoEncoder.SelectedIndexChanged -= new EventHandler(changePresetLabel);\r
268             check_2PassEncode.CheckedChanged -= new EventHandler(changePresetLabel);\r
269             check_turbo.CheckedChanged -= new EventHandler(changePresetLabel);\r
270             text_filesize.TextChanged -= new EventHandler(changePresetLabel);\r
271             text_bitrate.TextChanged -= new EventHandler(changePresetLabel);\r
272             slider_videoQuality.ValueChanged -= new EventHandler(changePresetLabel);\r
273 \r
274             // Audio Panel\r
275             AudioSettings.AudioListChanged -= new EventHandler(changePresetLabel);\r
276 \r
277             // Advanced Tab\r
278             x264Panel.rtf_x264Query.TextChanged -= new EventHandler(changePresetLabel);\r
279         }\r
280         private void changePresetLabel(object sender, EventArgs e)\r
281         {\r
282             labelPreset.Text = "Output Settings (Preset: Custom)";\r
283         }\r
284 \r
285         private static void frmMain_DragEnter(object sender, DragEventArgs e)\r
286         {\r
287             if (e.Data.GetDataPresent(DataFormats.FileDrop, false))\r
288                 e.Effect = DragDropEffects.All;\r
289         }\r
290         private void frmMain_DragDrop(object sender, DragEventArgs e)\r
291         {\r
292             string[] fileList = e.Data.GetData(DataFormats.FileDrop) as string[];\r
293             sourcePath = string.Empty;\r
294 \r
295             if (fileList != null)\r
296             {\r
297                 if (fileList[0].StartsWith("\\"))\r
298                 {\r
299                     MessageBox.Show(\r
300                         "Sorry, HandBrake does not support UNC file paths. \nTry mounting the network share as a network drive in My Computer",\r
301                         "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);\r
302                     UpdateSourceLabel();\r
303                 }\r
304                 else\r
305                 {\r
306                     if (fileList[0] != "")\r
307                         startScan(fileList[0]);\r
308                     else\r
309                         UpdateSourceLabel();\r
310                 }\r
311             }\r
312             else\r
313                 UpdateSourceLabel();\r
314         }\r
315         private void encodeStarted(object sender, EventArgs e)\r
316         {\r
317             lastAction = "encode";\r
318             setEncodeStarted();\r
319 \r
320             // Experimental HBProc Process Monitoring.\r
321             if (Properties.Settings.Default.enocdeStatusInGui)\r
322             {\r
323                 Thread encodeMon = new Thread(encodeMonitorThread);\r
324                 encodeMon.Start();\r
325             }\r
326         }\r
327         private void encodeEnded(object sender, EventArgs e)\r
328         {\r
329             setEncodeFinished();\r
330         }\r
331         private void encodePaused(object sender, EventArgs e)\r
332         {\r
333             setEncodeFinished();\r
334         }\r
335         #endregion\r
336 \r
337         // User Interface Menus / Tool Strips *********************************\r
338 \r
339         #region File Menu\r
340         private void mnu_killCLI_Click(object sender, EventArgs e)\r
341         {\r
342             killScan();\r
343         }\r
344         private void mnu_exit_Click(object sender, EventArgs e)\r
345         {\r
346             Application.Exit();\r
347         }\r
348         #endregion\r
349 \r
350         #region Tools Menu\r
351         private void mnu_encode_Click(object sender, EventArgs e)\r
352         {\r
353             queueWindow.Show();\r
354         }\r
355         private void mnu_encodeLog_Click(object sender, EventArgs e)\r
356         {\r
357             String file = lastAction == "scan" ? "last_scan_log.txt" : "last_encode_log.txt";\r
358 \r
359             frmActivityWindow dvdInfoWindow = new frmActivityWindow(file, encodeQueue, this);\r
360             dvdInfoWindow.Show();\r
361         }\r
362         private void mnu_options_Click(object sender, EventArgs e)\r
363         {\r
364             Form options = new frmOptions(this);\r
365             options.ShowDialog();\r
366         }\r
367         #endregion\r
368 \r
369         #region Presets Menu\r
370         private void mnu_presetReset_Click(object sender, EventArgs e)\r
371         {\r
372             presetHandler.UpdateBuiltInPresets();\r
373             loadPresetPanel();\r
374             if (treeView_presets.Nodes.Count == 0)\r
375                 MessageBox.Show("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!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
376             else\r
377                 MessageBox.Show("Presets have been updated!", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Information);\r
378 \r
379             treeView_presets.ExpandAll();\r
380         }\r
381         private void mnu_delete_preset_Click(object sender, EventArgs e)\r
382         {\r
383             presetHandler.RemoveBuiltInPresets();\r
384             loadPresetPanel(); // Reload the preset panel\r
385         }\r
386         private void mnu_SelectDefault_Click(object sender, EventArgs e)\r
387         {\r
388             loadNormalPreset();\r
389         }\r
390         private void mnu_importMacPreset_Click(object sender, EventArgs e)\r
391         {\r
392             importPreset();\r
393         }\r
394         private void btn_new_preset_Click(object sender, EventArgs e)\r
395         {\r
396             Form preset = new frmAddPreset(this, queryGen.GenerateCLIQuery(this, 0, null), presetHandler);\r
397             preset.ShowDialog();\r
398         }\r
399         #endregion\r
400 \r
401         #region Help Menu\r
402         private void mnu_handbrake_forums_Click(object sender, EventArgs e)\r
403         {\r
404             Process.Start("http://forum.handbrake.fr/");\r
405         }\r
406         private void mnu_user_guide_Click(object sender, EventArgs e)\r
407         {\r
408             Process.Start("http://trac.handbrake.fr/wiki/HandBrakeGuide");\r
409         }\r
410         private void mnu_handbrake_home_Click(object sender, EventArgs e)\r
411         {\r
412             Process.Start("http://handbrake.fr");\r
413         }\r
414         private void mnu_UpdateCheck_Click(object sender, EventArgs e)\r
415         {\r
416             lbl_updateCheck.Visible = true;\r
417             Main.BeginCheckForUpdates(new AsyncCallback(updateCheckDoneMenu), false);\r
418         }\r
419         private void updateCheckDoneMenu(IAsyncResult result)\r
420         {\r
421             // Make sure it's running on the calling thread\r
422             if (InvokeRequired)\r
423             {\r
424                 Invoke(new MethodInvoker(() => updateCheckDoneMenu(result)));\r
425                 return;\r
426             }\r
427             UpdateCheckInformation info;\r
428             try\r
429             {\r
430                 // Get the information about the new build, if any, and close the window\r
431                 info = Main.EndCheckForUpdates(result);\r
432 \r
433                 if (info.NewVersionAvailable && info.BuildInformation != null)\r
434                 {\r
435                     frmUpdater updateWindow = new frmUpdater(info.BuildInformation);\r
436                     updateWindow.ShowDialog();\r
437                 }\r
438                 else\r
439                     MessageBox.Show("There are no new updates at this time.", "Update Check", MessageBoxButtons.OK, MessageBoxIcon.Information);\r
440                 lbl_updateCheck.Visible = false;\r
441                 return;\r
442             }\r
443             catch (Exception ex)\r
444             {\r
445                 if ((bool)result.AsyncState)\r
446                     MessageBox.Show("Unable to check for updates, Please try again later.\n\nDetailed Error Information:\n" + ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
447             }\r
448         }\r
449         private void mnu_about_Click(object sender, EventArgs e)\r
450         {\r
451             using (frmAbout About = new frmAbout())\r
452             {\r
453                 About.ShowDialog();\r
454             }\r
455         }\r
456         #endregion\r
457 \r
458         #region Preset Bar\r
459         // Right Click Menu Code\r
460         private void pmnu_expandAll_Click(object sender, EventArgs e)\r
461         {\r
462             treeView_presets.ExpandAll();\r
463         }\r
464         private void pmnu_collapse_Click(object sender, EventArgs e)\r
465         {\r
466             treeView_presets.CollapseAll();\r
467         }\r
468         private void pmnu_import_Click(object sender, EventArgs e)\r
469         {\r
470             importPreset();\r
471         }\r
472         private void pmnu_saveChanges_Click(object sender, EventArgs e)\r
473         {\r
474             DialogResult result = MessageBox.Show("Do you wish to include picture settings when updating the preset: " + treeView_presets.SelectedNode.Text, "Update Preset", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);\r
475             if (result == DialogResult.Yes)\r
476                 presetHandler.Update(treeView_presets.SelectedNode.Text, QueryGenerator.GenerateTabbedComponentsQuery(this), true);\r
477             else if (result == DialogResult.No)\r
478                 presetHandler.Update(treeView_presets.SelectedNode.Text, QueryGenerator.GenerateTabbedComponentsQuery(this), false);\r
479         }\r
480         private void pmnu_delete_click(object sender, EventArgs e)\r
481         {\r
482             if (treeView_presets.SelectedNode != null)\r
483             {\r
484                 presetHandler.Remove(treeView_presets.SelectedNode.Text);\r
485                 treeView_presets.Nodes.Remove(treeView_presets.SelectedNode);\r
486             }\r
487             treeView_presets.Select();\r
488         }\r
489         private void presets_menu_Opening(object sender, System.ComponentModel.CancelEventArgs e)\r
490         {\r
491             // Make sure that the save menu is always disabled by default\r
492             pmnu_saveChanges.Enabled = false;\r
493 \r
494             // Now enable the save menu if the selected preset is a user preset\r
495             if (treeView_presets.SelectedNode != null)\r
496                 if (presetHandler.CheckIfUserPresetExists(treeView_presets.SelectedNode.Text))\r
497                     pmnu_saveChanges.Enabled = true;\r
498 \r
499             treeView_presets.Select();\r
500         }\r
501 \r
502         // Presets Management\r
503         private void btn_addPreset_Click(object sender, EventArgs e)\r
504         {\r
505             Form preset = new frmAddPreset(this, QueryGenerator.GenerateTabbedComponentsQuery(this), presetHandler);\r
506             preset.ShowDialog();\r
507         }\r
508         private void btn_removePreset_Click(object sender, EventArgs e)\r
509         {\r
510             DialogResult result = MessageBox.Show("Are you sure you wish to delete the selected preset?", "Preset", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
511             if (result == DialogResult.Yes)\r
512             {\r
513                 if (treeView_presets.SelectedNode != null)\r
514                 {\r
515                     presetHandler.Remove(treeView_presets.SelectedNode.Text);\r
516                     treeView_presets.Nodes.Remove(treeView_presets.SelectedNode);\r
517                 }\r
518             }\r
519             treeView_presets.Select();\r
520         }\r
521         private void btn_setDefault_Click(object sender, EventArgs e)\r
522         {\r
523             if (treeView_presets.SelectedNode != null)\r
524             {\r
525                 DialogResult result = MessageBox.Show("Are you sure you wish to set this preset as the default?", "Preset", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
526                 if (result == DialogResult.Yes)\r
527                 {\r
528                     Properties.Settings.Default.defaultPreset = treeView_presets.SelectedNode.Text;\r
529                     Properties.Settings.Default.Save();\r
530                     MessageBox.Show("New default preset set.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Information);\r
531                 }\r
532             }\r
533             else\r
534                 MessageBox.Show("Please select a preset first.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);\r
535         }\r
536         private void treeview_presets_mouseUp(object sender, MouseEventArgs e)\r
537         {\r
538             if (e.Button == MouseButtons.Right)\r
539                 treeView_presets.SelectedNode = treeView_presets.GetNodeAt(e.Location);\r
540             else if (e.Button == MouseButtons.Left)\r
541             {\r
542                 if (treeView_presets.GetNodeAt(e.Location) != null)\r
543                 {\r
544                     if (labelPreset.Text.Contains(treeView_presets.GetNodeAt(e.Location).Text))\r
545                         selectPreset();\r
546                 }\r
547             }\r
548 \r
549             treeView_presets.Select();\r
550         }\r
551         private void treeView_presets_AfterSelect(object sender, TreeViewEventArgs e)\r
552         {\r
553             selectPreset();\r
554         }\r
555         private void treeView_presets_deleteKey(object sender, KeyEventArgs e)\r
556         {\r
557             if (e.KeyCode == Keys.Delete)\r
558             {\r
559                 DialogResult result = MessageBox.Show("Are you sure you wish to delete the selected preset?", "Preset", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
560                 if (result == DialogResult.Yes)\r
561                 {\r
562                     if (treeView_presets.SelectedNode != null)\r
563                         presetHandler.Remove(treeView_presets.SelectedNode.Text);\r
564 \r
565                     // Remember each nodes expanded status so we can reload it\r
566                     List<Boolean> nodeStatus = new List<Boolean>();\r
567                     foreach (TreeNode node in treeView_presets.Nodes)\r
568                         nodeStatus.Add(node.IsExpanded);\r
569 \r
570                     // Now reload the preset panel\r
571                     loadPresetPanel();\r
572 \r
573                     // And finally, re-expand any of the nodes if required\r
574                     int i = 0;\r
575                     foreach (TreeNode node in treeView_presets.Nodes)\r
576                     {\r
577                         if (nodeStatus[i])\r
578                             node.Expand();\r
579 \r
580                         i++;\r
581                     }\r
582                 }\r
583             }\r
584         }\r
585         private void selectPreset()\r
586         {\r
587             if (treeView_presets.SelectedNode != null)\r
588             {\r
589                 // Ok, so, we've selected a preset. Now we want to load it.\r
590                 string presetName = treeView_presets.SelectedNode.Text;\r
591                 if (presetHandler.GetPreset(presetName) != null)\r
592                 {\r
593                     string query = presetHandler.GetPreset(presetName).Query;\r
594                     Boolean loadPictureSettings = presetHandler.GetPreset(presetName).PictureSettings;\r
595 \r
596                     if (query != null)\r
597                     {\r
598                         //Ok, Reset all the H264 widgets before changing the preset\r
599                         x264Panel.reset2Defaults();\r
600 \r
601                         // Send the query from the file to the Query Parser class\r
602                         QueryParser presetQuery = QueryParser.Parse(query);\r
603 \r
604                         // Now load the preset\r
605                         PresetLoader.presetLoader(this, presetQuery, presetName, loadPictureSettings);\r
606 \r
607                         // The x264 widgets will need updated, so do this now:\r
608                         x264Panel.X264_StandardizeOptString();\r
609                         x264Panel.X264_SetCurrentSettingsInPanel();\r
610                     }\r
611                 }\r
612             }\r
613         }\r
614         private void loadNormalPreset()\r
615         {\r
616             foreach (TreeNode treenode in treeView_presets.Nodes)\r
617             {\r
618                 foreach (TreeNode node in treenode.Nodes)\r
619                 {\r
620                     if (node.Text.Equals("Normal"))\r
621                         treeView_presets.SelectedNode = treeView_presets.Nodes[treenode.Index].Nodes[0];\r
622                 }\r
623             }\r
624         }\r
625         private void importPreset()\r
626         {\r
627             Import imp = new Import();\r
628             if (openPreset.ShowDialog() == DialogResult.OK)\r
629             {\r
630                 QueryParser parsed = imp.importMacPreset(openPreset.FileName);\r
631                 if (presetHandler.CheckIfUserPresetExists(parsed.PresetName + " (Imported)"))\r
632                 {\r
633                     DialogResult result = MessageBox.Show("This preset appears to already exist. Would you like to overwrite it?", "Overwrite preset?",\r
634                                                            MessageBoxButtons.YesNo, MessageBoxIcon.Warning);\r
635                     if (result == DialogResult.Yes)\r
636                     {\r
637                         PresetLoader.presetLoader(this, parsed, parsed.PresetName, parsed.UsesPictureSettings);\r
638                         presetHandler.Update(parsed.PresetName + " (Imported)", queryGen.GenerateCLIQuery(this, 0, null),\r
639                                                    parsed.UsesPictureSettings);\r
640                     }\r
641                 }\r
642                 else\r
643                 {\r
644                     PresetLoader.presetLoader(this, parsed, parsed.PresetName, parsed.UsesPictureSettings);\r
645                     presetHandler.Add(parsed.PresetName, queryGen.GenerateCLIQuery(this, 0, null), parsed.UsesPictureSettings);\r
646 \r
647                     if (presetHandler.Add(parsed.PresetName + " (Imported)", queryGen.GenerateCLIQuery(this, 0, null), parsed.UsesPictureSettings))\r
648                     {\r
649                         TreeNode preset_treeview = new TreeNode(parsed.PresetName + " (Imported)") { ForeColor = Color.Black };\r
650                         treeView_presets.Nodes.Add(preset_treeview);\r
651                     }\r
652                 }\r
653             }\r
654         }\r
655         #endregion\r
656 \r
657         #region ToolStrip\r
658         private void btn_source_Click(object sender, EventArgs e)\r
659         {\r
660             mnu_dvd_drive.Visible = true;\r
661             Thread driveInfoThread = new Thread(getDriveInfoThread);\r
662             driveInfoThread.Start();\r
663         }\r
664         private void btn_start_Click(object sender, EventArgs e)\r
665         {\r
666             if (btn_start.Text == "Stop")\r
667             {\r
668                 DialogResult result = MessageBox.Show("Are you sure you wish to cancel the encode?", "Cancel Encode?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
669 \r
670                 if (result == DialogResult.Yes)\r
671                 {\r
672                     // Pause The Queue\r
673                     encodeQueue.RequestPause();\r
674 \r
675                     // Allow the CLI to exit cleanly\r
676                     Win32.SetForegroundWindow((int)encodeQueue.processHandle);\r
677                     SendKeys.Send("^C");\r
678 \r
679                     // Update the GUI\r
680                     setEncodeFinished();\r
681                 }\r
682             }\r
683             else\r
684             {\r
685                 if (encodeQueue.Count != 0 || (!string.IsNullOrEmpty(sourcePath) && !string.IsNullOrEmpty(text_destination.Text)))\r
686                 {\r
687                     string generatedQuery = queryGen.GenerateCLIQuery(this, 0, null);\r
688                     string specifiedQuery = rtf_query.Text != "" ? rtf_query.Text : queryGen.GenerateCLIQuery(this, 0, null);\r
689                     string query = string.Empty;\r
690 \r
691                     // Check to make sure the generated query matches the GUI settings\r
692                     if (Properties.Settings.Default.PromptOnUnmatchingQueries && !string.IsNullOrEmpty(specifiedQuery) && generatedQuery != specifiedQuery)\r
693                     {\r
694                         DialogResult result = MessageBox.Show("The query under the \"Query Editor\" tab " +\r
695                             "does not match the current GUI settings. Because the manual query takes " +\r
696                             "priority over the GUI, your recently updated settings will not be taken " +\r
697                             "into account when encoding this job." + Environment.NewLine + Environment.NewLine +\r
698                             "Do you want to replace the manual query with the GUI-generated query?",\r
699                             "Manual Query does not Match GUI",\r
700                             MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk,\r
701                             MessageBoxDefaultButton.Button3);\r
702 \r
703                         switch (result)\r
704                         {\r
705                             case DialogResult.Yes:\r
706                                 // Replace the manual query with the generated one\r
707                                 query = generatedQuery;\r
708                                 rtf_query.Text = generatedQuery;\r
709                                 break;\r
710                             case DialogResult.No:\r
711                                 // Use the manual query\r
712                                 query = specifiedQuery;\r
713                                 break;\r
714                             case DialogResult.Cancel:\r
715                                 // Don't start the encode\r
716                                 return;\r
717                         }\r
718                     }\r
719                     else\r
720                     {\r
721                         query = generatedQuery;\r
722                     }\r
723 \r
724                     DialogResult overwrite = DialogResult.Yes;\r
725                     if (text_destination.Text != "")\r
726                         if (File.Exists(text_destination.Text))\r
727                             overwrite = MessageBox.Show("The destination file already exists. Are you sure you want to overwrite it?", "Overwrite File?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
728 \r
729                     if (overwrite == DialogResult.Yes)\r
730                     {\r
731                         if (encodeQueue.Count == 0)\r
732                             encodeQueue.AddJob(query, sourcePath, text_destination.Text);\r
733 \r
734                         queueWindow.setQueue();\r
735                         if (encodeQueue.Count > 1)\r
736                             queueWindow.Show(false);\r
737 \r
738                         setEncodeStarted(); // Encode is running, so setup the GUI appropriately\r
739                         encodeQueue.StartEncodeQueue(); // Start The Queue Encoding Process\r
740                         lastAction = "encode";   // Set the last action to encode - Used for activity window.\r
741 \r
742                         if (ActivityWindow != null)\r
743                             ActivityWindow.SetLogView(false);\r
744 \r
745                     }\r
746                     this.Focus();\r
747                 }\r
748                 else if (string.IsNullOrEmpty(sourcePath) || string.IsNullOrEmpty(text_destination.Text))\r
749                     MessageBox.Show("No source or destination selected.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);\r
750             }\r
751         }\r
752         private void btn_add2Queue_Click(object sender, EventArgs e)\r
753         {\r
754             if (string.IsNullOrEmpty(sourcePath) || string.IsNullOrEmpty(text_destination.Text))\r
755                 MessageBox.Show("No source or destination selected.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);\r
756             else\r
757             {\r
758                 String query = queryGen.GenerateCLIQuery(this, 0, null);\r
759                 if (rtf_query.Text != "")\r
760                     query = rtf_query.Text;\r
761 \r
762                 if (encodeQueue.CheckForDestinationDuplicate(text_destination.Text))\r
763                 {\r
764                     DialogResult result = MessageBox.Show("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
765                   "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);\r
766                     if (result == DialogResult.Yes)\r
767                         encodeQueue.AddJob(query, sourcePath, text_destination.Text);\r
768 \r
769                 }\r
770                 else\r
771                     encodeQueue.AddJob(query, sourcePath, text_destination.Text);\r
772 \r
773                 lbl_encode.Text = encodeQueue.Count + " encode(s) pending in the queue";\r
774 \r
775                 queueWindow.Show();\r
776             }\r
777         }\r
778         private void btn_showQueue_Click(object sender, EventArgs e)\r
779         {\r
780             queueWindow.Show();\r
781             queueWindow.Activate();\r
782         }\r
783         private void tb_preview_Click(object sender, EventArgs e)\r
784         {\r
785             if (string.IsNullOrEmpty(sourcePath) || string.IsNullOrEmpty(text_destination.Text))\r
786                 MessageBox.Show("No source or destination selected.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);\r
787             else\r
788             {\r
789                 if (qtpreview == null)\r
790                 {\r
791                     qtpreview = new frmPreview(this);\r
792                     qtpreview.Show();\r
793                 }\r
794                 else if (qtpreview.IsDisposed)\r
795                 {\r
796                     qtpreview = new frmPreview(this);\r
797                     qtpreview.Show();\r
798                 }\r
799                 else\r
800                     MessageBox.Show(qtpreview, "The preview window is already open!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);\r
801             }\r
802         }\r
803         private void btn_ActivityWindow_Click(object sender, EventArgs e)\r
804         {\r
805             String file = lastAction == "scan" ? "last_scan_log.txt" : "last_encode_log.txt";\r
806             if (ActivityWindow == null)\r
807                 ActivityWindow = new frmActivityWindow(file, encodeQueue, this);\r
808 \r
809             ActivityWindow.Show();\r
810         }\r
811         #endregion\r
812 \r
813         #region System Tray Icon\r
814         private void frmMain_Resize(object sender, EventArgs e)\r
815         {\r
816             if (FormWindowState.Minimized == this.WindowState)\r
817             {\r
818                 notifyIcon.Visible = true;\r
819                 this.Hide();\r
820             }\r
821             else if (FormWindowState.Normal == this.WindowState)\r
822                 notifyIcon.Visible = false;\r
823         }\r
824         private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)\r
825         {\r
826             this.Visible = true;\r
827             this.Activate();\r
828             this.WindowState = FormWindowState.Normal;\r
829             notifyIcon.Visible = false;\r
830         }\r
831         private void btn_restore_Click(object sender, EventArgs e)\r
832         {\r
833             this.Visible = true;\r
834             this.Activate();\r
835             this.WindowState = FormWindowState.Normal;\r
836             notifyIcon.Visible = false;\r
837         }\r
838         #endregion\r
839 \r
840         #region Tab Control\r
841 \r
842         //Source\r
843         private void btn_dvd_source_Click(object sender, EventArgs e)\r
844         {\r
845             if (DVD_Open.ShowDialog() == DialogResult.OK)\r
846             {\r
847                 this.selectedSourceType = SourceType.Folder;\r
848                 selectSource(DVD_Open.SelectedPath);\r
849             }\r
850             else\r
851                 UpdateSourceLabel();\r
852         }\r
853         private void btn_file_source_Click(object sender, EventArgs e)\r
854         {\r
855             if (ISO_Open.ShowDialog() == DialogResult.OK)\r
856             {\r
857                 this.selectedSourceType = SourceType.VideoFile;\r
858                 selectSource(ISO_Open.FileName);\r
859             }\r
860             else\r
861                 UpdateSourceLabel();\r
862         }\r
863         private void mnu_dvd_drive_Click(object sender, EventArgs e)\r
864         {\r
865             if (this.dvdDrivePath == null) return;\r
866             this.selectedSourceType = SourceType.DvdDrive;\r
867             selectSource(this.dvdDrivePath);\r
868         }\r
869         private void selectSource(string file)\r
870         {\r
871             Check_ChapterMarkers.Enabled = true;\r
872             lastAction = "scan";\r
873             sourcePath = string.Empty;\r
874 \r
875             if (file == string.Empty) // Must have a file or path\r
876             {\r
877                 UpdateSourceLabel();\r
878                 return;\r
879             }\r
880 \r
881             if (file.StartsWith("\\")) // NO UNC Paths\r
882             {\r
883                 MessageBox.Show(\r
884                     "Sorry, HandBrake does not support UNC file paths. \nTry mounting the share as a network drive in My Computer",\r
885                     "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);\r
886                 UpdateSourceLabel();\r
887                 return;\r
888             }\r
889 \r
890             sourcePath = Path.GetFileName(file);\r
891             startScan(file);\r
892         }\r
893         private void drp_dvdtitle_Click(object sender, EventArgs e)\r
894         {\r
895             if ((drp_dvdtitle.Items.Count == 1) && (drp_dvdtitle.Items[0].ToString() == "Automatic"))\r
896                 MessageBox.Show("There are no titles to select. Please load a source file by clicking the 'Source' button above before trying to select a title.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);\r
897         }\r
898         private void drp_dvdtitle_SelectedIndexChanged(object sender, EventArgs e)\r
899         {\r
900             UnRegisterPresetEventHandler();\r
901 \r
902             PictureSettings.lbl_Aspect.Text = "Select a Title"; // Reset some values on the form\r
903             drop_chapterStart.Items.Clear();\r
904             drop_chapterFinish.Items.Clear();\r
905 \r
906             // If the dropdown is set to automatic nothing else needs to be done.\r
907             // Otheriwse if its not, title data has to be loased from parsing.\r
908             if (drp_dvdtitle.Text != "Automatic")\r
909             {\r
910                 selectedTitle = drp_dvdtitle.SelectedItem as Title;\r
911                 lbl_duration.Text = selectedTitle.Duration.ToString();\r
912                 PictureSettings.Source = selectedTitle;  // Setup Picture Settings Tab Control\r
913 \r
914                 // Populate the Angles dropdown\r
915                 drop_angle.Items.Clear();\r
916                 if (Properties.Settings.Default.dvdnav)\r
917                 {\r
918                     drop_angle.Visible = true;\r
919                     lbl_angle.Visible = true;\r
920                     drop_angle.Items.AddRange(selectedTitle.Angles.ToArray());\r
921                     if (drop_angle.Items.Count != 0)\r
922                         drop_angle.SelectedIndex = 0;\r
923                 }\r
924                 else\r
925                 {\r
926                     drop_angle.Visible = false;\r
927                     lbl_angle.Visible = false;\r
928                 }\r
929 \r
930                 // Populate the Start chapter Dropdown\r
931                 drop_chapterStart.Items.Clear();\r
932                 drop_chapterStart.Items.AddRange(selectedTitle.Chapters.ToArray());\r
933                 if (drop_chapterStart.Items.Count > 0)\r
934                     drop_chapterStart.Text = drop_chapterStart.Items[0].ToString();\r
935 \r
936                 // Populate the Final Chapter Dropdown\r
937                 drop_chapterFinish.Items.Clear();\r
938                 drop_chapterFinish.Items.AddRange(selectedTitle.Chapters.ToArray());\r
939                 if (drop_chapterFinish.Items.Count > 0)\r
940                     drop_chapterFinish.Text = drop_chapterFinish.Items[drop_chapterFinish.Items.Count - 1].ToString();\r
941 \r
942                 // Populate the Audio Channels Dropdown\r
943                 AudioSettings.SetTrackList(selectedTitle);\r
944 \r
945                 // Populate the Subtitles dropdown\r
946                 Subtitles.drp_subtitleTracks.Items.Clear();\r
947                 Subtitles.drp_subtitleTracks.Items.Add("Foreign Audio Search (Bitmap)");\r
948                 Subtitles.drp_subtitleTracks.Items.AddRange(selectedTitle.Subtitles.ToArray());\r
949                 Subtitles.drp_subtitleTracks.SelectedIndex = 0;\r
950                 Subtitles.setSubtitleTrackAuto();\r
951             }\r
952 \r
953             // Run the autoName & chapterNaming functions\r
954             if (Properties.Settings.Default.autoNaming)\r
955             {\r
956                 string autoPath = Main.autoName(this);\r
957                 if (autoPath != null)\r
958                     text_destination.Text = autoPath;\r
959                 else\r
960                     MessageBox.Show("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')", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);\r
961             }\r
962 \r
963             data_chpt.Rows.Clear();\r
964             if (selectedTitle.Chapters.Count != 1)\r
965             {\r
966                 DataGridView chapterGridView = Main.chapterNaming(data_chpt, drop_chapterFinish.Text);\r
967                 if (chapterGridView != null)\r
968                     data_chpt = chapterGridView;\r
969             }\r
970             else\r
971             {\r
972                 Check_ChapterMarkers.Checked = false;\r
973                 Check_ChapterMarkers.Enabled = false;\r
974             }\r
975 \r
976             // Hack to force the redraw of the scrollbars which don't resize properly when the control is disabled.\r
977             data_chpt.Columns[0].Width = 166;\r
978             data_chpt.Columns[0].Width = 165;\r
979 \r
980             RegisterPresetEventHandler();\r
981         }\r
982         private void chapersChanged(object sender, EventArgs e)\r
983         {\r
984             Control ctl = (Control)sender;\r
985             int chapterStart, chapterEnd;\r
986             int.TryParse(drop_chapterStart.Text, out chapterStart);\r
987             int.TryParse(drop_chapterFinish.Text, out chapterEnd);\r
988 \r
989             switch (ctl.Name)\r
990             {\r
991                 case "drop_chapterStart":\r
992                     if (drop_chapterFinish.SelectedIndex == -1 && drop_chapterFinish.Items.Count != 0)\r
993                         drop_chapterFinish.SelectedIndex = drop_chapterFinish.Items.Count - 1;\r
994 \r
995                     if (chapterEnd != 0)\r
996                         if (chapterStart > chapterEnd)\r
997                             drop_chapterFinish.Text = chapterStart.ToString();\r
998                     break;\r
999                 case "drop_chapterFinish":\r
1000                     if (drop_chapterStart.Items.Count >= 1 && drop_chapterStart.SelectedIndex == -1)\r
1001                         drop_chapterStart.SelectedIndex = 0;\r
1002 \r
1003                     if (chapterStart != 0)\r
1004                         if (chapterEnd < chapterStart)\r
1005                             drop_chapterFinish.Text = chapterStart.ToString();\r
1006 \r
1007                     // Add more rows to the Chapter menu if needed.\r
1008                     if (Check_ChapterMarkers.Checked)\r
1009                     {\r
1010                         int i = data_chpt.Rows.Count, finish = 0;\r
1011                         int.TryParse(drop_chapterFinish.Text, out finish);\r
1012 \r
1013                         while (i < finish)\r
1014                         {\r
1015                             int n = data_chpt.Rows.Add();\r
1016                             data_chpt.Rows[n].Cells[0].Value = (i + 1);\r
1017                             data_chpt.Rows[n].Cells[1].Value = "Chapter " + (i + 1);\r
1018                             data_chpt.Rows[n].Cells[0].ValueType = typeof(int);\r
1019                             data_chpt.Rows[n].Cells[1].ValueType = typeof(string);\r
1020                             i++;\r
1021                         }\r
1022                     }\r
1023                     break;\r
1024             }\r
1025 \r
1026             // Update the Duration\r
1027             lbl_duration.Text = Main.calculateDuration(drop_chapterStart.SelectedIndex, drop_chapterFinish.SelectedIndex, selectedTitle).ToString();\r
1028 \r
1029             // Run the Autonaming function\r
1030             if (Properties.Settings.Default.autoNaming)\r
1031                 text_destination.Text = Main.autoName(this);\r
1032 \r
1033             // Disable chapter markers if only 1 chapter is selected.\r
1034             if (chapterStart == chapterEnd)\r
1035             {\r
1036                 Check_ChapterMarkers.Enabled = false;\r
1037                 btn_importChapters.Enabled = false;\r
1038                 data_chpt.Enabled = false;\r
1039             }\r
1040             else\r
1041             {\r
1042                 Check_ChapterMarkers.Enabled = true;\r
1043                 if (Check_ChapterMarkers.Checked)\r
1044                 {\r
1045                     btn_importChapters.Enabled = true;\r
1046                     data_chpt.Enabled = true;\r
1047                 }\r
1048             }\r
1049         }\r
1050 \r
1051         //Destination\r
1052         private void btn_destBrowse_Click(object sender, EventArgs e)\r
1053         {\r
1054             // This removes the file extension from the filename box on the save file dialog.\r
1055             // It's daft but some users don't realise that typing an extension overrides the dropdown extension selected.\r
1056             DVD_Save.FileName = Path.GetFileNameWithoutExtension(text_destination.Text);\r
1057 \r
1058             if (Path.IsPathRooted(text_destination.Text))\r
1059                 DVD_Save.InitialDirectory = Path.GetDirectoryName(text_destination.Text);\r
1060 \r
1061             // Show the dialog and set the main form file path\r
1062             if (drop_format.SelectedIndex.Equals(0))\r
1063                 DVD_Save.FilterIndex = 1;\r
1064             else if (drop_format.SelectedIndex.Equals(1))\r
1065                 DVD_Save.FilterIndex = 2;\r
1066 \r
1067             if (DVD_Save.ShowDialog() == DialogResult.OK)\r
1068             {\r
1069                 if (DVD_Save.FileName.StartsWith("\\"))\r
1070                     MessageBox.Show("Sorry, HandBrake does not support UNC file paths. \nTry mounting the share as a network drive in My Computer", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);\r
1071                 else\r
1072                 {\r
1073                     // Add a file extension manually, as FileDialog.AddExtension has issues with dots in filenames\r
1074                     switch (DVD_Save.FilterIndex)\r
1075                     {\r
1076                         case 1:\r
1077                             if (!Path.GetExtension(DVD_Save.FileName).Equals(".mp4", StringComparison.InvariantCultureIgnoreCase))\r
1078                                 if (Properties.Settings.Default.useM4v)\r
1079                                     DVD_Save.FileName = DVD_Save.FileName.Replace(".mp4", ".m4v").Replace(".mkv", ".m4v");\r
1080                                 else\r
1081                                     DVD_Save.FileName = DVD_Save.FileName.Replace(".m4v", ".mp4").Replace(".mkv", ".mp4");\r
1082                             break;\r
1083                         case 2:\r
1084                             if (!Path.GetExtension(DVD_Save.FileName).Equals(".mkv", StringComparison.InvariantCultureIgnoreCase))\r
1085                                 DVD_Save.FileName = DVD_Save.FileName.Replace(".mp4", ".mkv").Replace(".m4v", ".mkv");\r
1086                             break;\r
1087                         default:\r
1088                             //do nothing  \r
1089                             break;\r
1090                     }\r
1091                     text_destination.Text = DVD_Save.FileName;\r
1092 \r
1093                     // Quicktime requires .m4v file for chapter markers to work. If checked, change the extension to .m4v (mp4 and m4v are the same thing)\r
1094                     if (Check_ChapterMarkers.Checked && DVD_Save.FilterIndex != 2)\r
1095                         SetExtension(".m4v");\r
1096                 }\r
1097             }\r
1098         }\r
1099         private void text_destination_TextChanged(object sender, EventArgs e)\r
1100         {\r
1101             string path = text_destination.Text;\r
1102             if (path.EndsWith(".mp4") || path.EndsWith(".m4v"))\r
1103                 drop_format.SelectedIndex = 0;\r
1104             else if (path.EndsWith(".mkv"))\r
1105                 drop_format.SelectedIndex = 1;\r
1106         }\r
1107 \r
1108         // Output Settings\r
1109         private void drop_format_SelectedIndexChanged(object sender, EventArgs e)\r
1110         {\r
1111             switch (drop_format.SelectedIndex)\r
1112             {\r
1113                 case 0:\r
1114                     if (Properties.Settings.Default.useM4v || Check_ChapterMarkers.Checked || AudioSettings.RequiresM4V() || Subtitles.RequiresM4V())\r
1115                         SetExtension(".m4v");\r
1116                     else\r
1117                         SetExtension(".mp4");\r
1118                     break;\r
1119                 case 1:\r
1120                     SetExtension(".mkv");\r
1121                     break;\r
1122             }\r
1123 \r
1124             AudioSettings.SetContainer(drop_format.Text);\r
1125             Subtitles.setContainer(drop_format.SelectedIndex);\r
1126 \r
1127             if (drop_format.Text.Contains("MP4"))\r
1128             {\r
1129                 if (drp_videoEncoder.Items.Contains("VP3 (Theora)"))\r
1130                 {\r
1131                     drp_videoEncoder.Items.Remove("VP3 (Theora)");\r
1132                     drp_videoEncoder.SelectedIndex = 1;\r
1133                 }\r
1134             }\r
1135             else if (drop_format.Text.Contains("MKV"))\r
1136                 drp_videoEncoder.Items.Add("VP3 (Theora)");\r
1137         }\r
1138         public void SetExtension(string newExtension)\r
1139         {\r
1140             if (newExtension == ".mp4" || newExtension == ".m4v")\r
1141                 if (Properties.Settings.Default.useM4v || Check_ChapterMarkers.Checked || AudioSettings.RequiresM4V() || Subtitles.RequiresM4V())\r
1142                     newExtension = ".m4v";\r
1143                 else\r
1144                     newExtension = ".mp4";\r
1145 \r
1146             if (Path.HasExtension(newExtension))\r
1147                 text_destination.Text = Path.ChangeExtension(text_destination.Text, newExtension);\r
1148         }\r
1149 \r
1150         //Video Tab\r
1151         private void drp_videoEncoder_SelectedIndexChanged(object sender, EventArgs e)\r
1152         {\r
1153             setContainerOpts();\r
1154 \r
1155             //Turn off some options which are H.264 only when the user selects a non h.264 encoder\r
1156             if (drp_videoEncoder.Text.Contains("H.264"))\r
1157             {\r
1158                 if (check_2PassEncode.CheckState == CheckState.Checked)\r
1159                     check_turbo.Enabled = true;\r
1160 \r
1161                 tab_advanced.Enabled = true;\r
1162                 if ((drop_format.Text.Contains("MP4")) || (drop_format.Text.Contains("M4V")))\r
1163                     check_iPodAtom.Enabled = true;\r
1164                 else\r
1165                     check_iPodAtom.Enabled = false;\r
1166             }\r
1167             else\r
1168             {\r
1169                 check_turbo.CheckState = CheckState.Unchecked;\r
1170                 check_turbo.Enabled = false;\r
1171                 tab_advanced.Enabled = false;\r
1172                 x264Panel.x264Query = "";\r
1173                 check_iPodAtom.Enabled = false;\r
1174                 check_iPodAtom.Checked = false;\r
1175             }\r
1176 \r
1177             // Setup the CQ Slider\r
1178             switch (drp_videoEncoder.Text)\r
1179             {\r
1180                 case "MPEG-4 (FFmpeg)":\r
1181                     if (slider_videoQuality.Value > 31)\r
1182                         slider_videoQuality.Value = 20;   // Just reset to 70% QP 10 on encode change.\r
1183                     slider_videoQuality.Minimum = 1;\r
1184                     slider_videoQuality.Maximum = 31;\r
1185                     break;\r
1186                 case "H.264 (x264)":\r
1187                     slider_videoQuality.Minimum = 0;\r
1188                     slider_videoQuality.TickFrequency = 1;\r
1189 \r
1190                     CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");\r
1191                     double cqStep = Properties.Settings.Default.x264cqstep;\r
1192                     double multiplier = 1.0 / cqStep;\r
1193                     double value = slider_videoQuality.Value * multiplier;\r
1194 \r
1195                     switch (Properties.Settings.Default.x264cqstep.ToString(culture))\r
1196                     {\r
1197                         case "0.2":\r
1198                             slider_videoQuality.Maximum = 255;\r
1199                             break;\r
1200                         case "0.25":\r
1201                             slider_videoQuality.Maximum = 204;\r
1202                             break;\r
1203                         case "0.5":\r
1204                             slider_videoQuality.Maximum = 102;\r
1205                             break;\r
1206                         case "1":\r
1207                             slider_videoQuality.Maximum = 51;\r
1208                             break;\r
1209                         default:\r
1210                             slider_videoQuality.Maximum = 51;\r
1211                             break;\r
1212                     }\r
1213                     if (value < slider_videoQuality.Maximum)\r
1214                         slider_videoQuality.Value = slider_videoQuality.Maximum - (int)value;\r
1215 \r
1216                     break;\r
1217                 case "VP3 (Theora)":\r
1218                     if (slider_videoQuality.Value > 63)\r
1219                         slider_videoQuality.Value = 45;  // Just reset to 70% QP 45 on encode change.\r
1220                     slider_videoQuality.Minimum = 0;\r
1221                     slider_videoQuality.Maximum = 63;\r
1222                     break;\r
1223             }\r
1224         }\r
1225         /// <summary>\r
1226         /// Set the container format options\r
1227         /// </summary>\r
1228         public void setContainerOpts()\r
1229         {\r
1230             if ((drop_format.Text.Contains("MP4")) || (drop_format.Text.Contains("M4V")))\r
1231             {\r
1232                 check_largeFile.Enabled = true;\r
1233                 check_optimiseMP4.Enabled = true;\r
1234                 check_iPodAtom.Enabled = true;\r
1235             }\r
1236             else\r
1237             {\r
1238                 check_largeFile.Enabled = false;\r
1239                 check_optimiseMP4.Enabled = false;\r
1240                 check_iPodAtom.Enabled = false;\r
1241                 check_largeFile.Checked = false;\r
1242                 check_optimiseMP4.Checked = false;\r
1243                 check_iPodAtom.Checked = false;\r
1244             }\r
1245         }\r
1246         private double _cachedCqStep = Properties.Settings.Default.x264cqstep;\r
1247         /// <summary>\r
1248         /// Update the CQ slider for x264 for a new CQ step. This is set from option\r
1249         /// </summary>\r
1250         public void setQualityFromSlider()\r
1251         {\r
1252             // Work out the current RF value.\r
1253             double cqStep = _cachedCqStep;\r
1254             double rfValue = 51.0 - slider_videoQuality.Value * cqStep;\r
1255 \r
1256             // Change the maximum value for the slider\r
1257             switch (Properties.Settings.Default.x264cqstep.ToString(new CultureInfo("en-US")))\r
1258             {\r
1259                 case "0.2":\r
1260                     slider_videoQuality.Maximum = 255;\r
1261                     break;\r
1262                 case "0.25":\r
1263                     slider_videoQuality.Maximum = 204;\r
1264                     break;\r
1265                 case "0.5":\r
1266                     slider_videoQuality.Maximum = 102;\r
1267                     break;\r
1268                 case "1":\r
1269                     slider_videoQuality.Maximum = 51;\r
1270                     break;\r
1271                 default:\r
1272                     slider_videoQuality.Maximum = 51;\r
1273                     break;\r
1274             }\r
1275 \r
1276             // Reset the CQ slider to RF0\r
1277             slider_videoQuality.Value = slider_videoQuality.Maximum;\r
1278 \r
1279             // Reset the CQ slider back to the previous value as close as possible\r
1280             double cqStepNew = Properties.Settings.Default.x264cqstep;\r
1281             double rfValueCurrent = 51.0 - slider_videoQuality.Value * cqStepNew;\r
1282             while (rfValueCurrent < rfValue)\r
1283             {\r
1284                 slider_videoQuality.Value--;\r
1285                 rfValueCurrent = 51.0 - slider_videoQuality.Value * cqStepNew;\r
1286             }\r
1287 \r
1288             // Cache the CQ step for the next calculation\r
1289             _cachedCqStep = Properties.Settings.Default.x264cqstep;\r
1290         }\r
1291         private void slider_videoQuality_Scroll(object sender, EventArgs e)\r
1292         {\r
1293             double cqStep = Properties.Settings.Default.x264cqstep;\r
1294             switch (drp_videoEncoder.Text)\r
1295             {\r
1296                 case "MPEG-4 (FFmpeg)":\r
1297                     double rfValue = 31 - (slider_videoQuality.Value - 1);\r
1298                     double max = slider_videoQuality.Maximum;\r
1299                     double min = slider_videoQuality.Minimum;\r
1300                     double val = ((max - min) - (rfValue - min)) / (max - min);\r
1301                     SliderValue.Text = Math.Round((val * 100), 2).ToString(new CultureInfo("en-US")) + "% QP:" + (32 - slider_videoQuality.Value);\r
1302                     break;\r
1303                 case "H.264 (x264)":\r
1304                     rfValue = 51.0 - slider_videoQuality.Value * cqStep;\r
1305                     max = slider_videoQuality.Maximum * cqStep;\r
1306                     min = slider_videoQuality.Minimum;\r
1307                     val = ((max - min) - (rfValue - min)) / (max - min);\r
1308                     rfValue = Math.Round(rfValue, 2);\r
1309                     SliderValue.Text = Math.Round((val * 100), 2).ToString(new CultureInfo("en-US")) + "% RF:" + rfValue.ToString(new CultureInfo("en-US"));\r
1310                     break;\r
1311                 case "VP3 (Theora)":\r
1312                     rfValue = slider_videoQuality.Value;\r
1313                     double value = rfValue / 63;\r
1314                     SliderValue.Text = Math.Round((value * 100), 2).ToString(new CultureInfo("en-US")) + "% QP:" + slider_videoQuality.Value;\r
1315                     break;\r
1316             }\r
1317         }\r
1318         private void radio_targetFilesize_CheckedChanged(object sender, EventArgs e)\r
1319         {\r
1320             text_bitrate.Enabled = false;\r
1321             text_filesize.Enabled = true;\r
1322             slider_videoQuality.Enabled = false;\r
1323 \r
1324             check_2PassEncode.Enabled = true;\r
1325         }\r
1326         private void radio_avgBitrate_CheckedChanged(object sender, EventArgs e)\r
1327         {\r
1328             text_bitrate.Enabled = true;\r
1329             text_filesize.Enabled = false;\r
1330             slider_videoQuality.Enabled = false;\r
1331 \r
1332             check_2PassEncode.Enabled = true;\r
1333         }\r
1334         private void radio_cq_CheckedChanged(object sender, EventArgs e)\r
1335         {\r
1336             text_bitrate.Enabled = false;\r
1337             text_filesize.Enabled = false;\r
1338             slider_videoQuality.Enabled = true;\r
1339 \r
1340             check_2PassEncode.Enabled = false;\r
1341             check_2PassEncode.CheckState = CheckState.Unchecked;\r
1342         }\r
1343         private void check_2PassEncode_CheckedChanged(object sender, EventArgs e)\r
1344         {\r
1345             if (check_2PassEncode.CheckState.ToString() == "Checked")\r
1346             {\r
1347                 if (drp_videoEncoder.Text.Contains("H.264"))\r
1348                     check_turbo.Enabled = true;\r
1349             }\r
1350             else\r
1351             {\r
1352                 check_turbo.Enabled = false;\r
1353                 check_turbo.CheckState = CheckState.Unchecked;\r
1354             }\r
1355         }\r
1356 \r
1357         // Chapter Marker Tab\r
1358         private void Check_ChapterMarkers_CheckedChanged(object sender, EventArgs e)\r
1359         {\r
1360             if (Check_ChapterMarkers.Checked)\r
1361             {\r
1362                 if (drop_format.SelectedIndex != 1)\r
1363                     SetExtension(".m4v");\r
1364                 data_chpt.Enabled = true;\r
1365                 btn_importChapters.Enabled = true;\r
1366             }\r
1367             else\r
1368             {\r
1369                 if (drop_format.SelectedIndex != 1 && !Properties.Settings.Default.useM4v)\r
1370                     SetExtension(".mp4");\r
1371                 data_chpt.Enabled = false;\r
1372                 btn_importChapters.Enabled = false;\r
1373             }\r
1374         }\r
1375         private void btn_importChapters_Click(object sender, EventArgs e)\r
1376         {\r
1377             if (File_ChapterImport.ShowDialog() == DialogResult.OK)\r
1378             {\r
1379                 String filename = File_ChapterImport.FileName;\r
1380                 DataGridView imported = Main.importChapterNames(data_chpt, filename);\r
1381                 if (imported != null)\r
1382                     data_chpt = imported;\r
1383             }\r
1384         }\r
1385         private void mnu_resetChapters_Click(object sender, EventArgs e)\r
1386         {\r
1387             data_chpt.Rows.Clear();\r
1388             DataGridView chapterGridView = Main.chapterNaming(data_chpt, drop_chapterFinish.Text);\r
1389             if (chapterGridView != null)\r
1390             {\r
1391                 data_chpt = chapterGridView;\r
1392             }\r
1393         }\r
1394 \r
1395         // Query Editor Tab\r
1396         private void btn_generate_Query_Click(object sender, EventArgs e)\r
1397         {\r
1398             rtf_query.Text = queryGen.GenerateCLIQuery(this, 0, null);\r
1399         }\r
1400         private void btn_clear_Click(object sender, EventArgs e)\r
1401         {\r
1402             rtf_query.Clear();\r
1403         }\r
1404         #endregion\r
1405 \r
1406         // MainWindow Components, Actions and Functions ***********************\r
1407 \r
1408         #region Source Scan\r
1409         public Boolean isScanning { get; set; }\r
1410         private static int scanProcessID { get; set; }\r
1411         private void startScan(String filename)\r
1412         {\r
1413             // Setup the GUI components for the scan.\r
1414             sourcePath = filename;\r
1415             foreach (Control ctrl in Controls)\r
1416                 if (!(ctrl is StatusStrip || ctrl is MenuStrip || ctrl is ToolStrip))\r
1417                     ctrl.Enabled = false;\r
1418 \r
1419             lbl_encode.Visible = true;\r
1420             lbl_encode.Text = "Scanning ...";\r
1421             btn_source.Enabled = false;\r
1422             btn_start.Enabled = false;\r
1423             btn_showQueue.Enabled = false;\r
1424             btn_add2Queue.Enabled = false;\r
1425             tb_preview.Enabled = false;\r
1426             mnu_killCLI.Visible = true;\r
1427 \r
1428             // Start hte Scan Thread\r
1429             try\r
1430             {\r
1431                 if (ActivityWindow != null)\r
1432                     ActivityWindow.SetLogView(true);\r
1433                 isScanning = true;\r
1434                 ThreadPool.QueueUserWorkItem(scanProcess);\r
1435             }\r
1436             catch (Exception exc)\r
1437             {\r
1438                 MessageBox.Show("frmMain.cs - startScan " + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
1439             }\r
1440         }\r
1441         private void scanProcess(object state)\r
1442         {\r
1443             try\r
1444             {\r
1445                 string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");\r
1446                 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";\r
1447                 string dvdInfoPath = Path.Combine(logDir, "last_scan_log.txt");\r
1448 \r
1449                 // Make we don't pick up a stale last_encode_log.txt (and that we have rights to the file)\r
1450                 if (File.Exists(dvdInfoPath))\r
1451                     File.Delete(dvdInfoPath);\r
1452 \r
1453                 String dvdnav = string.Empty;\r
1454                 if (Properties.Settings.Default.dvdnav)\r
1455                     dvdnav = " --dvdnav";\r
1456                 string strCmdLine = String.Format(@"cmd /c """"{0}"" -i ""{1}"" -t0 {2} -v >""{3}"" 2>&1""", handbrakeCLIPath, sourcePath, dvdnav, dvdInfoPath);\r
1457 \r
1458                 ProcessStartInfo hbParseDvd = new ProcessStartInfo("CMD.exe", strCmdLine) { WindowStyle = ProcessWindowStyle.Hidden };\r
1459 \r
1460                 Boolean cleanExit = true;\r
1461                 using (hbproc = Process.Start(hbParseDvd))\r
1462                 {\r
1463                     Process[] before = Process.GetProcesses(); // Get a list of running processes before starting.\r
1464                     scanProcessID = Main.getCliProcess(before);\r
1465                     hbproc.WaitForExit();\r
1466                     if (hbproc.ExitCode != 0)\r
1467                         cleanExit = false;\r
1468                 }\r
1469 \r
1470                 if (cleanExit) // If 0 exit code, CLI exited cleanly.\r
1471                 {\r
1472                     if (!File.Exists(dvdInfoPath))\r
1473                         throw new Exception("Unable to retrieve the DVD Info. last_scan_log.txt is missing. \nExpected location of last_scan_log.txt: \n"\r
1474                                             + dvdInfoPath);\r
1475 \r
1476                     using (StreamReader sr = new StreamReader(dvdInfoPath))\r
1477                     {\r
1478                         thisDVD = DVD.Parse(sr);\r
1479                         sr.Close();\r
1480                         sr.Dispose();\r
1481                     }\r
1482 \r
1483                     updateUIafterScan();\r
1484                 }\r
1485             }\r
1486             catch (Exception exc)\r
1487             {\r
1488                 MessageBox.Show("frmMain.cs - scanProcess() " + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
1489                 enableGUI();\r
1490             }\r
1491         }\r
1492         private void updateUIafterScan()\r
1493         {\r
1494             try\r
1495             {\r
1496                 if (InvokeRequired)\r
1497                 {\r
1498                     BeginInvoke(new UpdateWindowHandler(updateUIafterScan));\r
1499                     return;\r
1500                 }\r
1501 \r
1502                 // Setup some GUI components\r
1503                 drp_dvdtitle.Items.Clear();\r
1504                 if (thisDVD.Titles.Count != 0)\r
1505                     drp_dvdtitle.Items.AddRange(thisDVD.Titles.ToArray());\r
1506 \r
1507                 // Now select the longest title\r
1508                 if (thisDVD.Titles.Count != 0)\r
1509                     drp_dvdtitle.SelectedItem = Main.selectLongestTitle(thisDVD);\r
1510 \r
1511                 // Enable the creation of chapter markers if the file is an image of a dvd.\r
1512                 if (sourcePath.ToLower().Contains(".iso") || sourcePath.Contains("VIDEO_TS"))\r
1513                     Check_ChapterMarkers.Enabled = true;\r
1514                 else\r
1515                 {\r
1516                     Check_ChapterMarkers.Enabled = false;\r
1517                     Check_ChapterMarkers.Checked = false;\r
1518                     data_chpt.Rows.Clear();\r
1519                 }\r
1520 \r
1521                 // If no titles were found, Display an error message\r
1522                 if (drp_dvdtitle.Items.Count == 0)\r
1523                 {\r
1524                     MessageBox.Show(\r
1525                         "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
1526                         "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);\r
1527                     sourcePath = string.Empty;\r
1528                 }\r
1529                 UpdateSourceLabel();\r
1530 \r
1531                 // Enable the GUI components and enable any disabled components\r
1532                 enableGUI();\r
1533             }\r
1534             catch (Exception exc)\r
1535             {\r
1536                 MessageBox.Show("frmMain.cs - updateUIafterScan " + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
1537                 enableGUI();\r
1538             }\r
1539         }\r
1540         private void enableGUI()\r
1541         {\r
1542             try\r
1543             {\r
1544                 if (InvokeRequired)\r
1545                     BeginInvoke(new UpdateWindowHandler(enableGUI));\r
1546                 lbl_encode.Text = "Scan Completed";\r
1547                 foreach (Control ctrl in Controls)\r
1548                     ctrl.Enabled = true;\r
1549                 btn_start.Enabled = true;\r
1550                 btn_showQueue.Enabled = true;\r
1551                 btn_add2Queue.Enabled = true;\r
1552                 tb_preview.Enabled = true;\r
1553                 btn_source.Enabled = true;\r
1554                 mnu_killCLI.Visible = false;\r
1555             }\r
1556             catch (Exception exc)\r
1557             {\r
1558                 MessageBox.Show("frmMain.cs - enableGUI() " + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
1559             }\r
1560         }\r
1561         private void killScan()\r
1562         {\r
1563             try\r
1564             {\r
1565                 enableGUI();\r
1566                 resetGUI();\r
1567 \r
1568                 Process[] prs = Process.GetProcesses();\r
1569                 foreach (Process process in prs)\r
1570                 {\r
1571                     if (process.Id == scanProcessID)\r
1572                     {\r
1573                         process.Refresh();\r
1574                         if (!process.HasExited)\r
1575                             process.Kill();\r
1576                     }\r
1577                 }\r
1578             }\r
1579             catch (Exception ex)\r
1580             {\r
1581                 MessageBox.Show("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" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
1582             }\r
1583         }\r
1584         private void resetGUI()\r
1585         {\r
1586             drp_dvdtitle.Items.Clear();\r
1587             drop_chapterStart.Items.Clear();\r
1588             drop_chapterFinish.Items.Clear();\r
1589             lbl_duration.Text = "Select a Title";\r
1590             PictureSettings.lbl_src_res.Text = "Select a Title";\r
1591             PictureSettings.lbl_Aspect.Text = "Select a Title";\r
1592             sourcePath = String.Empty;\r
1593             text_destination.Text = String.Empty;\r
1594             thisDVD = null;\r
1595             selectedTitle = null;\r
1596             isScanning = false;\r
1597         }\r
1598         private void UpdateSourceLabel()\r
1599         {\r
1600             labelSource.Text = string.IsNullOrEmpty(sourcePath) ? "Select \"Source\" to continue." : this.SourceName;\r
1601         }\r
1602         #endregion\r
1603 \r
1604         #region GUI\r
1605         /// <summary>\r
1606         /// Set the GUI to it's finished encoding state.\r
1607         /// </summary>\r
1608         private void setEncodeFinished()\r
1609         {\r
1610             try\r
1611             {\r
1612                 if (InvokeRequired)\r
1613                 {\r
1614                     BeginInvoke(new UpdateWindowHandler(setEncodeFinished));\r
1615                     return;\r
1616                 }\r
1617 \r
1618                 lbl_encode.Text = "Encoding Finished";\r
1619                 btn_start.Text = "Start";\r
1620                 btn_start.ToolTipText = "Start the encoding process";\r
1621                 btn_start.Image = Properties.Resources.Play;\r
1622 \r
1623                 // If the window is minimized, display the notification in a popup.\r
1624                 if (Properties.Settings.Default.trayIconAlerts)\r
1625                     if (FormWindowState.Minimized == this.WindowState)\r
1626                     {\r
1627                         notifyIcon.BalloonTipText = lbl_encode.Text;\r
1628                         notifyIcon.ShowBalloonTip(500);\r
1629                     }\r
1630             }\r
1631             catch (Exception exc)\r
1632             {\r
1633                 MessageBox.Show(exc.ToString());\r
1634             }\r
1635         }\r
1636 \r
1637         /// <summary>\r
1638         /// Set the GUI to it's started encoding state.\r
1639         /// </summary>\r
1640         private void setEncodeStarted()\r
1641         {\r
1642             try\r
1643             {\r
1644                 if (InvokeRequired)\r
1645                 {\r
1646                     BeginInvoke(new UpdateWindowHandler(setEncodeStarted));\r
1647                     return;\r
1648                 }\r
1649 \r
1650                 lbl_encode.Visible = true;\r
1651                 lbl_encode.Text = "Encoding with " + encodeQueue.Count + " encode(s) pending";\r
1652                 btn_start.Text = "Stop";\r
1653                 btn_start.ToolTipText = "Stop the encoding process.";\r
1654                 btn_start.Image = Properties.Resources.stop;\r
1655             }\r
1656             catch (Exception exc)\r
1657             {\r
1658                 MessageBox.Show(exc.ToString());\r
1659             }\r
1660         }\r
1661         #endregion\r
1662 \r
1663         #region DVD Drive Detection\r
1664         private void getDriveInfoThread()\r
1665         {\r
1666             try\r
1667             {\r
1668                 if (InvokeRequired)\r
1669                 {\r
1670                     BeginInvoke(new UpdateWindowHandler(getDriveInfoThread));\r
1671                     return;\r
1672                 }\r
1673 \r
1674                 Boolean foundDrive = false;\r
1675                 DriveInfo[] theCollectionOfDrives = DriveInfo.GetDrives();\r
1676                 foreach (DriveInfo curDrive in theCollectionOfDrives)\r
1677                 {\r
1678                     if (curDrive.DriveType == DriveType.CDRom && curDrive.IsReady)\r
1679                     {\r
1680                         if (File.Exists(curDrive.RootDirectory + "VIDEO_TS\\VIDEO_TS.IFO"))\r
1681                         {\r
1682                             this.dvdDrivePath = curDrive.RootDirectory + "VIDEO_TS";\r
1683                             this.dvdDriveLabel = curDrive.VolumeLabel;\r
1684                             mnu_dvd_drive.Text = this.dvdDrivePath + " (" + this.dvdDriveLabel + ")";\r
1685                             foundDrive = true;\r
1686                             break;\r
1687                         }\r
1688                     }\r
1689                 }\r
1690 \r
1691                 if (foundDrive == false)\r
1692                     mnu_dvd_drive.Text = "[No DVD Drive Ready]";\r
1693             }\r
1694             catch (Exception)\r
1695             {\r
1696                 mnu_dvd_drive.Text = "[No DVD Drive Ready / Found]";\r
1697             }\r
1698         }\r
1699         #endregion\r
1700 \r
1701         #region Public Methods\r
1702         /// <summary>\r
1703         /// Access the preset Handler and setup the preset panel.\r
1704         /// </summary>\r
1705         public void loadPresetPanel()\r
1706         {\r
1707             if (presetHandler.CheckIfPresetsAreOutOfDate())\r
1708                 if (!Properties.Settings.Default.presetNotification)\r
1709                     MessageBox.Show(splash,\r
1710                     "HandBrake has determined your built-in presets are out of date... These presets will now be updated.",\r
1711                     "Preset Update", MessageBoxButtons.OK, MessageBoxIcon.Information);\r
1712 \r
1713             presetHandler.GetPresetPanel(ref treeView_presets);\r
1714             treeView_presets.Update();\r
1715         }\r
1716         #endregion\r
1717 \r
1718         #region Overrides\r
1719         /// <summary>\r
1720         /// If the queue is being processed, prompt the user to confirm application close.\r
1721         /// </summary>\r
1722         /// <param name="e"></param>\r
1723         protected override void OnFormClosing(FormClosingEventArgs e)\r
1724         {\r
1725             // If currently encoding, the queue isn't paused, and there are queue items to process, prompt to confirm close.\r
1726             if ((encodeQueue.isEncoding) && (!encodeQueue.PauseRequested) && (encodeQueue.Count > 0))\r
1727             {\r
1728                 DialogResult result = MessageBox.Show("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
1729                     "Close HandBrake?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
1730                 if (result == DialogResult.No)\r
1731                     e.Cancel = true;\r
1732             }\r
1733             base.OnFormClosing(e);\r
1734         }\r
1735         #endregion\r
1736 \r
1737         #region In-GUI Encode Status (Experimental)\r
1738         private void encodeMonitorThread()\r
1739         {\r
1740             try\r
1741             {\r
1742                 Parser encode = new Parser(encodeQueue.hbProcess.StandardOutput.BaseStream);\r
1743                 encode.OnEncodeProgress += encodeOnEncodeProgress;\r
1744                 while (!encode.EndOfStream)\r
1745                     encode.readEncodeStatus();\r
1746             }\r
1747             catch (Exception exc)\r
1748             {\r
1749                 MessageBox.Show(exc.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
1750             }\r
1751         }\r
1752         private void encodeOnEncodeProgress(object Sender, int CurrentTask, int TaskCount, float PercentComplete, float CurrentFps, float AverageFps, TimeSpan TimeRemaining)\r
1753         {\r
1754             if (this.InvokeRequired)\r
1755             {\r
1756                 this.BeginInvoke(new EncodeProgressEventHandler(encodeOnEncodeProgress),\r
1757                     new object[] { Sender, CurrentTask, TaskCount, PercentComplete, CurrentFps, AverageFps, TimeRemaining });\r
1758                 return;\r
1759             }\r
1760             lbl_encode.Text = string.Format("Encode Progress: {0}%,       FPS: {1},       Avg FPS: {2},       Time Remaining: {3} ", PercentComplete, CurrentFps, AverageFps, TimeRemaining);\r
1761         }\r
1762         #endregion\r
1763 \r
1764         #region enum\r
1765         private enum SourceType\r
1766         {\r
1767             None = 0,\r
1768             Folder,\r
1769             DvdDrive,\r
1770             VideoFile\r
1771         }\r
1772         #endregion\r
1773 \r
1774         // This is the END of the road ****************************************\r
1775     }\r
1776 }