From: sr55 Date: Sat, 20 Feb 2010 22:30:12 +0000 (+0000) Subject: WinGui: X-Git-Url: http://git.osdn.net/view?a=commitdiff_plain;h=bbadff781cdcb5c4676d26141c493939ea28b769;p=handbrake-jp%2Fhandbrake-jp-git.git WinGui: - Cleanup more StyleCop warnings. git-svn-id: svn://localhost/HandBrake/trunk@3131 b64f7644-9d1e-0410-96f1-a4d463321fa5 --- diff --git a/win/C#/Controls/AudioPanel.cs b/win/C#/Controls/AudioPanel.cs index b60bf767..c377edd0 100644 --- a/win/C#/Controls/AudioPanel.cs +++ b/win/C#/Controls/AudioPanel.cs @@ -4,14 +4,15 @@ Homepage: . It may be used under the terms of the GNU General Public License. */ -using System; -using System.Collections; -using System.Linq; -using System.Windows.Forms; -using Handbrake.Model; - namespace Handbrake.Controls { + using System; + using System.Collections; + using System.Linq; + using System.Windows.Forms; + using Parsing; + using AudioTrack = Model.AudioTrack; + public partial class AudioPanel : UserControl { /// @@ -20,6 +21,7 @@ namespace Handbrake.Controls public event EventHandler AudioListChanged; /// + /// Initializes a new instance of the class. /// Create a new instance of the Audio Panel /// public AudioPanel() @@ -42,7 +44,7 @@ namespace Handbrake.Controls /// Set the File Container. This funciton is used to limit the available options for each file container. /// /// - public void SetContainer(String path) + public void SetContainer(string path) { string oldval = drp_audioEncoder.Text; if ((path.Contains("MP4")) || (path.Contains("M4V"))) @@ -54,7 +56,6 @@ namespace Handbrake.Controls drp_audioEncoder.SelectedIndex = 0; else drp_audioEncoder.SelectedItem = oldval; - } else if (path.Contains("MKV")) { @@ -82,7 +83,7 @@ namespace Handbrake.Controls /// Checks if the settings used required the .m4v (rather than .mp4) extension /// /// - public Boolean RequiresM4V() + public bool RequiresM4V() { return lv_audioList.Items.Cast().Any(item => item.SubItems[2].Text.Contains("AC3")); } @@ -116,7 +117,7 @@ namespace Handbrake.Controls /// Set the Track list dropdown from the parsed title captured during the scan /// /// - public void SetTrackList(Parsing.Title selectedTitle) + public void SetTrackList(Title selectedTitle) { drp_audioTrack.Items.Clear(); drp_audioTrack.Items.Add("Automatic"); @@ -154,7 +155,8 @@ namespace Handbrake.Controls } } else - drp_audioTrack.SelectedIndex = drp_audioTrack.Items.Count >= 3 ? 2 : 0; // "Use Foreign language audio and Subtitles" + drp_audioTrack.SelectedIndex = drp_audioTrack.Items.Count >= 3 ? 2 : 0; + // "Use Foreign language audio and Subtitles" } drp_audioMix.SelectedIndex = 0; } @@ -162,7 +164,7 @@ namespace Handbrake.Controls // Control and ListView private void controlChanged(object sender, EventArgs e) { - Control ctl = (Control)sender; + Control ctl = (Control) sender; switch (ctl.Name) { @@ -177,13 +179,19 @@ namespace Handbrake.Controls // Configure the widgets with values if (drp_audioEncoder.Text.Contains("AC3") || drp_audioEncoder.Text.Contains("DTS")) { - drp_audioMix.Enabled = drp_audioBitrate.Enabled = drp_audioSample.Enabled = tb_drc.Enabled = false; - lbl_bitrate.Enabled = lbl_drc.Enabled = lbl_drcHeader.Enabled = lbl_mixdown.Enabled = lbl_sampleRate.Enabled = false; + drp_audioMix.Enabled = + drp_audioBitrate.Enabled = drp_audioSample.Enabled = tb_drc.Enabled = false; + lbl_bitrate.Enabled = + lbl_drc.Enabled = + lbl_drcHeader.Enabled = lbl_mixdown.Enabled = lbl_sampleRate.Enabled = false; } else { - drp_audioMix.Enabled = drp_audioBitrate.Enabled = drp_audioSample.Enabled = tb_drc.Enabled = true; - lbl_bitrate.Enabled = lbl_drc.Enabled = lbl_drcHeader.Enabled = lbl_mixdown.Enabled = lbl_sampleRate.Enabled = true; + drp_audioMix.Enabled = + drp_audioBitrate.Enabled = drp_audioSample.Enabled = tb_drc.Enabled = true; + lbl_bitrate.Enabled = + lbl_drc.Enabled = + lbl_drcHeader.Enabled = lbl_mixdown.Enabled = lbl_sampleRate.Enabled = true; } // Update an item in the Audio list if required. @@ -209,7 +217,7 @@ namespace Handbrake.Controls double value; if (tb_drc.Value == 0) value = 0; else - value = ((tb_drc.Value - 1) / 10.0) + 1; + value = ((tb_drc.Value - 1)/10.0) + 1; lbl_drc.Text = value.ToString(); @@ -224,6 +232,7 @@ namespace Handbrake.Controls lv_audioList.Select(); } + private void lv_audioList_SelectedIndexChanged(object sender, EventArgs e) { // Set the dropdown controls based on the selected item in the Audio List. @@ -234,15 +243,17 @@ namespace Handbrake.Controls drp_audioMix.SelectedItem = lv_audioList.Items[lv_audioList.SelectedIndices[0]].SubItems[3].Text; drp_audioSample.SelectedItem = lv_audioList.Items[lv_audioList.SelectedIndices[0]].SubItems[4].Text; drp_audioBitrate.SelectedItem = lv_audioList.Items[lv_audioList.SelectedIndices[0]].SubItems[5].Text; - double drcValue; int drcCalculated; + double drcValue; + int drcCalculated; double.TryParse(lv_audioList.Items[lv_audioList.SelectedIndices[0]].SubItems[6].Text, out drcValue); if (drcValue != 0) - drcValue = ((drcValue * 10) + 1) - 10; + drcValue = ((drcValue*10) + 1) - 10; int.TryParse(drcValue.ToString(), out drcCalculated); tb_drc.Value = drcCalculated; lbl_drc.Text = lv_audioList.Items[lv_audioList.SelectedIndices[0]].SubItems[6].Text; - AudioTrackGroup.Text = "Selected Track: " + lv_audioList.Items[lv_audioList.SelectedIndices[0]].SubItems[0].Text; + AudioTrackGroup.Text = "Selected Track: " + + lv_audioList.Items[lv_audioList.SelectedIndices[0]].SubItems[0].Text; } else AudioTrackGroup.Text = "Selected Track: None (Click \"Add Track\" to add)"; @@ -253,7 +264,7 @@ namespace Handbrake.Controls { double value = 0; if (tb_drc.Value != 0) - value = ((tb_drc.Value - 1) / 10.0) + 1; + value = ((tb_drc.Value - 1)/10.0) + 1; // Create a new row for the Audio list based on the currently selected items in the dropdown. ListViewItem newTrack = new ListViewItem(GetNewID().ToString()); @@ -273,6 +284,7 @@ namespace Handbrake.Controls lv_audioList.Items[lv_audioList.Items.Count - 1].Selected = true; lv_audioList.Select(); } + private void btn_RemoveAudioTrack_Click(object sender, EventArgs e) { RemoveTrack(); @@ -283,10 +295,12 @@ namespace Handbrake.Controls { MoveTrack(true); } + private void audioList_movedown_Click(object sender, EventArgs e) { MoveTrack(false); } + private void audioList_remove_Click(object sender, EventArgs e) { RemoveTrack(); @@ -299,16 +313,19 @@ namespace Handbrake.Controls if (this.AudioListChanged != null) this.AudioListChanged(this, new EventArgs()); } + private void ClearAudioList() { lv_audioList.Items.Clear(); if (this.AudioListChanged != null) this.AudioListChanged(this, new EventArgs()); } + private int GetNewID() { return lv_audioList.Items.Count + 1; } + private void RemoveTrack() { // Remove the Item and reselect the control if the following conditions are met. @@ -337,6 +354,7 @@ namespace Handbrake.Controls ReGenerateListIDs(); } } + private void MoveTrack(bool up) { if (lv_audioList.SelectedIndices.Count == 0) return; @@ -344,7 +362,8 @@ namespace Handbrake.Controls ListViewItem item = lv_audioList.SelectedItems[0]; int index = item.Index; - if (up) index--; else index++; + if (up) index--; + else index++; if (index < lv_audioList.Items.Count || (lv_audioList.Items.Count > index && index >= 0)) { @@ -354,6 +373,7 @@ namespace Handbrake.Controls lv_audioList.Focus(); } } + private void ReGenerateListIDs() { int i = 1; @@ -363,6 +383,7 @@ namespace Handbrake.Controls i++; } } + private void SetBitrate() { int max = 0; @@ -418,6 +439,7 @@ namespace Handbrake.Controls if (drp_audioBitrate.SelectedItem == null) drp_audioBitrate.SelectedIndex = drp_audioBitrate.Items.Count - 1; } + private void SetMixDown() { drp_audioMix.Items.Clear(); diff --git a/win/C#/Controls/Filters.cs b/win/C#/Controls/Filters.cs index adf7bde1..47657b57 100644 --- a/win/C#/Controls/Filters.cs +++ b/win/C#/Controls/Filters.cs @@ -4,11 +4,11 @@ Homepage: . It may be used under the terms of the GNU General Public License. */ -using System; -using System.Windows.Forms; - namespace Handbrake.Controls { + using System; + using System.Windows.Forms; + public partial class Filters : UserControl { /// @@ -17,6 +17,7 @@ namespace Handbrake.Controls public event EventHandler FilterSettingsChanged; /// + /// Initializes a new instance of the class. /// Creates a new instance of Filters /// public Filters() @@ -35,12 +36,12 @@ namespace Handbrake.Controls { get { - string query = ""; + string query = string.Empty; - switch (drop_detelecine.Text) // DeTelecine + switch (drop_detelecine.Text) // DeTelecine { case "Off": - query += ""; + query += string.Empty; break; case "Default": query += " --detelecine"; @@ -49,7 +50,7 @@ namespace Handbrake.Controls query += " --detelecine=\"" + text_customDT.Text + "\""; break; default: - query += ""; + query += string.Empty; break; } @@ -57,7 +58,7 @@ namespace Handbrake.Controls switch (drop_decomb.Text) // Decomb { case "Off": - query += ""; + query += string.Empty; break; case "Default": query += " --decomb"; @@ -66,14 +67,14 @@ namespace Handbrake.Controls query += " --decomb=\"" + text_customDC.Text + "\""; break; default: - query += ""; + query += string.Empty; break; } switch (drop_deinterlace.Text) // DeInterlace { case "None": - query += ""; + query += string.Empty; break; case "Fast": query += " --deinterlace=\"fast\""; @@ -88,14 +89,14 @@ namespace Handbrake.Controls query += " --deinterlace=\"" + text_customDI.Text + "\""; break; default: - query += ""; + query += string.Empty; break; } switch (drop_denoise.Text) // Denoise { case "None": - query += ""; + query += string.Empty; break; case "Weak": query += " --denoise=\"weak\""; @@ -110,7 +111,7 @@ namespace Handbrake.Controls query += " --denoise=\"" + text_customDN.Text + "\""; break; default: - query += ""; + query += string.Empty; break; } @@ -130,7 +131,7 @@ namespace Handbrake.Controls /// The value part of the CLI string public void SetDeTelecine(string value) { - text_customDT.Text = ""; + text_customDT.Text = string.Empty; text_customDT.Visible = false; switch (value) { @@ -154,7 +155,7 @@ namespace Handbrake.Controls /// The value part of the CLI string public void SetDeNoise(string value) { - text_customDN.Text = ""; + text_customDN.Text = string.Empty; text_customDN.Visible = false; switch (value) { @@ -184,11 +185,10 @@ namespace Handbrake.Controls /// The value part of the CLI string public void SetDeInterlace(string value) { - text_customDI.Text = ""; + text_customDI.Text = string.Empty; text_customDI.Visible = false; switch (value) { - case "Off": drop_deinterlace.SelectedIndex = 0; break; @@ -216,7 +216,7 @@ namespace Handbrake.Controls /// The value part of the CLI string public void SetDecomb(string value) { - text_customDC.Text = ""; + text_customDC.Text = string.Empty; text_customDC.Visible = false; switch (value) { @@ -269,6 +269,7 @@ namespace Handbrake.Controls if (this.FilterSettingsChanged != null) this.FilterSettingsChanged(this, new EventArgs()); } + private void DropDecombSelectedIndexChanged(object sender, EventArgs e) { text_customDC.Visible = drop_decomb.Text == "Custom"; @@ -279,6 +280,7 @@ namespace Handbrake.Controls if (this.FilterSettingsChanged != null) this.FilterSettingsChanged(this, new EventArgs()); } + private void DropDeinterlaceSelectedIndexChanged(object sender, EventArgs e) { text_customDI.Visible = drop_deinterlace.Text == "Custom"; @@ -289,6 +291,7 @@ namespace Handbrake.Controls if (this.FilterSettingsChanged != null) this.FilterSettingsChanged(this, new EventArgs()); } + private void DropDenoiseSelectedIndexChanged(object sender, EventArgs e) { text_customDN.Visible = drop_denoise.Text == "Custom"; @@ -297,6 +300,7 @@ namespace Handbrake.Controls if (this.FilterSettingsChanged != null) this.FilterSettingsChanged(this, new EventArgs()); } + private void SliderDeblockScroll(object sender, EventArgs e) { lbl_deblockVal.Text = slider_deblock.Value == 4 ? "Off" : slider_deblock.Value.ToString(); @@ -306,4 +310,4 @@ namespace Handbrake.Controls this.FilterSettingsChanged(this, new EventArgs()); } } -} +} \ No newline at end of file diff --git a/win/C#/Controls/PictureSettings.cs b/win/C#/Controls/PictureSettings.cs index 5eedf24d..44de2003 100644 --- a/win/C#/Controls/PictureSettings.cs +++ b/win/C#/Controls/PictureSettings.cs @@ -4,27 +4,31 @@ Homepage: . It may be used under the terms of the GNU General Public License. */ -using System; -using System.ComponentModel; -using System.Drawing; -using System.Globalization; -using System.Windows.Forms; -using Handbrake.Parsing; -using Handbrake.Presets; - namespace Handbrake.Controls { + using System; + using System.Drawing; + using System.Globalization; + using System.Windows.Forms; + using Parsing; + using Presets; + public partial class PictureSettings : UserControl { private readonly CultureInfo culture = new CultureInfo("en-US", false); public event EventHandler PictureSettingsChanged; - private Boolean preventChangingWidth, preventChangingHeight, preventChangingCustom, preventChangingDisplayWidth; - private int presetMaximumWidth, presetMaximumHeight; + private bool preventChangingWidth; + private bool preventChangingHeight; + private bool preventChangingCustom; + private bool preventChangingDisplayWidth; + private int presetMaximumWidth; + private int presetMaximumHeight; private double cachedDar; private Title sourceTitle; /// + /// Initializes a new instance of the class. /// Creates a new instance of the Picture Settings Class /// public PictureSettings() @@ -73,7 +77,7 @@ namespace Handbrake.Controls else if (value.Height != 0) lbl_max.Text = "Max Height"; else - lbl_max.Text = ""; + lbl_max.Text = string.Empty; } } @@ -100,7 +104,8 @@ namespace Handbrake.Controls lbl_src_res.Text = sourceTitle.Resolution.Width + " x " + sourceTitle.Resolution.Height; // Set the Recommended Cropping values, but only if a preset doesn't have hard set picture settings. - if ((CurrentlySelectedPreset != null && CurrentlySelectedPreset.PictureSettings == false) || CurrentlySelectedPreset == null) + if ((CurrentlySelectedPreset != null && CurrentlySelectedPreset.PictureSettings == false) || + CurrentlySelectedPreset == null) { crop_top.Value = GetCropMod2Clean(sourceTitle.AutoCropDimensions[0]); crop_bottom.Value = GetCropMod2Clean(sourceTitle.AutoCropDimensions[1]); @@ -120,10 +125,11 @@ namespace Handbrake.Controls } else { - if (text_width.Value == 0 && text_height.Value == 0)// Only update the values if the fields don't already have values. + if (text_width.Value == 0 && text_height.Value == 0) + // Only update the values if the fields don't already have values. { text_width.Value = sourceTitle.Resolution.Width; - text_height.Value = sourceTitle.Resolution.Height - (int)crop_top.Value - (int)crop_bottom.Value; + text_height.Value = sourceTitle.Resolution.Height - (int) crop_top.Value - (int) crop_bottom.Value; } labelDisplaySize.Text = CalculateAnamorphicSizes().Width + "x" + CalculateAnamorphicSizes().Height; @@ -133,10 +139,10 @@ namespace Handbrake.Controls updownParHeight.Value = sourceTitle.ParVal.Height; Size croppedDar = CalculateAnamorphicSizes(); - cachedDar = (double)croppedDar.Width / croppedDar.Height; + cachedDar = (double) croppedDar.Width/croppedDar.Height; updownDisplayWidth.Value = croppedDar.Width; } - + // Picture Controls private void TextWidthValueChanged(object sender, EventArgs e) { @@ -158,17 +164,17 @@ namespace Handbrake.Controls { preventChangingHeight = true; - int width = (int)text_width.Value; + int width = (int) text_width.Value; - double crop_width = Source.Resolution.Width - (int)crop_left.Value - (int)crop_right.Value; - double crop_height = Source.Resolution.Height - (int)crop_top.Value - (int)crop_bottom.Value; + double crop_width = Source.Resolution.Width - (int) crop_left.Value - (int) crop_right.Value; + double crop_height = Source.Resolution.Height - (int) crop_top.Value - (int) crop_bottom.Value; if (SourceAspect.Width == 0 && SourceAspect.Height == 0) break; - double newHeight = ((double)width * Source.Resolution.Width * SourceAspect.Height * crop_height) / - (Source.Resolution.Height * SourceAspect.Width * crop_width); - text_height.Value = (decimal)GetModulusValue(newHeight); + double newHeight = ((double) width*Source.Resolution.Width*SourceAspect.Height*crop_height)/ + (Source.Resolution.Height*SourceAspect.Width*crop_width); + text_height.Value = (decimal) GetModulusValue(newHeight); preventChangingHeight = false; } @@ -180,7 +186,7 @@ namespace Handbrake.Controls break; preventChangingDisplayWidth = true; - updownDisplayWidth.Value = text_width.Value * updownParWidth.Value / updownParHeight.Value; + updownDisplayWidth.Value = text_width.Value*updownParWidth.Value/updownParHeight.Value; preventChangingDisplayWidth = false; labelDisplaySize.Text = Math.Truncate(updownDisplayWidth.Value) + "x" + text_height.Value; @@ -199,6 +205,7 @@ namespace Handbrake.Controls preventChangingWidth = false; } + private void TextHeightValueChanged(object sender, EventArgs e) { if (Properties.Settings.Default.disableResCalc) @@ -218,13 +225,14 @@ namespace Handbrake.Controls { preventChangingWidth = true; - double crop_width = Source.Resolution.Width - (int)crop_left.Value - (int)crop_right.Value; - double crop_height = Source.Resolution.Height - (int)crop_top.Value - (int)crop_bottom.Value; + double crop_width = Source.Resolution.Width - (int) crop_left.Value - (int) crop_right.Value; + double crop_height = Source.Resolution.Height - (int) crop_top.Value - (int) crop_bottom.Value; - double new_width = ((double)text_height.Value * Source.Resolution.Height * SourceAspect.Width * crop_width) / - (Source.Resolution.Width * SourceAspect.Height * crop_height); + double new_width = ((double) text_height.Value*Source.Resolution.Height*SourceAspect.Width* + crop_width)/ + (Source.Resolution.Width*SourceAspect.Height*crop_height); - text_width.Value = (decimal)GetModulusValue(new_width); + text_width.Value = (decimal) GetModulusValue(new_width); preventChangingWidth = false; } @@ -239,12 +247,12 @@ namespace Handbrake.Controls // - Changes PIXEL HEIGHT to STORAGE WIDTH // DAR = DISPLAY WIDTH / DISPLAY HEIGHT (cache after every modification) - double rawCalculatedDisplayWidth = (double)text_height.Value * cachedDar; + double rawCalculatedDisplayWidth = (double) text_height.Value*cachedDar; preventChangingDisplayWidth = true; // Start Guards preventChangingWidth = true; - updownDisplayWidth.Value = (decimal)rawCalculatedDisplayWidth; + updownDisplayWidth.Value = (decimal) rawCalculatedDisplayWidth; updownParWidth.Value = updownDisplayWidth.Value; updownParHeight.Value = text_width.Value; @@ -260,12 +268,13 @@ namespace Handbrake.Controls preventChangingHeight = false; } + private void CheckKeepArCheckedChanged(object sender, EventArgs e) { if (Properties.Settings.Default.disableResCalc) return; - //Force TextWidth to recalc height + // Force TextWidth to recalc height if (check_KeepAR.Checked) TextWidthValueChanged(this, new EventArgs()); @@ -280,6 +289,7 @@ namespace Handbrake.Controls if (PictureSettingsChanged != null) PictureSettingsChanged(this, new EventArgs()); } + private void UpdownDisplayWidthValueChanged(object sender, EventArgs e) { if (Properties.Settings.Default.disableResCalc) @@ -305,17 +315,16 @@ namespace Handbrake.Controls if (!int.TryParse(drp_modulus.SelectedItem.ToString(), out modulus)) modulus = 16; - int rawCalculatedHeight = (int)((int)updownDisplayWidth.Value / cachedDar); - int modulusHeight = rawCalculatedHeight - (rawCalculatedHeight % modulus); + int rawCalculatedHeight = (int) ((int) updownDisplayWidth.Value/cachedDar); + int modulusHeight = rawCalculatedHeight - (rawCalculatedHeight%modulus); // Update value preventChangingHeight = true; - text_height.Value = (decimal)modulusHeight; + text_height.Value = (decimal) modulusHeight; updownParWidth.Value = updownDisplayWidth.Value; updownParHeight.Value = text_width.Value; preventChangingHeight = false; } - } // Anamorphic Controls @@ -376,7 +385,6 @@ namespace Handbrake.Controls updownParWidth.Enabled = !check_KeepAR.Checked; updownParHeight.Enabled = !check_KeepAR.Checked; break; - } labelDisplaySize.Text = CalculateAnamorphicSizes().Width + "x" + CalculateAnamorphicSizes().Height; @@ -387,13 +395,14 @@ namespace Handbrake.Controls if (PictureSettingsChanged != null) PictureSettingsChanged(this, new EventArgs()); } + private void DrpModulusSelectedIndexChanged(object sender, EventArgs e) { preventChangingWidth = true; preventChangingHeight = true; - text_width.Value = (decimal)GetModulusValue((double)text_width.Value); - text_height.Value = (decimal)GetModulusValue((double)text_height.Value); + text_width.Value = (decimal) GetModulusValue((double) text_width.Value); + text_height.Value = (decimal) GetModulusValue((double) text_height.Value); preventChangingWidth = false; preventChangingHeight = false; @@ -421,6 +430,7 @@ namespace Handbrake.Controls crop_right.Value = Source.AutoCropDimensions[3]; } } + private void CropValueChanged(object sender, EventArgs e) { TextWidthValueChanged(this, new EventArgs()); @@ -446,22 +456,24 @@ namespace Handbrake.Controls get { if (Source != null) // display aspect = (width * par_width) / (height * par_height) - return new Size((Source.ParVal.Width * Source.Resolution.Width), (Source.ParVal.Height * Source.Resolution.Height)); + return new Size((Source.ParVal.Width*Source.Resolution.Width), + (Source.ParVal.Height*Source.Resolution.Height)); return new Size(0, 0); // Fall over to 16:9 and hope for the best } } + private Size CalculateAnamorphicSizes() { if (Source != null) { /* Set up some variables to make the math easier to follow. */ - int croppedWidth = Source.Resolution.Width - (int)crop_left.Value - (int)crop_right.Value; - int croppedHeight = Source.Resolution.Height - (int)crop_top.Value - (int)crop_bottom.Value; - double storageAspect = (double)croppedWidth / croppedHeight; + int croppedWidth = Source.Resolution.Width - (int) crop_left.Value - (int) crop_right.Value; + int croppedHeight = Source.Resolution.Height - (int) crop_top.Value - (int) crop_bottom.Value; + double storageAspect = (double) croppedWidth/croppedHeight; /* Figure out what width the source would display at. */ - double sourceDisplayWidth = (double)croppedWidth * Source.ParVal.Width / Source.ParVal.Height; + double sourceDisplayWidth = (double) croppedWidth*Source.ParVal.Width/Source.ParVal.Height; /* 3 different ways of deciding output dimensions: @@ -475,31 +487,31 @@ namespace Handbrake.Controls default: case 1: /* Strict anamorphic */ - double displayWidth = ((double)croppedWidth * Source.ParVal.Width / Source.ParVal.Height); + double displayWidth = ((double) croppedWidth*Source.ParVal.Width/Source.ParVal.Height); displayWidth = Math.Round(displayWidth, 0); - Size output = new Size((int)displayWidth, croppedHeight); + Size output = new Size((int) displayWidth, croppedHeight); return output; case 2: /* "Loose" anamorphic. - Uses mod16-compliant dimensions, - Allows users to set the width */ - width = (int)text_width.Value; + width = (int) text_width.Value; width = GetModulusValue(width); /* Time to get picture width that divide cleanly.*/ - height = (width / storageAspect) + 0.5; + height = (width/storageAspect) + 0.5; height = GetModulusValue(height); /* Time to get picture height that divide cleanly.*/ /* The film AR is the source's display width / cropped source height. The output display width is the output height * film AR. The output PAR is the output display width / output storage width. */ - double pixelAspectWidth = height * sourceDisplayWidth / croppedHeight; + double pixelAspectWidth = height*sourceDisplayWidth/croppedHeight; double pixelAspectHeight = width; - double disWidthLoose = (width * pixelAspectWidth / pixelAspectHeight); + double disWidthLoose = (width*pixelAspectWidth/pixelAspectHeight); if (double.IsNaN(disWidthLoose)) disWidthLoose = 0; - return new Size((int)disWidthLoose, (int)height); + return new Size((int) disWidthLoose, (int) height); case 3: // Get the User Interface Values @@ -507,31 +519,33 @@ namespace Handbrake.Controls double.TryParse(updownDisplayWidth.Text, out UIdisplayWidth); /* Anamorphic 3: Power User Jamboree - Set everything based on specified values */ - height = GetModulusValue((double)text_height.Value); + height = GetModulusValue((double) text_height.Value); if (check_KeepAR.Checked) - return new Size((int)Math.Truncate(UIdisplayWidth), (int)height); + return new Size((int) Math.Truncate(UIdisplayWidth), (int) height); - return new Size((int)Math.Truncate(UIdisplayWidth), (int)height); + return new Size((int) Math.Truncate(UIdisplayWidth), (int) height); } } // Return a default value of 0,0 to indicate failure return new Size(0, 0); } + private double GetModulusValue(double value) { int mod = int.Parse(drp_modulus.SelectedItem.ToString()); - double remainder = value % mod; + double remainder = value%mod; if (remainder == 0) return value; - return remainder >= ((double)mod / 2) ? value + (mod - remainder) : value - remainder; + return remainder >= ((double) mod/2) ? value + (mod - remainder) : value - remainder; } + private static int GetCropMod2Clean(int value) { - int remainder = value % 2; + int remainder = value%2; if (remainder == 0) return value; return (value + remainder); } diff --git a/win/C#/Controls/Subtitles.cs b/win/C#/Controls/Subtitles.cs index 34e2cddf..af4f5d89 100644 --- a/win/C#/Controls/Subtitles.cs +++ b/win/C#/Controls/Subtitles.cs @@ -4,21 +4,20 @@ Homepage: . It may be used under the terms of the GNU General Public License. */ -using System; -using System.Collections.Generic; -using System.IO; -using System.Windows.Forms; -using Handbrake.Functions; -using Handbrake.Model; - namespace Handbrake.Controls { + using System; + using System.Collections.Generic; + using System.IO; using System.Linq; + using System.Windows.Forms; + using Functions; + using Model; public partial class Subtitles : UserControl { - readonly IDictionary langMap = new Dictionary(); - readonly List subList = new List(); + private readonly IDictionary langMap = new Dictionary(); + private readonly List subList = new List(); private int fileContainer; public Subtitles() @@ -39,7 +38,10 @@ namespace Handbrake.Controls // Logic string forcedVal = check_forced.CheckState == CheckState.Checked ? "Yes" : "No"; string defaultSub = check_default.CheckState == CheckState.Checked ? "Yes" : "No"; - string burnedVal = check_burned.CheckState == CheckState.Checked && (!drp_subtitleTracks.Text.Contains("Text")) ? "Yes" : "No"; + string burnedVal = check_burned.CheckState == CheckState.Checked && + (!drp_subtitleTracks.Text.Contains("Text")) + ? "Yes" + : "No"; string srtCode = "-", srtLangVal = "-", srtPath = "-", srtFile = "-"; int srtOffsetMs = 0; @@ -51,25 +53,28 @@ namespace Handbrake.Controls srtFile = Path.GetFileName(openFileDialog.FileName); srtLangVal = srt_lang.SelectedItem.ToString(); srtCode = srt_charcode.SelectedItem.ToString(); - srtOffsetMs = (int)srt_offset.Value; + srtOffsetMs = (int) srt_offset.Value; if (defaultSub == "Yes") SetNoSrtDefault(); - } else + } + else { if (defaultSub == "Yes") SetNoDefault(); if (burnedVal == "Yes") SetNoBurned(); if (fileContainer == 0) - burnedVal = "Yes"; // MP4 must have bitmap subs burned in. + burnedVal = "Yes"; // MP4 must have bitmap subs burned in. } if (fileContainer == 0) // MP4 and M4V file extension { // Make sure we only have 1 bitmap track. - if (drp_subtitleTracks.SelectedItem != null && drp_subtitleTracks.SelectedItem.ToString().Contains("Bitmap")) + if (drp_subtitleTracks.SelectedItem != null && + drp_subtitleTracks.SelectedItem.ToString().Contains("Bitmap")) { if (lv_subList.Items.Cast().Any(item => item.SubItems[0].Text.Contains("Bitmap"))) { - MessageBox.Show(this, "More than one vobsub is not supported in mp4... Your first vobsub track will now be used.", + MessageBox.Show(this, + "More than one vobsub is not supported in mp4... Your first vobsub track will now be used.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } @@ -77,27 +82,27 @@ namespace Handbrake.Controls } string trackName = (drp_subtitleTracks.SelectedItem.ToString().Contains(".srt")) - ? srtLangVal + " (" + srtFile + ")" - : drp_subtitleTracks.SelectedItem.ToString(); + ? srtLangVal + " (" + srtFile + ")" + : drp_subtitleTracks.SelectedItem.ToString(); SubtitleInfo track = new SubtitleInfo { - Track = trackName, - Forced = forcedVal, - Burned = burnedVal, - Default = defaultSub, - SrtLang = srtLangVal, - SrtCharCode = srtCode, - SrtOffset = srtOffsetMs, - SrtPath = srtPath, + Track = trackName, + Forced = forcedVal, + Burned = burnedVal, + Default = defaultSub, + SrtLang = srtLangVal, + SrtCharCode = srtCode, + SrtOffset = srtOffsetMs, + SrtPath = srtPath, SrtFileName = srtFile }; lv_subList.Items.Add(track.ListView); subList.Add(track); - } + private void BtnSrtAddClick(object sender, EventArgs e) { if (openFileDialog.ShowDialog() != DialogResult.OK) @@ -105,6 +110,7 @@ namespace Handbrake.Controls drp_subtitleTracks.Items.Add(Path.GetFileName(openFileDialog.FileName)); drp_subtitleTracks.SelectedItem = Path.GetFileName(openFileDialog.FileName); } + private void BtnRemoveSubTrackClick(object sender, EventArgs e) { RemoveTrack(); @@ -119,7 +125,8 @@ namespace Handbrake.Controls SubtitleInfo track = subList[lv_subList.SelectedIndices[0]]; int c = 0; - if (lv_subList.Items[lv_subList.SelectedIndices[0]].SubItems[0].Text.ToLower().Contains(".srt")) // We have an SRT + if (lv_subList.Items[lv_subList.SelectedIndices[0]].SubItems[0].Text.ToLower().Contains(".srt")) + // We have an SRT { foreach (var item in drp_subtitleTracks.Items) { @@ -133,7 +140,7 @@ namespace Handbrake.Controls check_default.CheckState = track.Default == "Yes" ? CheckState.Checked : CheckState.Unchecked; SubGroupBox.Text = "Selected Track: " + track.Track; } - else // We have Bitmap/CC + else // We have Bitmap/CC { foreach (var item in drp_subtitleTracks.Items) { @@ -144,7 +151,8 @@ namespace Handbrake.Controls check_forced.CheckState = track.Forced == "Yes" ? CheckState.Checked : CheckState.Unchecked; check_burned.CheckState = track.Burned == "Yes" ? CheckState.Checked : CheckState.Unchecked; check_default.CheckState = track.Default == "Yes" ? CheckState.Checked : CheckState.Unchecked; - SubGroupBox.Text = "Selected Track: " + lv_subList.Items[lv_subList.SelectedIndices[0]].SubItems[0].Text; + SubGroupBox.Text = "Selected Track: " + + lv_subList.Items[lv_subList.SelectedIndices[0]].SubItems[0].Text; } } else @@ -176,17 +184,20 @@ namespace Handbrake.Controls if (drp_subtitleTracks.SelectedItem.ToString().Contains(".srt")) { lv_subList.Items[lv_subList.SelectedIndices[0]].SubItems[0].Text = srt_lang.SelectedItem + "(" + - drp_subtitleTracks.SelectedItem + ")"; + drp_subtitleTracks.SelectedItem + ")"; lv_subList.Select(); - } else + } + else { lv_subList.Items[lv_subList.SelectedIndices[0]].SubItems[0].Text = drp_subtitleTracks.SelectedItem.ToString(); lv_subList.Select(); } - subList[lv_subList.SelectedIndices[0]].Track = drp_subtitleTracks.SelectedItem.ToString(); // Update SubList List + subList[lv_subList.SelectedIndices[0]].Track = drp_subtitleTracks.SelectedItem.ToString(); + // Update SubList List } + private void CheckForcedCheckedChanged(object sender, EventArgs e) { if (lv_subList.Items.Count == 0 || lv_subList.SelectedIndices.Count == 0) return; @@ -194,8 +205,10 @@ namespace Handbrake.Controls lv_subList.Items[lv_subList.SelectedIndices[0]].SubItems[1].Text = check_forced.Checked ? "Yes" : "No"; lv_subList.Select(); - subList[lv_subList.SelectedIndices[0]].Forced = check_forced.Checked ? "Yes" : "No"; // Update SubList List + subList[lv_subList.SelectedIndices[0]].Forced = check_forced.Checked ? "Yes" : "No"; + // Update SubList List } + private void CheckBurnedCheckedChanged(object sender, EventArgs e) { if (lv_subList.Items.Count == 0 || lv_subList.SelectedIndices.Count == 0) return; @@ -206,8 +219,10 @@ namespace Handbrake.Controls lv_subList.Items[lv_subList.SelectedIndices[0]].SubItems[2].Text = check_burned.Checked ? "Yes" : "No"; lv_subList.Select(); - subList[lv_subList.SelectedIndices[0]].Burned = check_burned.Checked ? "Yes" : "No"; // Update SubList List + subList[lv_subList.SelectedIndices[0]].Burned = check_burned.Checked ? "Yes" : "No"; + // Update SubList List } + private void CheckDefaultCheckedChanged(object sender, EventArgs e) { if (lv_subList.Items.Count == 0 || lv_subList.SelectedIndices.Count == 0) return; @@ -221,8 +236,10 @@ namespace Handbrake.Controls lv_subList.Items[lv_subList.SelectedIndices[0]].SubItems[3].Text = check_default.Checked ? "Yes" : "No"; lv_subList.Select(); - subList[lv_subList.SelectedIndices[0]].Default = check_default.Checked ? "Yes" : "No"; // Update SubList List + subList[lv_subList.SelectedIndices[0]].Default = check_default.Checked ? "Yes" : "No"; + // Update SubList List } + private void SrtOffsetValueChanged(object sender, EventArgs e) { // Update an item in the list if required. @@ -232,8 +249,10 @@ namespace Handbrake.Controls lv_subList.Items[lv_subList.SelectedIndices[0]].SubItems[6].Text = srt_offset.Value.ToString(); lv_subList.Select(); - subList[lv_subList.SelectedIndices[0]].SrtOffset = (int)srt_offset.Value; // Update SubList List + subList[lv_subList.SelectedIndices[0]].SrtOffset = (int) srt_offset.Value; + // Update SubList List } + private void SrtCharcodeSelectedIndexChanged(object sender, EventArgs e) { if (lv_subList.Items.Count == 0 || lv_subList.SelectedIndices.Count == 0) return; @@ -241,8 +260,10 @@ namespace Handbrake.Controls lv_subList.Items[lv_subList.SelectedIndices[0]].SubItems[5].Text = srt_charcode.SelectedItem.ToString(); lv_subList.Select(); - subList[lv_subList.SelectedIndices[0]].SrtCharCode = srt_charcode.SelectedItem.ToString(); // Update SubList List + subList[lv_subList.SelectedIndices[0]].SrtCharCode = srt_charcode.SelectedItem.ToString(); + // Update SubList List } + private void SrtLangSelectedIndexChanged(object sender, EventArgs e) { if (lv_subList.Items.Count == 0 || lv_subList.SelectedIndices.Count == 0) return; @@ -250,7 +271,8 @@ namespace Handbrake.Controls lv_subList.Items[lv_subList.SelectedIndices[0]].SubItems[4].Text = srt_lang.SelectedItem.ToString(); lv_subList.Select(); - subList[lv_subList.SelectedIndices[0]].SrtLang = srt_lang.SelectedItem.ToString(); // Update SubList List + subList[lv_subList.SelectedIndices[0]].SrtLang = srt_lang.SelectedItem.ToString(); + // Update SubList List } // Right Click Menu @@ -271,6 +293,7 @@ namespace Handbrake.Controls } } } + private void MnuMovedownClick(object sender, EventArgs e) { if (lv_subList.SelectedIndices.Count != 0) @@ -288,6 +311,7 @@ namespace Handbrake.Controls } } } + private void MnuRemoveClick(object sender, EventArgs e) { RemoveTrack(); @@ -305,7 +329,7 @@ namespace Handbrake.Controls { item.SubItems[3].Text = "No"; subList[c].Default = "No"; - } + } } c++; } @@ -330,6 +354,7 @@ namespace Handbrake.Controls c++; } } + private void SetNoBurned() { int c = 0; @@ -343,6 +368,7 @@ namespace Handbrake.Controls c++; } } + private void RemoveTrack() { // Remove the Item and reselect the control if the following conditions are met. @@ -391,7 +417,7 @@ namespace Handbrake.Controls /// Checks of the current settings will require the m4v file extension /// /// True if Yes - public Boolean RequiresM4V() + public bool RequiresM4V() { foreach (ListViewItem item in lv_subList.Items) { @@ -443,7 +469,7 @@ namespace Handbrake.Controls public void SetContainer(int value) { fileContainer = value; - Boolean trigger = false; + bool trigger = false; if (fileContainer != 1) foreach (ListViewItem item in lv_subList.Items) { @@ -498,17 +524,17 @@ namespace Handbrake.Controls { srtCount++; // SRT track id. - srtLang += srtLang == "" ? langMap[item.SrtLang] : "," + langMap[item.SrtLang]; - srtCodeset += srtCodeset == "" ? item.SrtCharCode : "," + item.SrtCharCode; + srtLang += srtLang == string.Empty ? langMap[item.SrtLang] : "," + langMap[item.SrtLang]; + srtCodeset += srtCodeset == string.Empty ? item.SrtCharCode : "," + item.SrtCharCode; if (item.Default == "Yes") srtDefault = srtCount.ToString(); itemToAdd = item.SrtPath; - srtFile += srtFile == "" ? itemToAdd : "," + itemToAdd; + srtFile += srtFile == string.Empty ? itemToAdd : "," + itemToAdd; itemToAdd = item.SrtOffset.ToString(); - srtOffset += srtOffset == "" ? itemToAdd : "," + itemToAdd; + srtOffset += srtOffset == string.Empty ? itemToAdd : "," + itemToAdd; } else // We have Bitmap or CC { @@ -523,18 +549,18 @@ namespace Handbrake.Controls itemToAdd = tempSub[0]; } - subtitleTracks += subtitleTracks == "" ? itemToAdd : "," + itemToAdd; + subtitleTracks += subtitleTracks == string.Empty ? itemToAdd : "," + itemToAdd; // Find --subtitle-forced - itemToAdd = ""; + itemToAdd = string.Empty; tempSub = item.Track.Split(' '); trackId = tempSub[0]; if (item.Forced == "Yes") itemToAdd = "scan"; - if (itemToAdd != "") - subtitleForced += subtitleForced == "" ? itemToAdd : "," + itemToAdd; + if (itemToAdd != string.Empty) + subtitleForced += subtitleForced == string.Empty ? itemToAdd : "," + itemToAdd; // Find --subtitle-burn and --subtitle-default trackId = tempSub[0]; @@ -551,32 +577,31 @@ namespace Handbrake.Controls } // Build The CLI Subtitles Query - if (subtitleTracks != "") + if (subtitleTracks != string.Empty) { query += " --subtitle " + subtitleTracks; - if (subtitleForced != "") + if (subtitleForced != string.Empty) query += " --subtitle-forced=" + subtitleForced; - if (subtitleBurn != "") + if (subtitleBurn != string.Empty) query += " --subtitle-burn=" + subtitleBurn; - if (subtitleDefault != "") + if (subtitleDefault != string.Empty) query += " --subtitle-default=" + subtitleDefault; } - if (srtFile != "") // SRTs + if (srtFile != string.Empty) // SRTs { query += " --srt-file " + "\"" + srtFile + "\""; - if (srtCodeset != "") + if (srtCodeset != string.Empty) query += " --srt-codeset " + srtCodeset; - if (srtOffset != "") + if (srtOffset != string.Empty) query += " --srt-offset " + srtOffset; - if (srtLang != "") + if (srtLang != string.Empty) query += " --srt-lang " + srtLang; - if (srtDefault != "") + if (srtDefault != string.Empty) query += " --srt-default=" + srtDefault; } - } return query; } diff --git a/win/C#/Controls/x264Panel.cs b/win/C#/Controls/x264Panel.cs index 56146a0a..27809415 100644 --- a/win/C#/Controls/x264Panel.cs +++ b/win/C#/Controls/x264Panel.cs @@ -4,11 +4,11 @@ Homepage: . It may be used under the terms of the GNU General Public License. */ -using System; -using System.Windows.Forms; - namespace Handbrake.Controls { + using System; + using System.Windows.Forms; + public partial class x264Panel : UserControl { /* @@ -17,6 +17,7 @@ namespace Handbrake.Controls */ /// + /// Initializes a new instance of the class. /// Initializes a new instance of the x264 panel user control /// public x264Panel() @@ -37,7 +38,7 @@ namespace Handbrake.Controls get { return " -x " + rtf_x264Query.Text; } set { rtf_x264Query.Text = value; } } - + /// /// Reset all components to defaults and clears the x264 rtf box /// @@ -64,7 +65,7 @@ namespace Handbrake.Controls slider_psytrellis.Value = 0; drop_adaptBFrames.SelectedIndex = 0; - rtf_x264Query.Text = ""; + rtf_x264Query.Text = string.Empty; } /// @@ -73,14 +74,14 @@ namespace Handbrake.Controls public void X264_StandardizeOptString() { /* Set widgets depending on the opt string in field */ - String thisOpt; // The separated option such as "bframes=3" - String optName; // The option name such as "bframes" - String optValue;// The option value such as "3" - String changedOptString = ""; - String[] currentOptsArray; + string thisOpt; // The separated option such as "bframes=3" + string optName; // The option name such as "bframes" + string optValue; // The option value such as "3" + string changedOptString = string.Empty; + string[] currentOptsArray; /*First, we get an opt string to process */ - String currentOptString = rtf_x264Query.Text; + string currentOptString = rtf_x264Query.Text; /*verify there is an opt string to process */ if (currentOptString.Contains("=")) @@ -97,8 +98,8 @@ namespace Handbrake.Controls if (currentOptsArray[currentOptsArrayCount - 1] == string.Empty) break; - String[] splitOptRange = thisOpt.Split('='); - if (thisOpt != "") + string[] splitOptRange = thisOpt.Split('='); + if (thisOpt != string.Empty) { if (thisOpt.Contains("=")) { @@ -132,7 +133,7 @@ namespace Handbrake.Controls } /* Change the option string to reflect the new standardized option string */ - if (changedOptString != "") + if (changedOptString != string.Empty) rtf_x264Query.Text = changedOptString; } @@ -143,9 +144,9 @@ namespace Handbrake.Controls /// /// /// - private static string X264_StandardizeOptNames(String cleanOptNameString) + private static string X264_StandardizeOptNames(string cleanOptNameString) { - String input = cleanOptNameString; + string input = cleanOptNameString; if (input.Equals("ref") || input.Equals("frameref")) cleanOptNameString = "ref"; @@ -195,13 +196,13 @@ namespace Handbrake.Controls public void X264_SetCurrentSettingsInPanel() { /* Set widgets depending on the opt string in field */ - String thisOpt; // The separated option such as "bframes=3" - String optName; // The option name such as "bframes" - String optValue;// The option value such as "3" - String[] currentOptsArray; + string thisOpt; // The separated option such as "bframes=3" + string optName; // The option name such as "bframes" + string optValue; // The option value such as "3" + string[] currentOptsArray; - //Set currentOptString to the contents of the text box. - String currentOptString = rtf_x264Query.Text.Replace("\n", ""); + // Set currentOptString to the contents of the text box. + string currentOptString = rtf_x264Query.Text.Replace("\n", string.Empty); /*verify there is an opt string to process */ if (currentOptString.Contains("=")) @@ -217,7 +218,7 @@ namespace Handbrake.Controls for (loopcounter = 0; loopcounter < currentOptsArrayCount; loopcounter++) { thisOpt = currentOptsArray[loopcounter]; - String[] splitOptRange = thisOpt.Split('='); + string[] splitOptRange = thisOpt.Split('='); if (thisOpt.Contains("=")) { @@ -282,9 +283,9 @@ namespace Handbrake.Controls if (optValue == "auto") optValue = "Automatic"; - if (optValue != "") + if (optValue != string.Empty) { - Char[] letters = optValue.ToCharArray(); + char[] letters = optValue.ToCharArray(); letters[0] = Char.ToUpper(letters[0]); optValue = new string(letters); } @@ -296,7 +297,7 @@ namespace Handbrake.Controls string alphaDeblock = splitDeblock[0]; string betaDeblock = splitDeblock[1]; - if (alphaDeblock.Equals("0") && betaDeblock.Replace("\n", "").Equals("0")) + if (alphaDeblock.Equals("0") && betaDeblock.Replace("\n", string.Empty).Equals("0")) { drop_deblockAlpha.SelectedItem = "Default (0)"; drop_deblockBeta.SelectedItem = "Default (0)"; @@ -305,7 +306,9 @@ namespace Handbrake.Controls { drop_deblockAlpha.SelectedItem = !alphaDeblock.Equals("0") ? alphaDeblock : "0"; - drop_deblockBeta.SelectedItem = !betaDeblock.Replace("\n", "").Equals("0") ? betaDeblock.Replace("\n", "") : "0"; + drop_deblockBeta.SelectedItem = !betaDeblock.Replace("\n", string.Empty).Equals("0") + ? betaDeblock.Replace("\n", string.Empty) + : "0"; } continue; case "analyse": @@ -329,9 +332,9 @@ namespace Handbrake.Controls int val, val2; // default psy-rd = 1 (10 for the slider) - psyrd = double.TryParse(x[0], out psyrd) ? psyrd * 10 : 10.0; + psyrd = double.TryParse(x[0], out psyrd) ? psyrd*10 : 10.0; // default psy-trellis = 0 - psytrellis = double.TryParse(x[1], out psytrellis) ? psytrellis * 10 : 0.0; + psytrellis = double.TryParse(x[1], out psytrellis) ? psytrellis*10 : 0.0; int.TryParse(psyrd.ToString(), out val); int.TryParse(psytrellis.ToString(), out val2); @@ -351,16 +354,17 @@ namespace Handbrake.Controls private void OnX264WidgetChange(string sender) { Animate(sender); - String optNameToChange = sender; - String currentOptString = rtf_x264Query.Text; + string optNameToChange = sender; + string currentOptString = rtf_x264Query.Text; /*First, we create a pattern to check for ":"optNameToChange"=" to modify the option if the name falls after the first character of the opt string (hence the ":") */ - String checkOptNameToChange = ":" + optNameToChange + "="; - String checkOptNameToChangeBegin = optNameToChange + "="; + string checkOptNameToChange = ":" + optNameToChange + "="; + string checkOptNameToChangeBegin = optNameToChange + "="; // IF the current H264 Option String Contains Multiple Items or Just 1 Item - if ((currentOptString.Contains(checkOptNameToChange)) || (currentOptString.StartsWith(checkOptNameToChangeBegin))) + if ((currentOptString.Contains(checkOptNameToChange)) || + (currentOptString.StartsWith(checkOptNameToChangeBegin))) HasOptions(currentOptString, optNameToChange); else // IF there is no options in the rich text box! HasNoOptions(optNameToChange); @@ -374,12 +378,12 @@ namespace Handbrake.Controls /// private void HasOptions(string currentOptString, string optNameToChange) { - String thisOpt; // The separated option such as "bframes=3" - String optName; // The option name such as "bframes" - String[] currentOptsArray; + string thisOpt; // The separated option such as "bframes=3" + string optName; // The option name such as "bframes" + string[] currentOptsArray; /* Create new empty opt string*/ - String changedOptString = ""; + string changedOptString = string.Empty; /*Put individual options into an array based on the ":" separator for processing, result is "="*/ currentOptsArray = currentOptString.Split(':'); @@ -393,7 +397,7 @@ namespace Handbrake.Controls { string[] splitOptRange = thisOpt.Split('='); - optName = splitOptRange[0]; // e.g bframes + optName = splitOptRange[0]; // e.g bframes /* * Run through the available widgets for x264 opts and set them, as you add widgets, @@ -405,14 +409,15 @@ namespace Handbrake.Controls { if (optNameToChange.Equals("deblock")) { - String da = drop_deblockAlpha.SelectedItem.ToString(); - String db = drop_deblockBeta.SelectedItem.ToString(); + string da = drop_deblockAlpha.SelectedItem.ToString(); + string db = drop_deblockBeta.SelectedItem.ToString(); - if (((da.Contains("Default")) && (db.Contains("Default"))) || ((da.Contains("0")) && (db.Contains("0")))) + if (((da.Contains("Default")) && (db.Contains("Default"))) || + ((da.Contains("0")) && (db.Contains("0")))) { drop_deblockBeta.SelectedItem = "Default (0)"; drop_deblockAlpha.SelectedItem = "Default (0)"; - thisOpt = ""; + thisOpt = string.Empty; } else if ((!da.Contains("Default")) && (db.Contains("Default"))) { @@ -430,11 +435,11 @@ namespace Handbrake.Controls else if (optNameToChange.Equals("psy-rd")) { if (slider_psyrd.Value == 10 && slider_psytrellis.Value == 0) - thisOpt = ""; + thisOpt = string.Empty; else { - double psyrd = slider_psyrd.Value * 0.1; - double psytre = slider_psytrellis.Value * 0.1; + double psyrd = slider_psyrd.Value*0.1; + double psytre = slider_psytrellis.Value*0.1; string rd = psyrd.ToString("f1"); string rt = psytre.ToString("f1"); @@ -443,19 +448,21 @@ namespace Handbrake.Controls } } else if (optNameToChange.Equals("mixed-refs")) - thisOpt = check_mixedReferences.CheckState == CheckState.Checked ? "mixed-refs=1" : "mixed-refs=0"; + thisOpt = check_mixedReferences.CheckState == CheckState.Checked + ? "mixed-refs=1" + : "mixed-refs=0"; else if (optNameToChange.Equals("weightb")) - thisOpt = check_weightedBFrames.CheckState == CheckState.Checked ? "" : "weightb=0"; + thisOpt = check_weightedBFrames.CheckState == CheckState.Checked ? string.Empty : "weightb=0"; else if (optNameToChange.Equals("b-pyramid")) - thisOpt = check_pyrmidalBFrames.CheckState == CheckState.Checked ? "b-pyramid=1" : ""; + thisOpt = check_pyrmidalBFrames.CheckState == CheckState.Checked ? "b-pyramid=1" : string.Empty; else if (optNameToChange.Equals("no-fast-pskip")) - thisOpt = check_noFastPSkip.CheckState == CheckState.Checked ? "no-fast-pskip=1" : ""; + thisOpt = check_noFastPSkip.CheckState == CheckState.Checked ? "no-fast-pskip=1" : string.Empty; else if (optNameToChange.Equals("no-dct-decimate")) - thisOpt = check_noDCTDecimate.CheckState == CheckState.Checked ? "no-dct-decimate=1" : ""; + thisOpt = check_noDCTDecimate.CheckState == CheckState.Checked ? "no-dct-decimate=1" : string.Empty; else if (optNameToChange.Equals("8x8dct")) thisOpt = check_8x8DCT.CheckState == CheckState.Checked ? "8x8dct=1" : "8x8dct=0"; else if (optNameToChange.Equals("cabac")) - thisOpt = check_Cabac.CheckState == CheckState.Checked ? "" : "cabac=0"; + thisOpt = check_Cabac.CheckState == CheckState.Checked ? string.Empty : "cabac=0"; else if (optNameToChange.Equals("me")) { switch (drop_MotionEstimationMethod.SelectedIndex) @@ -481,7 +488,7 @@ namespace Handbrake.Controls break; default: - thisOpt = ""; + thisOpt = string.Empty; break; } } @@ -506,7 +513,7 @@ namespace Handbrake.Controls break; default: - thisOpt = ""; + thisOpt = string.Empty; break; } } @@ -523,7 +530,7 @@ namespace Handbrake.Controls break; default: - thisOpt = ""; + thisOpt = string.Empty; break; } } @@ -531,47 +538,47 @@ namespace Handbrake.Controls { thisOpt = !drop_MotionEstimationRange.SelectedItem.ToString().Contains("Default") ? "merange=" + drop_MotionEstimationRange.SelectedItem - : ""; + : string.Empty; } else if (optNameToChange.Equals("b-adapt")) { thisOpt = !drop_adaptBFrames.SelectedItem.ToString().Contains("Default") ? "b-adapt=" + (drop_adaptBFrames.SelectedIndex - 1) - : ""; + : string.Empty; } else if (optNameToChange.Equals("ref")) { thisOpt = !drop_refFrames.SelectedItem.ToString().Contains("Default") ? "ref=" + drop_refFrames.SelectedItem - : ""; + : string.Empty; } else if (optNameToChange.Equals("bframes")) { - String value = drop_bFrames.SelectedItem.ToString(); + string value = drop_bFrames.SelectedItem.ToString(); thisOpt = !drop_bFrames.SelectedItem.ToString().Contains("Default") ? "bframes=" + value - : ""; + : string.Empty; } else if (optNameToChange.Equals("subq")) { - String value = drop_subpixelMotionEstimation.SelectedItem.ToString(); + string value = drop_subpixelMotionEstimation.SelectedItem.ToString(); thisOpt = !drop_subpixelMotionEstimation.SelectedItem.ToString().Contains("Default") ? "subq=" + value - : ""; + : string.Empty; } else if (optNameToChange.Equals("trellis")) { - String value = drop_trellis.SelectedItem.ToString(); + string value = drop_trellis.SelectedItem.ToString(); thisOpt = !drop_trellis.SelectedItem.ToString().Contains("Default") ? "trellis=" + value - : ""; + : string.Empty; } } } /* Construct New String for opts here */ - if (!thisOpt.Equals("")) - changedOptString = changedOptString.Equals("") ? thisOpt : changedOptString + ":" + thisOpt; + if (!thisOpt.Equals(string.Empty)) + changedOptString = changedOptString.Equals(string.Empty) ? thisOpt : changedOptString + ":" + thisOpt; } /* Change the option string to reflect the new mod settings */ @@ -586,8 +593,8 @@ namespace Handbrake.Controls /// private void HasNoOptions(IEquatable optNameToChange) { - string colon = ""; - if (rtf_x264Query.Text != "") + string colon = string.Empty; + if (rtf_x264Query.Text != string.Empty) colon = ":"; string query = rtf_x264Query.Text; @@ -669,11 +676,10 @@ namespace Handbrake.Controls int value = drop_adaptBFrames.SelectedIndex - 1; query = query + colon + "b-adapt=" + value; } - else if (optNameToChange.Equals("deblock")) { - String da = drop_deblockAlpha.SelectedItem.ToString(); - String db = drop_deblockBeta.Text; + string da = drop_deblockAlpha.SelectedItem.ToString(); + string db = drop_deblockBeta.Text; if (((da.Contains("Default")) && (db.Contains("Default"))) || ((da.Contains("0")) && (db.Contains("0")))) { @@ -694,11 +700,11 @@ namespace Handbrake.Controls else if (optNameToChange.Equals("psy-rd")) { if (slider_psyrd.Value == 10 && slider_psytrellis.Value == 0) - query += ""; + query += string.Empty; else { - double psyrd = slider_psyrd.Value * 0.1; - double psytre = slider_psytrellis.Value * 0.1; + double psyrd = slider_psyrd.Value*0.1; + double psytre = slider_psytrellis.Value*0.1; string rd = psyrd.ToString("f1"); string rt = psytre.ToString("f1"); @@ -750,13 +756,13 @@ namespace Handbrake.Controls } else if (optNameToChange.Equals("bframes")) { - String value = drop_bFrames.SelectedItem.ToString(); + string value = drop_bFrames.SelectedItem.ToString(); if (!drop_bFrames.SelectedItem.ToString().Contains("Default")) query = query + colon + "bframes=" + value; } else if (optNameToChange.Equals("subq")) { - String value = drop_subpixelMotionEstimation.SelectedItem.ToString(); + string value = drop_subpixelMotionEstimation.SelectedItem.ToString(); if (!drop_subpixelMotionEstimation.SelectedItem.ToString().Contains("Default")) query = query + colon + "subq=" + value; } @@ -784,10 +790,10 @@ namespace Handbrake.Controls - trellis (if 0, turn off psy-trel) */ - switch(sender) + switch (sender) { case "bframes": - if (drop_bFrames.SelectedIndex >0 && drop_bFrames.SelectedIndex < 2 ) + if (drop_bFrames.SelectedIndex > 0 && drop_bFrames.SelectedIndex < 2) { /* If the b-frame widget is at 0 or 1, the user has chosen not to use b-frames at all. So disable the options @@ -828,7 +834,7 @@ namespace Handbrake.Controls drop_adaptBFrames.Visible = true; lbl_adaptBFrames.Visible = true; } - break; + break; case "cabac": if (check_Cabac.Checked == false) { @@ -842,7 +848,7 @@ namespace Handbrake.Controls drop_trellis.Visible = true; lbl_trellis.Visible = true; } - break; + break; case "analyse": if (drop_analysis.SelectedIndex == 1) { @@ -853,7 +859,7 @@ namespace Handbrake.Controls } else check_8x8DCT.Visible = true; - break; + break; case "ref": if (drop_refFrames.SelectedIndex > 0 && drop_refFrames.SelectedIndex < 3) { @@ -863,8 +869,8 @@ namespace Handbrake.Controls } else check_mixedReferences.Visible = true; - break; - case "me": // Motion Estimation + break; + case "me": // Motion Estimation if (drop_MotionEstimationMethod.SelectedIndex < 3) { drop_MotionEstimationRange.Visible = false; @@ -876,9 +882,10 @@ namespace Handbrake.Controls drop_MotionEstimationRange.Visible = true; lbl_merange.Visible = true; } - break; - case "subq": // subme - if (drop_subpixelMotionEstimation.SelectedIndex != 0 && drop_subpixelMotionEstimation.SelectedIndex < 7) + break; + case "subq": // subme + if (drop_subpixelMotionEstimation.SelectedIndex != 0 && + drop_subpixelMotionEstimation.SelectedIndex < 7) { slider_psyrd.Visible = false; slider_psyrd.Value = 10; @@ -900,9 +907,9 @@ namespace Handbrake.Controls lbl_psytrellis.Visible = true; } } - break; - case "trellis": // subme - if (drop_trellis.SelectedIndex > 0 && drop_trellis.SelectedIndex < 2 ) + break; + case "trellis": // subme + if (drop_trellis.SelectedIndex > 0 && drop_trellis.SelectedIndex < 2) { slider_psytrellis.Visible = false; slider_psytrellis.Value = 0; @@ -910,21 +917,23 @@ namespace Handbrake.Controls } else { - if ((drop_subpixelMotionEstimation.SelectedIndex == 0 || drop_subpixelMotionEstimation.SelectedIndex >= 7) && check_Cabac.Checked && slider_psytrellis.Visible == false) + if ((drop_subpixelMotionEstimation.SelectedIndex == 0 || + drop_subpixelMotionEstimation.SelectedIndex >= 7) && check_Cabac.Checked && + slider_psytrellis.Visible == false) { slider_psytrellis.Visible = true; lbl_psytrellis.Visible = true; } } - break; + break; } } private void widgetControlChanged(object sender, EventArgs e) { - Control changedControlName = (Control)sender; - string controlName = ""; + Control changedControlName = (Control) sender; + string controlName = string.Empty; switch (changedControlName.Name.Trim()) { @@ -991,11 +1000,12 @@ namespace Handbrake.Controls } OnX264WidgetChange(controlName); } + private void rtf_x264Query_TextChanged(object sender, EventArgs e) { if (rtf_x264Query.Text.EndsWith("\n")) { - string query = rtf_x264Query.Text.Replace("\n", ""); + string query = rtf_x264Query.Text.Replace("\n", string.Empty); Reset2Defaults(); rtf_x264Query.Text = query; X264_StandardizeOptString(); @@ -1005,9 +1015,10 @@ namespace Handbrake.Controls Reset2Defaults(); } } + private void btn_reset_Click(object sender, EventArgs e) { - rtf_x264Query.Text = ""; + rtf_x264Query.Text = string.Empty; Reset2Defaults(); } } diff --git a/win/C#/EncodeQueue/Encode.cs b/win/C#/EncodeQueue/Encode.cs index 60f460a5..2d788b71 100644 --- a/win/C#/EncodeQueue/Encode.cs +++ b/win/C#/EncodeQueue/Encode.cs @@ -83,11 +83,11 @@ namespace Handbrake.EncodeQueue /// public void SafelyClose() { - if ((int)this.ProcessHandle == 0) + if ((int) this.ProcessHandle == 0) return; // Allow the CLI to exit cleanly - Win32.SetForegroundWindow((int)this.ProcessHandle); + Win32.SetForegroundWindow((int) this.ProcessHandle); SendKeys.Send("^C"); // HbProcess.StandardInput.AutoFlush = true; @@ -166,7 +166,7 @@ namespace Handbrake.EncodeQueue { MessageBox.Show( "It would appear that HandBrakeCLI has not started correctly. You should take a look at the Activity log as it may indicate the reason why.\n\nDetailed Error Information: error occured in runCli()\n\n" + - exc, + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); @@ -361,9 +361,9 @@ namespace Handbrake.EncodeQueue catch (Exception exc) { MessageBox.Show( - "Something went a bit wrong trying to copy your log file.\nError Information:\n\n" + exc, - "Error", - MessageBoxButtons.OK, + "Something went a bit wrong trying to copy your log file.\nError Information:\n\n" + exc, + "Error", + MessageBoxButtons.OK, MessageBoxIcon.Error); } } diff --git a/win/C#/EncodeQueue/Queue.cs b/win/C#/EncodeQueue/Queue.cs index 891c2de2..d31caf9b 100644 --- a/win/C#/EncodeQueue/Queue.cs +++ b/win/C#/EncodeQueue/Queue.cs @@ -45,6 +45,7 @@ namespace Handbrake.EncodeQueue public event EventHandler QueueCompleted; #region Queue + /// /// Gets and removes the next job in the queue. /// @@ -93,7 +94,14 @@ namespace Handbrake.EncodeQueue /// public void Add(string query, string source, string destination, bool customJob) { - Job newJob = new Job { Id = this.nextJobId++, Query = query, Source = source, Destination = destination, CustomQuery = customJob }; + Job newJob = new Job + { + Id = this.nextJobId++, + Query = query, + Source = source, + Destination = destination, + CustomQuery = customJob + }; this.queue.Add(newJob); this.WriteQueueStateToFile("hb_queue_recovery.xml"); @@ -162,7 +170,8 @@ namespace Handbrake.EncodeQueue /// The location of the file to write the queue to. public void WriteQueueStateToFile(string file) { - string appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\hb_queue_recovery.xml"); + string appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + @"HandBrake\hb_queue_recovery.xml"); string tempPath = file == "hb_queue_recovery.xml" ? appDataPath : file; try @@ -170,7 +179,7 @@ namespace Handbrake.EncodeQueue using (FileStream strm = new FileStream(tempPath, FileMode.Create, FileAccess.Write)) { if (serializer == null) - serializer = new XmlSerializer(typeof(List)); + serializer = new XmlSerializer(typeof (List)); serializer.Serialize(strm, queue); strm.Close(); strm.Dispose(); @@ -212,13 +221,15 @@ namespace Handbrake.EncodeQueue line.WriteLine(strCmdLine); } - MessageBox.Show("Your batch script has been sucessfully saved.", "Status", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); + MessageBox.Show("Your batch script has been sucessfully saved.", "Status", MessageBoxButtons.OK, + MessageBoxIcon.Asterisk); } catch (Exception) { - MessageBox.Show("Unable to write to the file. Please make sure that the location has the correct permissions for file writing.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); + MessageBox.Show( + "Unable to write to the file. Please make sure that the location has the correct permissions for file writing.", + "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); } - } } @@ -228,7 +239,8 @@ namespace Handbrake.EncodeQueue /// The location of the file to read the queue from. public void LoadQueueFromFile(string file) { - string appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\hb_queue_recovery.xml"); + string appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + @"HandBrake\hb_queue_recovery.xml"); string tempPath = file == "hb_queue_recovery.xml" ? appDataPath : file; if (File.Exists(tempPath)) @@ -238,7 +250,7 @@ namespace Handbrake.EncodeQueue if (strm.Length != 0) { if (serializer == null) - serializer = new XmlSerializer(typeof(List)); + serializer = new XmlSerializer(typeof (List)); List list = serializer.Deserialize(strm) as List; @@ -348,7 +360,8 @@ namespace Handbrake.EncodeQueue // Growl if (Properties.Settings.Default.growlEncode) - GrowlCommunicator.Notify("Encode Completed", "Put down that cocktail...\nyour Handbrake encode is done."); + GrowlCommunicator.Notify("Encode Completed", + "Put down that cocktail...\nyour Handbrake encode is done."); while (this.PauseRequested) // Need to find a better way of doing this. { diff --git a/win/C#/Functions/AppcastReader.cs b/win/C#/Functions/AppcastReader.cs index 7248ffa7..e6bd64b0 100644 --- a/win/C#/Functions/AppcastReader.cs +++ b/win/C#/Functions/AppcastReader.cs @@ -54,7 +54,9 @@ namespace Handbrake.Functions Match verShort = Regex.Match(result, @"sparkle:shortVersionString=""(([svn]*)([0-9.\s]*))\"""); this.Build = ver.ToString().Replace("sparkle:version=", string.Empty).Replace("\"", string.Empty); - this.Version = verShort.ToString().Replace("sparkle:shortVersionString=", string.Empty).Replace("\"", string.Empty); + this.Version = verShort.ToString().Replace("sparkle:shortVersionString=", string.Empty).Replace("\"", + string. + Empty); this.DownloadFile = nodeItem["windows"].InnerText; this.DescriptionUrl = new Uri(nodeItem["sparkle:releaseNotesLink"].InnerText); } diff --git a/win/C#/Functions/GrowlCommunicator.cs b/win/C#/Functions/GrowlCommunicator.cs index 04450eef..5bb5efa7 100644 --- a/win/C#/Functions/GrowlCommunicator.cs +++ b/win/C#/Functions/GrowlCommunicator.cs @@ -6,10 +6,7 @@ namespace Handbrake.Functions { using System; - using System.Collections.Generic; - using System.Text; using Growl.Connector; - using Growl.CoreLibrary; /// /// Provides all functionality for communicating with Growl for Windows. @@ -35,7 +32,8 @@ namespace Handbrake.Functions /// /// Notification shown upon completion of encoding /// - private static NotificationType encodeOrQueueCompleted = new NotificationType("EncodeOrQueue", "HandBrake Status"); + private static NotificationType encodeOrQueueCompleted = new NotificationType("EncodeOrQueue", + "HandBrake Status"); /// /// Checks to see if Growl is currently running on the local machine. @@ -60,7 +58,7 @@ namespace Handbrake.Functions public static void Register() { Initialize(); - growl.Register(application, new NotificationType[] { encodeOrQueueCompleted }); + growl.Register(application, new[] {encodeOrQueueCompleted}); } /// @@ -75,7 +73,8 @@ namespace Handbrake.Functions /// public static void Notify(string title, string text) { - Notification notification = new Notification(application.Name, encodeOrQueueCompleted.Name, String.Empty, title, text); + Notification notification = new Notification(application.Name, encodeOrQueueCompleted.Name, String.Empty, + title, text); growl.Notify(notification); } @@ -89,9 +88,10 @@ namespace Handbrake.Functions /// The notification image as a url public static void Notify(NotificationType notificationType, string title, string text, string imageUrl) { - Notification notification = new Notification(application.Name, notificationType.Name, String.Empty, title, text) + Notification notification = new Notification(application.Name, notificationType.Name, String.Empty, title, + text) { - Icon = imageUrl + Icon = imageUrl }; growl.Notify(notification); @@ -116,4 +116,4 @@ namespace Handbrake.Functions } } } -} +} \ No newline at end of file diff --git a/win/C#/Functions/Main.cs b/win/C#/Functions/Main.cs index 96550706..758abdcc 100644 --- a/win/C#/Functions/Main.cs +++ b/win/C#/Functions/Main.cs @@ -16,6 +16,7 @@ namespace Handbrake.Functions using System.Xml.Serialization; using EncodeQueue; using Model; + using Parsing; /// /// Useful functions which various screens can use. @@ -25,7 +26,7 @@ namespace Handbrake.Functions /// /// The XML Serializer /// - private static readonly XmlSerializer Ser = new XmlSerializer(typeof(List)); + private static readonly XmlSerializer Ser = new XmlSerializer(typeof (List)); /// /// Calculate the duration of the selected title and chapters @@ -42,7 +43,7 @@ namespace Handbrake.Functions /// /// The calculated duration. /// - public static TimeSpan CalculateDuration(int chapterStart, int chapterEnd, Parsing.Title selectedTitle) + public static TimeSpan CalculateDuration(int chapterStart, int chapterEnd, Title selectedTitle) { TimeSpan duration = TimeSpan.FromSeconds(0.0); chapterStart++; @@ -65,12 +66,12 @@ namespace Handbrake.Functions /// /// The longest title. /// - public static Parsing.Title SelectLongestTitle(Parsing.DVD source) + public static Title SelectLongestTitle(DVD source) { TimeSpan longestDurationFound = TimeSpan.FromSeconds(0.0); - Parsing.Title returnTitle = null; + Title returnTitle = null; - foreach (Parsing.Title item in source.Titles) + foreach (Title item in source.Titles) { if (item.Duration > longestDurationFound) { @@ -105,8 +106,8 @@ namespace Handbrake.Functions int n = dataChpt.Rows.Add(); dataChpt.Rows[n].Cells[0].Value = i + 1; dataChpt.Rows[n].Cells[1].Value = "Chapter " + (i + 1); - dataChpt.Rows[n].Cells[0].ValueType = typeof(int); - dataChpt.Rows[n].Cells[1].ValueType = typeof(string); + dataChpt.Rows[n].Cells[0].ValueType = typeof (int); + dataChpt.Rows[n].Cells[1].ValueType = typeof (string); i++; } @@ -151,7 +152,7 @@ namespace Handbrake.Functions foreach (DataGridViewRow item in dataChpt.Rows) { string name; - chapterMap.TryGetValue((int)item.Cells[0].Value, out name); + chapterMap.TryGetValue((int) item.Cells[0].Value, out name); item.Cells[1].Value = name ?? "Chapter " + item.Cells[0].Value; } @@ -192,7 +193,9 @@ namespace Handbrake.Functions if (Properties.Settings.Default.autoNameFormat != string.Empty) { destinationFilename = Properties.Settings.Default.autoNameFormat; - destinationFilename = destinationFilename.Replace("{source}", sourceName).Replace("{title}", dvdTitle).Replace("{chapters}", combinedChapterTag); + destinationFilename = + destinationFilename.Replace("{source}", sourceName).Replace("{title}", dvdTitle).Replace( + "{chapters}", combinedChapterTag); } else destinationFilename = sourceName + "_T" + dvdTitle + "_C" + combinedChapterTag; @@ -200,7 +203,8 @@ namespace Handbrake.Functions // Add the appropriate file extension if (mainWindow.drop_format.SelectedIndex == 0) { - if (Properties.Settings.Default.useM4v || mainWindow.Check_ChapterMarkers.Checked || mainWindow.AudioSettings.RequiresM4V() || mainWindow.Subtitles.RequiresM4V()) + if (Properties.Settings.Default.useM4v || mainWindow.Check_ChapterMarkers.Checked || + mainWindow.AudioSettings.RequiresM4V() || mainWindow.Subtitles.RequiresM4V()) destinationFilename += ".m4v"; else destinationFilename += ".mp4"; @@ -213,7 +217,8 @@ namespace Handbrake.Functions if (!mainWindow.text_destination.Text.Contains(Path.DirectorySeparatorChar.ToString())) { // If there is an auto name path, use it... - if (Properties.Settings.Default.autoNamePath.Trim() != string.Empty && Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location") + if (Properties.Settings.Default.autoNamePath.Trim() != string.Empty && + Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location") autoNamePath = Path.Combine(Properties.Settings.Default.autoNamePath, destinationFilename); else // ...otherwise, output to the source directory autoNamePath = null; @@ -221,10 +226,12 @@ namespace Handbrake.Functions else // Otherwise, use the path that is already there. { // Use the path and change the file extension to match the previous destination - autoNamePath = Path.Combine(Path.GetDirectoryName(mainWindow.text_destination.Text), destinationFilename); + autoNamePath = Path.Combine(Path.GetDirectoryName(mainWindow.text_destination.Text), + destinationFilename); if (Path.HasExtension(mainWindow.text_destination.Text)) - autoNamePath = Path.ChangeExtension(autoNamePath, Path.GetExtension(mainWindow.text_destination.Text)); + autoNamePath = Path.ChangeExtension(autoNamePath, + Path.GetExtension(mainWindow.text_destination.Text)); } } @@ -250,9 +257,9 @@ namespace Handbrake.Functions Process cliProcess = new Process(); ProcessStartInfo handBrakeCli = new ProcessStartInfo("HandBrakeCLI.exe", " -u -v0") { - UseShellExecute = false, - RedirectStandardError = true, - RedirectStandardOutput = true, + UseShellExecute = false, + RedirectStandardError = true, + RedirectStandardOutput = true, CreateNoWindow = true }; cliProcess.StartInfo = handBrakeCli; @@ -272,7 +279,8 @@ namespace Handbrake.Functions if (m.Success) { - string data = line.Replace("(", string.Empty).Replace(")", string.Empty).Replace("HandBrake ", string.Empty); + string data = line.Replace("(", string.Empty).Replace(")", string.Empty).Replace("HandBrake ", + string.Empty); string[] arr = data.Split(' '); Properties.Settings.Default.hb_build = int.Parse(arr[1]); @@ -314,7 +322,8 @@ namespace Handbrake.Functions { try { - string tempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\hb_queue_recovery.xml"); + string tempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + @"HandBrake\hb_queue_recovery.xml"); if (File.Exists(tempPath)) { using (FileStream strm = new FileStream(tempPath, FileMode.Open, FileAccess.Read)) @@ -354,7 +363,8 @@ namespace Handbrake.Functions { hbProcesses = Process.GetProcessesByName("HandBrakeCLI"); duration = DateTime.Now - startTime; - if (duration.Seconds > 5 && hbProcesses.Length == 0) // Make sure we don't wait forever if the process doesn't start + if (duration.Seconds > 5 && hbProcesses.Length == 0) + // Make sure we don't wait forever if the process doesn't start return -1; } @@ -394,7 +404,8 @@ namespace Handbrake.Functions FileInfo[] logFiles = info.GetFiles("*.txt"); foreach (FileInfo file in logFiles) { - if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") && !file.Name.Contains("tmp_appReadable_log.txt")) + if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") && + !file.Name.Contains("tmp_appReadable_log.txt")) File.Delete(file.FullName); } } @@ -415,7 +426,8 @@ namespace Handbrake.Functions { if (file.LastWriteTime < DateTime.Now.AddDays(-30)) { - if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") && !file.Name.Contains("tmp_appReadable_log.txt")) + if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") && + !file.Name.Contains("tmp_appReadable_log.txt")) File.Delete(file.FullName); } } @@ -464,7 +476,7 @@ namespace Handbrake.Functions UpdateCheckInformation info = new UpdateCheckInformation { - NewVersionAvailable = false, + NewVersionAvailable = false, BuildInformation = null }; callback(new UpdateCheckResult(debug, info)); @@ -479,14 +491,18 @@ namespace Handbrake.Functions UpdateCheckInformation info2 = new UpdateCheckInformation { - NewVersionAvailable = latest > current, + NewVersionAvailable = latest > current, BuildInformation = reader }; callback(new UpdateCheckResult(debug, info2)); } catch (Exception exc) { - callback(new UpdateCheckResult(debug, new UpdateCheckInformation{Error = exc})); + callback(new UpdateCheckResult(debug, + new UpdateCheckInformation + { + Error = exc + })); } })); } @@ -502,7 +518,7 @@ namespace Handbrake.Functions /// public static UpdateCheckInformation EndCheckForUpdates(IAsyncResult result) { - UpdateCheckResult checkResult = (UpdateCheckResult)result; + UpdateCheckResult checkResult = (UpdateCheckResult) result; return checkResult.Result; } @@ -514,191 +530,191 @@ namespace Handbrake.Functions { IDictionary languageMap = new Dictionary { - {"Any", "und"}, - {"Afar", "aar"}, - {"Abkhazian", "abk"}, - {"Afrikaans", "afr"}, - {"Akan", "aka"}, - {"Albanian", "sqi"}, - {"Amharic", "amh"}, - {"Arabic", "ara"}, - {"Aragonese", "arg"}, - {"Armenian", "hye"}, - {"Assamese", "asm"}, - {"Avaric", "ava"}, - {"Avestan", "ave"}, - {"Aymara", "aym"}, - {"Azerbaijani", "aze"}, - {"Bashkir", "bak"}, - {"Bambara", "bam"}, - {"Basque", "eus"}, - {"Belarusian", "bel"}, - {"Bengali", "ben"}, - {"Bihari", "bih"}, - {"Bislama", "bis"}, - {"Bosnian", "bos"}, - {"Breton", "bre"}, - {"Bulgarian", "bul"}, - {"Burmese", "mya"}, - {"Catalan", "cat"}, - {"Chamorro", "cha"}, - {"Chechen", "che"}, - {"Chinese", "zho"}, - {"Church Slavic", "chu"}, - {"Chuvash", "chv"}, - {"Cornish", "cor"}, - {"Corsican", "cos"}, - {"Cree", "cre"}, - {"Czech", "ces"}, - {"Dansk", "dan"}, - {"Divehi", "div"}, - {"Nederlands", "nld"}, - {"Dzongkha", "dzo"}, - {"English", "eng"}, - {"Esperanto", "epo"}, - {"Estonian", "est"}, - {"Ewe", "ewe"}, - {"Faroese", "fao"}, - {"Fijian", "fij"}, - {"Suomi", "fin"}, - {"Francais", "fra"}, - {"Western Frisian", "fry"}, - {"Fulah", "ful"}, - {"Georgian", "kat"}, - {"Deutsch", "deu"}, - {"Gaelic (Scots)", "gla"}, - {"Irish", "gle"}, - {"Galician", "glg"}, - {"Manx", "glv"}, - {"Greek Modern", "ell"}, - {"Guarani", "grn"}, - {"Gujarati", "guj"}, - {"Haitian", "hat"}, - {"Hausa", "hau"}, - {"Hebrew", "heb"}, - {"Herero", "her"}, - {"Hindi", "hin"}, - {"Hiri Motu", "hmo"}, - {"Magyar", "hun"}, - {"Igbo", "ibo"}, - {"Islenska", "isl"}, - {"Ido", "ido"}, - {"Sichuan Yi", "iii"}, - {"Inuktitut", "iku"}, - {"Interlingue", "ile"}, - {"Interlingua", "ina"}, - {"Indonesian", "ind"}, - {"Inupiaq", "ipk"}, - {"Italiano", "ita"}, - {"Javanese", "jav"}, - {"Japanese", "jpn"}, - {"Kalaallisut", "kal"}, - {"Kannada", "kan"}, - {"Kashmiri", "kas"}, - {"Kanuri", "kau"}, - {"Kazakh", "kaz"}, - {"Central Khmer", "khm"}, - {"Kikuyu", "kik"}, - {"Kinyarwanda", "kin"}, - {"Kirghiz", "kir"}, - {"Komi", "kom"}, - {"Kongo", "kon"}, - {"Korean", "kor"}, - {"Kuanyama", "kua"}, - {"Kurdish", "kur"}, - {"Lao", "lao"}, - {"Latin", "lat"}, - {"Latvian", "lav"}, - {"Limburgan", "lim"}, - {"Lingala", "lin"}, - {"Lithuanian", "lit"}, - {"Luxembourgish", "ltz"}, - {"Luba-Katanga", "lub"}, - {"Ganda", "lug"}, - {"Macedonian", "mkd"}, - {"Marshallese", "mah"}, - {"Malayalam", "mal"}, - {"Maori", "mri"}, - {"Marathi", "mar"}, - {"Malay", "msa"}, - {"Malagasy", "mlg"}, - {"Maltese", "mlt"}, - {"Moldavian", "mol"}, - {"Mongolian", "mon"}, - {"Nauru", "nau"}, - {"Navajo", "nav"}, - {"Ndebele, South", "nbl"}, - {"Ndebele, North", "nde"}, - {"Ndonga", "ndo"}, - {"Nepali", "nep"}, - {"Norwegian Nynorsk", "nno"}, - {"Norwegian Bokmål", "nob"}, - {"Norsk", "nor"}, - {"Chichewa; Nyanja", "nya"}, - {"Occitan", "oci"}, - {"Ojibwa", "oji"}, - {"Oriya", "ori"}, - {"Oromo", "orm"}, - {"Ossetian", "oss"}, - {"Panjabi", "pan"}, - {"Persian", "fas"}, - {"Pali", "pli"}, - {"Polish", "pol"}, - {"Portugues", "por"}, - {"Pushto", "pus"}, - {"Quechua", "que"}, - {"Romansh", "roh"}, - {"Romanian", "ron"}, - {"Rundi", "run"}, - {"Russian", "rus"}, - {"Sango", "sag"}, - {"Sanskrit", "san"}, - {"Serbian", "srp"}, - {"Hrvatski", "hrv"}, - {"Sinhala", "sin"}, - {"Slovak", "slk"}, - {"Slovenian", "slv"}, - {"Northern Sami", "sme"}, - {"Samoan", "smo"}, - {"Shona", "sna"}, - {"Sindhi", "snd"}, - {"Somali", "som"}, - {"Sotho Southern", "sot"}, - {"Espanol", "spa"}, - {"Sardinian", "srd"}, - {"Swati", "ssw"}, - {"Sundanese", "sun"}, - {"Swahili", "swa"}, - {"Svenska", "swe"}, - {"Tahitian", "tah"}, - {"Tamil", "tam"}, - {"Tatar", "tat"}, - {"Telugu", "tel"}, - {"Tajik", "tgk"}, - {"Tagalog", "tgl"}, - {"Thai", "tha"}, - {"Tibetan", "bod"}, - {"Tigrinya", "tir"}, - {"Tonga", "ton"}, - {"Tswana", "tsn"}, - {"Tsonga", "tso"}, - {"Turkmen", "tuk"}, - {"Turkish", "tur"}, - {"Twi", "twi"}, - {"Uighur", "uig"}, - {"Ukrainian", "ukr"}, - {"Urdu", "urd"}, - {"Uzbek", "uzb"}, - {"Venda", "ven"}, - {"Vietnamese", "vie"}, - {"Volapük", "vol"}, - {"Welsh", "cym"}, - {"Walloon", "wln"}, - {"Wolof", "wol"}, - {"Xhosa", "xho"}, - {"Yiddish", "yid"}, - {"Yoruba", "yor"}, - {"Zhuang", "zha"}, + {"Any", "und"}, + {"Afar", "aar"}, + {"Abkhazian", "abk"}, + {"Afrikaans", "afr"}, + {"Akan", "aka"}, + {"Albanian", "sqi"}, + {"Amharic", "amh"}, + {"Arabic", "ara"}, + {"Aragonese", "arg"}, + {"Armenian", "hye"}, + {"Assamese", "asm"}, + {"Avaric", "ava"}, + {"Avestan", "ave"}, + {"Aymara", "aym"}, + {"Azerbaijani", "aze"}, + {"Bashkir", "bak"}, + {"Bambara", "bam"}, + {"Basque", "eus"}, + {"Belarusian", "bel"}, + {"Bengali", "ben"}, + {"Bihari", "bih"}, + {"Bislama", "bis"}, + {"Bosnian", "bos"}, + {"Breton", "bre"}, + {"Bulgarian", "bul"}, + {"Burmese", "mya"}, + {"Catalan", "cat"}, + {"Chamorro", "cha"}, + {"Chechen", "che"}, + {"Chinese", "zho"}, + {"Church Slavic", "chu"}, + {"Chuvash", "chv"}, + {"Cornish", "cor"}, + {"Corsican", "cos"}, + {"Cree", "cre"}, + {"Czech", "ces"}, + {"Dansk", "dan"}, + {"Divehi", "div"}, + {"Nederlands", "nld"}, + {"Dzongkha", "dzo"}, + {"English", "eng"}, + {"Esperanto", "epo"}, + {"Estonian", "est"}, + {"Ewe", "ewe"}, + {"Faroese", "fao"}, + {"Fijian", "fij"}, + {"Suomi", "fin"}, + {"Francais", "fra"}, + {"Western Frisian", "fry"}, + {"Fulah", "ful"}, + {"Georgian", "kat"}, + {"Deutsch", "deu"}, + {"Gaelic (Scots)", "gla"}, + {"Irish", "gle"}, + {"Galician", "glg"}, + {"Manx", "glv"}, + {"Greek Modern", "ell"}, + {"Guarani", "grn"}, + {"Gujarati", "guj"}, + {"Haitian", "hat"}, + {"Hausa", "hau"}, + {"Hebrew", "heb"}, + {"Herero", "her"}, + {"Hindi", "hin"}, + {"Hiri Motu", "hmo"}, + {"Magyar", "hun"}, + {"Igbo", "ibo"}, + {"Islenska", "isl"}, + {"Ido", "ido"}, + {"Sichuan Yi", "iii"}, + {"Inuktitut", "iku"}, + {"Interlingue", "ile"}, + {"Interlingua", "ina"}, + {"Indonesian", "ind"}, + {"Inupiaq", "ipk"}, + {"Italiano", "ita"}, + {"Javanese", "jav"}, + {"Japanese", "jpn"}, + {"Kalaallisut", "kal"}, + {"Kannada", "kan"}, + {"Kashmiri", "kas"}, + {"Kanuri", "kau"}, + {"Kazakh", "kaz"}, + {"Central Khmer", "khm"}, + {"Kikuyu", "kik"}, + {"Kinyarwanda", "kin"}, + {"Kirghiz", "kir"}, + {"Komi", "kom"}, + {"Kongo", "kon"}, + {"Korean", "kor"}, + {"Kuanyama", "kua"}, + {"Kurdish", "kur"}, + {"Lao", "lao"}, + {"Latin", "lat"}, + {"Latvian", "lav"}, + {"Limburgan", "lim"}, + {"Lingala", "lin"}, + {"Lithuanian", "lit"}, + {"Luxembourgish", "ltz"}, + {"Luba-Katanga", "lub"}, + {"Ganda", "lug"}, + {"Macedonian", "mkd"}, + {"Marshallese", "mah"}, + {"Malayalam", "mal"}, + {"Maori", "mri"}, + {"Marathi", "mar"}, + {"Malay", "msa"}, + {"Malagasy", "mlg"}, + {"Maltese", "mlt"}, + {"Moldavian", "mol"}, + {"Mongolian", "mon"}, + {"Nauru", "nau"}, + {"Navajo", "nav"}, + {"Ndebele, South", "nbl"}, + {"Ndebele, North", "nde"}, + {"Ndonga", "ndo"}, + {"Nepali", "nep"}, + {"Norwegian Nynorsk", "nno"}, + {"Norwegian Bokmål", "nob"}, + {"Norsk", "nor"}, + {"Chichewa; Nyanja", "nya"}, + {"Occitan", "oci"}, + {"Ojibwa", "oji"}, + {"Oriya", "ori"}, + {"Oromo", "orm"}, + {"Ossetian", "oss"}, + {"Panjabi", "pan"}, + {"Persian", "fas"}, + {"Pali", "pli"}, + {"Polish", "pol"}, + {"Portugues", "por"}, + {"Pushto", "pus"}, + {"Quechua", "que"}, + {"Romansh", "roh"}, + {"Romanian", "ron"}, + {"Rundi", "run"}, + {"Russian", "rus"}, + {"Sango", "sag"}, + {"Sanskrit", "san"}, + {"Serbian", "srp"}, + {"Hrvatski", "hrv"}, + {"Sinhala", "sin"}, + {"Slovak", "slk"}, + {"Slovenian", "slv"}, + {"Northern Sami", "sme"}, + {"Samoan", "smo"}, + {"Shona", "sna"}, + {"Sindhi", "snd"}, + {"Somali", "som"}, + {"Sotho Southern", "sot"}, + {"Espanol", "spa"}, + {"Sardinian", "srd"}, + {"Swati", "ssw"}, + {"Sundanese", "sun"}, + {"Swahili", "swa"}, + {"Svenska", "swe"}, + {"Tahitian", "tah"}, + {"Tamil", "tam"}, + {"Tatar", "tat"}, + {"Telugu", "tel"}, + {"Tajik", "tgk"}, + {"Tagalog", "tgl"}, + {"Thai", "tha"}, + {"Tibetan", "bod"}, + {"Tigrinya", "tir"}, + {"Tonga", "ton"}, + {"Tswana", "tsn"}, + {"Tsonga", "tso"}, + {"Turkmen", "tuk"}, + {"Turkish", "tur"}, + {"Twi", "twi"}, + {"Uighur", "uig"}, + {"Ukrainian", "ukr"}, + {"Urdu", "urd"}, + {"Uzbek", "uzb"}, + {"Venda", "ven"}, + {"Vietnamese", "vie"}, + {"Volapük", "vol"}, + {"Welsh", "cym"}, + {"Walloon", "wln"}, + {"Wolof", "wol"}, + {"Xhosa", "xho"}, + {"Yiddish", "yid"}, + {"Yoruba", "yor"}, + {"Zhuang", "zha"}, {"Zulu", "zul"} }; return languageMap; @@ -714,11 +730,12 @@ namespace Handbrake.Functions DriveInfo[] theCollectionOfDrives = DriveInfo.GetDrives(); foreach (DriveInfo curDrive in theCollectionOfDrives) { - if (curDrive.DriveType == DriveType.CDRom && curDrive.IsReady && File.Exists(curDrive.RootDirectory + "VIDEO_TS\\VIDEO_TS.IFO")) + if (curDrive.DriveType == DriveType.CDRom && curDrive.IsReady && + File.Exists(curDrive.RootDirectory + "VIDEO_TS\\VIDEO_TS.IFO")) { drives.Add(new DriveInformation { - VolumeLabel = curDrive.VolumeLabel, + VolumeLabel = curDrive.VolumeLabel, RootDirectory = curDrive.RootDirectory + "VIDEO_TS" }); } diff --git a/win/C#/Functions/PresetLoader.cs b/win/C#/Functions/PresetLoader.cs index a550bfa1..95d09e5f 100644 --- a/win/C#/Functions/PresetLoader.cs +++ b/win/C#/Functions/PresetLoader.cs @@ -33,6 +33,7 @@ namespace Handbrake.Functions public static void LoadPreset(frmMain mainWindow, QueryParser presetQuery, string name, bool pictureSettings) { #region Source + // Reset some vaules to stock first to prevent errors. mainWindow.check_iPodAtom.CheckState = CheckState.Unchecked; @@ -70,7 +71,9 @@ namespace Handbrake.Functions mainWindow.check_iPodAtom.CheckState = presetQuery.IpodAtom ? CheckState.Checked : CheckState.Unchecked; - mainWindow.check_optimiseMP4.CheckState = presetQuery.OptimizeMP4 ? CheckState.Checked : CheckState.Unchecked; + mainWindow.check_optimiseMP4.CheckState = presetQuery.OptimizeMP4 + ? CheckState.Checked + : CheckState.Unchecked; mainWindow.check_largeFile.CheckState = presetQuery.LargeMP4 ? CheckState.Checked : CheckState.Unchecked; @@ -79,6 +82,7 @@ namespace Handbrake.Functions #endregion #region Picture + mainWindow.PictureSettings.check_autoCrop.Checked = true; if (pictureSettings) // only Load picture settings if the perset requires it { @@ -102,7 +106,9 @@ namespace Handbrake.Functions mainWindow.PictureSettings.drp_anamorphic.SelectedIndex = presetQuery.AnamorphicMode; // Keep Aspect Ration Anamorphic Setting. - mainWindow.PictureSettings.check_KeepAR.CheckState = presetQuery.KeepDisplayAsect ? CheckState.Checked : CheckState.Unchecked; + mainWindow.PictureSettings.check_KeepAR.CheckState = presetQuery.KeepDisplayAsect + ? CheckState.Checked + : CheckState.Unchecked; // Set the Width and height as Required. if (presetQuery.Width != 0) @@ -130,7 +136,9 @@ namespace Handbrake.Functions // Aspect Ratio for non anamorphic sources if (presetQuery.AnamorphicMode == 0) - mainWindow.PictureSettings.check_KeepAR.CheckState = presetQuery.Height == 0 ? CheckState.Checked : CheckState.Unchecked; + mainWindow.PictureSettings.check_KeepAR.CheckState = presetQuery.Height == 0 + ? CheckState.Checked + : CheckState.Unchecked; // Custom Anamorphic Controls mainWindow.PictureSettings.updownDisplayWidth.Text = presetQuery.DisplayWidthValue.ToString(); @@ -141,15 +149,18 @@ namespace Handbrake.Functions #endregion #region Filters + mainWindow.Filters.SetDecomb(presetQuery.Decomb); mainWindow.Filters.SetDeInterlace(presetQuery.DeInterlace); mainWindow.Filters.SetDeNoise(presetQuery.DeNoise); mainWindow.Filters.SetDeTelecine(presetQuery.DeTelecine); mainWindow.Filters.SetDeBlock(presetQuery.DeBlock); mainWindow.Filters.SetGrayScale(presetQuery.Grayscale); + #endregion #region Video + mainWindow.drp_videoEncoder.Text = presetQuery.VideoEncoder; if (presetQuery.AverageVideoBitrate != null) @@ -175,9 +186,9 @@ namespace Handbrake.Functions double x264Step = cqStep; double presetValue = presetQuery.VideoQuality; - double x = 51 / x264Step; + double x = 51/x264Step; - double calculated = presetValue / x264Step; + double calculated = presetValue/x264Step; calculated = x - calculated; int.TryParse(calculated.ToString(), out value); @@ -222,14 +233,18 @@ namespace Handbrake.Functions #endregion #region Audio + mainWindow.AudioSettings.LoadTracks(presetQuery.AudioInformation); + #endregion #region Other + mainWindow.x264Panel.X264Query = presetQuery.H264Query; // Set the preset name mainWindow.labelPreset.Text = "Output Settings (Preset: " + name + ")"; + #endregion } } diff --git a/win/C#/Functions/QueryGenerator.cs b/win/C#/Functions/QueryGenerator.cs index 592640f7..c1cadfd7 100644 --- a/win/C#/Functions/QueryGenerator.cs +++ b/win/C#/Functions/QueryGenerator.cs @@ -37,8 +37,9 @@ namespace Handbrake.Functions public static string GenerateCliQuery(frmMain mainWindow, int mode, int duration, string preview) { string query = string.Empty; - - if (!string.IsNullOrEmpty(mainWindow.sourcePath) && mainWindow.sourcePath.Trim() != "Select \"Source\" to continue") + + if (!string.IsNullOrEmpty(mainWindow.sourcePath) && + mainWindow.sourcePath.Trim() != "Select \"Source\" to continue") query = " -i " + '"' + mainWindow.sourcePath + '"'; if (mainWindow.drp_dvdtitle.Text != string.Empty) @@ -54,10 +55,13 @@ namespace Handbrake.Functions switch (mode) { case 0: // Chapters - if (mainWindow.drop_chapterFinish.Text == mainWindow.drop_chapterStart.Text && mainWindow.drop_chapterStart.Text != string.Empty) + if (mainWindow.drop_chapterFinish.Text == mainWindow.drop_chapterStart.Text && + mainWindow.drop_chapterStart.Text != string.Empty) query += string.Format(" -c {0}", mainWindow.drop_chapterStart.Text); - else if (mainWindow.drop_chapterStart.Text != string.Empty && mainWindow.drop_chapterFinish.Text != string.Empty) - query += string.Format(" -c {0}-{1}", mainWindow.drop_chapterStart.Text, mainWindow.drop_chapterFinish.Text); + else if (mainWindow.drop_chapterStart.Text != string.Empty && + mainWindow.drop_chapterFinish.Text != string.Empty) + query += string.Format(" -c {0}-{1}", mainWindow.drop_chapterStart.Text, + mainWindow.drop_chapterFinish.Text); break; case 1: // Seconds int start, end; @@ -65,14 +69,16 @@ namespace Handbrake.Functions int.TryParse(mainWindow.drop_chapterFinish.Text, out end); int calculatedDuration = end - start; - query += string.Format(" --start-at duration:{0} --stop-at duration:{1}", mainWindow.drop_chapterStart.Text, calculatedDuration); + query += string.Format(" --start-at duration:{0} --stop-at duration:{1}", + mainWindow.drop_chapterStart.Text, calculatedDuration); break; case 2: // Frames int.TryParse(mainWindow.drop_chapterStart.Text, out start); int.TryParse(mainWindow.drop_chapterFinish.Text, out end); calculatedDuration = end - start; - query += string.Format(" --start-at frame:{0} --stop-at frame:{1}", mainWindow.drop_chapterStart.Text, calculatedDuration); + query += string.Format(" --start-at frame:{0} --stop-at frame:{1}", + mainWindow.drop_chapterStart.Text, calculatedDuration); break; case 3: // Preview query += " --previews " + Properties.Settings.Default.previewScanCount + " "; @@ -80,7 +86,8 @@ namespace Handbrake.Functions query += " --stop-at duration:" + duration + " "; if (mainWindow.text_destination.Text != string.Empty) - query += string.Format(" -o \"{0}\" ", mainWindow.text_destination.Text.Replace(".m", "_sample.m")); + query += string.Format(" -o \"{0}\" ", + mainWindow.text_destination.Text.Replace(".m", "_sample.m")); break; default: break; @@ -103,6 +110,7 @@ namespace Handbrake.Functions string query = string.Empty; #region Output Settings Box + query += " -f " + mainWindow.drop_format.Text.ToLower().Replace(" file", string.Empty); // These are output settings features @@ -114,6 +122,7 @@ namespace Handbrake.Functions if (mainWindow.check_optimiseMP4.Checked) query += " -O "; + #endregion #region Picture Settings Tab @@ -122,7 +131,8 @@ namespace Handbrake.Functions if (mainWindow.PictureSettings.PresetMaximumResolution.Width == 0) { if (mainWindow.PictureSettings.text_width.Value != 0) - if (mainWindow.PictureSettings.drp_anamorphic.SelectedIndex != 1) // Prevent usage for strict anamorphic + if (mainWindow.PictureSettings.drp_anamorphic.SelectedIndex != 1) + // Prevent usage for strict anamorphic query += " -w " + mainWindow.PictureSettings.text_width.Text; } else @@ -137,13 +147,16 @@ namespace Handbrake.Functions { if (mainWindow.PictureSettings.text_height.Value != 0) if (mainWindow.PictureSettings.text_height.Text != string.Empty) - if (mainWindow.PictureSettings.drp_anamorphic.SelectedIndex == 0 || mainWindow.PictureSettings.drp_anamorphic.SelectedIndex == 3) // Prevent usage for strict anamorphic + if (mainWindow.PictureSettings.drp_anamorphic.SelectedIndex == 0 || + mainWindow.PictureSettings.drp_anamorphic.SelectedIndex == 3) + // Prevent usage for strict anamorphic query += " -l " + mainWindow.PictureSettings.text_height.Text; } else { if (mainWindow.PictureSettings.text_height.Value != 0) - if (mainWindow.PictureSettings.drp_anamorphic.SelectedIndex == 0 || mainWindow.PictureSettings.drp_anamorphic.SelectedIndex == 3) + if (mainWindow.PictureSettings.drp_anamorphic.SelectedIndex == 0 || + mainWindow.PictureSettings.drp_anamorphic.SelectedIndex == 3) query += " -Y " + mainWindow.PictureSettings.text_height.Text; } @@ -193,10 +206,13 @@ namespace Handbrake.Functions query += " --keep-display-aspect "; if (!mainWindow.PictureSettings.check_KeepAR.Checked) - if (mainWindow.PictureSettings.updownParWidth.Text != string.Empty && mainWindow.PictureSettings.updownParHeight.Text != string.Empty) - query += " --pixel-aspect " + mainWindow.PictureSettings.updownParWidth.Text + ":" + mainWindow.PictureSettings.updownParHeight.Text + " "; + if (mainWindow.PictureSettings.updownParWidth.Text != string.Empty && + mainWindow.PictureSettings.updownParHeight.Text != string.Empty) + query += " --pixel-aspect " + mainWindow.PictureSettings.updownParWidth.Text + ":" + + mainWindow.PictureSettings.updownParHeight.Text + " "; break; } + #endregion // Filters Panel @@ -240,7 +256,7 @@ namespace Handbrake.Functions break; case "H.264 (x264)": CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US"); - value = 51 - mainWindow.slider_videoQuality.Value * cqStep; + value = 51 - mainWindow.slider_videoQuality.Value*cqStep; value = Math.Round(value, 2); query += " -q " + value.ToString(culture); break; @@ -259,6 +275,7 @@ namespace Handbrake.Functions if (mainWindow.drp_videoFramerate.Text != "Same as source") query += " -r " + mainWindow.drp_videoFramerate.Text; + #endregion #region Audio Settings Tab @@ -417,8 +434,8 @@ namespace Handbrake.Functions // This is for the queue. It allows different chapter name files for each title. string[] destName = mainWindow.text_destination.Text.Split('\\'); string dest_name = destName[destName.Length - 1]; - dest_name = dest_name.Replace("\"", ""); - dest_name = dest_name.Replace(".mp4", "").Replace(".m4v", "").Replace(".mkv", ""); + dest_name = dest_name.Replace("\"", string.Empty); + dest_name = dest_name.Replace(".mp4", string.Empty).Replace(".m4v", string.Empty).Replace(".mkv", string.Empty); string sourceTitle = mainWindow.drp_dvdtitle.Text; string[] titlesplit = sourceTitle.Split(' '); @@ -440,12 +457,14 @@ namespace Handbrake.Functions else query += " -m"; } + #endregion // X264 Panel query += " -x " + mainWindow.x264Panel.X264Query; #region Processors / Other + string processors = Properties.Settings.Default.Processors; if (processors != "Automatic") query += " -C " + processors + " "; @@ -454,6 +473,7 @@ namespace Handbrake.Functions if (Properties.Settings.Default.noDvdNav) query += " --no-dvdnav"; + #endregion return query; @@ -540,7 +560,9 @@ namespace Handbrake.Functions } catch (Exception exc) { - MessageBox.Show("Unable to save Chapter Makrers file! \nChapter marker names will NOT be saved in your encode \n\n" + exc, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); + MessageBox.Show( + "Unable to save Chapter Makrers file! \nChapter marker names will NOT be saved in your encode \n\n" + + exc, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } } diff --git a/win/C#/Functions/QueryParser.cs b/win/C#/Functions/QueryParser.cs index 216d114a..9d5b9a9e 100644 --- a/win/C#/Functions/QueryParser.cs +++ b/win/C#/Functions/QueryParser.cs @@ -4,15 +4,15 @@ Homepage: . It may be used under the terms of the GNU General Public License. */ -using System; -using System.Globalization; -using System.Text.RegularExpressions; -using System.Windows.Forms; -using System.Collections; -using Handbrake.Model; - namespace Handbrake.Functions { + using System; + using System.Collections; + using System.Globalization; + using System.Text.RegularExpressions; + using System.Windows.Forms; + using Model; + public class QueryParser { private static readonly CultureInfo Culture = new CultureInfo("en-US", false); @@ -26,9 +26,9 @@ namespace Handbrake.Functions // Output Settings public string Format { get; set; } - public Boolean LargeMP4 { get; set; } - public Boolean IpodAtom { get; set; } - public Boolean OptimizeMP4 { get; set; } + public bool LargeMP4 { get; set; } + public bool IpodAtom { get; set; } + public bool OptimizeMP4 { get; set; } // Picture Settings public int Width { get; set; } @@ -41,7 +41,7 @@ namespace Handbrake.Functions public string CropLeft { get; set; } public string CropRight { get; set; } public int AnamorphicMode { get; set; } - public Boolean KeepDisplayAsect { get; set; } + public bool KeepDisplayAsect { get; set; } public double DisplayWidthValue { get; set; } public int PixelAspectWidth { get; set; } public int PixelAspectHeight { get; set; } @@ -56,9 +56,9 @@ namespace Handbrake.Functions // Video Settings public string VideoEncoder { get; set; } - public Boolean Grayscale { get; set; } - public Boolean TwoPass { get; set; } - public Boolean TurboFirstPass { get; set; } + public bool Grayscale { get; set; } + public bool TwoPass { get; set; } + public bool TurboFirstPass { get; set; } public string VideoFramerate { get; set; } public string AverageVideoBitrate { get; set; } public string VideoTargetSize { get; set; } @@ -67,23 +67,23 @@ namespace Handbrake.Functions // Audio Settings public ArrayList AudioInformation { get; set; } public string Subtitles { get; set; } - public Boolean ForcedSubtitles { get; set; } + public bool ForcedSubtitles { get; set; } // Chapter Markers - public Boolean ChapterMarkers { get; set; } + public bool ChapterMarkers { get; set; } // Other public string H264Query { get; set; } - public Boolean Verbose { get; set; } + public bool Verbose { get; set; } // Preset Information public int PresetBuildNumber { get; set; } public string PresetDescription { get; set; } public string PresetName { get; set; } public string Type { get; set; } - public Boolean UsesMaxPictureSettings { get; set; } - public Boolean UsesPictureFilters { get; set; } - public Boolean UsesPictureSettings { get; set; } + public bool UsesMaxPictureSettings { get; set; } + public bool UsesPictureFilters { get; set; } + public bool UsesPictureSettings { get; set; } #endregion @@ -93,23 +93,23 @@ namespace Handbrake.Functions /// /// A ClI Query /// A Parsed Query - public static QueryParser Parse(String input) + public static QueryParser Parse(string input) { var thisQuery = new QueryParser(); #region Regular Expressions - //Source + // Source Match title = Regex.Match(input, @"-t ([0-9]*)"); Match chapters = Regex.Match(input, @"-c ([0-9-]*)"); - //Output Settings + // Output Settings Match format = Regex.Match(input, @"-f ([a-z0-9a-z0-9a-z0-9]*)"); Match grayscale = Regex.Match(input, @" -g"); Match largerMp4 = Regex.Match(input, @" -4"); Match ipodAtom = Regex.Match(input, @" -I"); - //Picture Settings Tab + // Picture Settings Tab Match width = Regex.Match(input, @"-w ([0-9]*)"); Match height = Regex.Match(input, @"-l ([0-9]*)"); Match maxWidth = Regex.Match(input, @"-X ([0-9]*)"); @@ -134,7 +134,7 @@ namespace Handbrake.Functions Match detelecine = Regex.Match(input, @"--detelecine"); Match detelecineValue = Regex.Match(input, @" --detelecine=\""([a-zA-Z0-9.:]*)\"""); - //Video Settings Tab + // Video Settings Tab Match videoEncoder = Regex.Match(input, @"-e ([a-zA-Z0-9]*)"); Match videoFramerate = Regex.Match(input, @"-r ([0-9.]*)"); Match videoBitrate = Regex.Match(input, @"-b ([0-9]*)"); @@ -144,13 +144,13 @@ namespace Handbrake.Functions Match turboFirstPass = Regex.Match(input, @" -T"); Match optimizeMP4 = Regex.Match(input, @" -O"); - //Audio Settings Tab + // Audio Settings Tab Match noAudio = Regex.Match(input, @"-a none"); Match audioTracks = Regex.Match(input, @"-a ([0-9,]*)"); Match audioTrackMixes = Regex.Match(input, @"-6 ([0-9a-zA-Z,]*)"); Match audioEncoders = Regex.Match(input, @"-E ([a-zA-Z0-9+,]*)"); - Match audioBitrates = Regex.Match(input, @"-B ([0-9a-zA-Z,]*)"); // Auto = a-z - Match audioSampleRates = Regex.Match(input, @"-R ([0-9a-zA-Z.,]*)"); // Auto = a-z + Match audioBitrates = Regex.Match(input, @"-B ([0-9a-zA-Z,]*)"); // Auto = a-z + Match audioSampleRates = Regex.Match(input, @"-R ([0-9a-zA-Z.,]*)"); // Auto = a-z Match drcValues = Regex.Match(input, @"-D ([0-9.,]*)"); Match subtitles = Regex.Match(input, @"-s ([0-9a-zA-Z]*)"); @@ -161,10 +161,10 @@ namespace Handbrake.Functions Match chapterMarkers = Regex.Match(input, @" -m"); Match chapterMarkersFileMode = Regex.Match(input, @"--markers"); - //H264 Tab + // H264 Tab Match x264 = Regex.Match(input, @"-x ([.,/a-zA-Z0-9=:-]*)"); - //Program Options + // Program Options Match verbose = Regex.Match(input, @" -v"); #endregion @@ -176,11 +176,11 @@ namespace Handbrake.Functions #region Source Tab if (title.Success) - thisQuery.DVDTitle = int.Parse(title.ToString().Replace("-t ", "")); + thisQuery.DVDTitle = int.Parse(title.ToString().Replace("-t ", string.Empty)); if (chapters.Success) { - string[] actTitles = chapters.ToString().Replace("-c ", "").Split('-'); + string[] actTitles = chapters.ToString().Replace("-c ", string.Empty).Split('-'); thisQuery.DVDChapterStart = int.Parse(actTitles[0]); if (actTitles.Length > 1) { @@ -190,12 +190,13 @@ namespace Handbrake.Functions if ((thisQuery.DVDChapterStart == 1) && (thisQuery.DVDChapterFinish == 0)) thisQuery.DVDChapterFinish = thisQuery.DVDChapterStart; } + #endregion #region Output Settings if (format.Success) - thisQuery.Format = format.ToString().Replace("-f ", ""); + thisQuery.Format = format.ToString().Replace("-f ", string.Empty); thisQuery.LargeMP4 = largerMp4.Success; thisQuery.IpodAtom = ipodAtom.Success; thisQuery.OptimizeMP4 = optimizeMP4.Success; @@ -205,20 +206,20 @@ namespace Handbrake.Functions #region Picture Tab if (width.Success) - thisQuery.Width = int.Parse(width.Groups[0].Value.Replace("-w ", "")); + thisQuery.Width = int.Parse(width.Groups[0].Value.Replace("-w ", string.Empty)); if (height.Success) - thisQuery.Height = int.Parse(height.Groups[0].Value.Replace("-l ", "")); + thisQuery.Height = int.Parse(height.Groups[0].Value.Replace("-l ", string.Empty)); if (maxWidth.Success) - thisQuery.MaxWidth = int.Parse(maxWidth.Groups[0].Value.Replace("-X ", "")); + thisQuery.MaxWidth = int.Parse(maxWidth.Groups[0].Value.Replace("-X ", string.Empty)); if (maxHeight.Success) - thisQuery.MaxHeight = int.Parse(maxHeight.Groups[0].Value.Replace("-Y ", "")); + thisQuery.MaxHeight = int.Parse(maxHeight.Groups[0].Value.Replace("-Y ", string.Empty)); if (crop.Success) { - thisQuery.CropValues = crop.ToString().Replace("--crop ", ""); + thisQuery.CropValues = crop.ToString().Replace("--crop ", string.Empty); string[] actCropValues = thisQuery.CropValues.Split(':'); thisQuery.CropTop = actCropValues[0]; thisQuery.CropBottom = actCropValues[1]; @@ -238,17 +239,17 @@ namespace Handbrake.Functions thisQuery.KeepDisplayAsect = keepDisplayAsect.Success; if (displayWidth.Success) - thisQuery.DisplayWidthValue = double.Parse(displayWidth.Groups[0].Value.Replace("--display-width ", "")); + thisQuery.DisplayWidthValue = + double.Parse(displayWidth.Groups[0].Value.Replace("--display-width ", string.Empty)); if (pixelAspect.Success) - thisQuery.PixelAspectWidth = int.Parse(pixelAspect.Groups[1].Value.Replace("--pixel-aspect ", "")); + thisQuery.PixelAspectWidth = int.Parse(pixelAspect.Groups[1].Value.Replace("--pixel-aspect ", string.Empty)); - if (pixelAspect.Success && pixelAspect.Groups.Count >=3) - thisQuery.PixelAspectHeight = int.Parse(pixelAspect.Groups[2].Value.Replace("--pixel-aspect ", "")); + if (pixelAspect.Success && pixelAspect.Groups.Count >= 3) + thisQuery.PixelAspectHeight = int.Parse(pixelAspect.Groups[2].Value.Replace("--pixel-aspect ", string.Empty)); if (modulus.Success) - thisQuery.AnamorphicModulus = int.Parse(modulus.Groups[0].Value.Replace("--modulus ", "")); - + thisQuery.AnamorphicModulus = int.Parse(modulus.Groups[0].Value.Replace("--modulus ", string.Empty)); #endregion @@ -259,31 +260,33 @@ namespace Handbrake.Functions { thisQuery.Decomb = "Default"; if (decombValue.Success) - thisQuery.Decomb = decombValue.ToString().Replace("--decomb=", "").Replace("\"", ""); + thisQuery.Decomb = decombValue.ToString().Replace("--decomb=", string.Empty).Replace("\"", string.Empty); } thisQuery.DeInterlace = "Off"; if (deinterlace.Success) { - thisQuery.DeInterlace = deinterlace.ToString().Replace("--deinterlace=", "").Replace("\"", ""); - thisQuery.DeInterlace = thisQuery.DeInterlace.Replace("fast", "Fast").Replace("slow", "Slow").Replace("slower", "Slower"); + thisQuery.DeInterlace = deinterlace.ToString().Replace("--deinterlace=", string.Empty).Replace("\"", string.Empty); + thisQuery.DeInterlace = + thisQuery.DeInterlace.Replace("fast", "Fast").Replace("slow", "Slow").Replace("slower", "Slower"); thisQuery.DeInterlace = thisQuery.DeInterlace.Replace("slowest", "Slowest"); } thisQuery.DeNoise = "Off"; if (denoise.Success) { - thisQuery.DeNoise = denoise.ToString().Replace("--denoise=", "").Replace("\"", ""); - thisQuery.DeNoise = thisQuery.DeNoise.Replace("weak", "Weak").Replace("medium", "Medium").Replace("strong", "Strong"); + thisQuery.DeNoise = denoise.ToString().Replace("--denoise=", string.Empty).Replace("\"", string.Empty); + thisQuery.DeNoise = + thisQuery.DeNoise.Replace("weak", "Weak").Replace("medium", "Medium").Replace("strong", "Strong"); } - string deblockValue = ""; + string deblockValue = string.Empty; thisQuery.DeBlock = 0; if (deblock.Success) - deblockValue = deblock.ToString().Replace("--deblock=", ""); + deblockValue = deblock.ToString().Replace("--deblock=", string.Empty); int dval = 0; - if (deblockValue != "") + if (deblockValue != string.Empty) int.TryParse(deblockValue, out dval); thisQuery.DeBlock = dval; @@ -292,14 +295,14 @@ namespace Handbrake.Functions { thisQuery.DeTelecine = "Default"; if (detelecineValue.Success) - thisQuery.DeTelecine = detelecineValue.ToString().Replace("--detelecine=", "").Replace("\"", ""); + thisQuery.DeTelecine = detelecineValue.ToString().Replace("--detelecine=", string.Empty).Replace("\"", string.Empty); } #endregion #region Video Settings Tab - string videoEncoderConvertion = videoEncoder.ToString().Replace("-e ", ""); + string videoEncoderConvertion = videoEncoder.ToString().Replace("-e ", string.Empty); switch (videoEncoderConvertion) { case "ffmpeg": @@ -316,31 +319,35 @@ namespace Handbrake.Functions break; } thisQuery.VideoEncoder = videoEncoderConvertion; - thisQuery.VideoFramerate = videoFramerate.Success ? videoFramerate.ToString().Replace("-r ", "") : "Same as source"; + thisQuery.VideoFramerate = videoFramerate.Success + ? videoFramerate.ToString().Replace("-r ", string.Empty) + : "Same as source"; thisQuery.Grayscale = grayscale.Success; thisQuery.TwoPass = twoPass.Success; thisQuery.TurboFirstPass = turboFirstPass.Success; if (videoBitrate.Success) - thisQuery.AverageVideoBitrate = videoBitrate.ToString().Replace("-b ", ""); + thisQuery.AverageVideoBitrate = videoBitrate.ToString().Replace("-b ", string.Empty); if (videoFilesize.Success) - thisQuery.VideoTargetSize = videoFilesize.ToString().Replace("-S ", ""); + thisQuery.VideoTargetSize = videoFilesize.ToString().Replace("-S ", string.Empty); if (videoQuality.Success) { - float qConvert = float.Parse(videoQuality.ToString().Replace("-q ", ""), Culture); + float qConvert = float.Parse(videoQuality.ToString().Replace("-q ", string.Empty), Culture); thisQuery.VideoQuality = qConvert; - } + } else thisQuery.VideoQuality = -1; + #endregion #region Audio Tab + // Find out how many tracks we need to add by checking how many encoders or audio tracks are selected. int encoderCount = 0; if (audioEncoders.Success) { - string[] audioDataCounters = audioEncoders.ToString().Replace("-E ", "").Split(','); + string[] audioDataCounters = audioEncoders.ToString().Replace("-E ", string.Empty).Split(','); encoderCount = audioDataCounters.Length; } @@ -353,17 +360,17 @@ namespace Handbrake.Functions string[] trackDRCvalues = null; if (audioTracks.Success) - trackData = audioTracks.ToString().Replace("-a ", "").Split(','); + trackData = audioTracks.ToString().Replace("-a ", string.Empty).Split(','); if (audioTrackMixes.Success) - trackMixes = audioTrackMixes.ToString().Replace("-6 ", "").Split(','); + trackMixes = audioTrackMixes.ToString().Replace("-6 ", string.Empty).Split(','); if (audioEncoders.Success) - trackEncoders = audioEncoders.ToString().Replace("-E ", "").Split(','); + trackEncoders = audioEncoders.ToString().Replace("-E ", string.Empty).Split(','); if (audioBitrates.Success) - trackBitrates = audioBitrates.ToString().Replace("-B ", "").Split(','); + trackBitrates = audioBitrates.ToString().Replace("-B ", string.Empty).Split(','); if (audioSampleRates.Success) - trackSamplerates = audioSampleRates.ToString().Replace("-R ", "").Split(','); + trackSamplerates = audioSampleRates.ToString().Replace("-R ", string.Empty).Split(','); if (drcValues.Success) - trackDRCvalues = drcValues.ToString().Replace("-D ", "").Split(','); + trackDRCvalues = drcValues.ToString().Replace("-D ", string.Empty).Split(','); // Create new Audio Track Classes and store them in the ArrayList ArrayList allAudioTrackInfo = new ArrayList(); @@ -371,27 +378,27 @@ namespace Handbrake.Functions { AudioTrack track = new AudioTrack(); if (trackData != null) - if (trackData.Length >= (x + 1)) // Audio Track + if (trackData.Length >= (x + 1)) // Audio Track track.Track = trackData[x].Trim(); if (trackMixes != null) - if (trackMixes.Length >= (x + 1)) // Audio Mix + if (trackMixes.Length >= (x + 1)) // Audio Mix track.MixDown = GetMixDown(trackMixes[x].Trim()); if (trackEncoders != null) - if (trackEncoders.Length >= (x + 1)) // Audio Mix + if (trackEncoders.Length >= (x + 1)) // Audio Mix track.Encoder = GetAudioEncoder(trackEncoders[x].Trim()); if (trackBitrates != null) - if (trackBitrates.Length >= (x + 1)) // Audio Encoder + if (trackBitrates.Length >= (x + 1)) // Audio Encoder track.Bitrate = trackBitrates[x].Trim() == "auto" ? "Auto" : trackBitrates[x].Trim(); if (trackSamplerates != null) - if (trackSamplerates.Length >= (x + 1)) // Audio SampleRate + if (trackSamplerates.Length >= (x + 1)) // Audio SampleRate track.SampleRate = trackSamplerates[x].Trim() == "0" ? "Auto" : trackSamplerates[x].Trim(); if (trackDRCvalues != null) - if (trackDRCvalues.Length >= (x + 1)) // Audio DRC Values + if (trackDRCvalues.Length >= (x + 1)) // Audio DRC Values track.DRC = trackDRCvalues[x].Trim(); allAudioTrackInfo.Add(track); @@ -400,22 +407,25 @@ namespace Handbrake.Functions // Subtitle Stuff if (subtitles.Success) - thisQuery.Subtitles = subtitles.ToString().Replace("-s ", ""); + thisQuery.Subtitles = subtitles.ToString().Replace("-s ", string.Empty); else thisQuery.Subtitles = subScan.Success ? "Autoselect" : "None"; thisQuery.ForcedSubtitles = forcedSubtitles.Success; + #endregion #region Chapters Tab + if (chapterMarkersFileMode.Success || chapterMarkers.Success) thisQuery.ChapterMarkers = true; + #endregion #region H.264 and other if (x264.Success) - thisQuery.H264Query = x264.ToString().Replace("-x ", ""); + thisQuery.H264Query = x264.ToString().Replace("-x ", string.Empty); thisQuery.Verbose = verbose.Success; diff --git a/win/C#/Functions/Scan.cs b/win/C#/Functions/Scan.cs index 124f2309..78d15856 100644 --- a/win/C#/Functions/Scan.cs +++ b/win/C#/Functions/Scan.cs @@ -113,7 +113,8 @@ namespace Handbrake.Functions this.ScanStared(this, new EventArgs()); string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe"); - string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs"; + string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + + "\\HandBrake\\logs"; string dvdInfoPath = Path.Combine(logDir, "last_scan_log.txt"); // Make we don't pick up a stale last_encode_log.txt (and that we have rights to the file) @@ -125,18 +126,18 @@ namespace Handbrake.Functions dvdnav = " --no-dvdnav"; this.hbProc = new Process - { - StartInfo = - { - FileName = handbrakeCLIPath, - Arguments = - String.Format(@" -i ""{0}"" -t{1} {2} -v ", sourcePath, title, dvdnav), - RedirectStandardOutput = true, - RedirectStandardError = true, - UseShellExecute = false, - CreateNoWindow = true - } - }; + { + StartInfo = + { + FileName = handbrakeCLIPath, + Arguments = + String.Format(@" -i ""{0}"" -t{1} {2} -v ", sourcePath, title, dvdnav), + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true + } + }; this.hbProc.Start(); this.readData = new Parser(this.hbProc.StandardError.BaseStream); diff --git a/win/C#/Functions/System.cs b/win/C#/Functions/System.cs index 1af1170a..212579eb 100644 --- a/win/C#/Functions/System.cs +++ b/win/C#/Functions/System.cs @@ -25,7 +25,7 @@ namespace Handbrake.Functions Win32.GlobalMemoryStatus(ref memStatus); uint memoryInfo = memStatus.dwTotalPhys; - memoryInfo = memoryInfo / 1024 / 1024; + memoryInfo = memoryInfo/1024/1024; return memoryInfo; } @@ -54,4 +54,4 @@ namespace Handbrake.Functions get { return Screen.PrimaryScreen; } } } -} +} \ No newline at end of file diff --git a/win/C#/Model/DriveInformation.cs b/win/C#/Model/DriveInformation.cs index 8db3ed8f..d71d3a8e 100644 --- a/win/C#/Model/DriveInformation.cs +++ b/win/C#/Model/DriveInformation.cs @@ -20,4 +20,4 @@ namespace Handbrake.Model /// public string RootDirectory { get; set; } } -} +} \ No newline at end of file diff --git a/win/C#/Model/SourceType.cs b/win/C#/Model/SourceType.cs index 4cc8b416..2081ce98 100644 --- a/win/C#/Model/SourceType.cs +++ b/win/C#/Model/SourceType.cs @@ -13,21 +13,21 @@ namespace Handbrake.Model /// /// No Source Selected /// - None = 0, + None = 0, /// /// The soruce selected is a folder /// - Folder, + Folder, /// /// The source selected is a DVD drive /// - DvdDrive, + DvdDrive, /// /// The source selected is a Video File /// VideoFile } -} +} \ No newline at end of file diff --git a/win/C#/Parsing/AudioTrack.cs b/win/C#/Parsing/AudioTrack.cs index 56a35194..a28e0173 100644 --- a/win/C#/Parsing/AudioTrack.cs +++ b/win/C#/Parsing/AudioTrack.cs @@ -4,13 +4,13 @@ Homepage: . It may be used under the terms of the GNU General Public License. */ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text.RegularExpressions; - namespace Handbrake.Parsing { + using System; + using System.Collections.Generic; + using System.IO; + using System.Text.RegularExpressions; + /// /// An object represending an AudioTrack associated with a Title, in a DVD /// @@ -74,7 +74,7 @@ namespace Handbrake.Parsing public string ISO639_2 { - get { return m_iso639_2; } + get { return m_iso639_2; } } /// @@ -85,13 +85,13 @@ namespace Handbrake.Parsing { if (m_subFormat == null) return string.Format("{0} {1} ({2})", m_trackNumber, m_language, m_format); - + return string.Format("{0} {1} ({2}) ({3})", m_trackNumber, m_language, m_format, m_subFormat); } public static AudioTrack Parse(StringReader output) { - String audio_track = output.ReadLine(); + string audio_track = output.ReadLine(); Match m = Regex.Match(audio_track, @"^ \+ ([0-9]*), ([A-Za-z0-9]*) \((.*)\) \((.*)\)"); Match track = Regex.Match(audio_track, @"^ \+ ([0-9]*), ([A-Za-z0-9]*) \((.*)\)"); // ID and Language Match iso639_2 = Regex.Match(audio_track, @"iso639-2: ([a-zA-Z]*)\)"); @@ -99,24 +99,25 @@ namespace Handbrake.Parsing Match bitrate = Regex.Match(audio_track, @"([0-9]*)bps"); string subformat = m.Groups[4].Value.Trim().Contains("iso639") ? null : m.Groups[4].Value; - string samplerateVal = samplerate.Success ? samplerate.Groups[0].Value.Replace("Hz", "").Trim() : "0"; - string bitrateVal = bitrate.Success ? bitrate.Groups[0].Value.Replace("bps", "").Trim() : "0"; + string samplerateVal = samplerate.Success ? samplerate.Groups[0].Value.Replace("Hz", string.Empty).Trim() : "0"; + string bitrateVal = bitrate.Success ? bitrate.Groups[0].Value.Replace("bps", string.Empty).Trim() : "0"; if (track.Success) { var thisTrack = new AudioTrack - { - m_trackNumber = int.Parse(track.Groups[1].Value.Trim()), - m_language = track.Groups[2].Value, - m_format = m.Groups[3].Value, - m_subFormat = subformat, - m_frequency = int.Parse(samplerateVal), - m_bitrate = int.Parse(bitrateVal), - m_iso639_2 = iso639_2.Value.Replace("iso639-2: ", "").Replace(")", "") - }; - return thisTrack; + { + m_trackNumber = int.Parse(track.Groups[1].Value.Trim()), + m_language = track.Groups[2].Value, + m_format = m.Groups[3].Value, + m_subFormat = subformat, + m_frequency = int.Parse(samplerateVal), + m_bitrate = int.Parse(bitrateVal), + m_iso639_2 = + iso639_2.Value.Replace("iso639-2: ", string.Empty).Replace(")", string.Empty) + }; + return thisTrack; } - + return null; } diff --git a/win/C#/Parsing/Chapter.cs b/win/C#/Parsing/Chapter.cs index 1bf38f4d..31d57aa2 100644 --- a/win/C#/Parsing/Chapter.cs +++ b/win/C#/Parsing/Chapter.cs @@ -4,13 +4,13 @@ Homepage: . It may be used under the terms of the GNU General Public License. */ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text.RegularExpressions; - namespace Handbrake.Parsing { + using System; + using System.Collections.Generic; + using System.IO; + using System.Text.RegularExpressions; + /// /// An object representing a Chapter aosciated with a Title, in a DVD /// @@ -47,13 +47,13 @@ namespace Handbrake.Parsing public static Chapter Parse(StringReader output) { - Match m = Regex.Match(output.ReadLine(), + Match m = Regex.Match(output.ReadLine(), @"^ \+ ([0-9]*): cells ([0-9]*)->([0-9]*), ([0-9]*) blocks, duration ([0-9]{2}:[0-9]{2}:[0-9]{2})"); if (m.Success) { var thisChapter = new Chapter { - m_chapterNumber = int.Parse(m.Groups[1].Value.Trim()), + m_chapterNumber = int.Parse(m.Groups[1].Value.Trim()), m_duration = TimeSpan.Parse(m.Groups[5].Value) }; return thisChapter; diff --git a/win/C#/Parsing/DVD.cs b/win/C#/Parsing/DVD.cs index 31fe2de1..348da319 100644 --- a/win/C#/Parsing/DVD.cs +++ b/win/C#/Parsing/DVD.cs @@ -4,11 +4,11 @@ Homepage: . It may be used under the terms of the GNU General Public License. */ -using System.Collections.Generic; -using System.IO; - namespace Handbrake.Parsing { + using System.Collections.Generic; + using System.IO; + /// /// An object representing a scanned DVD /// @@ -17,6 +17,7 @@ namespace Handbrake.Parsing private readonly List m_titles; /// <summary> + /// Initializes a new instance of the <see cref="DVD"/> class. /// Default constructor for this object /// </summary> public DVD() diff --git a/win/C#/Parsing/Parser.cs b/win/C#/Parsing/Parser.cs index 2fc4e632..e643d3bd 100644 --- a/win/C#/Parsing/Parser.cs +++ b/win/C#/Parsing/Parser.cs @@ -4,14 +4,14 @@ Homepage: <http://handbrake.fr>. It may be used under the terms of the GNU General Public License. */ -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System; -using System.Globalization; - namespace Handbrake.Parsing { + using System; + using System.Globalization; + using System.IO; + using System.Text; + using System.Text.RegularExpressions; + /// <summary> /// A delegate to handle custom events regarding data being parsed from the buffer /// </summary> @@ -37,7 +37,9 @@ namespace Handbrake.Parsing /// <param name="CurrentFps">The current encoding fps</param> /// <param name="AverageFps">The average encoding fps for this task</param> /// <param name="TimeRemaining">The estimated time remaining for this task to complete</param> - public delegate void EncodeProgressEventHandler(object Sender, int CurrentTask, int TaskCount, float PercentComplete, float CurrentFps, float AverageFps, TimeSpan TimeRemaining); + public delegate void EncodeProgressEventHandler( + object Sender, int CurrentTask, int TaskCount, float PercentComplete, float CurrentFps, float AverageFps, + TimeSpan TimeRemaining); /// <summary> @@ -45,16 +47,14 @@ namespace Handbrake.Parsing /// </summary> internal class Parser : StreamReader { - private StringBuilder _buffer = new StringBuilder(""); + private StringBuilder _buffer = new StringBuilder(string.Empty); + /// <summary> /// The output from the CLI process /// </summary> - public String Buffer + public string Buffer { - get - { - return _buffer.ToString(); - } + get { return _buffer.ToString(); } } /// <summary> @@ -73,16 +73,21 @@ namespace Handbrake.Parsing public event ScanProgressEventHandler OnScanProgress; #region Experimetnal Code + /// <summary> /// Raised upon the catching of a "Scanning title # of #..." in the stream /// </summary> public event EncodeProgressEventHandler OnEncodeProgress; + #endregion /// <summary> + /// Initializes a new instance of the <see cref="Parser"/> class. /// Default constructor for this object /// </summary> - /// <param name="baseStream">The stream to parse from</param> + /// <param name="baseStream"> + /// The stream to parse from + /// </param> public Parser(Stream baseStream) : base(baseStream) { @@ -128,7 +133,8 @@ namespace Handbrake.Parsing CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US"); string tmp = base.ReadLine(); - Match m = Regex.Match(tmp, @"^Encoding: task ([0-9]*) of ([0-9]*), ([0-9]*\.[0-9]*) %( \(([0-9]*\.[0-9]*) fps, avg ([0-9]*\.[0-9]*) fps, ETA ([0-9]{2})h([0-9]{2})m([0-9]{2})s\))?"); + Match m = Regex.Match(tmp, + @"^Encoding: task ([0-9]*) of ([0-9]*), ([0-9]*\.[0-9]*) %( \(([0-9]*\.[0-9]*) fps, avg ([0-9]*\.[0-9]*) fps, ETA ([0-9]{2})h([0-9]{2})m([0-9]{2})s\))?"); if (m.Success && OnEncodeProgress != null) { int currentTask = int.Parse(m.Groups[1].Value); @@ -145,4 +151,4 @@ namespace Handbrake.Parsing } } } -} +} \ No newline at end of file diff --git a/win/C#/Parsing/Subtitle.cs b/win/C#/Parsing/Subtitle.cs index a765f1de..178e4470 100644 --- a/win/C#/Parsing/Subtitle.cs +++ b/win/C#/Parsing/Subtitle.cs @@ -4,12 +4,12 @@ Homepage: <http://handbrake.fr>. It may be used under the terms of the GNU General Public License. */ -using System.Collections.Generic; -using System.IO; -using System.Text.RegularExpressions; - namespace Handbrake.Parsing { + using System.Collections.Generic; + using System.IO; + using System.Text.RegularExpressions; + /// <summary> /// An object that represents a subtitle associated with a Title, in a DVD /// </summary> @@ -72,9 +72,9 @@ namespace Handbrake.Parsing { var thisSubtitle = new Subtitle { - m_trackNumber = int.Parse(m.Groups[1].Value.Trim()), - m_language = m.Groups[2].Value, - m_typecode = m.Groups[3].Value, + m_trackNumber = int.Parse(m.Groups[1].Value.Trim()), + m_language = m.Groups[2].Value, + m_typecode = m.Groups[3].Value, m_type = m.Groups[4].Value }; return thisSubtitle; diff --git a/win/C#/Parsing/Title.cs b/win/C#/Parsing/Title.cs index e13858fd..764c7cdb 100644 --- a/win/C#/Parsing/Title.cs +++ b/win/C#/Parsing/Title.cs @@ -4,15 +4,15 @@ Homepage: <http://handbrake.fr>. It may be used under the terms of the GNU General Public License. */ -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Globalization; -using System.IO; -using System.Text.RegularExpressions; - namespace Handbrake.Parsing { + using System; + using System.Collections.Generic; + using System.Drawing; + using System.Globalization; + using System.IO; + using System.Text.RegularExpressions; + /// <summary> /// An object that represents a single Title of a DVD /// </summary> @@ -22,7 +22,7 @@ namespace Handbrake.Parsing private readonly List<AudioTrack> m_audioTracks; private readonly List<Chapter> m_chapters; private readonly List<Subtitle> m_subtitles; - private List<String> m_angles = new List<string>(); + private List<string> m_angles = new List<string>(); private float m_aspectRatio; private float m_fps; private int[] m_autoCrop; @@ -31,8 +31,9 @@ namespace Handbrake.Parsing private Size m_resolution; private int m_titleNumber; private Size m_parVal; - + /// <summary> + /// Initializes a new instance of the <see cref="Title"/> class. /// The constructor for this object /// </summary> public Title() @@ -79,7 +80,7 @@ namespace Handbrake.Parsing /// </summary> public string SourceName { - get { return source; } + get { return source; } } /// <summary> @@ -142,14 +143,14 @@ namespace Handbrake.Parsing { get { return m_fps; } } - + /// <summary> /// Override of the ToString method to provide an easy way to use this object in the UI /// </summary> /// <returns>A string representing this track in the format: {title #} (00:00:00)</returns> public override string ToString() { - return string.Format("{0} ({1:00}:{2:00}:{3:00})", m_titleNumber, m_duration.Hours, + return string.Format("{0} ({1:00}:{2:00}:{3:00})", m_titleNumber, m_duration.Hours, m_duration.Minutes, m_duration.Seconds); } @@ -171,15 +172,15 @@ namespace Handbrake.Parsing string path = output.ReadLine(); m = Regex.Match(path, @"^ \+ stream:"); if (m.Success) - thisTitle.source = path.Replace("+ stream:", "").Trim(); - + thisTitle.source = path.Replace("+ stream:", string.Empty).Trim(); + if (!Properties.Settings.Default.noDvdNav) { // Get the Angles for the title. m = Regex.Match(output.ReadLine(), @" \+ angle\(s\) ([0-9])"); if (m.Success) { - String angleList = m.Value.Replace("+ angle(s) ", "").Trim(); + string angleList = m.Value.Replace("+ angle(s) ", string.Empty).Trim(); int angleCount; int.TryParse(angleList, out angleCount); @@ -194,9 +195,9 @@ namespace Handbrake.Parsing thisTitle.m_duration = TimeSpan.Parse(m.Groups[1].Value); // Get resolution, aspect ratio and FPS for this title - m = Regex.Match(output.ReadLine(), + m = Regex.Match(output.ReadLine(), @"^ \+ size: ([0-9]*)x([0-9]*), pixel aspect: ([0-9]*)/([0-9]*), display aspect: ([0-9]*\.[0-9]*), ([0-9]*\.[0-9]*) fps"); - //size: 720x576, pixel aspect: 16/15, display aspect: 1.33, 25.000 fps + // size: 720x576, pixel aspect: 16/15, display aspect: 1.33, 25.000 fps if (m.Success) { @@ -209,9 +210,9 @@ namespace Handbrake.Parsing // Get autocrop region for this title m = Regex.Match(output.ReadLine(), @"^ \+ autocrop: ([0-9]*)/([0-9]*)/([0-9]*)/([0-9]*)"); if (m.Success) - thisTitle.m_autoCrop = new int[] + thisTitle.m_autoCrop = new[] { - int.Parse(m.Groups[1].Value), int.Parse(m.Groups[2].Value), + int.Parse(m.Groups[1].Value), int.Parse(m.Groups[2].Value), int.Parse(m.Groups[3].Value), int.Parse(m.Groups[4].Value) }; diff --git a/win/C#/Presets/PlistPresetHandler.cs b/win/C#/Presets/PlistPresetHandler.cs index 871ef38a..4fd08518 100644 --- a/win/C#/Presets/PlistPresetHandler.cs +++ b/win/C#/Presets/PlistPresetHandler.cs @@ -4,17 +4,17 @@ Homepage: <http://handbrake.fr/>. It may be used under the terms of the GNU General Public License. */ -using System; -using System.IO; -using System.Text; -using System.Xml; -using System.Windows.Forms; -using System.Collections; -using Handbrake.Functions; -using Handbrake.Model; - namespace Handbrake.Presets { + using System; + using System.Collections; + using System.IO; + using System.Text; + using System.Windows.Forms; + using System.Xml; + using Functions; + using Model; + public class PlistPresetHandler { /* WARNING This file is not complete!!!!!! @@ -53,7 +53,8 @@ namespace Handbrake.Presets if (!root.HasChildNodes) { MessageBox.Show( - "The Preset file you selected appears to be invlaid or from an older version of HandBrake", "Error", + "The Preset file you selected appears to be invlaid or from an older version of HandBrake", + "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return null; } @@ -61,8 +62,9 @@ namespace Handbrake.Presets catch (Exception) { MessageBox.Show( - "The Preset file you selected appears to be invlaid or from an older version of HandBrake.\n\n Please note, if you are exporting from the MacGui you may need to rebuild your preset so that it uses the current preset plist format.\n The MacGui does not currently update user presets automatically.", "Error", - MessageBoxButtons.OK, MessageBoxIcon.Error); + "The Preset file you selected appears to be invlaid or from an older version of HandBrake.\n\n Please note, if you are exporting from the MacGui you may need to rebuild your preset so that it uses the current preset plist format.\n The MacGui does not currently update user presets automatically.", + "Error", + MessageBoxButtons.OK, MessageBoxIcon.Error); } // We'll query a query parser object and use it's public var structures to store all the data. @@ -110,14 +112,15 @@ namespace Handbrake.Presets /***** Get the rest of the settings. *****/ XmlNode presetSettings = root.ChildNodes[2].ChildNodes[0].FirstChild; - for (int i = 2; i < presetSettings.ChildNodes.Count; i += 2) // Start from 2 to avoid the audio settings which we don't need. + for (int i = 2; i < presetSettings.ChildNodes.Count; i += 2) + // Start from 2 to avoid the audio settings which we don't need. { string key = presetSettings.ChildNodes[i].InnerText; string value = presetSettings.ChildNodes[i + 1].InnerText; switch (key) { - // Output Settings + // Output Settings case "FileFormat": queryParsed.Format = value; break; @@ -131,7 +134,7 @@ namespace Handbrake.Presets queryParsed.IpodAtom = value == "1"; break; - // Picture Settings + // Picture Settings case "PictureAutoCrop": break; case "PictureTopCrop": @@ -160,7 +163,7 @@ namespace Handbrake.Presets break; - // Filters + // Filters case "PictureDeblock": queryParsed.DeBlock = int.Parse(value); break; @@ -169,7 +172,7 @@ namespace Handbrake.Presets if (value == "2") queryParsed.Decomb = "Default"; break; case "PictureDecombCustom": - if (value != "") + if (value != string.Empty) queryParsed.Decomb = value; break; case "PictureDecombDeinterlace": @@ -193,7 +196,7 @@ namespace Handbrake.Presets } break; case "PictureDeinterlaceCustom": - if (value != "") + if (value != string.Empty) queryParsed.DeInterlace = value; break; case "PictureDenoise": @@ -215,7 +218,7 @@ namespace Handbrake.Presets break; case "PictureDenoiseCustom": - if (value != "") + if (value != string.Empty) queryParsed.DeNoise = value; break; case "PictureDetelecine": @@ -223,11 +226,11 @@ namespace Handbrake.Presets if (value == "1") queryParsed.DeTelecine = "Default"; break; case "PictureDetelecineCustom": - if (value != "") + if (value != string.Empty) queryParsed.DeTelecine = value; break; - // Video Tab + // Video Tab case "VideoAvgBitrate": queryParsed.Width = int.Parse(value); break; @@ -255,17 +258,17 @@ namespace Handbrake.Presets queryParsed.TwoPass = value == "1"; break; - // Chapter Markers Tab + // Chapter Markers Tab case "ChapterMarkers": queryParsed.ChapterMarkers = value == "1"; break; - // Advanced x264 tab + // Advanced x264 tab case "x264Option": queryParsed.H264Query = value; break; - // Preset Information + // Preset Information case "PresetBuildNumber": queryParsed.PresetBuildNumber = int.Parse(value); break; @@ -302,7 +305,8 @@ namespace Handbrake.Presets // Header Writer.WriteStartDocument(); - Writer.WriteDocType("plist", "-//Apple//DTD PLIST 1.0//EN", @"http://www.apple.com/DTDs/PropertyList-1.0.dtd", null); + Writer.WriteDocType("plist", "-//Apple//DTD PLIST 1.0//EN", + @"http://www.apple.com/DTDs/PropertyList-1.0.dtd", null); Writer.WriteStartElement("plist"); Writer.WriteStartElement("array"); @@ -319,7 +323,7 @@ namespace Handbrake.Presets // Closeout Writer.Close(); } - + /// <summary> /// Write a Plist file /// </summary> @@ -337,49 +341,49 @@ namespace Handbrake.Presets /// </summary> private void AddEncodeSettings() { - AddEncodeElement("ChapterMarkers", "integer", ""); - AddEncodeElement("Default", "integer", ""); - AddEncodeElement("FileFormat", "String", ""); + AddEncodeElement("ChapterMarkers", "integer", string.Empty); + AddEncodeElement("Default", "integer", string.Empty); + AddEncodeElement("FileFormat", "String", string.Empty); AddBooleanElement("Folder", true); - AddEncodeElement("Mp4HttpOptimize", "integer", ""); - AddEncodeElement("Mp4LargeFile", "integer", ""); - AddEncodeElement("Mp4iPodCompatible", "integer", ""); - AddEncodeElement("PictureAutoCrop", "integer", ""); - AddEncodeElement("PictureBottomCrop", "integer", ""); - AddEncodeElement("PictureDeblock", "integer", ""); - AddEncodeElement("PictureDecomb", "integer", ""); - AddEncodeElement("PictureDecombCustom", "string", ""); - AddEncodeElement("PictureDecombDeinterlace", "integer", ""); - AddEncodeElement("PictureDeinterlace", "integer", ""); - AddEncodeElement("PictureDeinterlaceCustom", "string", ""); - AddEncodeElement("PictureDenoise", "integer", ""); - AddEncodeElement("PictureDenoiseCustom", "string", ""); - AddEncodeElement("PictureDetelecine", "integer", ""); - AddEncodeElement("PictureDetelecineCustom", "string", ""); - AddEncodeElement("PictureHeight", "integer", ""); - AddEncodeElement("PictureKeepRatio", "integer", ""); - AddEncodeElement("PictureLeftCrop", "integer", ""); - AddEncodeElement("PicturePAR", "integer", ""); - AddEncodeElement("PictureRightCrop", "integer", ""); - AddEncodeElement("PictureTopCrop", "integer", ""); - AddEncodeElement("PictureWidth", "integer", ""); - AddEncodeElement("PresetBuildNumber", "string", ""); - AddEncodeElement("PresetDescription", "string", ""); - AddEncodeElement("PresetName", "string", ""); - AddEncodeElement("Type", "integer", ""); - AddEncodeElement("UsesMaxPictureSettings", "integer", ""); - AddEncodeElement("UsesPictureFilters", "integer", ""); - AddEncodeElement("UsesPictureSettings", "integer", ""); - AddEncodeElement("VideoAvgBitrate", "string", ""); - AddEncodeElement("VideoEncoder", "string", ""); - AddEncodeElement("VideoFramerate", "string", ""); - AddEncodeElement("VideoGrayScale", "integer", ""); - AddEncodeElement("VideoQualitySlider", "real", ""); - AddEncodeElement("VideoQualityType", "integer", ""); - AddEncodeElement("VideoTargetSize", "string", ""); - AddEncodeElement("VideoTurboTwoPass", "integer", ""); - AddEncodeElement("VideoTwoPass", "integer", ""); - AddEncodeElement("x264Option", "string", ""); + AddEncodeElement("Mp4HttpOptimize", "integer", string.Empty); + AddEncodeElement("Mp4LargeFile", "integer", string.Empty); + AddEncodeElement("Mp4iPodCompatible", "integer", string.Empty); + AddEncodeElement("PictureAutoCrop", "integer", string.Empty); + AddEncodeElement("PictureBottomCrop", "integer", string.Empty); + AddEncodeElement("PictureDeblock", "integer", string.Empty); + AddEncodeElement("PictureDecomb", "integer", string.Empty); + AddEncodeElement("PictureDecombCustom", "string", string.Empty); + AddEncodeElement("PictureDecombDeinterlace", "integer", string.Empty); + AddEncodeElement("PictureDeinterlace", "integer", string.Empty); + AddEncodeElement("PictureDeinterlaceCustom", "string", string.Empty); + AddEncodeElement("PictureDenoise", "integer", string.Empty); + AddEncodeElement("PictureDenoiseCustom", "string", string.Empty); + AddEncodeElement("PictureDetelecine", "integer", string.Empty); + AddEncodeElement("PictureDetelecineCustom", "string", string.Empty); + AddEncodeElement("PictureHeight", "integer", string.Empty); + AddEncodeElement("PictureKeepRatio", "integer", string.Empty); + AddEncodeElement("PictureLeftCrop", "integer", string.Empty); + AddEncodeElement("PicturePAR", "integer", string.Empty); + AddEncodeElement("PictureRightCrop", "integer", string.Empty); + AddEncodeElement("PictureTopCrop", "integer", string.Empty); + AddEncodeElement("PictureWidth", "integer", string.Empty); + AddEncodeElement("PresetBuildNumber", "string", string.Empty); + AddEncodeElement("PresetDescription", "string", string.Empty); + AddEncodeElement("PresetName", "string", string.Empty); + AddEncodeElement("Type", "integer", string.Empty); + AddEncodeElement("UsesMaxPictureSettings", "integer", string.Empty); + AddEncodeElement("UsesPictureFilters", "integer", string.Empty); + AddEncodeElement("UsesPictureSettings", "integer", string.Empty); + AddEncodeElement("VideoAvgBitrate", "string", string.Empty); + AddEncodeElement("VideoEncoder", "string", string.Empty); + AddEncodeElement("VideoFramerate", "string", string.Empty); + AddEncodeElement("VideoGrayScale", "integer", string.Empty); + AddEncodeElement("VideoQualitySlider", "real", string.Empty); + AddEncodeElement("VideoQualityType", "integer", string.Empty); + AddEncodeElement("VideoTargetSize", "string", string.Empty); + AddEncodeElement("VideoTurboTwoPass", "integer", string.Empty); + AddEncodeElement("VideoTwoPass", "integer", string.Empty); + AddEncodeElement("x264Option", "string", string.Empty); } /// <summary> @@ -387,7 +391,7 @@ namespace Handbrake.Presets /// </summary> /// <param name="keyName"></param> /// <param name="value"></param> - private void AddBooleanElement(string keyName, Boolean value) + private void AddBooleanElement(string keyName, bool value) { Writer.WriteStartElement("key"); Writer.WriteString(keyName); diff --git a/win/C#/Presets/Preset.cs b/win/C#/Presets/Preset.cs index 088d39c8..ef643874 100644 --- a/win/C#/Presets/Preset.cs +++ b/win/C#/Presets/Preset.cs @@ -4,10 +4,10 @@ Homepage: <http://handbrake.fr>. It may be used under the terms of the GNU General Public License. */ -using System; - namespace Handbrake.Presets { + using System; + public class Preset { /// <summary> @@ -28,7 +28,7 @@ namespace Handbrake.Presets /// <summary> /// Get or set the usage of Picture Settings in presets. /// </summary> - public Boolean PictureSettings { get; set; } + public bool PictureSettings { get; set; } /// <summary> /// The version number which associates this preset with a HB build diff --git a/win/C#/Presets/PresetsHandler.cs b/win/C#/Presets/PresetsHandler.cs index 155086b5..a5978fcc 100644 --- a/win/C#/Presets/PresetsHandler.cs +++ b/win/C#/Presets/PresetsHandler.cs @@ -3,24 +3,28 @@ This file is part of the HandBrake source code. Homepage: <http://handbrake.fr>. It may be used under the terms of the GNU General Public License. */ -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Windows.Forms; -using System.IO; -using System.Text.RegularExpressions; -using System.Diagnostics; -using System.Xml.Serialization; - namespace Handbrake.Presets { + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.Drawing; + using System.IO; + using System.Text.RegularExpressions; + using System.Windows.Forms; + using System.Xml.Serialization; + public class PresetsHandler { - List<Preset> Presets = new List<Preset>(); - List<Preset> UserPresets = new List<Preset>(); - private static readonly XmlSerializer Ser = new XmlSerializer(typeof(List<Preset>)); - readonly string UserPresetFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\user_presets.xml"; - readonly string HbPresetFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\presets.xml"; + private List<Preset> Presets = new List<Preset>(); + private List<Preset> UserPresets = new List<Preset>(); + private static readonly XmlSerializer Ser = new XmlSerializer(typeof (List<Preset>)); + + private readonly string UserPresetFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + + "\\HandBrake\\user_presets.xml"; + + private readonly string HbPresetFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + + "\\HandBrake\\presets.xml"; /// <summary> /// Add a new preset to the system @@ -28,11 +32,17 @@ namespace Handbrake.Presets /// <param name="presetName">String, The name of the new preset</param> /// <param name="query">String, the CLI query for the new preset</param> /// <param name="pictureSettings"> Bool, store crop/picture sizes in the Presets</param> - public Boolean Add(string presetName, string query, Boolean pictureSettings) + public bool Add(string presetName, string query, bool pictureSettings) { if (CheckIfPresetExists(presetName) == false) { - Preset newPreset = new Preset { Name = presetName, Query = query, PictureSettings = pictureSettings, Version = Properties.Settings.Default.hb_version }; + Preset newPreset = new Preset + { + Name = presetName, + Query = query, + PictureSettings = pictureSettings, + Version = Properties.Settings.Default.hb_version + }; UserPresets.Add(newPreset); UpdatePresetFiles(); return true; @@ -89,7 +99,7 @@ namespace Handbrake.Presets /// <param name="presetName">String, The name of the new preset</param> /// <param name="query">String, the CLI query for the new preset</param> /// <param name="pictureSettings"> Bool, store crop/picture sizes in the preset</param> - public void Update(string presetName, string query, Boolean pictureSettings) + public void Update(string presetName, string query, bool pictureSettings) { // User Presets foreach (Preset item in UserPresets) @@ -98,7 +108,8 @@ namespace Handbrake.Presets { item.Query = query; item.PictureSettings = pictureSettings; - MessageBox.Show("Changes to \"" + presetName + "\" Saved", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); + MessageBox.Show("Changes to \"" + presetName + "\" Saved", "Success", MessageBoxButtons.OK, + MessageBoxIcon.Information); UpdatePresetFiles(); } } @@ -136,9 +147,13 @@ namespace Handbrake.Presets // Create a new tempory file and execute the CLI to get the built in Presets. string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe"); string presetsPath = Path.Combine(Path.GetTempPath(), "temp_presets.dat"); - string strCmdLine = String.Format(@"cmd /c """"{0}"" --preset-list >""{1}"" 2>&1""", handbrakeCLIPath, presetsPath); + string strCmdLine = String.Format(@"cmd /c """"{0}"" --preset-list >""{1}"" 2>&1""", handbrakeCLIPath, + presetsPath); - ProcessStartInfo hbGetPresets = new ProcessStartInfo("CMD.exe", strCmdLine) { WindowStyle = ProcessWindowStyle.Hidden }; + ProcessStartInfo hbGetPresets = new ProcessStartInfo("CMD.exe", strCmdLine) + { + WindowStyle = ProcessWindowStyle.Hidden + }; Process hbproc = Process.Start(hbGetPresets); if (hbproc != null) { @@ -160,7 +175,7 @@ namespace Handbrake.Presets { string line = presetInput.ReadLine(); if (line.Contains("<") && !line.Contains("<<")) // Found the beginning of a preset block - category = line.Replace("<", "").Trim(); + category = line.Replace("<", string.Empty).Trim(); if (line.Contains("+")) // A Preset { @@ -173,10 +188,10 @@ namespace Handbrake.Presets Preset newPreset = new Preset { - Category = category, - Name = presetName[0].Replace("+", "").Trim(), - Query = presetName[2], - Version = Properties.Settings.Default.hb_version, + Category = category, + Name = presetName[0].Replace("+", string.Empty).Trim(), + Query = presetName[2], + Version = Properties.Settings.Default.hb_version, PictureSettings = pic }; Presets.Add(newPreset); @@ -222,7 +237,8 @@ namespace Handbrake.Presets { MessageBox.Show( "HandBrakes preset file appears to have been corrupted. This file will now be re-generated!\n" + - "If the problem presists, please delete the file: \n\n" + HbPresetFile, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + "If the problem presists, please delete the file: \n\n" + HbPresetFile, "Error", + MessageBoxButtons.OK, MessageBoxIcon.Error); UpdateBuiltInPresets(); } @@ -251,7 +267,8 @@ namespace Handbrake.Presets "Your presets will not be loaded. You may need to re-create your presets.\n\n" + "Your user presets file has been renamed to 'user_presets.xml.old' and is located in:\n " + Path.GetDirectoryName(UserPresetFile) + "\n" + - "You may be able to recover some presets if you know the XML language.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + "You may be able to recover some presets if you know the XML language.", "Error", + MessageBoxButtons.OK, MessageBoxIcon.Error); // Recover from Error. if (File.Exists(UserPresetFile)) @@ -261,7 +278,6 @@ namespace Handbrake.Presets File.Delete(disabledFile); File.Move(UserPresetFile, disabledFile); } - } } @@ -278,7 +294,6 @@ namespace Handbrake.Presets if (Presets.Count != 0) // Built In Presets { - foreach (Preset preset in Presets) { if (preset.Category != category) @@ -293,20 +308,21 @@ namespace Handbrake.Presets } } - rootNode = null; category = null; + rootNode = null; + category = null; foreach (Preset preset in UserPresets) // User Presets { if (preset.Category != category && preset.Category != null) { - rootNode = new TreeNode(preset.Category) { ForeColor = Color.Black }; + rootNode = new TreeNode(preset.Category) {ForeColor = Color.Black}; presetPanel.Nodes.Add(rootNode); category = preset.Category; } if (preset.Category == category && rootNode != null) - rootNode.Nodes.Add(new TreeNode(preset.Name) { ForeColor = Color.Black }); + rootNode.Nodes.Add(new TreeNode(preset.Name) {ForeColor = Color.Black}); else - presetPanel.Nodes.Add(new TreeNode(preset.Name) { ForeColor = Color.Black }); + presetPanel.Nodes.Add(new TreeNode(preset.Name) {ForeColor = Color.Black}); } } @@ -333,7 +349,9 @@ namespace Handbrake.Presets } catch (Exception exc) { - MessageBox.Show("Unable to write to the file. Please make sure the location has the correct permissions for file writing.\n Error Information: \n\n" + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); + MessageBox.Show( + "Unable to write to the file. Please make sure the location has the correct permissions for file writing.\n Error Information: \n\n" + + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); } } @@ -342,7 +360,7 @@ namespace Handbrake.Presets /// </summary> /// <param name="name"></param> /// <returns></returns> - private Boolean CheckIfPresetExists(string name) + private bool CheckIfPresetExists(string name) { if (name == string.Empty) return true; @@ -369,7 +387,7 @@ namespace Handbrake.Presets /// </summary> /// <param name="name"></param> /// <returns></returns> - public Boolean CheckIfUserPresetExists(string name) + public bool CheckIfUserPresetExists(string name) { if (name == string.Empty) return false; @@ -389,7 +407,7 @@ namespace Handbrake.Presets /// Update them if they are. /// </summary> /// <returns></returns> - public Boolean CheckIfPresetsAreOutOfDate() + public bool CheckIfPresetsAreOutOfDate() { LoadPresetData(); // Update built-in Presets if the built-in Presets belong to an older version. diff --git a/win/C#/Properties/AssemblyInfo.cs b/win/C#/Properties/AssemblyInfo.cs index cc93c31e..e0dc882a 100644 --- a/win/C#/Properties/AssemblyInfo.cs +++ b/win/C#/Properties/AssemblyInfo.cs @@ -5,13 +5,13 @@ It may be used under the terms of the GNU General Public License. */ using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using System.Resources; +using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. + [assembly: AssemblyTitle("HandBrake")] [assembly: AssemblyDescription("HandBrake is a GPL-licensed, multiplatform, multithreaded video transcoder.")] [assembly: AssemblyConfiguration("")] @@ -24,9 +24,11 @@ using System.Resources; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. + [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM + [assembly: Guid("5e4e3f97-5252-41f6-aae9-3846f62cbc66")] // Version information for an assembly consists of the following four values: @@ -36,6 +38,7 @@ using System.Resources; // Build Number // Revision // + [assembly: AssemblyVersion("0.9.4.5")] [assembly: AssemblyFileVersion("0.9.4.5")] -[assembly: NeutralResourcesLanguageAttribute("")] +[assembly: NeutralResourcesLanguage("")] \ No newline at end of file diff --git a/win/C#/app.config b/win/C#/app.config index f52e8f08..2696c0fa 100644 --- a/win/C#/app.config +++ b/win/C#/app.config @@ -1,135 +1,143 @@ <?xml version="1.0"?> + <configuration> - <configSections> - <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> - <section name="Handbrake.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false"/> - </sectionGroup> - </configSections> - <userSettings> - <Handbrake.Properties.Settings> - <setting name="processPriority" serializeAs="String"> - <value>Below Normal</value> - </setting> - <setting name="Processors" serializeAs="String"> - <value>Automatic</value> - </setting> - <setting name="updateStatus" serializeAs="String"> - <value>True</value> - </setting> - <setting name="hb_version" serializeAs="String"> - <value>{hb_version}</value> - </setting> - <setting name="tooltipEnable" serializeAs="String"> - <value>True</value> - </setting> - <setting name="CompletionOption" serializeAs="String"> - <value>Do Nothing</value> - </setting> - <setting name="defaultPreset" serializeAs="String"> - <value/> - </setting> - <setting name="hb_build" serializeAs="String"> - <value>0</value> - </setting> - <setting name="skipversion" serializeAs="String"> - <value>0</value> - </setting> - <setting name="autoNaming" serializeAs="String"> - <value>True</value> - </setting> - <setting name="autoNamePath" serializeAs="String"> - <value/> - </setting> - <setting name="appcast" serializeAs="String"> - <value>http://handbrake.fr/appcast.xml</value> - </setting> - <setting name="appcast_unstable" serializeAs="String"> - <value>http://handbrake.fr/appcast_unstable.xml</value> - </setting> - <setting name="cli_minimized" serializeAs="String"> - <value>False</value> - </setting> - <setting name="autoNameFormat" serializeAs="String"> - <value>{source}-{title}</value> - </setting> - <setting name="saveLogToSpecifiedPath" serializeAs="String"> - <value>False</value> - </setting> - <setting name="saveLogPath" serializeAs="String"> - <value/> - </setting> - <setting name="saveLogWithVideo" serializeAs="String"> - <value>False</value> - </setting> - <setting name="VLC_Path" serializeAs="String"> - <value>C:\Program Files\VideoLAN\vlc\vlc.exe</value> - </setting> - <setting name="MainWindowMinimize" serializeAs="String"> - <value>True</value> - </setting> - <setting name="QueryEditorTab" serializeAs="String"> - <value>False</value> - </setting> - <setting name="x264cqstep" serializeAs="String"> - <value>0.25</value> - </setting> - <setting name="verboseLevel" serializeAs="String"> - <value>1</value> - </setting> - <setting name="noDvdNav" serializeAs="String"> - <value>False</value> - </setting> - <setting name="presetNotification" serializeAs="String"> - <value>False</value> - </setting> - <setting name="enocdeStatusInGui" serializeAs="String"> - <value>False</value> - </setting> - <setting name="trayIconAlerts" serializeAs="String"> - <value>True</value> - </setting> - <setting name="lastUpdateCheckDate" serializeAs="String"> - <value/> - </setting> - <setting name="daysBetweenUpdateCheck" serializeAs="String"> - <value>7</value> - </setting> - <setting name="useM4v" serializeAs="String"> - <value>True</value> - </setting> - <setting name="PromptOnUnmatchingQueries" serializeAs="String"> - <value>True</value> - </setting> - <setting name="NativeLanguage" serializeAs="String"> - <value>Any</value> - </setting> - <setting name="DubAudio" serializeAs="String"> - <value>False</value> - </setting> - <setting name="hb_platform" serializeAs="String"> - <value/> - </setting> - <setting name="disableResCalc" serializeAs="String"> - <value>False</value> - </setting> - <setting name="growlQueue" serializeAs="String"> - <value>False</value> - </setting> - <setting name="growlEncode" serializeAs="String"> - <value>False</value> - </setting> - <setting name="cliLastModified" serializeAs="String"> - <value/> - </setting> - <setting name="previewScanCount" serializeAs="String"> - <value>10</value> - </setting> - <setting name="clearOldLogs" serializeAs="String"> - <value>False</value> - </setting> - <setting name="showCliForInGuiEncodeStatus" serializeAs="String"> - <value>True</value> - </setting> - </Handbrake.Properties.Settings> - </userSettings> - <startup/></configuration> + <configSections> + <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> + <section name="Handbrake.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" /> + </sectionGroup> + </configSections> + <userSettings> + <Handbrake.Properties.Settings> + <setting name="processPriority" serializeAs="String"> + <value>Below Normal</value> + </setting> + <setting name="Processors" serializeAs="String"> + <value>Automatic</value> + </setting> + <setting name="updateStatus" serializeAs="String"> + <value>True</value> + </setting> + <setting name="hb_version" serializeAs="String"> + <value>{hb_version}</value> + </setting> + <setting name="tooltipEnable" serializeAs="String"> + <value>True</value> + </setting> + <setting name="CompletionOption" serializeAs="String"> + <value>Do Nothing</value> + </setting> + <setting name="defaultPreset" serializeAs="String"> + <value /> + </setting> + <setting name="hb_build" serializeAs="String"> + <value>0</value> + </setting> + <setting name="skipversion" serializeAs="String"> + <value>0</value> + </setting> + <setting name="autoNaming" serializeAs="String"> + <value>True</value> + </setting> + <setting name="autoNamePath" serializeAs="String"> + <value /> + </setting> + <setting name="appcast" serializeAs="String"> + <value> + http://handbrake.fr/appcast.xml + </value> + </setting> + <setting name="appcast_unstable" serializeAs="String"> + <value> + http://handbrake.fr/appcast_unstable.xml + </value> + </setting> + <setting name="cli_minimized" serializeAs="String"> + <value>False</value> + </setting> + <setting name="autoNameFormat" serializeAs="String"> + <value>{source}-{title}</value> + </setting> + <setting name="saveLogToSpecifiedPath" serializeAs="String"> + <value>False</value> + </setting> + <setting name="saveLogPath" serializeAs="String"> + <value /> + </setting> + <setting name="saveLogWithVideo" serializeAs="String"> + <value>False</value> + </setting> + <setting name="VLC_Path" serializeAs="String"> + <value> + C:\Program Files\VideoLAN\vlc\vlc.exe + </value> + </setting> + <setting name="MainWindowMinimize" serializeAs="String"> + <value>True</value> + </setting> + <setting name="QueryEditorTab" serializeAs="String"> + <value>False</value> + </setting> + <setting name="x264cqstep" serializeAs="String"> + <value>0.25</value> + </setting> + <setting name="verboseLevel" serializeAs="String"> + <value>1</value> + </setting> + <setting name="noDvdNav" serializeAs="String"> + <value>False</value> + </setting> + <setting name="presetNotification" serializeAs="String"> + <value>False</value> + </setting> + <setting name="enocdeStatusInGui" serializeAs="String"> + <value>False</value> + </setting> + <setting name="trayIconAlerts" serializeAs="String"> + <value>True</value> + </setting> + <setting name="lastUpdateCheckDate" serializeAs="String"> + <value /> + </setting> + <setting name="daysBetweenUpdateCheck" serializeAs="String"> + <value>7</value> + </setting> + <setting name="useM4v" serializeAs="String"> + <value>True</value> + </setting> + <setting name="PromptOnUnmatchingQueries" serializeAs="String"> + <value>True</value> + </setting> + <setting name="NativeLanguage" serializeAs="String"> + <value>Any</value> + </setting> + <setting name="DubAudio" serializeAs="String"> + <value>False</value> + </setting> + <setting name="hb_platform" serializeAs="String"> + <value /> + </setting> + <setting name="disableResCalc" serializeAs="String"> + <value>False</value> + </setting> + <setting name="growlQueue" serializeAs="String"> + <value>False</value> + </setting> + <setting name="growlEncode" serializeAs="String"> + <value>False</value> + </setting> + <setting name="cliLastModified" serializeAs="String"> + <value /> + </setting> + <setting name="previewScanCount" serializeAs="String"> + <value>10</value> + </setting> + <setting name="clearOldLogs" serializeAs="String"> + <value>False</value> + </setting> + <setting name="showCliForInGuiEncodeStatus" serializeAs="String"> + <value>True</value> + </setting> + </Handbrake.Properties.Settings> + </userSettings> + <startup /> +</configuration> \ No newline at end of file diff --git a/win/C#/frmAbout.cs b/win/C#/frmAbout.cs index a35779a3..cae109d7 100644 --- a/win/C#/frmAbout.cs +++ b/win/C#/frmAbout.cs @@ -4,17 +4,18 @@ Homepage: <http://handbrake.fr>. It may be used under the terms of the GNU General Public License. */ -using System; -using System.Windows.Forms; - namespace Handbrake { + using System; + using System.Windows.Forms; + public partial class frmAbout : Form { public frmAbout() { InitializeComponent(); - lbl_HBBuild.Text = Properties.Settings.Default.hb_version + " (" + Properties.Settings.Default.hb_build + ") - " + Properties.Settings.Default.hb_platform; + lbl_HBBuild.Text = Properties.Settings.Default.hb_version + " (" + Properties.Settings.Default.hb_build + + ") - " + Properties.Settings.Default.hb_platform; } private void btn_close_Click(object sender, EventArgs e) diff --git a/win/C#/frmActivityWindow.cs b/win/C#/frmActivityWindow.cs index ca4edcfd..07e8f3dc 100644 --- a/win/C#/frmActivityWindow.cs +++ b/win/C#/frmActivityWindow.cs @@ -4,26 +4,29 @@ Homepage: <http://handbrake.fr>. It may be used under the terms of the GNU General Public License. */ -using System; -using System.ComponentModel; -using System.Text; -using System.Windows.Forms; -using System.IO; -using System.Threading; -using Handbrake.Functions; -using Timer = System.Threading.Timer; - namespace Handbrake { + using System; + using System.ComponentModel; + using System.Diagnostics; + using System.IO; + using System.Text; + using System.Threading; + using System.Windows.Forms; + using Functions; + using Timer = System.Threading.Timer; + public partial class frmActivityWindow : Form { private delegate void SetTextCallback(StringBuilder text); + private delegate void SetTextClearCallback(); + private int Position; private string LastMode; private string CurrentMode; private Timer WindowTimer; - + public frmActivityWindow(string mode) { InitializeComponent(); @@ -57,6 +60,7 @@ namespace Handbrake break; } } + private StringBuilder ReadFile(string file) { StringBuilder appendText = new StringBuilder(); @@ -103,7 +107,6 @@ namespace Handbrake } sr.Close(); sr.Dispose(); - } catch (Exception) { @@ -115,6 +118,7 @@ namespace Handbrake } return appendText; } + private void AppendWindowText(StringBuilder text) { try @@ -123,7 +127,7 @@ namespace Handbrake { if (rtf_actLog.InvokeRequired) { - IAsyncResult invoked = BeginInvoke(new SetTextCallback(AppendWindowText), new object[] { text }); + IAsyncResult invoked = BeginInvoke(new SetTextCallback(AppendWindowText), new object[] {text}); EndInvoke(invoked); } else @@ -136,6 +140,7 @@ namespace Handbrake return; } } + private void ClearWindowText() { try @@ -148,7 +153,7 @@ namespace Handbrake EndInvoke(invoked); } else - lock(rtf_actLog) + lock (rtf_actLog) rtf_actLog.Clear(); } } @@ -157,6 +162,7 @@ namespace Handbrake return; } } + private void PrintLogHeader() { try @@ -173,14 +179,14 @@ namespace Handbrake lock (rtf_actLog) { // Print the log header. This function will be re-implimented later. Do not delete. - rtf_actLog.AppendText(String.Format("### Windows GUI {1} {0} \n", - Properties.Settings.Default.hb_build, + rtf_actLog.AppendText(String.Format("### Windows GUI {1} {0} \n", + Properties.Settings.Default.hb_build, Properties.Settings.Default.hb_version)); rtf_actLog.AppendText(String.Format("### Running: {0} \n###\n", Environment.OSVersion)); rtf_actLog.AppendText(String.Format("### CPU: {0} \n", SystemInfo.GetCpuCount)); rtf_actLog.AppendText(String.Format("### Ram: {0} MB \n", SystemInfo.TotalPhysicalMemory)); - rtf_actLog.AppendText(String.Format("### Screen: {0}x{1} \n", - SystemInfo.ScreenBounds.Bounds.Width, + rtf_actLog.AppendText(String.Format("### Screen: {0}x{1} \n", + SystemInfo.ScreenBounds.Bounds.Width, SystemInfo.ScreenBounds.Bounds.Height)); rtf_actLog.AppendText(String.Format("### Temp Dir: {0} \n", Path.GetTempPath())); rtf_actLog.AppendText(String.Format("### Install Dir: {0} \n", Application.StartupPath)); @@ -194,15 +200,15 @@ namespace Handbrake { return; } - } + private void Reset() { if (WindowTimer != null) WindowTimer.Dispose(); Position = 0; ClearWindowText(); - PrintLogHeader(); + PrintLogHeader(); WindowTimer = new Timer(new TimerCallback(LogMonitor), null, 1000, 1000); } @@ -210,15 +216,17 @@ namespace Handbrake public string SetLogFile { - get { return string.IsNullOrEmpty(CurrentMode) ? "" : CurrentMode; } + get { return string.IsNullOrEmpty(CurrentMode) ? string.Empty : CurrentMode; } set { CurrentMode = value; } } + public void SetScanMode() { Reset(); SetLogFile = "last_scan_log.txt"; this.Text = "Activity Window (Scan Log)"; } + public void SetEncodeMode() { Reset(); @@ -229,36 +237,42 @@ namespace Handbrake #endregion #region User Interface + private void mnu_copy_log_Click(object sender, EventArgs e) { - Clipboard.SetDataObject(rtf_actLog.SelectedText != "" ? rtf_actLog.SelectedText : rtf_actLog.Text, true); + Clipboard.SetDataObject(rtf_actLog.SelectedText != string.Empty ? rtf_actLog.SelectedText : rtf_actLog.Text, true); } + private void mnu_openLogFolder_Click(object sender, EventArgs e) { string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs"; string windir = Environment.GetEnvironmentVariable("WINDIR"); - System.Diagnostics.Process prc = new System.Diagnostics.Process - { - StartInfo = - { - FileName = windir + @"\explorer.exe", - Arguments = logDir - } - }; + Process prc = new Process + { + StartInfo = + { + FileName = windir + @"\explorer.exe", + Arguments = logDir + } + }; prc.Start(); } + private void btn_copy_Click(object sender, EventArgs e) { - Clipboard.SetDataObject(rtf_actLog.SelectedText != "" ? rtf_actLog.SelectedText : rtf_actLog.Text, true); + Clipboard.SetDataObject(rtf_actLog.SelectedText != string.Empty ? rtf_actLog.SelectedText : rtf_actLog.Text, true); } + private void btn_scan_log_Click(object sender, EventArgs e) { SetScanMode(); } + private void btn_encode_log_Click(object sender, EventArgs e) { SetEncodeMode(); } + #endregion protected override void OnClosing(CancelEventArgs e) diff --git a/win/C#/frmAddPreset.cs b/win/C#/frmAddPreset.cs index 256b9b9f..30537f9e 100644 --- a/win/C#/frmAddPreset.cs +++ b/win/C#/frmAddPreset.cs @@ -4,19 +4,20 @@ Homepage: <http://handbrake.fr>. It may be used under the terms of the GNU General Public License. */ -using System; -using System.Drawing; -using System.Windows.Forms; - namespace Handbrake { + using System; + using System.Drawing; + using System.Windows.Forms; + using Presets; + public partial class frmAddPreset : Form { private readonly frmMain _frmMainWindow; - readonly Presets.PresetsHandler _presetCode; - private readonly string _query = ""; + private readonly PresetsHandler _presetCode; + private readonly string _query = string.Empty; - public frmAddPreset(frmMain fmw, string queryString, Presets.PresetsHandler presetHandler) + public frmAddPreset(frmMain fmw, string queryString, PresetsHandler presetHandler) { InitializeComponent(); _frmMainWindow = fmw; @@ -28,12 +29,13 @@ namespace Handbrake { if (_presetCode.Add(txt_preset_name.Text.Trim(), _query, check_pictureSettings.Checked)) { - TreeNode presetTreeview = new TreeNode(txt_preset_name.Text.Trim()) { ForeColor = Color.Black }; + TreeNode presetTreeview = new TreeNode(txt_preset_name.Text.Trim()) {ForeColor = Color.Black}; _frmMainWindow.treeView_presets.Nodes.Add(presetTreeview); this.Close(); - } + } else - MessageBox.Show("Sorry, that preset name already exists. Please choose another!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); + MessageBox.Show("Sorry, that preset name already exists. Please choose another!", "Warning", + MessageBoxButtons.OK, MessageBoxIcon.Warning); } private void btn_cancel_Click(object sender, EventArgs e) diff --git a/win/C#/frmDownload.cs b/win/C#/frmDownload.cs index 72b0fdef..17ce3ec4 100644 --- a/win/C#/frmDownload.cs +++ b/win/C#/frmDownload.cs @@ -4,15 +4,15 @@ Homepage: <http://handbrake.fr>. It may be used under the terms of the GNU General Public License. */ -using System; -using System.Windows.Forms; -using System.Net; -using System.IO; -using System.Threading; -using System.Diagnostics; - namespace Handbrake { + using System; + using System.Diagnostics; + using System.IO; + using System.Net; + using System.Threading; + using System.Windows.Forms; + public partial class frmDownload : Form { private readonly Thread _downloadThread; @@ -21,9 +21,12 @@ namespace Handbrake private HttpWebRequest _webRequest; private HttpWebResponse _webResponse; private static int _progress; - private Boolean _killThread; - private delegate void UpdateProgessCallback(Int64 bytesRead, Int64 totalBytes); + private bool _killThread; + + private delegate void UpdateProgessCallback(long bytesRead, long totalBytes); + private delegate void DownloadCompleteCallback(); + private delegate void DownloadFailedCallback(); @@ -38,7 +41,7 @@ namespace Handbrake private void Download(object file) { string tempPath = Path.Combine(Path.GetTempPath(), "handbrake-setup.exe"); - string hbUpdate = (string)file; + string hbUpdate = (string) file; WebClient wcDownload = new WebClient(); try @@ -46,10 +49,10 @@ namespace Handbrake if (File.Exists(tempPath)) File.Delete(tempPath); - _webRequest = (HttpWebRequest)WebRequest.Create(hbUpdate); + _webRequest = (HttpWebRequest) WebRequest.Create(hbUpdate); _webRequest.Credentials = CredentialCache.DefaultCredentials; - _webResponse = (HttpWebResponse)_webRequest.GetResponse(); - Int64 fileSize = _webResponse.ContentLength; + _webResponse = (HttpWebResponse) _webRequest.GetResponse(); + long fileSize = _webResponse.ContentLength; _responceStream = wcDownload.OpenRead(hbUpdate); _loacalStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None); @@ -64,7 +67,7 @@ namespace Handbrake return; _loacalStream.Write(downBuffer, 0, bytesSize); flength = _loacalStream.Length; - Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { _loacalStream.Length, fileSize }); + Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] {_loacalStream.Length, fileSize}); } _responceStream.Close(); @@ -81,12 +84,12 @@ namespace Handbrake } } - private void UpdateProgress(Int64 bytesRead, Int64 totalBytes) + private void UpdateProgress(long bytesRead, long totalBytes) { - long p = (bytesRead * 100) / totalBytes; + long p = (bytesRead*100)/totalBytes; int.TryParse(p.ToString(), out _progress); progress_download.Value = _progress; - lblProgress.Text = (bytesRead / 1024) + "k of " + (totalBytes / 1024) + "k "; + lblProgress.Text = (bytesRead/1024) + "k of " + (totalBytes/1024) + "k "; } private void DownloadComplete() diff --git a/win/C#/frmMain.cs b/win/C#/frmMain.cs index 18e39f7c..ca36cb9f 100644 --- a/win/C#/frmMain.cs +++ b/win/C#/frmMain.cs @@ -4,27 +4,28 @@ Homepage: <http://handbrake.fr/>. It may be used under the terms of the GNU General Public License. */ -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Globalization; -using System.Windows.Forms; -using System.IO; -using System.Diagnostics; -using System.Threading; -using Handbrake.EncodeQueue; -using Handbrake.Functions; -using Handbrake.Model; -using Handbrake.Presets; -using Handbrake.Parsing; - namespace Handbrake { + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Diagnostics; + using System.Drawing; + using System.Globalization; + using System.IO; + using System.Threading; + using System.Windows.Forms; + using EncodeQueue; + using Functions; + using Model; + using Parsing; + using Presets; + public partial class frmMain : Form { // Objects which may be used by one or more other objects ************* - Queue encodeQueue = new Queue(); - PresetsHandler presetHandler = new PresetsHandler(); + private Queue encodeQueue = new Queue(); + private PresetsHandler presetHandler = new PresetsHandler(); // Globals: Mainly used for tracking. ********************************* public Title selectedTitle; @@ -46,12 +47,13 @@ namespace Handbrake // Applicaiton Startup ************************************************ #region Application Startup + public frmMain() { // Load and setup the splash screen in this thread splash = new frmSplashScreen(); splash.Show(this); - Label lblStatus = new Label { Size = new Size(150, 20), Location = new Point(182, 102) }; + Label lblStatus = new Label {Size = new Size(150, 20), Location = new Point(182, 102)}; splash.Controls.Add(lblStatus); InitializeComponent(); @@ -93,28 +95,30 @@ namespace Handbrake // Setup the GUI components lblStatus.Text = "Setting up the GUI ..."; Application.DoEvents(); - LoadPresetPanel(); // Load the Preset Panel + LoadPresetPanel(); // Load the Preset Panel treeView_presets.ExpandAll(); - lbl_encode.Text = ""; + lbl_encode.Text = string.Empty; drop_mode.SelectedIndex = 0; - queueWindow = new frmQueue(encodeQueue, this); // Prepare the Queue + queueWindow = new frmQueue(encodeQueue, this); // Prepare the Queue if (!Properties.Settings.Default.QueryEditorTab) tabs_panel.TabPages.RemoveAt(7); // Remove the query editor tab if the user does not want it enabled. // Load the user's default settings or Normal Preset - if (Properties.Settings.Default.defaultPreset != "") + if (Properties.Settings.Default.defaultPreset != string.Empty) { if (presetHandler.GetPreset(Properties.Settings.Default.defaultPreset) != null) { string query = presetHandler.GetPreset(Properties.Settings.Default.defaultPreset).Query; - Boolean loadPictureSettings = presetHandler.GetPreset(Properties.Settings.Default.defaultPreset).PictureSettings; + bool loadPictureSettings = + presetHandler.GetPreset(Properties.Settings.Default.defaultPreset).PictureSettings; if (query != null) { x264Panel.Reset2Defaults(); QueryParser presetQuery = QueryParser.Parse(query); - PresetLoader.LoadPreset(this, presetQuery, Properties.Settings.Default.defaultPreset, loadPictureSettings); + PresetLoader.LoadPreset(this, presetQuery, Properties.Settings.Default.defaultPreset, + loadPictureSettings); x264Panel.X264_StandardizeOptString(); x264Panel.X264_SetCurrentSettingsInPanel(); @@ -133,7 +137,7 @@ namespace Handbrake // Register with Growl (if not using Growl for the encoding completion action, this wont hurt anything) GrowlCommunicator.Register(); - //Finished Loading + // Finished Loading lblStatus.Text = "Loading Complete!"; Application.DoEvents(); splash.Close(); @@ -167,8 +171,10 @@ namespace Handbrake } catch (Exception ex) { - if ((bool)result.AsyncState) - MessageBox.Show("Unable to check for updates, Please try again later.\n\nDetailed Error Information:\n" + ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + if ((bool) result.AsyncState) + MessageBox.Show( + "Unable to check for updates, Please try again later.\n\nDetailed Error Information:\n" + ex, + "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -177,7 +183,10 @@ namespace Handbrake { if (Main.CheckQueueRecovery()) { - 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); + 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); if (result == DialogResult.Yes) encodeQueue.LoadQueueFromFile("hb_queue_recovery.xml"); // Start Recovery @@ -190,9 +199,11 @@ namespace Handbrake } } } + #endregion #region Properties + public string SourceName { get @@ -208,9 +219,11 @@ namespace Handbrake return Path.GetFileNameWithoutExtension(Path.GetDirectoryName(this.sourcePath)); } } + #endregion #region Events + // Encoding Events for setting up the GUI private void events() { @@ -242,7 +255,7 @@ namespace Handbrake check_optimiseMP4.CheckedChanged += new EventHandler(changePresetLabel); // Picture Settings - //PictureSettings.PictureSettingsChanged += new EventHandler(changePresetLabel); + // PictureSettings.PictureSettingsChanged += new EventHandler(changePresetLabel); // Filter Settings Filters.FilterSettingsChanged += new EventHandler(changePresetLabel); @@ -261,6 +274,7 @@ namespace Handbrake // Advanced Tab x264Panel.rtf_x264Query.TextChanged += new EventHandler(changePresetLabel); } + private void UnRegisterPresetEventHandler() { // Output Settings @@ -270,7 +284,7 @@ namespace Handbrake check_optimiseMP4.CheckedChanged -= new EventHandler(changePresetLabel); // Picture Settings - //PictureSettings.PictureSettingsChanged -= new EventHandler(changePresetLabel); + // PictureSettings.PictureSettingsChanged -= new EventHandler(changePresetLabel); // Filter Settings Filters.FilterSettingsChanged -= new EventHandler(changePresetLabel); @@ -289,6 +303,7 @@ namespace Handbrake // Advanced Tab x264Panel.rtf_x264Query.TextChanged -= new EventHandler(changePresetLabel); } + private void changePresetLabel(object sender, EventArgs e) { labelPreset.Text = "Output Settings (Preset: Custom)"; @@ -300,6 +315,7 @@ namespace Handbrake if (e.Data.GetDataPresent(DataFormats.FileDrop, false)) e.Effect = DragDropEffects.All; } + private void frmMain_DragDrop(object sender, DragEventArgs e) { string[] fileList = e.Data.GetData(DataFormats.FileDrop) as string[]; @@ -307,7 +323,7 @@ namespace Handbrake if (fileList != null) { - if (fileList[0] != "") + if (fileList[0] != string.Empty) { this.selectedSourceType = SourceType.VideoFile; StartScan(fileList[0], 0); @@ -318,6 +334,7 @@ namespace Handbrake else UpdateSourceLabel(); } + private void encodeStarted(object sender, EventArgs e) { lastAction = "encode"; @@ -330,92 +347,115 @@ namespace Handbrake encodeMon.Start(); } } + private void encodeEnded(object sender, EventArgs e) { SetEncodeFinished(); } + private void encodePaused(object sender, EventArgs e) { SetEncodeFinished(); } + #endregion // User Interface Menus / Tool Strips ********************************* #region File Menu + private void mnu_killCLI_Click(object sender, EventArgs e) { KillScan(); } + private void mnu_exit_Click(object sender, EventArgs e) { Application.Exit(); } + #endregion #region Tools Menu + private void mnu_encode_Click(object sender, EventArgs e) { queueWindow.Show(); } + private void mnu_encodeLog_Click(object sender, EventArgs e) { frmActivityWindow dvdInfoWindow = new frmActivityWindow(lastAction); dvdInfoWindow.Show(); } + private void mnu_options_Click(object sender, EventArgs e) { Form options = new frmOptions(this); options.ShowDialog(); } + #endregion #region Presets Menu + private void mnu_presetReset_Click(object sender, EventArgs e) { presetHandler.UpdateBuiltInPresets(); LoadPresetPanel(); if (treeView_presets.Nodes.Count == 0) - 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); + 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); else MessageBox.Show("Presets have been updated!", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Information); treeView_presets.ExpandAll(); } + private void mnu_delete_preset_Click(object sender, EventArgs e) { presetHandler.RemoveBuiltInPresets(); LoadPresetPanel(); // Reload the preset panel } + private void mnu_SelectDefault_Click(object sender, EventArgs e) { loadNormalPreset(); } + private void mnu_importMacPreset_Click(object sender, EventArgs e) { importPreset(); } + private void btn_new_preset_Click(object sender, EventArgs e) { - Form preset = new frmAddPreset(this, QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null), presetHandler); + Form preset = new frmAddPreset(this, QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null), + presetHandler); preset.ShowDialog(); } + #endregion #region Help Menu + private void mnu_user_guide_Click(object sender, EventArgs e) { Process.Start("http://trac.handbrake.fr/wiki/HandBrakeGuide"); } + private void mnu_handbrake_home_Click(object sender, EventArgs e) { Process.Start("http://handbrake.fr"); } + private void mnu_UpdateCheck_Click(object sender, EventArgs e) { lbl_updateCheck.Visible = true; Main.BeginCheckForUpdates(new AsyncCallback(updateCheckDoneMenu), false); } + private void updateCheckDoneMenu(IAsyncResult result) { // Make sure it's running on the calling thread @@ -436,16 +476,20 @@ namespace Handbrake updateWindow.ShowDialog(); } else - MessageBox.Show("There are no new updates at this time.", "Update Check", MessageBoxButtons.OK, MessageBoxIcon.Information); + MessageBox.Show("There are no new updates at this time.", "Update Check", MessageBoxButtons.OK, + MessageBoxIcon.Information); lbl_updateCheck.Visible = false; return; } catch (Exception ex) { - if ((bool)result.AsyncState) - MessageBox.Show("Unable to check for updates, Please try again later.\n\nDetailed Error Information:\n" + ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + if ((bool) result.AsyncState) + MessageBox.Show( + "Unable to check for updates, Please try again later.\n\nDetailed Error Information:\n" + ex, + "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } + private void mnu_about_Click(object sender, EventArgs e) { using (frmAbout About = new frmAbout()) @@ -453,30 +497,42 @@ namespace Handbrake About.ShowDialog(); } } + #endregion #region Preset Bar + // Right Click Menu Code private void pmnu_expandAll_Click(object sender, EventArgs e) { treeView_presets.ExpandAll(); } + private void pmnu_collapse_Click(object sender, EventArgs e) { treeView_presets.CollapseAll(); } + private void pmnu_import_Click(object sender, EventArgs e) { importPreset(); } + private void pmnu_saveChanges_Click(object sender, EventArgs e) { - 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); + 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); if (result == DialogResult.Yes) - presetHandler.Update(treeView_presets.SelectedNode.Text, QueryGenerator.GenerateTabbedComponentsQuery(this), true); + presetHandler.Update(treeView_presets.SelectedNode.Text, + QueryGenerator.GenerateTabbedComponentsQuery(this), true); else if (result == DialogResult.No) - presetHandler.Update(treeView_presets.SelectedNode.Text, QueryGenerator.GenerateTabbedComponentsQuery(this), false); + presetHandler.Update(treeView_presets.SelectedNode.Text, + QueryGenerator.GenerateTabbedComponentsQuery(this), false); } + private void pmnu_delete_click(object sender, EventArgs e) { if (treeView_presets.SelectedNode != null) @@ -486,7 +542,8 @@ namespace Handbrake } treeView_presets.Select(); } - private void presets_menu_Opening(object sender, System.ComponentModel.CancelEventArgs e) + + private void presets_menu_Opening(object sender, CancelEventArgs e) { // Make sure that the save menu is always disabled by default pmnu_saveChanges.Enabled = false; @@ -505,9 +562,11 @@ namespace Handbrake Form preset = new frmAddPreset(this, QueryGenerator.GenerateTabbedComponentsQuery(this), presetHandler); preset.ShowDialog(); } + private void btn_removePreset_Click(object sender, EventArgs e) { - DialogResult result = MessageBox.Show("Are you sure you wish to delete the selected preset?", "Preset", MessageBoxButtons.YesNo, MessageBoxIcon.Question); + DialogResult result = MessageBox.Show("Are you sure you wish to delete the selected preset?", "Preset", + MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { if (treeView_presets.SelectedNode != null) @@ -518,11 +577,13 @@ namespace Handbrake } treeView_presets.Select(); } + private void btn_setDefault_Click(object sender, EventArgs e) { if (treeView_presets.SelectedNode != null) { - DialogResult result = MessageBox.Show("Are you sure you wish to set this preset as the default?", "Preset", MessageBoxButtons.YesNo, MessageBoxIcon.Question); + DialogResult result = MessageBox.Show("Are you sure you wish to set this preset as the default?", + "Preset", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { Properties.Settings.Default.defaultPreset = treeView_presets.SelectedNode.Text; @@ -533,6 +594,7 @@ namespace Handbrake else MessageBox.Show("Please select a preset first.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } + private void treeview_presets_mouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) @@ -548,22 +610,25 @@ namespace Handbrake treeView_presets.Select(); } + private void treeView_presets_AfterSelect(object sender, TreeViewEventArgs e) { selectPreset(); } + private void treeView_presets_deleteKey(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Delete) { - DialogResult result = MessageBox.Show("Are you sure you wish to delete the selected preset?", "Preset", MessageBoxButtons.YesNo, MessageBoxIcon.Question); + DialogResult result = MessageBox.Show("Are you sure you wish to delete the selected preset?", "Preset", + MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { if (treeView_presets.SelectedNode != null) presetHandler.Remove(treeView_presets.SelectedNode.Text); // Remember each nodes expanded status so we can reload it - List<Boolean> nodeStatus = new List<Boolean>(); + List<bool> nodeStatus = new List<bool>(); foreach (TreeNode node in treeView_presets.Nodes) nodeStatus.Add(node.IsExpanded); @@ -582,6 +647,7 @@ namespace Handbrake } } } + private void selectPreset() { if (treeView_presets.SelectedNode != null) @@ -592,11 +658,11 @@ namespace Handbrake if (preset != null) { string query = presetHandler.GetPreset(presetName).Query; - Boolean loadPictureSettings = presetHandler.GetPreset(presetName).PictureSettings; + bool loadPictureSettings = presetHandler.GetPreset(presetName).PictureSettings; if (query != null) { - //Ok, Reset all the H264 widgets before changing the preset + // Ok, Reset all the H264 widgets before changing the preset x264Panel.Reset2Defaults(); // Send the query from the file to the Query Parser class @@ -616,6 +682,7 @@ namespace Handbrake } } } + private void loadNormalPreset() { foreach (TreeNode treenode in treeView_presets.Nodes) @@ -627,6 +694,7 @@ namespace Handbrake } } } + private void importPreset() { if (openPreset.ShowDialog() == DialogResult.OK) @@ -634,51 +702,65 @@ namespace Handbrake QueryParser parsed = PlistPresetHandler.Import(openPreset.FileName); if (presetHandler.CheckIfUserPresetExists(parsed.PresetName + " (Imported)")) { - DialogResult result = MessageBox.Show("This preset appears to already exist. Would you like to overwrite it?", "Overwrite preset?", - MessageBoxButtons.YesNo, MessageBoxIcon.Warning); + DialogResult result = + MessageBox.Show("This preset appears to already exist. Would you like to overwrite it?", + "Overwrite preset?", + MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (result == DialogResult.Yes) { PresetLoader.LoadPreset(this, parsed, parsed.PresetName, parsed.UsesPictureSettings); - presetHandler.Update(parsed.PresetName + " (Imported)", QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null), - parsed.UsesPictureSettings); + presetHandler.Update(parsed.PresetName + " (Imported)", + QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null), + parsed.UsesPictureSettings); } } else { PresetLoader.LoadPreset(this, parsed, parsed.PresetName, parsed.UsesPictureSettings); - presetHandler.Add(parsed.PresetName, QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null), parsed.UsesPictureSettings); + presetHandler.Add(parsed.PresetName, + QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null), + parsed.UsesPictureSettings); - if (presetHandler.Add(parsed.PresetName + " (Imported)", QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null), parsed.UsesPictureSettings)) + if (presetHandler.Add(parsed.PresetName + " (Imported)", + QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null), + parsed.UsesPictureSettings)) { - TreeNode preset_treeview = new TreeNode(parsed.PresetName + " (Imported)") { ForeColor = Color.Black }; + TreeNode preset_treeview = new TreeNode(parsed.PresetName + " (Imported)") + { + ForeColor = Color.Black + }; treeView_presets.Nodes.Add(preset_treeview); } } } } + #endregion #region ToolStrip + private void btn_source_Click(object sender, EventArgs e) { mnu_dvd_drive.Visible = true; Thread driveInfoThread = new Thread(SetDriveSelectionMenuItem); driveInfoThread.Start(); } + private void btn_start_Click(object sender, EventArgs e) { if (btn_start.Text == "Stop") { DialogResult result; - if (Properties.Settings.Default.enocdeStatusInGui && !Properties.Settings.Default.showCliForInGuiEncodeStatus) + if (Properties.Settings.Default.enocdeStatusInGui && + !Properties.Settings.Default.showCliForInGuiEncodeStatus) { result = MessageBox.Show( - "Are you sure you wish to cancel the encode?\n\nPlease note, when 'Enable in-GUI encode status' is enabled, stopping this encode will render the file unplayable. ", - "Cancel Encode?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); + "Are you sure you wish to cancel the encode?\n\nPlease note, when 'Enable in-GUI encode status' is enabled, stopping this encode will render the file unplayable. ", + "Cancel Encode?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); } else { - result = MessageBox.Show("Are you sure you wish to cancel the encode?", "Cancel Encode?", + result = MessageBox.Show("Are you sure you wish to cancel the encode?", "Cancel Encode?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); } @@ -687,7 +769,8 @@ namespace Handbrake // Pause The Queue encodeQueue.Pause(); - if (Properties.Settings.Default.enocdeStatusInGui && !Properties.Settings.Default.showCliForInGuiEncodeStatus) + if (Properties.Settings.Default.enocdeStatusInGui && + !Properties.Settings.Default.showCliForInGuiEncodeStatus) { encodeQueue.Stop(); if (encodeQueue.HbProcess != null) @@ -704,23 +787,28 @@ namespace Handbrake } else { - if (encodeQueue.Count != 0 || (!string.IsNullOrEmpty(sourcePath) && !string.IsNullOrEmpty(text_destination.Text))) + if (encodeQueue.Count != 0 || + (!string.IsNullOrEmpty(sourcePath) && !string.IsNullOrEmpty(text_destination.Text))) { string generatedQuery = QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null); - string specifiedQuery = rtf_query.Text != "" ? rtf_query.Text : QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null); + string specifiedQuery = rtf_query.Text != string.Empty + ? rtf_query.Text + : QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null); string query = string.Empty; // Check to make sure the generated query matches the GUI settings - if (Properties.Settings.Default.PromptOnUnmatchingQueries && !string.IsNullOrEmpty(specifiedQuery) && generatedQuery != specifiedQuery) + if (Properties.Settings.Default.PromptOnUnmatchingQueries && !string.IsNullOrEmpty(specifiedQuery) && + generatedQuery != specifiedQuery) { DialogResult result = MessageBox.Show("The query under the \"Query Editor\" tab " + - "does not match the current GUI settings.\n\nBecause the manual query takes " + - "priority over the GUI, your recently updated settings will not be taken " + - "into account when encoding this job." + Environment.NewLine + Environment.NewLine + - "Do you want to replace the manual query with the updated GUI-generated query?", - "Manual Query does not Match GUI", - MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk, - MessageBoxDefaultButton.Button3); + "does not match the current GUI settings.\n\nBecause the manual query takes " + + "priority over the GUI, your recently updated settings will not be taken " + + "into account when encoding this job." + + Environment.NewLine + Environment.NewLine + + "Do you want to replace the manual query with the updated GUI-generated query?", + "Manual Query does not Match GUI", + MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk, + MessageBoxDefaultButton.Button3); switch (result) { @@ -744,14 +832,17 @@ namespace Handbrake } DialogResult overwrite = DialogResult.Yes; - if (text_destination.Text != "") + if (text_destination.Text != string.Empty) if (File.Exists(text_destination.Text)) - overwrite = MessageBox.Show("The destination file already exists. Are you sure you want to overwrite it?", "Overwrite File?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); + overwrite = + MessageBox.Show( + "The destination file already exists. Are you sure you want to overwrite it?", + "Overwrite File?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (overwrite == DialogResult.Yes) { if (encodeQueue.Count == 0) - encodeQueue.Add(query, sourcePath, text_destination.Text, (rtf_query.Text != "")); + encodeQueue.Add(query, sourcePath, text_destination.Text, (rtf_query.Text != string.Empty)); queueWindow.SetQueue(); if (encodeQueue.Count > 1) @@ -759,7 +850,7 @@ namespace Handbrake SetEncodeStarted(); // Encode is running, so setup the GUI appropriately encodeQueue.Start(); // Start The Queue Encoding Process - lastAction = "encode"; // Set the last action to encode - Used for activity window. + lastAction = "encode"; // Set the last action to encode - Used for activity window. } if (ActivityWindow != null) ActivityWindow.SetEncodeMode(); @@ -767,44 +858,51 @@ namespace Handbrake this.Focus(); } else if (string.IsNullOrEmpty(sourcePath) || string.IsNullOrEmpty(text_destination.Text)) - MessageBox.Show("No source or destination selected.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); + MessageBox.Show("No source or destination selected.", "Warning", MessageBoxButtons.OK, + MessageBoxIcon.Warning); } } + private void btn_add2Queue_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(sourcePath) || string.IsNullOrEmpty(text_destination.Text)) - MessageBox.Show("No source or destination selected.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); + MessageBox.Show("No source or destination selected.", "Warning", MessageBoxButtons.OK, + MessageBoxIcon.Warning); else { - String query = QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null); - if (rtf_query.Text != "") + string query = QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null); + if (rtf_query.Text != string.Empty) query = rtf_query.Text; if (encodeQueue.CheckForDestinationDuplicate(text_destination.Text)) { - 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?", - "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); + 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?", + "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (result == DialogResult.Yes) - encodeQueue.Add(query, sourcePath, text_destination.Text, (rtf_query.Text != "")); - + encodeQueue.Add(query, sourcePath, text_destination.Text, (rtf_query.Text != string.Empty)); } else - encodeQueue.Add(query, sourcePath, text_destination.Text, (rtf_query.Text != "")); + encodeQueue.Add(query, sourcePath, text_destination.Text, (rtf_query.Text != string.Empty)); lbl_encode.Text = encodeQueue.Count + " encode(s) pending in the queue"; queueWindow.Show(); } } + private void btn_showQueue_Click(object sender, EventArgs e) { queueWindow.Show(); queueWindow.Activate(); } + private void tb_preview_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(sourcePath) || string.IsNullOrEmpty(text_destination.Text)) - MessageBox.Show("No source or destination selected.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); + MessageBox.Show("No source or destination selected.", "Warning", MessageBoxButtons.OK, + MessageBoxIcon.Warning); else { if (qtpreview == null) @@ -818,9 +916,11 @@ namespace Handbrake qtpreview.Show(); } else - MessageBox.Show(qtpreview, "The preview window is already open!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); + MessageBox.Show(qtpreview, "The preview window is already open!", "Warning", MessageBoxButtons.OK, + MessageBoxIcon.Warning); } } + private void btn_ActivityWindow_Click(object sender, EventArgs e) { if (ActivityWindow == null || !ActivityWindow.IsHandleCreated) @@ -842,9 +942,11 @@ namespace Handbrake ActivityWindow.Show(); ActivityWindow.Activate(); } + #endregion #region System Tray Icon + private void frmMain_Resize(object sender, EventArgs e) { if (FormWindowState.Minimized == this.WindowState) @@ -855,6 +957,7 @@ namespace Handbrake else if (FormWindowState.Normal == this.WindowState) notifyIcon.Visible = false; } + private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e) { this.Visible = true; @@ -862,6 +965,7 @@ namespace Handbrake this.WindowState = FormWindowState.Normal; notifyIcon.Visible = false; } + private void btn_restore_Click(object sender, EventArgs e) { this.Visible = true; @@ -869,11 +973,12 @@ namespace Handbrake this.WindowState = FormWindowState.Normal; notifyIcon.Visible = false; } + #endregion #region Tab Control - //Source + // Source private void btn_dvd_source_Click(object sender, EventArgs e) { if (DVD_Open.ShowDialog() == DialogResult.OK) @@ -884,6 +989,7 @@ namespace Handbrake else UpdateSourceLabel(); } + private void btn_file_source_Click(object sender, EventArgs e) { if (ISO_Open.ShowDialog() == DialogResult.OK) @@ -894,12 +1000,14 @@ namespace Handbrake else UpdateSourceLabel(); } + private void mnu_dvd_drive_Click(object sender, EventArgs e) { if (this.dvdDrivePath == null) return; this.selectedSourceType = SourceType.DvdDrive; SelectSource(this.dvdDrivePath); } + private void SelectSource(string file) { Check_ChapterMarkers.Enabled = true; @@ -915,11 +1023,15 @@ namespace Handbrake sourcePath = Path.GetFileName(file); StartScan(file, 0); } + private void drp_dvdtitle_Click(object sender, EventArgs e) { if ((drp_dvdtitle.Items.Count == 1) && (drp_dvdtitle.Items[0].ToString() == "Automatic")) - 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); + 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); } + private void drp_dvdtitle_SelectedIndexChanged(object sender, EventArgs e) { UnRegisterPresetEventHandler(); @@ -936,7 +1048,7 @@ namespace Handbrake selectedTitle = drp_dvdtitle.SelectedItem as Title; lbl_duration.Text = selectedTitle.Duration.ToString(); PictureSettings.CurrentlySelectedPreset = CurrentlySelectedPreset; - PictureSettings.Source = selectedTitle; // Setup Picture Settings Tab Control + PictureSettings.Source = selectedTitle; // Setup Picture Settings Tab Control // Populate the Angles dropdown drop_angle.Items.Clear(); @@ -984,7 +1096,9 @@ namespace Handbrake if (autoPath != null) text_destination.Text = autoPath; else - 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); + 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); } data_chpt.Rows.Clear(); @@ -1006,12 +1120,13 @@ namespace Handbrake RegisterPresetEventHandler(); } + private void chapersChanged(object sender, EventArgs e) { if (drop_mode.SelectedIndex != 0) // Function is not used if we are not in chapters mode. return; - Control ctl = (Control)sender; + Control ctl = (Control) sender; int chapterStart, chapterEnd; int.TryParse(drop_chapterStart.Text, out chapterStart); int.TryParse(drop_chapterFinish.Text, out chapterEnd); @@ -1045,8 +1160,8 @@ namespace Handbrake int n = data_chpt.Rows.Add(); data_chpt.Rows[n].Cells[0].Value = (i + 1); data_chpt.Rows[n].Cells[1].Value = "Chapter " + (i + 1); - data_chpt.Rows[n].Cells[0].ValueType = typeof(int); - data_chpt.Rows[n].Cells[1].ValueType = typeof(string); + data_chpt.Rows[n].Cells[0].ValueType = typeof (int); + data_chpt.Rows[n].Cells[1].ValueType = typeof (string); i++; } } @@ -1054,7 +1169,9 @@ namespace Handbrake } // Update the Duration - lbl_duration.Text = Main.CalculateDuration(drop_chapterStart.SelectedIndex, drop_chapterFinish.SelectedIndex, selectedTitle).ToString(); + lbl_duration.Text = + Main.CalculateDuration(drop_chapterStart.SelectedIndex, drop_chapterFinish.SelectedIndex, selectedTitle) + .ToString(); // Run the Autonaming function if (Properties.Settings.Default.autoNaming) @@ -1077,6 +1194,7 @@ namespace Handbrake } } } + private void SecondsOrFramesChanged(object sender, EventArgs e) { int start, end; @@ -1092,7 +1210,7 @@ namespace Handbrake case 2: if (selectedTitle != null) { - duration = duration / selectedTitle.Fps; + duration = duration/selectedTitle.Fps; lbl_duration.Text = TimeSpan.FromSeconds(duration).ToString(); } else @@ -1101,11 +1219,12 @@ namespace Handbrake return; } } + private void drop_mode_SelectedIndexChanged(object sender, EventArgs e) { // Reset - this.drop_chapterFinish.TextChanged -= new System.EventHandler(this.SecondsOrFramesChanged); - this.drop_chapterStart.TextChanged -= new System.EventHandler(this.SecondsOrFramesChanged); + this.drop_chapterFinish.TextChanged -= new EventHandler(this.SecondsOrFramesChanged); + this.drop_chapterStart.TextChanged -= new EventHandler(this.SecondsOrFramesChanged); // Do Work switch (drop_mode.SelectedIndex) @@ -1122,8 +1241,8 @@ namespace Handbrake lbl_duration.Text = "--:--:--"; return; case 1: - this.drop_chapterStart.TextChanged += new System.EventHandler(this.SecondsOrFramesChanged); - this.drop_chapterFinish.TextChanged += new System.EventHandler(this.SecondsOrFramesChanged); + this.drop_chapterStart.TextChanged += new EventHandler(this.SecondsOrFramesChanged); + this.drop_chapterFinish.TextChanged += new EventHandler(this.SecondsOrFramesChanged); drop_chapterStart.DropDownStyle = ComboBoxStyle.Simple; drop_chapterFinish.DropDownStyle = ComboBoxStyle.Simple; if (selectedTitle != null) @@ -1133,20 +1252,20 @@ namespace Handbrake } return; case 2: - this.drop_chapterStart.TextChanged += new System.EventHandler(this.SecondsOrFramesChanged); - this.drop_chapterFinish.TextChanged += new System.EventHandler(this.SecondsOrFramesChanged); + this.drop_chapterStart.TextChanged += new EventHandler(this.SecondsOrFramesChanged); + this.drop_chapterFinish.TextChanged += new EventHandler(this.SecondsOrFramesChanged); drop_chapterStart.DropDownStyle = ComboBoxStyle.Simple; drop_chapterFinish.DropDownStyle = ComboBoxStyle.Simple; if (selectedTitle != null) { drop_chapterStart.Text = "0"; - drop_chapterFinish.Text = (selectedTitle.Fps * selectedTitle.Duration.TotalSeconds).ToString(); + drop_chapterFinish.Text = (selectedTitle.Fps*selectedTitle.Duration.TotalSeconds).ToString(); } return; } } - //Destination + // Destination private void btn_destBrowse_Click(object sender, EventArgs e) { // This removes the file extension from the filename box on the save file dialog. @@ -1168,18 +1287,22 @@ namespace Handbrake switch (DVD_Save.FilterIndex) { case 1: - if (!Path.GetExtension(DVD_Save.FileName).Equals(".mp4", StringComparison.InvariantCultureIgnoreCase)) + if ( + !Path.GetExtension(DVD_Save.FileName).Equals(".mp4", + StringComparison.InvariantCultureIgnoreCase)) if (Properties.Settings.Default.useM4v) DVD_Save.FileName = DVD_Save.FileName.Replace(".mp4", ".m4v").Replace(".mkv", ".m4v"); else DVD_Save.FileName = DVD_Save.FileName.Replace(".m4v", ".mp4").Replace(".mkv", ".mp4"); break; case 2: - if (!Path.GetExtension(DVD_Save.FileName).Equals(".mkv", StringComparison.InvariantCultureIgnoreCase)) + if ( + !Path.GetExtension(DVD_Save.FileName).Equals(".mkv", + StringComparison.InvariantCultureIgnoreCase)) DVD_Save.FileName = DVD_Save.FileName.Replace(".mp4", ".mkv").Replace(".m4v", ".mkv"); break; default: - //do nothing + // do nothing break; } text_destination.Text = DVD_Save.FileName; @@ -1189,6 +1312,7 @@ namespace Handbrake SetExtension(".m4v"); } } + private void text_destination_TextChanged(object sender, EventArgs e) { string path = text_destination.Text; @@ -1204,7 +1328,8 @@ namespace Handbrake switch (drop_format.SelectedIndex) { case 0: - if (Properties.Settings.Default.useM4v || Check_ChapterMarkers.Checked || AudioSettings.RequiresM4V() || Subtitles.RequiresM4V()) + if (Properties.Settings.Default.useM4v || Check_ChapterMarkers.Checked || + AudioSettings.RequiresM4V() || Subtitles.RequiresM4V()) SetExtension(".m4v"); else SetExtension(".mp4"); @@ -1228,10 +1353,12 @@ namespace Handbrake else if (drop_format.Text.Contains("MKV")) drp_videoEncoder.Items.Add("VP3 (Theora)"); } + public void SetExtension(string newExtension) { if (newExtension == ".mp4" || newExtension == ".m4v") - if (Properties.Settings.Default.useM4v || Check_ChapterMarkers.Checked || AudioSettings.RequiresM4V() || Subtitles.RequiresM4V()) + if (Properties.Settings.Default.useM4v || Check_ChapterMarkers.Checked || AudioSettings.RequiresM4V() || + Subtitles.RequiresM4V()) newExtension = ".m4v"; else newExtension = ".mp4"; @@ -1240,12 +1367,12 @@ namespace Handbrake text_destination.Text = Path.ChangeExtension(text_destination.Text, newExtension); } - //Video Tab + // Video Tab private void drp_videoEncoder_SelectedIndexChanged(object sender, EventArgs e) { setContainerOpts(); - //Turn off some options which are H.264 only when the user selects a non h.264 encoder + // Turn off some options which are H.264 only when the user selects a non h.264 encoder if (drp_videoEncoder.Text.Contains("H.264")) { if (check_2PassEncode.CheckState == CheckState.Checked) @@ -1262,7 +1389,7 @@ namespace Handbrake check_turbo.CheckState = CheckState.Unchecked; check_turbo.Enabled = false; tab_advanced.Enabled = false; - x264Panel.X264Query = ""; + x264Panel.X264Query = string.Empty; check_iPodAtom.Enabled = false; check_iPodAtom.Checked = false; } @@ -1272,7 +1399,7 @@ namespace Handbrake { case "MPEG-4 (FFmpeg)": if (slider_videoQuality.Value > 31) - slider_videoQuality.Value = 20; // Just reset to 70% QP 10 on encode change. + slider_videoQuality.Value = 20; // Just reset to 70% QP 10 on encode change. slider_videoQuality.Minimum = 1; slider_videoQuality.Maximum = 31; break; @@ -1282,8 +1409,8 @@ namespace Handbrake CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US"); double cqStep = Properties.Settings.Default.x264cqstep; - double multiplier = 1.0 / cqStep; - double value = slider_videoQuality.Value * multiplier; + double multiplier = 1.0/cqStep; + double value = slider_videoQuality.Value*multiplier; switch (Properties.Settings.Default.x264cqstep.ToString(culture)) { @@ -1304,17 +1431,18 @@ namespace Handbrake break; } if (value < slider_videoQuality.Maximum) - slider_videoQuality.Value = slider_videoQuality.Maximum - (int)value; + slider_videoQuality.Value = slider_videoQuality.Maximum - (int) value; break; case "VP3 (Theora)": if (slider_videoQuality.Value > 63) - slider_videoQuality.Value = 45; // Just reset to 70% QP 45 on encode change. + slider_videoQuality.Value = 45; // Just reset to 70% QP 45 on encode change. slider_videoQuality.Minimum = 0; slider_videoQuality.Maximum = 63; break; } } + /// <summary> /// Set the container format options /// </summary> @@ -1336,7 +1464,9 @@ namespace Handbrake check_iPodAtom.Checked = false; } } + private double _cachedCqStep = Properties.Settings.Default.x264cqstep; + /// <summary> /// Update the CQ slider for x264 for a new CQ step. This is set from option /// </summary> @@ -1344,7 +1474,7 @@ namespace Handbrake { // Work out the current RF value. double cqStep = _cachedCqStep; - double rfValue = 51.0 - slider_videoQuality.Value * cqStep; + double rfValue = 51.0 - slider_videoQuality.Value*cqStep; // Change the maximum value for the slider switch (Properties.Settings.Default.x264cqstep.ToString(new CultureInfo("en-US"))) @@ -1371,16 +1501,17 @@ namespace Handbrake // Reset the CQ slider back to the previous value as close as possible double cqStepNew = Properties.Settings.Default.x264cqstep; - double rfValueCurrent = 51.0 - slider_videoQuality.Value * cqStepNew; + double rfValueCurrent = 51.0 - slider_videoQuality.Value*cqStepNew; while (rfValueCurrent < rfValue) { slider_videoQuality.Value--; - rfValueCurrent = 51.0 - slider_videoQuality.Value * cqStepNew; + rfValueCurrent = 51.0 - slider_videoQuality.Value*cqStepNew; } // Cache the CQ step for the next calculation _cachedCqStep = Properties.Settings.Default.x264cqstep; } + private void slider_videoQuality_Scroll(object sender, EventArgs e) { double cqStep = Properties.Settings.Default.x264cqstep; @@ -1390,7 +1521,7 @@ namespace Handbrake lbl_SliderValue.Text = "QP:" + (32 - slider_videoQuality.Value); break; case "H.264 (x264)": - double rfValue = 51.0 - slider_videoQuality.Value * cqStep; + double rfValue = 51.0 - slider_videoQuality.Value*cqStep; rfValue = Math.Round(rfValue, 2); lbl_SliderValue.Text = "RF:" + rfValue.ToString(new CultureInfo("en-US")); break; @@ -1399,6 +1530,7 @@ namespace Handbrake break; } } + private void radio_targetFilesize_CheckedChanged(object sender, EventArgs e) { text_bitrate.Enabled = false; @@ -1407,6 +1539,7 @@ namespace Handbrake check_2PassEncode.Enabled = true; } + private void radio_avgBitrate_CheckedChanged(object sender, EventArgs e) { text_bitrate.Enabled = true; @@ -1415,6 +1548,7 @@ namespace Handbrake check_2PassEncode.Enabled = true; } + private void radio_cq_CheckedChanged(object sender, EventArgs e) { text_bitrate.Enabled = false; @@ -1424,6 +1558,7 @@ namespace Handbrake check_2PassEncode.Enabled = false; check_2PassEncode.CheckState = CheckState.Unchecked; } + private void check_2PassEncode_CheckedChanged(object sender, EventArgs e) { if (check_2PassEncode.CheckState.ToString() == "Checked") @@ -1456,16 +1591,18 @@ namespace Handbrake btn_importChapters.Enabled = false; } } + private void btn_importChapters_Click(object sender, EventArgs e) { if (File_ChapterImport.ShowDialog() == DialogResult.OK) { - String filename = File_ChapterImport.FileName; + string filename = File_ChapterImport.FileName; DataGridView imported = Main.ImportChapterNames(data_chpt, filename); if (imported != null) data_chpt = imported; } } + private void mnu_resetChapters_Click(object sender, EventArgs e) { data_chpt.Rows.Clear(); @@ -1481,19 +1618,22 @@ namespace Handbrake { rtf_query.Text = QueryGenerator.GenerateCliQuery(this, drop_mode.SelectedIndex, 0, null); } + private void btn_clear_Click(object sender, EventArgs e) { rtf_query.Clear(); } + #endregion // MainWindow Components, Actions and Functions *********************** #region Source Scan - public Boolean isScanning { get; set; } + + public bool isScanning { get; set; } private Scan SourceScan; - private void StartScan(String filename, int title) + private void StartScan(string filename, int title) { // Setup the GUI components for the scan. sourcePath = filename; @@ -1528,11 +1668,12 @@ namespace Handbrake } } - void SourceScan_ScanStatusChanged(object sender, EventArgs e) + private void SourceScan_ScanStatusChanged(object sender, EventArgs e) { UpdateScanStatusLabel(); } - void SourceScan_ScanCompleted(object sender, EventArgs e) + + private void SourceScan_ScanCompleted(object sender, EventArgs e) { UpdateGuiAfterScan(); } @@ -1546,6 +1687,7 @@ namespace Handbrake } lbl_encode.Text = SourceScan.ScanStatus(); } + private void UpdateGuiAfterScan() { if (InvokeRequired) @@ -1568,7 +1710,8 @@ namespace Handbrake drp_dvdtitle.SelectedItem = Main.SelectLongestTitle(currentSource); // Enable the creation of chapter markers if the file is an image of a dvd. - if (sourcePath.ToLower().Contains(".iso") || sourcePath.Contains("VIDEO_TS") || Directory.Exists(Path.Combine(sourcePath, "VIDEO_TS"))) + if (sourcePath.ToLower().Contains(".iso") || sourcePath.Contains("VIDEO_TS") || + Directory.Exists(Path.Combine(sourcePath, "VIDEO_TS"))) Check_ChapterMarkers.Enabled = true; else { @@ -1581,7 +1724,7 @@ namespace Handbrake if (drp_dvdtitle.Items.Count == 0) { MessageBox.Show( - "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).", + "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).", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); sourcePath = string.Empty; } @@ -1592,7 +1735,8 @@ namespace Handbrake } catch (Exception exc) { - MessageBox.Show("frmMain.cs - updateUIafterScan " + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("frmMain.cs - updateUIafterScan " + exc, "Error", MessageBoxButtons.OK, + MessageBoxIcon.Error); EnableGUI(); } } @@ -1618,6 +1762,7 @@ namespace Handbrake MessageBox.Show("frmMain.cs - EnableGUI() " + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } + private void KillScan() { try @@ -1633,9 +1778,12 @@ namespace Handbrake } catch (Exception ex) { - 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); + 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); } } + private void ResetGUI() { drp_dvdtitle.Items.Clear(); @@ -1649,12 +1797,14 @@ namespace Handbrake selectedTitle = null; isScanning = false; } + private void UpdateSourceLabel() { labelSource.Text = string.IsNullOrEmpty(sourcePath) ? "Select \"Source\" to continue." : this.SourceName; if (selectedTitle != null) - if (!string.IsNullOrEmpty(selectedTitle.SourceName)) // If it's one of multiple source files, make sure we don't use the folder name + if (!string.IsNullOrEmpty(selectedTitle.SourceName)) + // If it's one of multiple source files, make sure we don't use the folder name labelSource.Text = Path.GetFileName(selectedTitle.SourceName); } @@ -1666,7 +1816,7 @@ namespace Handbrake if (query != null) { - //Ok, Reset all the H264 widgets before changing the preset + // Ok, Reset all the H264 widgets before changing the preset x264Panel.Reset2Defaults(); // Send the query from the file to the Query Parser class @@ -1683,11 +1833,12 @@ namespace Handbrake CurrentlySelectedPreset = null; PictureSettings.SetPresetCropWarningLabel(null); } - } + #endregion #region GUI Functions and Actions + /// <summary> /// Set the GUI to it's finished encoding state. /// </summary> @@ -1783,13 +1934,14 @@ namespace Handbrake { if (presetHandler.CheckIfPresetsAreOutOfDate()) if (!Properties.Settings.Default.presetNotification) - MessageBox.Show(splash, - "HandBrake has determined your built-in presets are out of date... These presets will now be updated.", - "Preset Update", MessageBoxButtons.OK, MessageBoxIcon.Information); + MessageBox.Show(splash, + "HandBrake has determined your built-in presets are out of date... These presets will now be updated.", + "Preset Update", MessageBoxButtons.OK, MessageBoxIcon.Information); presetHandler.GetPresetPanel(ref treeView_presets); treeView_presets.Update(); } + #endregion #region Overrides @@ -1825,16 +1977,20 @@ namespace Handbrake // If currently encoding, the queue isn't paused, and there are queue items to process, prompt to confirm close. if ((encodeQueue.IsEncoding) && (!encodeQueue.PauseRequested) && (encodeQueue.Count > 0)) { - 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?", - "Close HandBrake?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); + 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?", + "Close HandBrake?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.No) e.Cancel = true; } base.OnFormClosing(e); } + #endregion #region In-GUI Encode Status (Experimental) + /// <summary> /// Starts a new thread to monitor and process the CLI encode status /// </summary> @@ -1852,7 +2008,7 @@ namespace Handbrake MessageBox.Show(exc.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - + /// <summary> /// Displays the Encode status in the GUI /// </summary> @@ -1863,16 +2019,24 @@ namespace Handbrake /// <param name="CurrentFps"></param> /// <param name="AverageFps"></param> /// <param name="TimeRemaining"></param> - private void EncodeOnEncodeProgress(object Sender, int CurrentTask, int TaskCount, float PercentComplete, float CurrentFps, float AverageFps, TimeSpan TimeRemaining) + private void EncodeOnEncodeProgress(object Sender, int CurrentTask, int TaskCount, float PercentComplete, + float CurrentFps, float AverageFps, TimeSpan TimeRemaining) { if (this.InvokeRequired) { - this.BeginInvoke(new EncodeProgressEventHandler(EncodeOnEncodeProgress), - new object[] { Sender, CurrentTask, TaskCount, PercentComplete, CurrentFps, AverageFps, TimeRemaining }); + this.BeginInvoke(new EncodeProgressEventHandler(EncodeOnEncodeProgress), + new[] + { + Sender, CurrentTask, TaskCount, PercentComplete, CurrentFps, AverageFps, + TimeRemaining + }); return; } - lbl_encode.Text = string.Format("Encode Progress: {0}%, FPS: {1}, Avg FPS: {2}, Time Remaining: {3} ", PercentComplete, CurrentFps, AverageFps, TimeRemaining); + lbl_encode.Text = + string.Format("Encode Progress: {0}%, FPS: {1}, Avg FPS: {2}, Time Remaining: {3} ", + PercentComplete, CurrentFps, AverageFps, TimeRemaining); } + #endregion // This is the END of the road **************************************** diff --git a/win/C#/frmOptions.cs b/win/C#/frmOptions.cs index 5427aeb2..aef75551 100644 --- a/win/C#/frmOptions.cs +++ b/win/C#/frmOptions.cs @@ -4,14 +4,15 @@ Homepage: <http://handbrake.fr>. It may be used under the terms of the GNU General Public License. */ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Windows.Forms; -using Handbrake.Functions; - namespace Handbrake { + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.Globalization; + using System.Windows.Forms; + using Functions; + public partial class frmOptions : Form { private frmMain mainWindow; @@ -193,6 +194,7 @@ namespace Handbrake } #region General + private void check_updateCheck_CheckedChanged(object sender, EventArgs e) { Properties.Settings.Default.updateStatus = check_updateCheck.Checked; @@ -254,7 +256,7 @@ namespace Handbrake { if (text_an_path.Text == string.Empty) { - Properties.Settings.Default.autoNamePath = ""; + Properties.Settings.Default.autoNamePath = string.Empty; text_an_path.Text = "Click 'Browse' to set the default location"; } else @@ -265,39 +267,48 @@ namespace Handbrake { Properties.Settings.Default.useM4v = check_m4v.Checked; } + #endregion #region Picture + private void btn_vlcPath_Click(object sender, EventArgs e) { openFile_vlc.ShowDialog(); if (openFile_vlc.FileName != string.Empty) txt_vlcPath.Text = openFile_vlc.FileName; } + private void txt_vlcPath_TextChanged(object sender, EventArgs e) { Properties.Settings.Default.VLC_Path = txt_vlcPath.Text; } + #endregion #region Audio and Subtitles + private void drop_preferredLang_SelectedIndexChanged(object sender, EventArgs e) { Properties.Settings.Default.NativeLanguage = drop_preferredLang.SelectedItem.ToString(); } + private void radio_dub_CheckedChanged(object sender, EventArgs e) { if (radio_dub.Checked) Properties.Settings.Default.DubAudio = true; } + private void radio_foreignAndSubs_CheckedChanged(object sender, EventArgs e) { if (radio_foreignAndSubs.Checked) Properties.Settings.Default.DubAudio = false; } + #endregion #region CLI + private void check_cli_minimized_CheckedChanged(object sender, EventArgs e) { Properties.Settings.Default.cli_minimized = check_cli_minimized.Checked; @@ -345,7 +356,7 @@ namespace Handbrake { string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs"; string windir = Environment.GetEnvironmentVariable("WINDIR"); - System.Diagnostics.Process prc = new System.Diagnostics.Process(); + Process prc = new Process(); prc.StartInfo.FileName = windir + @"\explorer.exe"; prc.StartInfo.Arguments = logDir; prc.Start(); @@ -353,11 +364,12 @@ namespace Handbrake private void btn_clearLogs_Click(object sender, EventArgs e) { - DialogResult result = MessageBox.Show("Are you sure you wish to clear the log file directory?", "Clear Logs", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); + DialogResult result = MessageBox.Show("Are you sure you wish to clear the log file directory?", "Clear Logs", + MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == DialogResult.Yes) { Main.ClearLogs(); - MessageBox.Show(this, "HandBrake's Log file directory has been cleared!", "Notice", MessageBoxButtons.OK, + MessageBox.Show(this, "HandBrake's Log file directory has been cleared!", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information); } } @@ -366,6 +378,7 @@ namespace Handbrake { Properties.Settings.Default.clearOldLogs = check_clearOldLogs.Checked; } + #endregion #region Advanced @@ -406,11 +419,12 @@ namespace Handbrake if (this.IsHandleCreated) if (check_inGuiStatus.Checked) { - MessageBox.Show("This feature is experimental!\n\n You will not be able to ‘Stop’ an encode mid-process.\n" - + "Doing so will render the file unplayable.\n" + - "If you enable 'Show CLI Window', you'll be ablt to hit ctrl-c in the encode window to cleanly exit the CLI. This will give you a playable file.\n\n" + - "You are also limited to 1 instance of HandBrakeCLI on your system.", - "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); + MessageBox.Show( + "This feature is experimental!\n\n You will not be able to ‘Stop’ an encode mid-process.\n" + + "Doing so will render the file unplayable.\n" + + "If you enable 'Show CLI Window', you'll be ablt to hit ctrl-c in the encode window to cleanly exit the CLI. This will give you a playable file.\n\n" + + "You are also limited to 1 instance of HandBrakeCLI on your system.", + "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } @@ -448,13 +462,16 @@ namespace Handbrake { Properties.Settings.Default.noDvdNav = check_dvdnav.Checked; } + #endregion #region Debug + private void check_disableResCalc_CheckedChanged(object sender, EventArgs e) { Properties.Settings.Default.disableResCalc = check_disableResCalc.Checked; } + #endregion private void btn_close_Click(object sender, EventArgs e) diff --git a/win/C#/frmPreview.cs b/win/C#/frmPreview.cs index 0059ede3..43668856 100644 --- a/win/C#/frmPreview.cs +++ b/win/C#/frmPreview.cs @@ -1,24 +1,26 @@ -using System; -using System.Windows.Forms; -using System.Threading; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.IO; -using Handbrake.EncodeQueue; -using Handbrake.Functions; -using QTOControlLib; -using QTOLibrary; - -namespace Handbrake +namespace Handbrake { + using System; + using System.Diagnostics; + using System.IO; + using System.Runtime.InteropServices; + using System.Threading; + using System.Windows.Forms; + using EncodeQueue; + using Functions; + using QTOControlLib; + using QTOLibrary; + public partial class frmPreview : Form { - readonly Queue Process = new Queue(); + private readonly Queue Process = new Queue(); + private delegate void UpdateUIHandler(); - String CurrentlyPlaying = ""; - readonly frmMain MainWindow; + + private string CurrentlyPlaying = string.Empty; + private readonly frmMain MainWindow; private Thread Player; - private readonly Boolean NoQT; + private readonly bool NoQT; public frmPreview(frmMain mw) { @@ -41,20 +43,22 @@ namespace Handbrake } #region Encode Sample + private void btn_playVLC_Click(object sender, EventArgs e) { lbl_status.Visible = true; try { if (!NoQT) - QTControl.URL = ""; + QTControl.URL = string.Empty; if (File.Exists(CurrentlyPlaying)) File.Delete(CurrentlyPlaying); } catch (Exception) { - MessageBox.Show(this, "Unable to delete previous preview file. You may need to restart the application.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(this, "Unable to delete previous preview file. You may need to restart the application.", + "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } btn_playQT.Enabled = false; @@ -62,20 +66,23 @@ namespace Handbrake lbl_status.Text = "Encoding Sample for (VLC) ..."; int duration; int.TryParse(cb_duration.Text, out duration); - String query = QueryGenerator.GenerateCliQuery(MainWindow, 3, duration, cb_preview.Text); + string query = QueryGenerator.GenerateCliQuery(MainWindow, 3, duration, cb_preview.Text); ThreadPool.QueueUserWorkItem(ProcMonitor, query); } + private void btn_playQT_Click(object sender, EventArgs e) { if (NoQT) { - MessageBox.Show(this, "It would appear QuickTime 7 is not installed or not accessible. Please (re)install QuickTime.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); + MessageBox.Show(this, + "It would appear QuickTime 7 is not installed or not accessible. Please (re)install QuickTime.", + "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (MainWindow.text_destination.Text.Contains(".mkv")) { - MessageBox.Show(this, - "The QuickTime Control does not support MKV files, It is recommended you use VLC option instead.", + MessageBox.Show(this, + "The QuickTime Control does not support MKV files, It is recommended you use VLC option instead.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else @@ -83,13 +90,15 @@ namespace Handbrake lbl_status.Visible = true; try { - QTControl.URL = ""; + QTControl.URL = string.Empty; if (File.Exists(CurrentlyPlaying)) File.Delete(CurrentlyPlaying); } catch (Exception) { - MessageBox.Show(this, "Unable to delete previous preview file. You may need to restart the application.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(this, + "Unable to delete previous preview file. You may need to restart the application.", + "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } btn_playQT.Enabled = false; @@ -97,19 +106,21 @@ namespace Handbrake lbl_status.Text = "Encoding Sample for (QT) ..."; int duration; int.TryParse(cb_duration.Text, out duration); - String query = QueryGenerator.GenerateCliQuery(MainWindow, 3, duration, cb_preview.Text); + string query = QueryGenerator.GenerateCliQuery(MainWindow, 3, duration, cb_preview.Text); ThreadPool.QueueUserWorkItem(ProcMonitor, query); } } + private void ProcMonitor(object state) { // Make sure we are not already encoding and if we are then display an error. if (Process.HbProcess != null) - MessageBox.Show(this, "Handbrake is already encoding a video!", "Status", MessageBoxButtons.OK, MessageBoxIcon.Warning); + MessageBox.Show(this, "Handbrake is already encoding a video!", "Status", MessageBoxButtons.OK, + MessageBoxIcon.Warning); else { - Process.CreatePreviewSample((string)state); + Process.CreatePreviewSample((string) state); if (Process.HbProcess != null) { Process.HbProcess.WaitForExit(); @@ -118,6 +129,7 @@ namespace Handbrake EncodeCompleted(); } } + private void EncodeCompleted() { try @@ -132,13 +144,16 @@ namespace Handbrake btn_playVLC.Enabled = true; // Decide which Player to use. - String playerSelection = lbl_status.Text.Contains("QT") ? "QT" : "VLC"; + string playerSelection = lbl_status.Text.Contains("QT") ? "QT" : "VLC"; lbl_status.Text = "Loading Clip ..."; // Get the sample filename - if (MainWindow.text_destination.Text != "") - CurrentlyPlaying = MainWindow.text_destination.Text.Replace(".mp4", "_sample.mp4").Replace(".m4v", "_sample.m4v").Replace(".mkv", "_sample.mkv"); ; + if (MainWindow.text_destination.Text != string.Empty) + CurrentlyPlaying = + MainWindow.text_destination.Text.Replace(".mp4", "_sample.mp4").Replace(".m4v", "_sample.m4v"). + Replace(".mkv", "_sample.mkv"); + ; // Play back in QT or VLC if (playerSelection == "QT") @@ -146,13 +161,15 @@ namespace Handbrake else PlayVLC(); - lbl_status.Text = ""; + lbl_status.Text = string.Empty; } catch (Exception exc) { - MessageBox.Show(this, "frmPreview.cs EncodeCompleted " + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(this, "frmPreview.cs EncodeCompleted " + exc, "Error", MessageBoxButtons.OK, + MessageBoxIcon.Error); } } + #endregion #region Playback @@ -162,7 +179,7 @@ namespace Handbrake /// </summary> private void Play() { - Player = new Thread(OpenMovie) { IsBackground = true }; + Player = new Thread(OpenMovie) {IsBackground = true}; Player.Start(); lbl_status.Visible = false; } @@ -173,20 +190,23 @@ namespace Handbrake private void PlayVLC() { // Launch VLC and Play video. - if (CurrentlyPlaying != "") + if (CurrentlyPlaying != string.Empty) { if (File.Exists(CurrentlyPlaying)) { // Attempt to find VLC if it doesn't exist in the default set location. string vlcPath; - - if (8 == IntPtr.Size || (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432")))) + + if (8 == IntPtr.Size || + (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432")))) vlcPath = Environment.GetEnvironmentVariable("ProgramFiles(x86)"); else vlcPath = Environment.GetEnvironmentVariable("ProgramFiles"); - - vlcPath = vlcPath != null ? vlcPath + @"\VideoLAN\VLC\vlc.exe" : @"C:\Program Files (x86)\VideoLAN\VLC\vlc.exe"; - + + vlcPath = vlcPath != null + ? vlcPath + @"\VideoLAN\VLC\vlc.exe" + : @"C:\Program Files (x86)\VideoLAN\VLC\vlc.exe"; + if (!File.Exists(Properties.Settings.Default.VLC_Path)) { if (File.Exists(vlcPath)) @@ -196,23 +216,24 @@ namespace Handbrake } else { - MessageBox.Show(this, - "Unable to detect VLC Player. \nPlease make sure VLC is installed and the directory specified in HandBrake's options is correct. (See: \"Tools Menu > Options > Picture Tab\") ", + MessageBox.Show(this, + "Unable to detect VLC Player. \nPlease make sure VLC is installed and the directory specified in HandBrake's options is correct. (See: \"Tools Menu > Options > Picture Tab\") ", "VLC", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } if (File.Exists(Properties.Settings.Default.VLC_Path)) { - String args = "\"" + CurrentlyPlaying + "\""; + string args = "\"" + CurrentlyPlaying + "\""; ProcessStartInfo vlc = new ProcessStartInfo(Properties.Settings.Default.VLC_Path, args); System.Diagnostics.Process.Start(vlc); lbl_status.Text = "VLC will now launch."; } - } else - MessageBox.Show(this, "Unable to find the preview file. Either the file was deleted or the encode failed. Check the activity log for details.", "VLC", MessageBoxButtons.OK, MessageBoxIcon.Warning); + MessageBox.Show(this, + "Unable to find the preview file. Either the file was deleted or the encode failed. Check the activity log for details.", + "VLC", MessageBoxButtons.OK, MessageBoxIcon.Warning); } lbl_status.Visible = false; } @@ -241,13 +262,18 @@ namespace Handbrake catch (COMException ex) { QTUtils qtu = new QTUtils(); - MessageBox.Show(this, "Unable to open movie:\n\nError Code: " + ex.ErrorCode.ToString("X") + "\nQT Error code : " + qtu.QTErrorFromErrorCode(ex.ErrorCode), "QT", MessageBoxButtons.OK, MessageBoxIcon.Warning); + MessageBox.Show(this, + "Unable to open movie:\n\nError Code: " + ex.ErrorCode.ToString("X") + + "\nQT Error code : " + qtu.QTErrorFromErrorCode(ex.ErrorCode), "QT", + MessageBoxButtons.OK, MessageBoxIcon.Warning); } catch (Exception ex) { - MessageBox.Show(this, "Unable to open movie:\n\n" + ex, "QT", MessageBoxButtons.OK, MessageBoxIcon.Warning); + MessageBox.Show(this, "Unable to open movie:\n\n" + ex, "QT", MessageBoxButtons.OK, + MessageBoxIcon.Warning); } } + #endregion } -} +} \ No newline at end of file diff --git a/win/C#/frmQueue.cs b/win/C#/frmQueue.cs index 326fb724..86596e05 100644 --- a/win/C#/frmQueue.cs +++ b/win/C#/frmQueue.cs @@ -4,19 +4,21 @@ Homepage: <http://handbrake.fr>. It may be used under the terms of the GNU General Public License. */ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Windows.Forms; -using Handbrake.EncodeQueue; -using System.Collections.ObjectModel; -using Handbrake.Model; - namespace Handbrake { + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.ComponentModel; + using System.Windows.Forms; + using EncodeQueue; + using Functions; + using Model; + public partial class frmQueue : Form { private delegate void UpdateHandler(); + private Queue queue; private frmMain mainWindow; @@ -37,11 +39,13 @@ namespace Handbrake SetUIEncodeFinished(); UpdateUIElements(); } + private void QueueOnQueueFinished(object sender, EventArgs e) { SetUIEncodeFinished(); ResetQueue(); // Reset the Queue Window } + private void QueueOnEncodeStart(object sender, EventArgs e) { SetUIEncodeStarted(); // make sure the UI is set correctly @@ -62,7 +66,7 @@ namespace Handbrake /// </summary> public new void Show() { - Show(true); + Show(true); } /// <summary> @@ -74,7 +78,7 @@ namespace Handbrake if (doSetQueue) SetQueue(); base.Show(); - //Activate(); + // Activate(); } // Start and Stop Controls @@ -88,14 +92,16 @@ namespace Handbrake if (!queue.IsEncoding) queue.Start(); - } + private void btn_pause_Click(object sender, EventArgs e) { queue.Pause(); SetUIEncodeFinished(); ResetQueue(); - MessageBox.Show("No further items on the queue will start. The current encode process will continue until it is finished. \nClick 'Encode' when you wish to continue encoding the queue.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); + MessageBox.Show( + "No further items on the queue will start. The current encode process will continue until it is finished. \nClick 'Encode' when you wish to continue encoding the queue.", + "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } @@ -110,6 +116,7 @@ namespace Handbrake btn_encode.Enabled = false; btn_pause.Visible = true; } + private void SetUIEncodeFinished() { if (InvokeRequired) @@ -120,6 +127,7 @@ namespace Handbrake btn_pause.Visible = false; btn_encode.Enabled = true; } + private void ResetQueue() { if (InvokeRequired) @@ -139,6 +147,7 @@ namespace Handbrake lbl_encodesPending.Text = list_queue.Items.Count + " encode(s) pending"; } + private void RedrawQueue() { if (InvokeRequired) @@ -152,7 +161,7 @@ namespace Handbrake foreach (Job queue_item in theQueue) { string q_item = queue_item.Query; - Functions.QueryParser parsed = Functions.QueryParser.Parse(q_item); + QueryParser parsed = Functions.QueryParser.Parse(q_item); // Get the DVD Title string title = parsed.DVDTitle == 0 ? "Auto" : parsed.DVDTitle.ToString(); @@ -179,7 +188,7 @@ namespace Handbrake string audio = string.Empty; foreach (AudioTrack track in parsed.AudioInformation) { - if (audio != "") + if (audio != string.Empty) audio += ", " + track.Encoder; else audio = track.Encoder; @@ -189,6 +198,7 @@ namespace Handbrake list_queue.Items.Add(item); } } + private void UpdateUIElements() { if (InvokeRequired) @@ -200,6 +210,7 @@ namespace Handbrake RedrawQueue(); lbl_encodesPending.Text = list_queue.Items.Count + " encode(s) pending"; } + private void SetCurrentEncodeInformation() { try @@ -210,7 +221,7 @@ namespace Handbrake } // found query is a global varible - Functions.QueryParser parsed = Functions.QueryParser.Parse(queue.LastEncode.Query); + QueryParser parsed = Functions.QueryParser.Parse(queue.LastEncode.Query); lbl_source.Text = queue.LastEncode.Source; lbl_dest.Text = queue.LastEncode.Destination; @@ -232,7 +243,7 @@ namespace Handbrake string audio = string.Empty; foreach (AudioTrack track in parsed.AudioInformation) { - if (audio != "") + if (audio != string.Empty) audio += ", " + track.Encoder; else audio = track.Encoder; @@ -244,6 +255,7 @@ namespace Handbrake // Do Nothing } } + private void DeleteSelectedItems() { // If there are selected items @@ -278,31 +290,38 @@ namespace Handbrake { MoveUp(); } + private void mnu_Down_Click(object sender, EventArgs e) { MoveDown(); } + private void mnu_delete_Click(object sender, EventArgs e) { DeleteSelectedItems(); } + private void btn_up_Click(object sender, EventArgs e) { MoveUp(); } + private void btn_down_Click(object sender, EventArgs e) { MoveDown(); } + private void btn_delete_Click(object sender, EventArgs e) { DeleteSelectedItems(); } + private void list_queue_deleteKey(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Delete) DeleteSelectedItems(); } + private void MoveUp() { // If there are selected items and the first item is not selected @@ -327,6 +346,7 @@ namespace Handbrake list_queue.Select(); // Activate the control to show the selected items } + private void MoveDown() { // If there are selected items and the last item is not selected @@ -359,36 +379,41 @@ namespace Handbrake // Queue Import/Export Features private void mnu_batch_Click(object sender, EventArgs e) { - SaveFile.FileName = ""; + SaveFile.FileName = string.Empty; SaveFile.Filter = "Batch|.bat"; SaveFile.ShowDialog(); if (SaveFile.FileName != String.Empty) queue.WriteBatchScriptToFile(SaveFile.FileName); } + private void mnu_export_Click(object sender, EventArgs e) { - SaveFile.FileName = ""; + SaveFile.FileName = string.Empty; SaveFile.Filter = "HandBrake Queue|*.queue"; SaveFile.ShowDialog(); if (SaveFile.FileName != String.Empty) queue.WriteQueueStateToFile(SaveFile.FileName); } + private void mnu_import_Click(object sender, EventArgs e) { - OpenFile.FileName = ""; + OpenFile.FileName = string.Empty; OpenFile.ShowDialog(); if (OpenFile.FileName != String.Empty) queue.LoadQueueFromFile(OpenFile.FileName); UpdateUIElements(); } + private void mnu_readd_Click(object sender, EventArgs e) { if (!queue.LastEncode.IsEmpty) { - queue.Add(queue.LastEncode.Query, queue.LastEncode.Source, queue.LastEncode.Destination, queue.LastEncode.CustomQuery); + queue.Add(queue.LastEncode.Query, queue.LastEncode.Source, queue.LastEncode.Destination, + queue.LastEncode.CustomQuery); UpdateUIElements(); } } + private void mnu_reconfigureJob_Click(object sender, EventArgs e) { if (list_queue.SelectedIndices != null) @@ -415,4 +440,4 @@ namespace Handbrake base.OnClosing(e); } } -} +} \ No newline at end of file diff --git a/win/C#/frmSplashScreen.cs b/win/C#/frmSplashScreen.cs index dca8bd2f..68441d4d 100644 --- a/win/C#/frmSplashScreen.cs +++ b/win/C#/frmSplashScreen.cs @@ -4,10 +4,10 @@ Homepage: <http://handbrake.fr>. It may be used under the terms of the GNU General Public License. */ -using System.Windows.Forms; - namespace Handbrake { + using System.Windows.Forms; + public partial class frmSplashScreen : Form { public frmSplashScreen() diff --git a/win/C#/frmUpdater.cs b/win/C#/frmUpdater.cs index 12376068..f2e7c02d 100644 --- a/win/C#/frmUpdater.cs +++ b/win/C#/frmUpdater.cs @@ -4,15 +4,16 @@ Homepage: <http://handbrake.fr>. It may be used under the terms of the GNU General Public License. */ -using System; -using System.Windows.Forms; -using Handbrake.Functions; - namespace Handbrake { + using System; + using System.Windows.Forms; + using Functions; + public partial class frmUpdater : Form { - readonly AppcastReader Appcast; + private readonly AppcastReader Appcast; + public frmUpdater(AppcastReader reader) { InitializeComponent(); @@ -29,7 +30,8 @@ namespace Handbrake private void SetVersions() { - string old = "(You have: " + Properties.Settings.Default.hb_version.Trim() + " / " + Properties.Settings.Default.hb_build.ToString().Trim() + ")"; + string old = "(You have: " + Properties.Settings.Default.hb_version.Trim() + " / " + + Properties.Settings.Default.hb_build.ToString().Trim() + ")"; string newBuild = Appcast.Version.Trim() + " (" + Appcast.Build + ")"; lbl_update_text.Text = "HandBrake " + newBuild + " is now available. " + old; } @@ -53,6 +55,5 @@ namespace Handbrake this.Close(); } - } } \ No newline at end of file