OSDN Git Service

510454dab3d019655692eb0e29e4433599ef3b52
[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, (rtf_query.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, (rtf_query.Text != ""));\r
768 \r
769                 }\r
770                 else\r
771                     encodeQueue.AddJob(query, sourcePath, text_destination.Text, (rtf_query.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.SetLogView(!encodeQueue.isEncoding);\r
810 \r
811             ActivityWindow.Show();\r
812         }\r
813         #endregion\r
814 \r
815         #region System Tray Icon\r
816         private void frmMain_Resize(object sender, EventArgs e)\r
817         {\r
818             if (FormWindowState.Minimized == this.WindowState)\r
819             {\r
820                 notifyIcon.Visible = true;\r
821                 this.Hide();\r
822             }\r
823             else if (FormWindowState.Normal == this.WindowState)\r
824                 notifyIcon.Visible = false;\r
825         }\r
826         private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)\r
827         {\r
828             this.Visible = true;\r
829             this.Activate();\r
830             this.WindowState = FormWindowState.Normal;\r
831             notifyIcon.Visible = false;\r
832         }\r
833         private void btn_restore_Click(object sender, EventArgs e)\r
834         {\r
835             this.Visible = true;\r
836             this.Activate();\r
837             this.WindowState = FormWindowState.Normal;\r
838             notifyIcon.Visible = false;\r
839         }\r
840         #endregion\r
841 \r
842         #region Tab Control\r
843 \r
844         //Source\r
845         private void btn_dvd_source_Click(object sender, EventArgs e)\r
846         {\r
847             if (DVD_Open.ShowDialog() == DialogResult.OK)\r
848             {\r
849                 this.selectedSourceType = SourceType.Folder;\r
850                 selectSource(DVD_Open.SelectedPath);\r
851             }\r
852             else\r
853                 UpdateSourceLabel();\r
854         }\r
855         private void btn_file_source_Click(object sender, EventArgs e)\r
856         {\r
857             if (ISO_Open.ShowDialog() == DialogResult.OK)\r
858             {\r
859                 this.selectedSourceType = SourceType.VideoFile;\r
860                 selectSource(ISO_Open.FileName);\r
861             }\r
862             else\r
863                 UpdateSourceLabel();\r
864         }\r
865         private void mnu_dvd_drive_Click(object sender, EventArgs e)\r
866         {\r
867             if (this.dvdDrivePath == null) return;\r
868             this.selectedSourceType = SourceType.DvdDrive;\r
869             selectSource(this.dvdDrivePath);\r
870         }\r
871         private void selectSource(string file)\r
872         {\r
873             Check_ChapterMarkers.Enabled = true;\r
874             lastAction = "scan";\r
875             sourcePath = string.Empty;\r
876 \r
877             if (file == string.Empty) // Must have a file or path\r
878             {\r
879                 UpdateSourceLabel();\r
880                 return;\r
881             }\r
882 \r
883             if (file.StartsWith("\\")) // NO UNC Paths\r
884             {\r
885                 MessageBox.Show(\r
886                     "Sorry, HandBrake does not support UNC file paths. \nTry mounting the share as a network drive in My Computer",\r
887                     "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);\r
888                 UpdateSourceLabel();\r
889                 return;\r
890             }\r
891 \r
892             sourcePath = Path.GetFileName(file);\r
893             startScan(file);\r
894         }\r
895         private void drp_dvdtitle_Click(object sender, EventArgs e)\r
896         {\r
897             if ((drp_dvdtitle.Items.Count == 1) && (drp_dvdtitle.Items[0].ToString() == "Automatic"))\r
898                 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
899         }\r
900         private void drp_dvdtitle_SelectedIndexChanged(object sender, EventArgs e)\r
901         {\r
902             UnRegisterPresetEventHandler();\r
903 \r
904             PictureSettings.lbl_Aspect.Text = "Select a Title"; // Reset some values on the form\r
905             drop_chapterStart.Items.Clear();\r
906             drop_chapterFinish.Items.Clear();\r
907 \r
908             // If the dropdown is set to automatic nothing else needs to be done.\r
909             // Otheriwse if its not, title data has to be loased from parsing.\r
910             if (drp_dvdtitle.Text != "Automatic")\r
911             {\r
912                 selectedTitle = drp_dvdtitle.SelectedItem as Title;\r
913                 lbl_duration.Text = selectedTitle.Duration.ToString();\r
914                 PictureSettings.Source = selectedTitle;  // Setup Picture Settings Tab Control\r
915 \r
916                 // Populate the Angles dropdown\r
917                 drop_angle.Items.Clear();\r
918                 if (Properties.Settings.Default.dvdnav)\r
919                 {\r
920                     drop_angle.Visible = true;\r
921                     lbl_angle.Visible = true;\r
922                     drop_angle.Items.AddRange(selectedTitle.Angles.ToArray());\r
923                     if (drop_angle.Items.Count != 0)\r
924                         drop_angle.SelectedIndex = 0;\r
925                 }\r
926                 else\r
927                 {\r
928                     drop_angle.Visible = false;\r
929                     lbl_angle.Visible = false;\r
930                 }\r
931 \r
932                 // Populate the Start chapter Dropdown\r
933                 drop_chapterStart.Items.Clear();\r
934                 drop_chapterStart.Items.AddRange(selectedTitle.Chapters.ToArray());\r
935                 if (drop_chapterStart.Items.Count > 0)\r
936                     drop_chapterStart.Text = drop_chapterStart.Items[0].ToString();\r
937 \r
938                 // Populate the Final Chapter Dropdown\r
939                 drop_chapterFinish.Items.Clear();\r
940                 drop_chapterFinish.Items.AddRange(selectedTitle.Chapters.ToArray());\r
941                 if (drop_chapterFinish.Items.Count > 0)\r
942                     drop_chapterFinish.Text = drop_chapterFinish.Items[drop_chapterFinish.Items.Count - 1].ToString();\r
943 \r
944                 // Populate the Audio Channels Dropdown\r
945                 AudioSettings.SetTrackList(selectedTitle);\r
946 \r
947                 // Populate the Subtitles dropdown\r
948                 Subtitles.drp_subtitleTracks.Items.Clear();\r
949                 Subtitles.drp_subtitleTracks.Items.Add("Foreign Audio Search (Bitmap)");\r
950                 Subtitles.drp_subtitleTracks.Items.AddRange(selectedTitle.Subtitles.ToArray());\r
951                 Subtitles.drp_subtitleTracks.SelectedIndex = 0;\r
952                 Subtitles.Clear();\r
953                 Subtitles.setSubtitleTrackAuto();\r
954             }\r
955 \r
956             // Run the autoName & chapterNaming functions\r
957             if (Properties.Settings.Default.autoNaming)\r
958             {\r
959                 string autoPath = Main.autoName(this);\r
960                 if (autoPath != null)\r
961                     text_destination.Text = autoPath;\r
962                 else\r
963                     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
964             }\r
965 \r
966             data_chpt.Rows.Clear();\r
967             if (selectedTitle.Chapters.Count != 1)\r
968             {\r
969                 DataGridView chapterGridView = Main.chapterNaming(data_chpt, drop_chapterFinish.Text);\r
970                 if (chapterGridView != null)\r
971                     data_chpt = chapterGridView;\r
972             }\r
973             else\r
974             {\r
975                 Check_ChapterMarkers.Checked = false;\r
976                 Check_ChapterMarkers.Enabled = false;\r
977             }\r
978 \r
979             // Hack to force the redraw of the scrollbars which don't resize properly when the control is disabled.\r
980             data_chpt.Columns[0].Width = 166;\r
981             data_chpt.Columns[0].Width = 165;\r
982 \r
983             RegisterPresetEventHandler();\r
984         }\r
985         private void chapersChanged(object sender, EventArgs e)\r
986         {\r
987             Control ctl = (Control)sender;\r
988             int chapterStart, chapterEnd;\r
989             int.TryParse(drop_chapterStart.Text, out chapterStart);\r
990             int.TryParse(drop_chapterFinish.Text, out chapterEnd);\r
991 \r
992             switch (ctl.Name)\r
993             {\r
994                 case "drop_chapterStart":\r
995                     if (drop_chapterFinish.SelectedIndex == -1 && drop_chapterFinish.Items.Count != 0)\r
996                         drop_chapterFinish.SelectedIndex = drop_chapterFinish.Items.Count - 1;\r
997 \r
998                     if (chapterEnd != 0)\r
999                         if (chapterStart > chapterEnd)\r
1000                             drop_chapterFinish.Text = chapterStart.ToString();\r
1001                     break;\r
1002                 case "drop_chapterFinish":\r
1003                     if (drop_chapterStart.Items.Count >= 1 && drop_chapterStart.SelectedIndex == -1)\r
1004                         drop_chapterStart.SelectedIndex = 0;\r
1005 \r
1006                     if (chapterStart != 0)\r
1007                         if (chapterEnd < chapterStart)\r
1008                             drop_chapterFinish.Text = chapterStart.ToString();\r
1009 \r
1010                     // Add more rows to the Chapter menu if needed.\r
1011                     if (Check_ChapterMarkers.Checked)\r
1012                     {\r
1013                         int i = data_chpt.Rows.Count, finish = 0;\r
1014                         int.TryParse(drop_chapterFinish.Text, out finish);\r
1015 \r
1016                         while (i < finish)\r
1017                         {\r
1018                             int n = data_chpt.Rows.Add();\r
1019                             data_chpt.Rows[n].Cells[0].Value = (i + 1);\r
1020                             data_chpt.Rows[n].Cells[1].Value = "Chapter " + (i + 1);\r
1021                             data_chpt.Rows[n].Cells[0].ValueType = typeof(int);\r
1022                             data_chpt.Rows[n].Cells[1].ValueType = typeof(string);\r
1023                             i++;\r
1024                         }\r
1025                     }\r
1026                     break;\r
1027             }\r
1028 \r
1029             // Update the Duration\r
1030             lbl_duration.Text = Main.calculateDuration(drop_chapterStart.SelectedIndex, drop_chapterFinish.SelectedIndex, selectedTitle).ToString();\r
1031 \r
1032             // Run the Autonaming function\r
1033             if (Properties.Settings.Default.autoNaming)\r
1034                 text_destination.Text = Main.autoName(this);\r
1035 \r
1036             // Disable chapter markers if only 1 chapter is selected.\r
1037             if (chapterStart == chapterEnd)\r
1038             {\r
1039                 Check_ChapterMarkers.Enabled = false;\r
1040                 btn_importChapters.Enabled = false;\r
1041                 data_chpt.Enabled = false;\r
1042             }\r
1043             else\r
1044             {\r
1045                 Check_ChapterMarkers.Enabled = true;\r
1046                 if (Check_ChapterMarkers.Checked)\r
1047                 {\r
1048                     btn_importChapters.Enabled = true;\r
1049                     data_chpt.Enabled = true;\r
1050                 }\r
1051             }\r
1052         }\r
1053 \r
1054         //Destination\r
1055         private void btn_destBrowse_Click(object sender, EventArgs e)\r
1056         {\r
1057             // This removes the file extension from the filename box on the save file dialog.\r
1058             // It's daft but some users don't realise that typing an extension overrides the dropdown extension selected.\r
1059             DVD_Save.FileName = Path.GetFileNameWithoutExtension(text_destination.Text);\r
1060 \r
1061             if (Path.IsPathRooted(text_destination.Text))\r
1062                 DVD_Save.InitialDirectory = Path.GetDirectoryName(text_destination.Text);\r
1063 \r
1064             // Show the dialog and set the main form file path\r
1065             if (drop_format.SelectedIndex.Equals(0))\r
1066                 DVD_Save.FilterIndex = 1;\r
1067             else if (drop_format.SelectedIndex.Equals(1))\r
1068                 DVD_Save.FilterIndex = 2;\r
1069 \r
1070             if (DVD_Save.ShowDialog() == DialogResult.OK)\r
1071             {\r
1072                 if (DVD_Save.FileName.StartsWith("\\"))\r
1073                     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
1074                 else\r
1075                 {\r
1076                     // Add a file extension manually, as FileDialog.AddExtension has issues with dots in filenames\r
1077                     switch (DVD_Save.FilterIndex)\r
1078                     {\r
1079                         case 1:\r
1080                             if (!Path.GetExtension(DVD_Save.FileName).Equals(".mp4", StringComparison.InvariantCultureIgnoreCase))\r
1081                                 if (Properties.Settings.Default.useM4v)\r
1082                                     DVD_Save.FileName = DVD_Save.FileName.Replace(".mp4", ".m4v").Replace(".mkv", ".m4v");\r
1083                                 else\r
1084                                     DVD_Save.FileName = DVD_Save.FileName.Replace(".m4v", ".mp4").Replace(".mkv", ".mp4");\r
1085                             break;\r
1086                         case 2:\r
1087                             if (!Path.GetExtension(DVD_Save.FileName).Equals(".mkv", StringComparison.InvariantCultureIgnoreCase))\r
1088                                 DVD_Save.FileName = DVD_Save.FileName.Replace(".mp4", ".mkv").Replace(".m4v", ".mkv");\r
1089                             break;\r
1090                         default:\r
1091                             //do nothing  \r
1092                             break;\r
1093                     }\r
1094                     text_destination.Text = DVD_Save.FileName;\r
1095 \r
1096                     // Quicktime requires .m4v file for chapter markers to work. If checked, change the extension to .m4v (mp4 and m4v are the same thing)\r
1097                     if (Check_ChapterMarkers.Checked && DVD_Save.FilterIndex != 2)\r
1098                         SetExtension(".m4v");\r
1099                 }\r
1100             }\r
1101         }\r
1102         private void text_destination_TextChanged(object sender, EventArgs e)\r
1103         {\r
1104             string path = text_destination.Text;\r
1105             if (path.EndsWith(".mp4") || path.EndsWith(".m4v"))\r
1106                 drop_format.SelectedIndex = 0;\r
1107             else if (path.EndsWith(".mkv"))\r
1108                 drop_format.SelectedIndex = 1;\r
1109         }\r
1110 \r
1111         // Output Settings\r
1112         private void drop_format_SelectedIndexChanged(object sender, EventArgs e)\r
1113         {\r
1114             switch (drop_format.SelectedIndex)\r
1115             {\r
1116                 case 0:\r
1117                     if (Properties.Settings.Default.useM4v || Check_ChapterMarkers.Checked || AudioSettings.RequiresM4V() || Subtitles.RequiresM4V())\r
1118                         SetExtension(".m4v");\r
1119                     else\r
1120                         SetExtension(".mp4");\r
1121                     break;\r
1122                 case 1:\r
1123                     SetExtension(".mkv");\r
1124                     break;\r
1125             }\r
1126 \r
1127             AudioSettings.SetContainer(drop_format.Text);\r
1128             Subtitles.setContainer(drop_format.SelectedIndex);\r
1129 \r
1130             if (drop_format.Text.Contains("MP4"))\r
1131             {\r
1132                 if (drp_videoEncoder.Items.Contains("VP3 (Theora)"))\r
1133                 {\r
1134                     drp_videoEncoder.Items.Remove("VP3 (Theora)");\r
1135                     drp_videoEncoder.SelectedIndex = 1;\r
1136                 }\r
1137             }\r
1138             else if (drop_format.Text.Contains("MKV"))\r
1139                 drp_videoEncoder.Items.Add("VP3 (Theora)");\r
1140         }\r
1141         public void SetExtension(string newExtension)\r
1142         {\r
1143             if (newExtension == ".mp4" || newExtension == ".m4v")\r
1144                 if (Properties.Settings.Default.useM4v || Check_ChapterMarkers.Checked || AudioSettings.RequiresM4V() || Subtitles.RequiresM4V())\r
1145                     newExtension = ".m4v";\r
1146                 else\r
1147                     newExtension = ".mp4";\r
1148 \r
1149             if (Path.HasExtension(newExtension))\r
1150                 text_destination.Text = Path.ChangeExtension(text_destination.Text, newExtension);\r
1151         }\r
1152 \r
1153         //Video Tab\r
1154         private void drp_videoEncoder_SelectedIndexChanged(object sender, EventArgs e)\r
1155         {\r
1156             setContainerOpts();\r
1157 \r
1158             //Turn off some options which are H.264 only when the user selects a non h.264 encoder\r
1159             if (drp_videoEncoder.Text.Contains("H.264"))\r
1160             {\r
1161                 if (check_2PassEncode.CheckState == CheckState.Checked)\r
1162                     check_turbo.Enabled = true;\r
1163 \r
1164                 tab_advanced.Enabled = true;\r
1165                 if ((drop_format.Text.Contains("MP4")) || (drop_format.Text.Contains("M4V")))\r
1166                     check_iPodAtom.Enabled = true;\r
1167                 else\r
1168                     check_iPodAtom.Enabled = false;\r
1169             }\r
1170             else\r
1171             {\r
1172                 check_turbo.CheckState = CheckState.Unchecked;\r
1173                 check_turbo.Enabled = false;\r
1174                 tab_advanced.Enabled = false;\r
1175                 x264Panel.x264Query = "";\r
1176                 check_iPodAtom.Enabled = false;\r
1177                 check_iPodAtom.Checked = false;\r
1178             }\r
1179 \r
1180             // Setup the CQ Slider\r
1181             switch (drp_videoEncoder.Text)\r
1182             {\r
1183                 case "MPEG-4 (FFmpeg)":\r
1184                     if (slider_videoQuality.Value > 31)\r
1185                         slider_videoQuality.Value = 20;   // Just reset to 70% QP 10 on encode change.\r
1186                     slider_videoQuality.Minimum = 1;\r
1187                     slider_videoQuality.Maximum = 31;\r
1188                     break;\r
1189                 case "H.264 (x264)":\r
1190                     slider_videoQuality.Minimum = 0;\r
1191                     slider_videoQuality.TickFrequency = 1;\r
1192 \r
1193                     CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");\r
1194                     double cqStep = Properties.Settings.Default.x264cqstep;\r
1195                     double multiplier = 1.0 / cqStep;\r
1196                     double value = slider_videoQuality.Value * multiplier;\r
1197 \r
1198                     switch (Properties.Settings.Default.x264cqstep.ToString(culture))\r
1199                     {\r
1200                         case "0.2":\r
1201                             slider_videoQuality.Maximum = 255;\r
1202                             break;\r
1203                         case "0.25":\r
1204                             slider_videoQuality.Maximum = 204;\r
1205                             break;\r
1206                         case "0.5":\r
1207                             slider_videoQuality.Maximum = 102;\r
1208                             break;\r
1209                         case "1":\r
1210                             slider_videoQuality.Maximum = 51;\r
1211                             break;\r
1212                         default:\r
1213                             slider_videoQuality.Maximum = 51;\r
1214                             break;\r
1215                     }\r
1216                     if (value < slider_videoQuality.Maximum)\r
1217                         slider_videoQuality.Value = slider_videoQuality.Maximum - (int)value;\r
1218 \r
1219                     break;\r
1220                 case "VP3 (Theora)":\r
1221                     if (slider_videoQuality.Value > 63)\r
1222                         slider_videoQuality.Value = 45;  // Just reset to 70% QP 45 on encode change.\r
1223                     slider_videoQuality.Minimum = 0;\r
1224                     slider_videoQuality.Maximum = 63;\r
1225                     break;\r
1226             }\r
1227         }\r
1228         /// <summary>\r
1229         /// Set the container format options\r
1230         /// </summary>\r
1231         public void setContainerOpts()\r
1232         {\r
1233             if ((drop_format.Text.Contains("MP4")) || (drop_format.Text.Contains("M4V")))\r
1234             {\r
1235                 check_largeFile.Enabled = true;\r
1236                 check_optimiseMP4.Enabled = true;\r
1237                 check_iPodAtom.Enabled = true;\r
1238             }\r
1239             else\r
1240             {\r
1241                 check_largeFile.Enabled = false;\r
1242                 check_optimiseMP4.Enabled = false;\r
1243                 check_iPodAtom.Enabled = false;\r
1244                 check_largeFile.Checked = false;\r
1245                 check_optimiseMP4.Checked = false;\r
1246                 check_iPodAtom.Checked = false;\r
1247             }\r
1248         }\r
1249         private double _cachedCqStep = Properties.Settings.Default.x264cqstep;\r
1250         /// <summary>\r
1251         /// Update the CQ slider for x264 for a new CQ step. This is set from option\r
1252         /// </summary>\r
1253         public void setQualityFromSlider()\r
1254         {\r
1255             // Work out the current RF value.\r
1256             double cqStep = _cachedCqStep;\r
1257             double rfValue = 51.0 - slider_videoQuality.Value * cqStep;\r
1258 \r
1259             // Change the maximum value for the slider\r
1260             switch (Properties.Settings.Default.x264cqstep.ToString(new CultureInfo("en-US")))\r
1261             {\r
1262                 case "0.2":\r
1263                     slider_videoQuality.Maximum = 255;\r
1264                     break;\r
1265                 case "0.25":\r
1266                     slider_videoQuality.Maximum = 204;\r
1267                     break;\r
1268                 case "0.5":\r
1269                     slider_videoQuality.Maximum = 102;\r
1270                     break;\r
1271                 case "1":\r
1272                     slider_videoQuality.Maximum = 51;\r
1273                     break;\r
1274                 default:\r
1275                     slider_videoQuality.Maximum = 51;\r
1276                     break;\r
1277             }\r
1278 \r
1279             // Reset the CQ slider to RF0\r
1280             slider_videoQuality.Value = slider_videoQuality.Maximum;\r
1281 \r
1282             // Reset the CQ slider back to the previous value as close as possible\r
1283             double cqStepNew = Properties.Settings.Default.x264cqstep;\r
1284             double rfValueCurrent = 51.0 - slider_videoQuality.Value * cqStepNew;\r
1285             while (rfValueCurrent < rfValue)\r
1286             {\r
1287                 slider_videoQuality.Value--;\r
1288                 rfValueCurrent = 51.0 - slider_videoQuality.Value * cqStepNew;\r
1289             }\r
1290 \r
1291             // Cache the CQ step for the next calculation\r
1292             _cachedCqStep = Properties.Settings.Default.x264cqstep;\r
1293         }\r
1294         private void slider_videoQuality_Scroll(object sender, EventArgs e)\r
1295         {\r
1296             double cqStep = Properties.Settings.Default.x264cqstep;\r
1297             switch (drp_videoEncoder.Text)\r
1298             {\r
1299                 case "MPEG-4 (FFmpeg)":\r
1300                     double rfValue = 31 - (slider_videoQuality.Value - 1);\r
1301                     double max = slider_videoQuality.Maximum;\r
1302                     double min = slider_videoQuality.Minimum;\r
1303                     double val = ((max - min) - (rfValue - min)) / (max - min);\r
1304                     SliderValue.Text = Math.Round((val * 100), 2).ToString(new CultureInfo("en-US")) + "% QP:" + (32 - slider_videoQuality.Value);\r
1305                     break;\r
1306                 case "H.264 (x264)":\r
1307                     rfValue = 51.0 - slider_videoQuality.Value * cqStep;\r
1308                     max = slider_videoQuality.Maximum * cqStep;\r
1309                     min = slider_videoQuality.Minimum;\r
1310                     val = ((max - min) - (rfValue - min)) / (max - min);\r
1311                     rfValue = Math.Round(rfValue, 2);\r
1312                     SliderValue.Text = Math.Round((val * 100), 2).ToString(new CultureInfo("en-US")) + "% RF:" + rfValue.ToString(new CultureInfo("en-US"));\r
1313                     break;\r
1314                 case "VP3 (Theora)":\r
1315                     rfValue = slider_videoQuality.Value;\r
1316                     double value = rfValue / 63;\r
1317                     SliderValue.Text = Math.Round((value * 100), 2).ToString(new CultureInfo("en-US")) + "% QP:" + slider_videoQuality.Value;\r
1318                     break;\r
1319             }\r
1320         }\r
1321         private void radio_targetFilesize_CheckedChanged(object sender, EventArgs e)\r
1322         {\r
1323             text_bitrate.Enabled = false;\r
1324             text_filesize.Enabled = true;\r
1325             slider_videoQuality.Enabled = false;\r
1326 \r
1327             check_2PassEncode.Enabled = true;\r
1328         }\r
1329         private void radio_avgBitrate_CheckedChanged(object sender, EventArgs e)\r
1330         {\r
1331             text_bitrate.Enabled = true;\r
1332             text_filesize.Enabled = false;\r
1333             slider_videoQuality.Enabled = false;\r
1334 \r
1335             check_2PassEncode.Enabled = true;\r
1336         }\r
1337         private void radio_cq_CheckedChanged(object sender, EventArgs e)\r
1338         {\r
1339             text_bitrate.Enabled = false;\r
1340             text_filesize.Enabled = false;\r
1341             slider_videoQuality.Enabled = true;\r
1342 \r
1343             check_2PassEncode.Enabled = false;\r
1344             check_2PassEncode.CheckState = CheckState.Unchecked;\r
1345         }\r
1346         private void check_2PassEncode_CheckedChanged(object sender, EventArgs e)\r
1347         {\r
1348             if (check_2PassEncode.CheckState.ToString() == "Checked")\r
1349             {\r
1350                 if (drp_videoEncoder.Text.Contains("H.264"))\r
1351                     check_turbo.Enabled = true;\r
1352             }\r
1353             else\r
1354             {\r
1355                 check_turbo.Enabled = false;\r
1356                 check_turbo.CheckState = CheckState.Unchecked;\r
1357             }\r
1358         }\r
1359 \r
1360         // Chapter Marker Tab\r
1361         private void Check_ChapterMarkers_CheckedChanged(object sender, EventArgs e)\r
1362         {\r
1363             if (Check_ChapterMarkers.Checked)\r
1364             {\r
1365                 if (drop_format.SelectedIndex != 1)\r
1366                     SetExtension(".m4v");\r
1367                 data_chpt.Enabled = true;\r
1368                 btn_importChapters.Enabled = true;\r
1369             }\r
1370             else\r
1371             {\r
1372                 if (drop_format.SelectedIndex != 1 && !Properties.Settings.Default.useM4v)\r
1373                     SetExtension(".mp4");\r
1374                 data_chpt.Enabled = false;\r
1375                 btn_importChapters.Enabled = false;\r
1376             }\r
1377         }\r
1378         private void btn_importChapters_Click(object sender, EventArgs e)\r
1379         {\r
1380             if (File_ChapterImport.ShowDialog() == DialogResult.OK)\r
1381             {\r
1382                 String filename = File_ChapterImport.FileName;\r
1383                 DataGridView imported = Main.importChapterNames(data_chpt, filename);\r
1384                 if (imported != null)\r
1385                     data_chpt = imported;\r
1386             }\r
1387         }\r
1388         private void mnu_resetChapters_Click(object sender, EventArgs e)\r
1389         {\r
1390             data_chpt.Rows.Clear();\r
1391             DataGridView chapterGridView = Main.chapterNaming(data_chpt, drop_chapterFinish.Text);\r
1392             if (chapterGridView != null)\r
1393             {\r
1394                 data_chpt = chapterGridView;\r
1395             }\r
1396         }\r
1397 \r
1398         // Query Editor Tab\r
1399         private void btn_generate_Query_Click(object sender, EventArgs e)\r
1400         {\r
1401             rtf_query.Text = queryGen.GenerateCLIQuery(this, 0, null);\r
1402         }\r
1403         private void btn_clear_Click(object sender, EventArgs e)\r
1404         {\r
1405             rtf_query.Clear();\r
1406         }\r
1407         #endregion\r
1408 \r
1409         // MainWindow Components, Actions and Functions ***********************\r
1410 \r
1411         #region Source Scan\r
1412         public Boolean isScanning { get; set; }\r
1413         private static int scanProcessID { get; set; }\r
1414         private void startScan(String filename)\r
1415         {\r
1416             // Setup the GUI components for the scan.\r
1417             sourcePath = filename;\r
1418             foreach (Control ctrl in Controls)\r
1419                 if (!(ctrl is StatusStrip || ctrl is MenuStrip || ctrl is ToolStrip))\r
1420                     ctrl.Enabled = false;\r
1421 \r
1422             lbl_encode.Visible = true;\r
1423             lbl_encode.Text = "Scanning ...";\r
1424             btn_source.Enabled = false;\r
1425             btn_start.Enabled = false;\r
1426             btn_showQueue.Enabled = false;\r
1427             btn_add2Queue.Enabled = false;\r
1428             tb_preview.Enabled = false;\r
1429             mnu_killCLI.Visible = true;\r
1430 \r
1431             // Start hte Scan Thread\r
1432             try\r
1433             {\r
1434                 if (ActivityWindow != null)\r
1435                     ActivityWindow.SetLogView(true);\r
1436                 isScanning = true;\r
1437                 ThreadPool.QueueUserWorkItem(scanProcess);\r
1438             }\r
1439             catch (Exception exc)\r
1440             {\r
1441                 MessageBox.Show("frmMain.cs - startScan " + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
1442             }\r
1443         }\r
1444         private void scanProcess(object state)\r
1445         {\r
1446             try\r
1447             {\r
1448                 string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");\r
1449                 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";\r
1450                 string dvdInfoPath = Path.Combine(logDir, "last_scan_log.txt");\r
1451 \r
1452                 // Make we don't pick up a stale last_encode_log.txt (and that we have rights to the file)\r
1453                 if (File.Exists(dvdInfoPath))\r
1454                     File.Delete(dvdInfoPath);\r
1455 \r
1456                 String dvdnav = string.Empty;\r
1457                 if (Properties.Settings.Default.dvdnav)\r
1458                     dvdnav = " --dvdnav";\r
1459                 string strCmdLine = String.Format(@"cmd /c """"{0}"" -i ""{1}"" -t0 {2} -v >""{3}"" 2>&1""", handbrakeCLIPath, sourcePath, dvdnav, dvdInfoPath);\r
1460 \r
1461                 ProcessStartInfo hbParseDvd = new ProcessStartInfo("CMD.exe", strCmdLine) { WindowStyle = ProcessWindowStyle.Hidden };\r
1462 \r
1463                 Boolean cleanExit = true;\r
1464                 using (hbproc = Process.Start(hbParseDvd))\r
1465                 {\r
1466                     Process[] before = Process.GetProcesses(); // Get a list of running processes before starting.\r
1467                     scanProcessID = Main.getCliProcess(before);\r
1468                     hbproc.WaitForExit();\r
1469                     if (hbproc.ExitCode != 0)\r
1470                         cleanExit = false;\r
1471                 }\r
1472 \r
1473                 if (cleanExit) // If 0 exit code, CLI exited cleanly.\r
1474                 {\r
1475                     if (!File.Exists(dvdInfoPath))\r
1476                         throw new Exception("Unable to retrieve the DVD Info. last_scan_log.txt is missing. \nExpected location of last_scan_log.txt: \n"\r
1477                                             + dvdInfoPath);\r
1478 \r
1479                     using (StreamReader sr = new StreamReader(dvdInfoPath))\r
1480                     {\r
1481                         thisDVD = DVD.Parse(sr);\r
1482                         sr.Close();\r
1483                         sr.Dispose();\r
1484                     }\r
1485 \r
1486                     updateUIafterScan();\r
1487                 }\r
1488             }\r
1489             catch (Exception exc)\r
1490             {\r
1491                 MessageBox.Show("frmMain.cs - scanProcess() " + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
1492                 enableGUI();\r
1493             }\r
1494         }\r
1495         private void updateUIafterScan()\r
1496         {\r
1497             try\r
1498             {\r
1499                 if (InvokeRequired)\r
1500                 {\r
1501                     BeginInvoke(new UpdateWindowHandler(updateUIafterScan));\r
1502                     return;\r
1503                 }\r
1504 \r
1505                 // Setup some GUI components\r
1506                 drp_dvdtitle.Items.Clear();\r
1507                 if (thisDVD.Titles.Count != 0)\r
1508                     drp_dvdtitle.Items.AddRange(thisDVD.Titles.ToArray());\r
1509 \r
1510                 // Now select the longest title\r
1511                 if (thisDVD.Titles.Count != 0)\r
1512                     drp_dvdtitle.SelectedItem = Main.selectLongestTitle(thisDVD);\r
1513 \r
1514                 // Enable the creation of chapter markers if the file is an image of a dvd.\r
1515                 if (sourcePath.ToLower().Contains(".iso") || sourcePath.Contains("VIDEO_TS"))\r
1516                     Check_ChapterMarkers.Enabled = true;\r
1517                 else\r
1518                 {\r
1519                     Check_ChapterMarkers.Enabled = false;\r
1520                     Check_ChapterMarkers.Checked = false;\r
1521                     data_chpt.Rows.Clear();\r
1522                 }\r
1523 \r
1524                 // If no titles were found, Display an error message\r
1525                 if (drp_dvdtitle.Items.Count == 0)\r
1526                 {\r
1527                     MessageBox.Show(\r
1528                         "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
1529                         "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);\r
1530                     sourcePath = string.Empty;\r
1531                 }\r
1532                 UpdateSourceLabel();\r
1533 \r
1534                 // Enable the GUI components and enable any disabled components\r
1535                 enableGUI();\r
1536             }\r
1537             catch (Exception exc)\r
1538             {\r
1539                 MessageBox.Show("frmMain.cs - updateUIafterScan " + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
1540                 enableGUI();\r
1541             }\r
1542         }\r
1543         private void enableGUI()\r
1544         {\r
1545             try\r
1546             {\r
1547                 if (InvokeRequired)\r
1548                     BeginInvoke(new UpdateWindowHandler(enableGUI));\r
1549                 lbl_encode.Text = "Scan Completed";\r
1550                 foreach (Control ctrl in Controls)\r
1551                     ctrl.Enabled = true;\r
1552                 btn_start.Enabled = true;\r
1553                 btn_showQueue.Enabled = true;\r
1554                 btn_add2Queue.Enabled = true;\r
1555                 tb_preview.Enabled = true;\r
1556                 btn_source.Enabled = true;\r
1557                 mnu_killCLI.Visible = false;\r
1558             }\r
1559             catch (Exception exc)\r
1560             {\r
1561                 MessageBox.Show("frmMain.cs - enableGUI() " + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
1562             }\r
1563         }\r
1564         private void killScan()\r
1565         {\r
1566             try\r
1567             {\r
1568                 enableGUI();\r
1569                 resetGUI();\r
1570 \r
1571                 Process[] prs = Process.GetProcesses();\r
1572                 foreach (Process process in prs)\r
1573                 {\r
1574                     if (process.Id == scanProcessID)\r
1575                     {\r
1576                         process.Refresh();\r
1577                         if (!process.HasExited)\r
1578                             process.Kill();\r
1579                     }\r
1580                 }\r
1581             }\r
1582             catch (Exception ex)\r
1583             {\r
1584                 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
1585             }\r
1586         }\r
1587         private void resetGUI()\r
1588         {\r
1589             drp_dvdtitle.Items.Clear();\r
1590             drop_chapterStart.Items.Clear();\r
1591             drop_chapterFinish.Items.Clear();\r
1592             lbl_duration.Text = "Select a Title";\r
1593             PictureSettings.lbl_src_res.Text = "Select a Title";\r
1594             PictureSettings.lbl_Aspect.Text = "Select a Title";\r
1595             sourcePath = String.Empty;\r
1596             text_destination.Text = String.Empty;\r
1597             thisDVD = null;\r
1598             selectedTitle = null;\r
1599             isScanning = false;\r
1600         }\r
1601         private void UpdateSourceLabel()\r
1602         {\r
1603             labelSource.Text = string.IsNullOrEmpty(sourcePath) ? "Select \"Source\" to continue." : this.SourceName;\r
1604         }\r
1605         #endregion\r
1606 \r
1607         #region GUI\r
1608         /// <summary>\r
1609         /// Set the GUI to it's finished encoding state.\r
1610         /// </summary>\r
1611         private void setEncodeFinished()\r
1612         {\r
1613             try\r
1614             {\r
1615                 if (InvokeRequired)\r
1616                 {\r
1617                     BeginInvoke(new UpdateWindowHandler(setEncodeFinished));\r
1618                     return;\r
1619                 }\r
1620 \r
1621                 lbl_encode.Text = "Encoding Finished";\r
1622                 btn_start.Text = "Start";\r
1623                 btn_start.ToolTipText = "Start the encoding process";\r
1624                 btn_start.Image = Properties.Resources.Play;\r
1625 \r
1626                 // If the window is minimized, display the notification in a popup.\r
1627                 if (Properties.Settings.Default.trayIconAlerts)\r
1628                     if (FormWindowState.Minimized == this.WindowState)\r
1629                     {\r
1630                         notifyIcon.BalloonTipText = lbl_encode.Text;\r
1631                         notifyIcon.ShowBalloonTip(500);\r
1632                     }\r
1633             }\r
1634             catch (Exception exc)\r
1635             {\r
1636                 MessageBox.Show(exc.ToString());\r
1637             }\r
1638         }\r
1639 \r
1640         /// <summary>\r
1641         /// Set the GUI to it's started encoding state.\r
1642         /// </summary>\r
1643         private void setEncodeStarted()\r
1644         {\r
1645             try\r
1646             {\r
1647                 if (InvokeRequired)\r
1648                 {\r
1649                     BeginInvoke(new UpdateWindowHandler(setEncodeStarted));\r
1650                     return;\r
1651                 }\r
1652 \r
1653                 lbl_encode.Visible = true;\r
1654                 lbl_encode.Text = "Encoding with " + encodeQueue.Count + " encode(s) pending";\r
1655                 btn_start.Text = "Stop";\r
1656                 btn_start.ToolTipText = "Stop the encoding process.";\r
1657                 btn_start.Image = Properties.Resources.stop;\r
1658             }\r
1659             catch (Exception exc)\r
1660             {\r
1661                 MessageBox.Show(exc.ToString());\r
1662             }\r
1663         }\r
1664         #endregion\r
1665 \r
1666         #region DVD Drive Detection\r
1667         private void getDriveInfoThread()\r
1668         {\r
1669             try\r
1670             {\r
1671                 if (InvokeRequired)\r
1672                 {\r
1673                     BeginInvoke(new UpdateWindowHandler(getDriveInfoThread));\r
1674                     return;\r
1675                 }\r
1676 \r
1677                 Boolean foundDrive = false;\r
1678                 DriveInfo[] theCollectionOfDrives = DriveInfo.GetDrives();\r
1679                 foreach (DriveInfo curDrive in theCollectionOfDrives)\r
1680                 {\r
1681                     if (curDrive.DriveType == DriveType.CDRom && curDrive.IsReady)\r
1682                     {\r
1683                         if (File.Exists(curDrive.RootDirectory + "VIDEO_TS\\VIDEO_TS.IFO"))\r
1684                         {\r
1685                             this.dvdDrivePath = curDrive.RootDirectory + "VIDEO_TS";\r
1686                             this.dvdDriveLabel = curDrive.VolumeLabel;\r
1687                             mnu_dvd_drive.Text = this.dvdDrivePath + " (" + this.dvdDriveLabel + ")";\r
1688                             foundDrive = true;\r
1689                             break;\r
1690                         }\r
1691                     }\r
1692                 }\r
1693 \r
1694                 if (foundDrive == false)\r
1695                     mnu_dvd_drive.Text = "[No DVD Drive Ready]";\r
1696             }\r
1697             catch (Exception)\r
1698             {\r
1699                 mnu_dvd_drive.Text = "[No DVD Drive Ready / Found]";\r
1700             }\r
1701         }\r
1702         #endregion\r
1703 \r
1704         #region Public Methods\r
1705         /// <summary>\r
1706         /// Access the preset Handler and setup the preset panel.\r
1707         /// </summary>\r
1708         public void loadPresetPanel()\r
1709         {\r
1710             if (presetHandler.CheckIfPresetsAreOutOfDate())\r
1711                 if (!Properties.Settings.Default.presetNotification)\r
1712                     MessageBox.Show(splash,\r
1713                     "HandBrake has determined your built-in presets are out of date... These presets will now be updated.",\r
1714                     "Preset Update", MessageBoxButtons.OK, MessageBoxIcon.Information);\r
1715 \r
1716             presetHandler.GetPresetPanel(ref treeView_presets);\r
1717             treeView_presets.Update();\r
1718         }\r
1719         #endregion\r
1720 \r
1721         #region Overrides\r
1722         /// <summary>\r
1723         /// If the queue is being processed, prompt the user to confirm application close.\r
1724         /// </summary>\r
1725         /// <param name="e"></param>\r
1726         protected override void OnFormClosing(FormClosingEventArgs e)\r
1727         {\r
1728             // If currently encoding, the queue isn't paused, and there are queue items to process, prompt to confirm close.\r
1729             if ((encodeQueue.isEncoding) && (!encodeQueue.PauseRequested) && (encodeQueue.Count > 0))\r
1730             {\r
1731                 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
1732                     "Close HandBrake?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\r
1733                 if (result == DialogResult.No)\r
1734                     e.Cancel = true;\r
1735             }\r
1736             base.OnFormClosing(e);\r
1737         }\r
1738         #endregion\r
1739 \r
1740         #region In-GUI Encode Status (Experimental)\r
1741         private void encodeMonitorThread()\r
1742         {\r
1743             try\r
1744             {\r
1745                 Parser encode = new Parser(encodeQueue.hbProcess.StandardOutput.BaseStream);\r
1746                 encode.OnEncodeProgress += encodeOnEncodeProgress;\r
1747                 while (!encode.EndOfStream)\r
1748                     encode.readEncodeStatus();\r
1749             }\r
1750             catch (Exception exc)\r
1751             {\r
1752                 MessageBox.Show(exc.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
1753             }\r
1754         }\r
1755         private void encodeOnEncodeProgress(object Sender, int CurrentTask, int TaskCount, float PercentComplete, float CurrentFps, float AverageFps, TimeSpan TimeRemaining)\r
1756         {\r
1757             if (this.InvokeRequired)\r
1758             {\r
1759                 this.BeginInvoke(new EncodeProgressEventHandler(encodeOnEncodeProgress),\r
1760                     new object[] { Sender, CurrentTask, TaskCount, PercentComplete, CurrentFps, AverageFps, TimeRemaining });\r
1761                 return;\r
1762             }\r
1763             lbl_encode.Text = string.Format("Encode Progress: {0}%,       FPS: {1},       Avg FPS: {2},       Time Remaining: {3} ", PercentComplete, CurrentFps, AverageFps, TimeRemaining);\r
1764         }\r
1765         #endregion\r
1766 \r
1767         #region enum\r
1768         private enum SourceType\r
1769         {\r
1770             None = 0,\r
1771             Folder,\r
1772             DvdDrive,\r
1773             VideoFile\r
1774         }\r
1775         #endregion\r
1776 \r
1777         // This is the END of the road ****************************************\r
1778     }\r
1779 }