diff --git a/Greenshot.ImageEditor/Configuration/CoreConfiguration.cs b/Greenshot.ImageEditor/Configuration/CoreConfiguration.cs index 85266f961..7ed28d85f 100644 --- a/Greenshot.ImageEditor/Configuration/CoreConfiguration.cs +++ b/Greenshot.ImageEditor/Configuration/CoreConfiguration.cs @@ -205,6 +205,9 @@ public class CoreConfiguration : IniSection, INotifyPropertyChanged [IniProperty("OptimizeForRDP", Description = "Make some optimizations for usage with remote desktop", DefaultValue = "False")] public bool OptimizeForRDP; + [IniProperty("DisableRDPOptimizing", Description = "Disable all optimizations for usage with remote desktop", DefaultValue = "False")] + public bool DisableRDPOptimizing; + [IniProperty("MinimizeWorkingSetSize", Description = "Optimize memory footprint, but with a performance penalty!", DefaultValue = "False")] public bool MinimizeWorkingSetSize; diff --git a/Greenshot.ImageEditor/Configuration/EditorConfiguration.cs b/Greenshot.ImageEditor/Configuration/EditorConfiguration.cs index ade53a8ed..3862923df 100644 --- a/Greenshot.ImageEditor/Configuration/EditorConfiguration.cs +++ b/Greenshot.ImageEditor/Configuration/EditorConfiguration.cs @@ -77,7 +77,7 @@ public override void AfterLoad() /// Type of the class for which to create the field /// FieldType of the field to construct - /// FieldType of the field to construct + /// FieldType of the field to construct /// a new Field of the given fieldType, with the scope of it's value being restricted to the Type scope public Field CreateField(Type requestingType, FieldType fieldType, object preferredDefaultValue) { diff --git a/Greenshot.ImageEditor/Controls/BackgroundForm.cs b/Greenshot.ImageEditor/Controls/BackgroundForm.cs index 97975df1b..e4bbf9bfa 100644 --- a/Greenshot.ImageEditor/Controls/BackgroundForm.cs +++ b/Greenshot.ImageEditor/Controls/BackgroundForm.cs @@ -32,7 +32,7 @@ namespace GreenshotPlugin.Controls /// internal partial class BackgroundForm : Form { - private volatile bool shouldClose = false; + private volatile bool _shouldClose; private void BackgroundShowDialog() { @@ -43,7 +43,7 @@ public static BackgroundForm ShowAndWait(string title, string text) { BackgroundForm backgroundForm = new BackgroundForm(title, text); // Show form in background thread - Thread backgroundTask = new Thread(new ThreadStart(backgroundForm.BackgroundShowDialog)); + Thread backgroundTask = new Thread(backgroundForm.BackgroundShowDialog); backgroundForm.Name = "Background form"; backgroundTask.IsBackground = true; backgroundTask.SetApartmentState(ApartmentState.STA); @@ -58,7 +58,7 @@ public BackgroundForm(string title, string text) // InitializeComponent(); Icon = GreenshotResources.getGreenshotIcon(); - shouldClose = false; + _shouldClose = false; Text = title; label_pleasewait.Text = text; FormClosing += PreventFormClose; @@ -87,7 +87,7 @@ public BackgroundForm(string title, string text) private void PreventFormClose(object sender, FormClosingEventArgs e) { - if (!shouldClose) + if (!_shouldClose) { e.Cancel = true; } @@ -95,7 +95,7 @@ private void PreventFormClose(object sender, FormClosingEventArgs e) private void Timer_checkforcloseTick(object sender, EventArgs e) { - if (shouldClose) + if (_shouldClose) { timer_checkforclose.Stop(); BeginInvoke(new EventHandler(delegate { Close(); })); @@ -104,7 +104,7 @@ private void Timer_checkforcloseTick(object sender, EventArgs e) public void CloseDialog() { - shouldClose = true; + _shouldClose = true; Application.DoEvents(); } diff --git a/Greenshot.ImageEditor/Controls/BindableToolStripButton.cs b/Greenshot.ImageEditor/Controls/BindableToolStripButton.cs index 65977d846..7b45869a8 100644 --- a/Greenshot.ImageEditor/Controls/BindableToolStripButton.cs +++ b/Greenshot.ImageEditor/Controls/BindableToolStripButton.cs @@ -40,7 +40,7 @@ public string LanguageKey set; } - public BindableToolStripButton() : base() + public BindableToolStripButton() { CheckedChanged += BindableToolStripButton_CheckedChanged; } diff --git a/Greenshot.ImageEditor/Controls/BindableToolStripComboBox.cs b/Greenshot.ImageEditor/Controls/BindableToolStripComboBox.cs index 10c830037..63e52cf51 100644 --- a/Greenshot.ImageEditor/Controls/BindableToolStripComboBox.cs +++ b/Greenshot.ImageEditor/Controls/BindableToolStripComboBox.cs @@ -40,7 +40,7 @@ public string LanguageKey set; } - public BindableToolStripComboBox() : base() + public BindableToolStripComboBox() { SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged; } diff --git a/Greenshot.ImageEditor/Controls/BindableToolStripDropDownButton.cs b/Greenshot.ImageEditor/Controls/BindableToolStripDropDownButton.cs index d096f447e..1848ac25f 100644 --- a/Greenshot.ImageEditor/Controls/BindableToolStripDropDownButton.cs +++ b/Greenshot.ImageEditor/Controls/BindableToolStripDropDownButton.cs @@ -41,10 +41,6 @@ public string LanguageKey set; } - public BindableToolStripDropDownButton() - { - } - public object SelectedTag { get { if (Tag == null && DropDownItems.Count > 0) Tag = DropDownItems[0].Tag; return Tag; } diff --git a/Greenshot.ImageEditor/Controls/FontFamilyComboBox.cs b/Greenshot.ImageEditor/Controls/FontFamilyComboBox.cs index 75a17a9e3..afb0ab27b 100644 --- a/Greenshot.ImageEditor/Controls/FontFamilyComboBox.cs +++ b/Greenshot.ImageEditor/Controls/FontFamilyComboBox.cs @@ -51,11 +51,14 @@ public FontFamily FontFamily public FontFamilyComboBox() : base() { - ComboBox.DataSource = FontFamily.Families; - ComboBox.DisplayMember = "Name"; - SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged; - ComboBox.DrawMode = DrawMode.OwnerDrawFixed; - ComboBox.DrawItem += ComboBox_DrawItem; + if (ComboBox != null) + { + ComboBox.DataSource = FontFamily.Families; + ComboBox.DisplayMember = "Name"; + SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged; + ComboBox.DrawMode = DrawMode.OwnerDrawFixed; + ComboBox.DrawItem += ComboBox_DrawItem; + } } private void ComboBox_DrawItem(object sender, DrawItemEventArgs e) @@ -69,7 +72,7 @@ private void ComboBox_DrawItem(object sender, DrawItemEventArgs e) { FontFamily fontFamily = Items[e.Index] as FontFamily; FontStyle fontStyle = FontStyle.Regular; - if (!fontFamily.IsStyleAvailable(FontStyle.Regular)) + if (fontFamily != null && !fontFamily.IsStyleAvailable(FontStyle.Regular)) { if (fontFamily.IsStyleAvailable(FontStyle.Bold)) { @@ -90,12 +93,18 @@ private void ComboBox_DrawItem(object sender, DrawItemEventArgs e) } try { - DrawText(e.Graphics, fontFamily, fontStyle, e.Bounds, fontFamily.Name); + if (fontFamily != null) + { + DrawText(e.Graphics, fontFamily, fontStyle, e.Bounds, fontFamily.Name); + } } catch { - // If the drawing failed, BUG-1770 seems to have a weird case that causes: Font 'Lucida Sans Typewriter' does not support style 'Regular' - DrawText(e.Graphics, FontFamily.GenericSansSerif, FontStyle.Regular, e.Bounds, fontFamily.Name); + if (fontFamily != null) + { + // If the drawing failed, BUG-1770 seems to have a weird case that causes: Font 'Lucida Sans Typewriter' does not support style 'Regular' + DrawText(e.Graphics, FontFamily.GenericSansSerif, FontStyle.Regular, e.Bounds, fontFamily.Name); + } } } // Uncomment this if you actually like the way the focus rectangle looks @@ -112,7 +121,7 @@ private void ComboBox_DrawItem(object sender, DrawItemEventArgs e) /// private void DrawText(Graphics graphics, FontFamily fontFamily, FontStyle fontStyle, Rectangle bounds, string text) { - using (Font font = new Font(fontFamily, this.Font.Size + 5, fontStyle, GraphicsUnit.Pixel)) + using (Font font = new Font(fontFamily, Font.Size + 5, fontStyle, GraphicsUnit.Pixel)) { // Make sure the text is visible by centering it in the line using (StringFormat stringFormat = new StringFormat()) diff --git a/Greenshot.ImageEditor/Controls/GreenshotCheckBox.cs b/Greenshot.ImageEditor/Controls/GreenshotCheckBox.cs index 3ffd49254..cd70b69c7 100644 --- a/Greenshot.ImageEditor/Controls/GreenshotCheckBox.cs +++ b/Greenshot.ImageEditor/Controls/GreenshotCheckBox.cs @@ -36,19 +36,8 @@ public string LanguageKey set; } - private string sectionName = "Core"; [Category("Greenshot"), DefaultValue("Core"), Description("Specifies the Ini-Section to map this control with.")] - public string SectionName - { - get - { - return sectionName; - } - set - { - sectionName = value; - } - } + public string SectionName { get; set; } = "Core"; [Category("Greenshot"), DefaultValue(null), Description("Specifies the property name to map the configuration.")] public string PropertyName diff --git a/Greenshot.ImageEditor/Controls/GreenshotColumnSorter.cs b/Greenshot.ImageEditor/Controls/GreenshotColumnSorter.cs index 88719439d..87d933034 100644 --- a/Greenshot.ImageEditor/Controls/GreenshotColumnSorter.cs +++ b/Greenshot.ImageEditor/Controls/GreenshotColumnSorter.cs @@ -32,15 +32,15 @@ internal class GreenshotColumnSorter : IComparer /// /// Specifies the column to be sorted /// - private int ColumnToSort; + private int _columnToSort; /// /// Specifies the order in which to sort (i.e. 'Ascending'). /// - private SortOrder OrderOfSort; + private SortOrder _orderOfSort; /// /// Case insensitive comparer object /// - private CaseInsensitiveComparer ObjectCompare; + private readonly CaseInsensitiveComparer _objectCompare; /// /// Class constructor. Initializes various elements @@ -48,13 +48,13 @@ internal class GreenshotColumnSorter : IComparer public GreenshotColumnSorter() { // Initialize the column to '0' - ColumnToSort = 0; + _columnToSort = 0; // Initialize the sort order to 'none' - OrderOfSort = SortOrder.None; + _orderOfSort = SortOrder.None; // Initialize the CaseInsensitiveComparer object - ObjectCompare = new CaseInsensitiveComparer(); + _objectCompare = new CaseInsensitiveComparer(); } /// @@ -65,44 +65,39 @@ public GreenshotColumnSorter() /// The result of the comparison. "0" if equal, negative if 'x' is less than 'y' and positive if 'x' is greater than 'y' public int Compare(object x, object y) { - int compareResult; - ListViewItem listviewX, listviewY; - if (x == null && y == null) { return 0; } - else if (x == null && y != null) + if (x == null) { return -1; } - else if (x != null && y == null) + if (y == null) { return 1; } // Cast the objects to be compared to ListViewItem objects - listviewX = (ListViewItem)x; - listviewY = (ListViewItem)y; + var listviewX = (ListViewItem)x; + var listviewY = (ListViewItem)y; // Compare the two items - compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text); + var compareResult = _objectCompare.Compare(listviewX.SubItems[_columnToSort].Text, listviewY.SubItems[_columnToSort].Text); // Calculate correct return value based on object comparison - if (OrderOfSort == SortOrder.Ascending) + if (_orderOfSort == SortOrder.Ascending) { // Ascending sort is selected, return normal result of compare operation return compareResult; } - else if (OrderOfSort == SortOrder.Descending) + if (_orderOfSort == SortOrder.Descending) { // Descending sort is selected, return negative result of compare operation return (-compareResult); } - else - { - // Return '0' to indicate they are equal - return 0; - } + + // Return '0' to indicate they are equal + return 0; } /// @@ -112,11 +107,11 @@ public int SortColumn { set { - ColumnToSort = value; + _columnToSort = value; } get { - return ColumnToSort; + return _columnToSort; } } @@ -127,11 +122,11 @@ public SortOrder Order { set { - OrderOfSort = value; + _orderOfSort = value; } get { - return OrderOfSort; + return _orderOfSort; } } } diff --git a/Greenshot.ImageEditor/Controls/GreenshotComboBox.cs b/Greenshot.ImageEditor/Controls/GreenshotComboBox.cs index f0188127f..14b2e4781 100644 --- a/Greenshot.ImageEditor/Controls/GreenshotComboBox.cs +++ b/Greenshot.ImageEditor/Controls/GreenshotComboBox.cs @@ -27,21 +27,11 @@ namespace GreenshotPlugin.Controls { internal class GreenshotComboBox : ComboBox, IGreenshotConfigBindable { - private Type enumType = null; - private Enum selectedEnum = null; - private string sectionName = "Core"; + private Type _enumType = null; + private Enum _selectedEnum = null; + [Category("Greenshot"), DefaultValue("Core"), Description("Specifies the Ini-Section to map this control with.")] - public string SectionName - { - get - { - return sectionName; - } - set - { - sectionName = value; - } - } + public string SectionName { get; set; } = "Core"; [Category("Greenshot"), DefaultValue(null), Description("Specifies the property name to map the configuration.")] public string PropertyName @@ -62,7 +52,7 @@ public void SetValue(Enum currentValue) { if (currentValue != null) { - selectedEnum = currentValue; + _selectedEnum = currentValue; SelectedItem = currentValue; } } @@ -75,11 +65,10 @@ public void SetValue(Enum currentValue) public void Populate(Type enumType) { // Store the enum-type, so we can work with it - this.enumType = enumType; + _enumType = enumType; var availableValues = Enum.GetValues(enumType); Items.Clear(); - string enumTypeName = enumType.Name; foreach (var enumValue in availableValues) { Items.Add(enumValue); @@ -91,20 +80,20 @@ public void Populate(Type enumType) /// private void StoreSelectedEnum() { - string enumTypeName = enumType.Name; + string enumTypeName = _enumType.Name; string selectedValue = SelectedItem as string; - var availableValues = Enum.GetValues(enumType); + var availableValues = Enum.GetValues(_enumType); object returnValue = null; try { - returnValue = Enum.Parse(enumType, selectedValue); + returnValue = Enum.Parse(_enumType, selectedValue); } catch (Exception) { } - selectedEnum = (Enum)returnValue; + _selectedEnum = (Enum)returnValue; } /// @@ -113,7 +102,7 @@ private void StoreSelectedEnum() /// The enum value of the combobox public Enum GetSelectedEnum() { - return selectedEnum; + return _selectedEnum; } } } \ No newline at end of file diff --git a/Greenshot.ImageEditor/Controls/GreenshotForm.cs b/Greenshot.ImageEditor/Controls/GreenshotForm.cs index 8534f1007..f22652b31 100644 --- a/Greenshot.ImageEditor/Controls/GreenshotForm.cs +++ b/Greenshot.ImageEditor/Controls/GreenshotForm.cs @@ -36,9 +36,9 @@ namespace GreenshotPlugin.Controls public class GreenshotForm : Form, IGreenshotLanguageBindable { protected static CoreConfiguration coreConfiguration; - private static IDictionary reflectionCache = new Dictionary(); + private static readonly IDictionary reflectionCache = new Dictionary(); private IComponentChangeService m_changeService; - private bool _storeFieldsManually = false; + private bool _storeFieldsManually; private IDictionary _designTimeControls; private IDictionary _designTimeToolStripItems; @@ -184,7 +184,7 @@ private void ClearChangeNotifications() // Clear our the component change events to prepare for re-siting. if (m_changeService != null) { - m_changeService.ComponentAdded -= new ComponentEventHandler(OnComponentAdded); + m_changeService.ComponentAdded -= OnComponentAdded; } } @@ -193,7 +193,7 @@ private void RegisterChangeNotifications() // Register the event handlers for the IComponentChangeService events if (m_changeService != null) { - m_changeService.ComponentAdded += new ComponentEventHandler(OnComponentAdded); + m_changeService.ComponentAdded += OnComponentAdded; } } @@ -303,7 +303,6 @@ protected void FillFields() comboxBox.Populate(iniValue.ValueType); comboxBox.SetValue((Enum)iniValue.Value); comboxBox.Enabled = !iniValue.IsFixed; - continue; } } } diff --git a/Greenshot.ImageEditor/Controls/GreenshotTextBox.cs b/Greenshot.ImageEditor/Controls/GreenshotTextBox.cs index 1a5c6f390..c95a1a025 100644 --- a/Greenshot.ImageEditor/Controls/GreenshotTextBox.cs +++ b/Greenshot.ImageEditor/Controls/GreenshotTextBox.cs @@ -26,19 +26,8 @@ namespace GreenshotPlugin.Controls { internal class GreenshotTextBox : TextBox, IGreenshotConfigBindable { - private string sectionName = "Core"; [Category("Greenshot"), DefaultValue("Core"), Description("Specifies the Ini-Section to map this control with.")] - public string SectionName - { - get - { - return sectionName; - } - set - { - sectionName = value; - } - } + public string SectionName { get; set; } = "Core"; [Category("Greenshot"), DefaultValue(null), Description("Specifies the property name to map the configuration.")] public string PropertyName diff --git a/Greenshot.ImageEditor/Controls/MenuStripEx.cs b/Greenshot.ImageEditor/Controls/MenuStripEx.cs index 3d550b4d2..f890b05df 100644 --- a/Greenshot.ImageEditor/Controls/MenuStripEx.cs +++ b/Greenshot.ImageEditor/Controls/MenuStripEx.cs @@ -36,11 +36,9 @@ private enum NativeConstants : uint { MA_ACTIVATE = 1, MA_ACTIVATEANDEAT = 2, - MA_NOACTIVATE = 3, - MA_NOACTIVATEANDEAT = 4, } - private bool clickThrough = false; + private bool _clickThrough; /// /// Gets or sets whether the ToolStripEx honors item clicks when its containing form does not have input focus. /// @@ -51,19 +49,19 @@ public bool ClickThrough { get { - return clickThrough; + return _clickThrough; } set { - clickThrough = value; + _clickThrough = value; } } protected override void WndProc(ref Message m) { base.WndProc(ref m); - if (clickThrough && m.Msg == WM_MOUSEACTIVATE && m.Result == (IntPtr)NativeConstants.MA_ACTIVATEANDEAT) + if (_clickThrough && m.Msg == WM_MOUSEACTIVATE && m.Result == (IntPtr)NativeConstants.MA_ACTIVATEANDEAT) { m.Result = (IntPtr)NativeConstants.MA_ACTIVATE; } diff --git a/Greenshot.ImageEditor/Controls/NonJumpingPanel.cs b/Greenshot.ImageEditor/Controls/NonJumpingPanel.cs index b68714fef..f0c336a57 100644 --- a/Greenshot.ImageEditor/Controls/NonJumpingPanel.cs +++ b/Greenshot.ImageEditor/Controls/NonJumpingPanel.cs @@ -19,15 +19,14 @@ * along with this program. If not, see . */ -/// -/// See: http://nickstips.wordpress.com/2010/03/03/c-panel-resets-scroll-position-after-focus-is-lost-and-regained/ -/// - using System.Drawing; using System.Windows.Forms; namespace GreenshotPlugin.Controls { + /// + /// See: http://nickstips.wordpress.com/2010/03/03/c-panel-resets-scroll-position-after-focus-is-lost-and-regained/ + /// internal class NonJumpingPanel : Panel { protected override Point ScrollToControl(Control activeControl) @@ -36,5 +35,23 @@ protected override Point ScrollToControl(Control activeControl) // scrolling to the active control when the panel loses and regains focus return DisplayRectangle.Location; } + + /// + /// Add horizontal scrolling to the panel, when using the wheel and the shift key is pressed + /// + /// MouseEventArgs + protected override void OnMouseWheel(MouseEventArgs e) + { + if (VScroll && (ModifierKeys & Keys.Shift) == Keys.Shift) + { + VScroll = false; + base.OnMouseWheel(e); + VScroll = true; + } + else + { + base.OnMouseWheel(e); + } + } } } \ No newline at end of file diff --git a/Greenshot.ImageEditor/Controls/Pipette.cs b/Greenshot.ImageEditor/Controls/Pipette.cs index 92ea1f7ac..e1fc1e8ed 100644 --- a/Greenshot.ImageEditor/Controls/Pipette.cs +++ b/Greenshot.ImageEditor/Controls/Pipette.cs @@ -37,7 +37,7 @@ internal class Pipette : Label, IMessageFilter, IDisposable private MovableShowColorForm movableShowColorForm; private bool dragging; private Cursor _cursor; - private Bitmap _image; + private readonly Bitmap _image; private const int VK_ESC = 27; public event EventHandler PipetteUsed; @@ -129,7 +129,10 @@ protected override void OnMouseUp(MouseEventArgs e) { //Release Capture should consume MouseUp when canceled with the escape key User32.ReleaseCapture(); - PipetteUsed(this, new PipetteUsedArgs(movableShowColorForm.color)); + if (PipetteUsed != null) + { + PipetteUsed(this, new PipetteUsedArgs(movableShowColorForm.color)); + } } base.OnMouseUp(e); } diff --git a/Greenshot.ImageEditor/Controls/PleaseWaitForm.cs b/Greenshot.ImageEditor/Controls/PleaseWaitForm.cs index 52ffae5c7..ac168d48f 100644 --- a/Greenshot.ImageEditor/Controls/PleaseWaitForm.cs +++ b/Greenshot.ImageEditor/Controls/PleaseWaitForm.cs @@ -31,7 +31,7 @@ namespace GreenshotPlugin.Controls /// internal partial class PleaseWaitForm : Form { - private Thread waitFor = null; + private Thread waitFor; private string title; public PleaseWaitForm() diff --git a/Greenshot.ImageEditor/Controls/QualityDialog.cs b/Greenshot.ImageEditor/Controls/QualityDialog.cs index 9ce9b69fa..218f878bb 100644 --- a/Greenshot.ImageEditor/Controls/QualityDialog.cs +++ b/Greenshot.ImageEditor/Controls/QualityDialog.cs @@ -31,7 +31,7 @@ namespace GreenshotPlugin.Controls /// internal partial class QualityDialog : GreenshotForm { - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); public SurfaceOutputSettings Settings { get; diff --git a/Greenshot.ImageEditor/Controls/SaveImageFileDialog.cs b/Greenshot.ImageEditor/Controls/SaveImageFileDialog.cs index db923ae9b..5df8c9343 100644 --- a/Greenshot.ImageEditor/Controls/SaveImageFileDialog.cs +++ b/Greenshot.ImageEditor/Controls/SaveImageFileDialog.cs @@ -34,11 +34,11 @@ namespace GreenshotPlugin.Controls /// internal class SaveImageFileDialog : IDisposable { - private static CoreConfiguration conf = IniConfig.GetIniSection(); - protected SaveFileDialog saveFileDialog; - private FilterOption[] filterOptions; - private DirectoryInfo eagerlyCreatedDirectory; - private ICaptureDetails captureDetails = null; + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); + protected SaveFileDialog SaveFileDialog; + private FilterOption[] _filterOptions; + private DirectoryInfo _eagerlyCreatedDirectory; + private readonly ICaptureDetails _captureDetails = null; public void Dispose() { @@ -50,29 +50,29 @@ protected virtual void Dispose(bool disposing) { if (disposing) { - if (saveFileDialog != null) + if (SaveFileDialog != null) { - saveFileDialog.Dispose(); - saveFileDialog = null; + SaveFileDialog.Dispose(); + SaveFileDialog = null; } } } public SaveImageFileDialog() { - init(); + Init(); } public SaveImageFileDialog(ICaptureDetails captureDetails) { - this.captureDetails = captureDetails; - init(); + _captureDetails = captureDetails; + Init(); } - private void init() + private void Init() { - saveFileDialog = new SaveFileDialog(); - applyFilterOptions(); + SaveFileDialog = new SaveFileDialog(); + ApplyFilterOptions(); string initialDirectory = null; try { @@ -85,50 +85,52 @@ private void init() if (!string.IsNullOrEmpty(initialDirectory) && Directory.Exists(initialDirectory)) { - saveFileDialog.InitialDirectory = initialDirectory; + SaveFileDialog.InitialDirectory = initialDirectory; } else if (Directory.Exists(conf.OutputFilePath)) { - saveFileDialog.InitialDirectory = conf.OutputFilePath; + SaveFileDialog.InitialDirectory = conf.OutputFilePath; } // The following property fixes a problem that the directory where we save is locked (bug #2899790) - saveFileDialog.RestoreDirectory = true; - saveFileDialog.OverwritePrompt = true; - saveFileDialog.CheckPathExists = false; - saveFileDialog.AddExtension = true; + SaveFileDialog.RestoreDirectory = true; + SaveFileDialog.OverwritePrompt = true; + SaveFileDialog.CheckPathExists = false; + SaveFileDialog.AddExtension = true; ApplySuggestedValues(); } - private void applyFilterOptions() + private void ApplyFilterOptions() { - prepareFilterOptions(); + PrepareFilterOptions(); string fdf = ""; int preselect = 0; var outputFileFormatAsString = Enum.GetName(typeof(OutputFormat), conf.OutputFileFormat); - for (int i = 0; i < filterOptions.Length; i++) + for (int i = 0; i < _filterOptions.Length; i++) { - FilterOption fo = filterOptions[i]; + FilterOption fo = _filterOptions[i]; fdf += fo.Label + "|*." + fo.Extension + "|"; if (outputFileFormatAsString == fo.Extension) preselect = i; } fdf = fdf.Substring(0, fdf.Length - 1); - saveFileDialog.Filter = fdf; - saveFileDialog.FilterIndex = preselect + 1; + SaveFileDialog.Filter = fdf; + SaveFileDialog.FilterIndex = preselect + 1; } - private void prepareFilterOptions() + private void PrepareFilterOptions() { OutputFormat[] supportedImageFormats = (OutputFormat[])Enum.GetValues(typeof(OutputFormat)); - filterOptions = new FilterOption[supportedImageFormats.Length]; - for (int i = 0; i < filterOptions.Length; i++) + _filterOptions = new FilterOption[supportedImageFormats.Length]; + for (int i = 0; i < _filterOptions.Length; i++) { string ifo = supportedImageFormats[i].ToString(); if (ifo.ToLower().Equals("jpeg")) ifo = "Jpg"; // we dont want no jpeg files, so let the dialog check for jpg - FilterOption fo = new FilterOption(); - fo.Label = ifo.ToUpper(); - fo.Extension = ifo.ToLower(); - filterOptions.SetValue(fo, i); + FilterOption fo = new FilterOption + { + Label = ifo.ToUpper(), + Extension = ifo.ToLower() + }; + _filterOptions.SetValue(fo, i); } } @@ -137,8 +139,8 @@ private void prepareFilterOptions() /// public string FileName { - get { return saveFileDialog.FileName; } - set { saveFileDialog.FileName = value; } + get { return SaveFileDialog.FileName; } + set { SaveFileDialog.FileName = value; } } /// @@ -146,8 +148,8 @@ public string FileName /// public string InitialDirectory { - get { return saveFileDialog.InitialDirectory; } - set { saveFileDialog.InitialDirectory = value; } + get { return SaveFileDialog.InitialDirectory; } + set { SaveFileDialog.InitialDirectory = value; } } /// @@ -159,7 +161,7 @@ public string FileNameWithExtension { get { - string fn = saveFileDialog.FileName; + string fn = SaveFileDialog.FileName; // if the filename contains a valid extension, which is the same like the selected filter item's extension, the filename is okay if (fn.EndsWith(Extension, StringComparison.CurrentCultureIgnoreCase)) return fn; // otherwise we just add the selected filter item's extension @@ -179,15 +181,15 @@ public string Extension { get { - return filterOptions[saveFileDialog.FilterIndex - 1].Extension; + return _filterOptions[SaveFileDialog.FilterIndex - 1].Extension; } set { - for (int i = 0; i < filterOptions.Length; i++) + for (int i = 0; i < _filterOptions.Length; i++) { - if (value.Equals(filterOptions[i].Extension, StringComparison.CurrentCultureIgnoreCase)) + if (value.Equals(_filterOptions[i].Extension, StringComparison.CurrentCultureIgnoreCase)) { - saveFileDialog.FilterIndex = i + 1; + SaveFileDialog.FilterIndex = i + 1; } } } @@ -195,7 +197,7 @@ public string Extension public DialogResult ShowDialog() { - DialogResult ret = saveFileDialog.ShowDialog(); + DialogResult ret = SaveFileDialog.ShowDialog(); CleanUp(); return ret; } @@ -203,18 +205,10 @@ public DialogResult ShowDialog() /// /// sets InitialDirectory and FileName property of a SaveFileDialog smartly, considering default pattern and last used path /// - /// a SaveFileDialog instance private void ApplySuggestedValues() { // build the full path and set dialog properties - FileName = FilenameHelper.GetFilenameWithoutExtensionFromPattern(conf.OutputFileFilenamePattern, captureDetails); - } - - private string GetRootDirFromConfig() - { - string rootDir = conf.OutputFilePath; - rootDir = FilenameHelper.FillVariables(rootDir, false); - return rootDir; + FileName = FilenameHelper.GetFilenameWithoutExtensionFromPattern(conf.OutputFileFilenamePattern, _captureDetails); } private class FilterOption @@ -228,37 +222,18 @@ private void CleanUp() // fix for bug #3379053 try { - if (eagerlyCreatedDirectory != null && eagerlyCreatedDirectory.GetFiles().Length == 0 && eagerlyCreatedDirectory.GetDirectories().Length == 0) + if (_eagerlyCreatedDirectory != null && _eagerlyCreatedDirectory.GetFiles().Length == 0 && _eagerlyCreatedDirectory.GetDirectories().Length == 0) { - eagerlyCreatedDirectory.Delete(); - eagerlyCreatedDirectory = null; + _eagerlyCreatedDirectory.Delete(); + _eagerlyCreatedDirectory = null; } } catch (Exception e) { LOG.WarnFormat("Couldn't cleanup directory due to: {0}", e.Message); - eagerlyCreatedDirectory = null; + _eagerlyCreatedDirectory = null; } } - private string CreateDirectoryIfNotExists(string fullPath) - { - string dirName = null; - try - { - dirName = Path.GetDirectoryName(fullPath); - DirectoryInfo di = new DirectoryInfo(dirName); - if (!di.Exists) - { - di = Directory.CreateDirectory(dirName); - eagerlyCreatedDirectory = di; - } - } - catch (Exception e) - { - LOG.Error("Error in CreateDirectoryIfNotExists", e); - } - return dirName; - } } } \ No newline at end of file diff --git a/Greenshot.ImageEditor/Controls/ToolStripEx.cs b/Greenshot.ImageEditor/Controls/ToolStripEx.cs index 1767a38af..ffd6f39fa 100644 --- a/Greenshot.ImageEditor/Controls/ToolStripEx.cs +++ b/Greenshot.ImageEditor/Controls/ToolStripEx.cs @@ -36,11 +36,9 @@ private enum NativeConstants : uint { MA_ACTIVATE = 1, MA_ACTIVATEANDEAT = 2, - MA_NOACTIVATE = 3, - MA_NOACTIVATEANDEAT = 4, } - private bool clickThrough = false; + private bool _clickThrough = false; /// /// Gets or sets whether the ToolStripEx honors item clicks when its containing form does not have input focus. /// @@ -52,19 +50,19 @@ public bool ClickThrough { get { - return clickThrough; + return _clickThrough; } set { - clickThrough = value; + _clickThrough = value; } } protected override void WndProc(ref Message m) { base.WndProc(ref m); - if (clickThrough && m.Msg == WM_MOUSEACTIVATE && m.Result == (IntPtr)NativeConstants.MA_ACTIVATEANDEAT) + if (_clickThrough && m.Msg == WM_MOUSEACTIVATE && m.Result == (IntPtr)NativeConstants.MA_ACTIVATEANDEAT) { m.Result = (IntPtr)NativeConstants.MA_ACTIVATE; } diff --git a/Greenshot.ImageEditor/Core/Cache.cs b/Greenshot.ImageEditor/Core/Cache.cs index a09d3d928..413ed9a4f 100644 --- a/Greenshot.ImageEditor/Core/Cache.cs +++ b/Greenshot.ImageEditor/Core/Cache.cs @@ -32,10 +32,10 @@ namespace GreenshotPlugin.Core /// Type of value public class Cache { - private IDictionary internalCache = new Dictionary(); - private object lockObject = new object(); - private int secondsToExpire = 10; - private CacheObjectExpired expiredCallback = null; + private readonly IDictionary internalCache = new Dictionary(); + private readonly object lockObject = new object(); + private readonly int secondsToExpire = 10; + private readonly CacheObjectExpired expiredCallback = null; public delegate void CacheObjectExpired(TK key, TV cacheValue); /// @@ -82,9 +82,12 @@ public IEnumerable Elements { List elements = new List(); - foreach (TV element in internalCache.Values) + lock (lockObject) { - elements.Add(element); + foreach (TV element in internalCache.Values) + { + elements.Add(element); + } } foreach (TV element in elements) { @@ -121,7 +124,10 @@ public TV this[TK key] /// true if the cache contains the key public bool Contains(TK key) { - return internalCache.ContainsKey(key); + lock (lockObject) + { + return internalCache.ContainsKey(key); + } } /// @@ -198,7 +204,7 @@ public void Remove(TK key) private class CachedItem { public event CacheObjectExpired Expired; - private int secondsToExpire; + private readonly int secondsToExpire; private readonly Timer _timerEvent; public CachedItem(TK key, TV item, int secondsToExpire) diff --git a/Greenshot.ImageEditor/Core/ClipboardHelper.cs b/Greenshot.ImageEditor/Core/ClipboardHelper.cs index 16bc9a26b..dfe33f6b1 100644 --- a/Greenshot.ImageEditor/Core/ClipboardHelper.cs +++ b/Greenshot.ImageEditor/Core/ClipboardHelper.cs @@ -396,11 +396,11 @@ private static Image GetImage(IDataObject dataObject) { // Outlook ?? LOG.Info("Most likely the current clipboard contents come from Outlook, as this has a problem with PNG and others we place the DIB format to the front..."); - retrieveFormats = new string[] { DataFormats.Dib, FORMAT_BITMAP, FORMAT_FILECONTENTS, FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JFIF, DataFormats.Tiff, FORMAT_GIF }; + retrieveFormats = new[] { DataFormats.Dib, FORMAT_BITMAP, FORMAT_FILECONTENTS, FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JFIF, DataFormats.Tiff, FORMAT_GIF }; } else { - retrieveFormats = new string[] { FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_17, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JFIF, DataFormats.Tiff, DataFormats.Dib, FORMAT_BITMAP, FORMAT_FILECONTENTS, FORMAT_GIF }; + retrieveFormats = new[] { FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_17, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JFIF, DataFormats.Tiff, DataFormats.Dib, FORMAT_BITMAP, FORMAT_FILECONTENTS, FORMAT_GIF }; } foreach (string currentFormat in retrieveFormats) { @@ -867,7 +867,7 @@ public static List GetFormats(IDataObject dataObj) /// true if one the format is found public static bool ContainsFormat(string format) { - return ContainsFormat(GetDataObject(), new string[] { format }); + return ContainsFormat(GetDataObject(), new[] { format }); } /// @@ -877,7 +877,7 @@ public static bool ContainsFormat(string format) /// true if one the format is found public static bool ContainsFormat(IDataObject dataObject, string format) { - return ContainsFormat(dataObject, new string[] { format }); + return ContainsFormat(dataObject, new[] { format }); } /// diff --git a/Greenshot.ImageEditor/Core/Effects.cs b/Greenshot.ImageEditor/Core/Effects.cs index 675e94d0a..b5e59ef43 100644 --- a/Greenshot.ImageEditor/Core/Effects.cs +++ b/Greenshot.ImageEditor/Core/Effects.cs @@ -97,7 +97,7 @@ public virtual Image Apply(Image sourceImage, Matrix matrix) [TypeConverter(typeof(EffectConverter))] public class TornEdgeEffect : DropShadowEffect { - public TornEdgeEffect() : base() + public TornEdgeEffect() { Reset(); } @@ -135,7 +135,7 @@ public override void Reset() ToothHeight = 12; HorizontalToothRange = 20; VerticalToothRange = 20; - Edges = new bool[] { true, true, true, true }; + Edges = new[] { true, true, true, true }; GenerateShadow = true; } @@ -174,12 +174,12 @@ public void Reset() /// public class MonochromeEffect : IEffect { - private byte threshold; + private readonly byte _threshold; /// Threshold for monochrome filter (0 - 255), lower value means less black public MonochromeEffect(byte threshold) { - this.threshold = threshold; + _threshold = threshold; } public void Reset() @@ -189,7 +189,7 @@ public void Reset() public Image Apply(Image sourceImage, Matrix matrix) { - return ImageHelper.CreateMonochrome(sourceImage, threshold); + return ImageHelper.CreateMonochrome(sourceImage, _threshold); } } @@ -198,7 +198,7 @@ public Image Apply(Image sourceImage, Matrix matrix) /// public class AdjustEffect : IEffect { - public AdjustEffect() : base() + public AdjustEffect() { Reset(); } @@ -237,7 +237,7 @@ public Image Apply(Image sourceImage, Matrix matrix) /// public class ReduceColorsEffect : IEffect { - public ReduceColorsEffect() : base() + public ReduceColorsEffect() { Reset(); } @@ -460,9 +460,9 @@ public Image Apply(Image sourceImage, Matrix matrix) public class EffectConverter : TypeConverter { // Fix to prevent BUG-1753 - private NumberFormatInfo numberFormatInfo = new NumberFormatInfo(); + private readonly NumberFormatInfo numberFormatInfo = new NumberFormatInfo(); - public EffectConverter() : base() + public EffectConverter() { numberFormatInfo.NumberDecimalSeparator = "."; numberFormatInfo.NumberGroupSeparator = ","; @@ -494,7 +494,7 @@ public override bool CanConvertTo(ITypeDescriptorContext context, Type destinati return base.CanConvertTo(context, destinationType); } - public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { // to string if (destinationType == typeof(string)) @@ -516,7 +516,7 @@ public override object ConvertTo(ITypeDescriptorContext context, System.Globaliz } } // from string - if (value.GetType() == typeof(string)) + if (value is string) { string settings = value as string; if (destinationType == typeof(DropShadowEffect)) @@ -536,19 +536,16 @@ public override object ConvertTo(ITypeDescriptorContext context, System.Globaliz return base.ConvertTo(context, culture, value, destinationType); } - public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - if (value != null && value.GetType() == typeof(string)) + if (value != null && value is string) { string settings = value as string; if (settings.Contains("ToothHeight")) { return ConvertTo(context, culture, value, typeof(TornEdgeEffect)); } - else - { - return ConvertTo(context, culture, value, typeof(DropShadowEffect)); - } + return ConvertTo(context, culture, value, typeof(DropShadowEffect)); } return base.ConvertFrom(context, culture, value); } diff --git a/Greenshot.ImageEditor/Core/EventDelay.cs b/Greenshot.ImageEditor/Core/EventDelay.cs index b6f63e576..d6787077d 100644 --- a/Greenshot.ImageEditor/Core/EventDelay.cs +++ b/Greenshot.ImageEditor/Core/EventDelay.cs @@ -25,12 +25,12 @@ namespace GreenshotPlugin.Core { public class EventDelay { - private long lastCheck = 0; - private long waitTime; + private long lastCheck; + private readonly long waitTime; public EventDelay(long ticks) { - this.waitTime = ticks; + waitTime = ticks; } public bool Check() diff --git a/Greenshot.ImageEditor/Core/FastBitmap.cs b/Greenshot.ImageEditor/Core/FastBitmap.cs index fc5d0bc2d..53d713c83 100644 --- a/Greenshot.ImageEditor/Core/FastBitmap.cs +++ b/Greenshot.ImageEditor/Core/FastBitmap.cs @@ -343,7 +343,7 @@ public bool InvertClip protected BitmapData bmData; protected int stride; /* bytes per pixel row */ - protected bool bitsLocked = false; + protected bool bitsLocked; protected byte* pointer; public static IFastBitmap Create(Bitmap source) @@ -825,8 +825,8 @@ void IFastBitmapWithOffset.SetColorAt(int x, int y, Color color) public unsafe class FastChunkyBitmap : FastBitmap { // Used for indexed images - private Color[] colorEntries; - private Dictionary colorCache = new Dictionary(); + private readonly Color[] colorEntries; + private readonly Dictionary colorCache = new Dictionary(); public FastChunkyBitmap(Bitmap source, Rectangle area) : base(source, area) { diff --git a/Greenshot.ImageEditor/Core/FilenameHelper.cs b/Greenshot.ImageEditor/Core/FilenameHelper.cs index 76fc4bfa3..f14e31144 100644 --- a/Greenshot.ImageEditor/Core/FilenameHelper.cs +++ b/Greenshot.ImageEditor/Core/FilenameHelper.cs @@ -39,10 +39,11 @@ public static class FilenameHelper // The parameter format is a single alpha followed by the value belonging to the parameter, e.g. : // ${capturetime:d"yyyy-MM-dd HH_mm_ss"} private static readonly Regex VAR_REGEXP = new Regex(@"\${(?[^:}]+)[:]?(?[^}]*)}", RegexOptions.Compiled); + private static readonly Regex CMD_VAR_REGEXP = new Regex(@"%(?[^%]+)%", RegexOptions.Compiled); private static readonly Regex SPLIT_REGEXP = new Regex(";(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", RegexOptions.Compiled); private const int MAX_TITLE_LENGTH = 80; - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); private const string UNSAFE_REPLACEMENT = "_"; /// @@ -79,7 +80,7 @@ public static string MakeFilenameSafe(string filename) /// /// Remove invalid characters from the path /// - /// string with the full path to a file + /// string with the full path to a file /// string with the full path to a file, without invalid characters public static string MakePathSafe(string path) { @@ -180,7 +181,7 @@ private static string MatchVarEvaluatorInternal(Match match, ICaptureDetails cap { // Padding p[,pad-character] case "p": - string[] padParams = parameter.Substring(1).Split(new char[] { ',' }); + string[] padParams = parameter.Substring(1).Split(new[] { ',' }); try { padWidth = int.Parse(padParams[0]); @@ -196,7 +197,7 @@ private static string MatchVarEvaluatorInternal(Match match, ICaptureDetails cap // replace // r, case "r": - string[] replaceParameters = parameter.Substring(1).Split(new char[] { ',' }); + string[] replaceParameters = parameter.Substring(1).Split(new[] { ',' }); if (replaceParameters != null && replaceParameters.Length == 2) { replacements.Add(replaceParameters[0], replaceParameters[1]); @@ -219,7 +220,7 @@ private static string MatchVarEvaluatorInternal(Match match, ICaptureDetails cap // s[,length] case "s": string range = parameter.Substring(1); - string[] rangelist = range.Split(new char[] { ',' }); + string[] rangelist = range.Split(new[] { ',' }); if (rangelist.Length > 0) { try @@ -469,6 +470,51 @@ private static string MatchVarEvaluatorInternal(Match match, ICaptureDetails cap return replaceValue; } + /// + /// "Simply" fill the pattern with environment variables + /// + /// String with pattern %var% + /// true to make sure everything is filenamesafe + /// Filled string + public static string FillCmdVariables(string pattern, bool filenameSafeMode) + { + IDictionary processVars = null; + IDictionary userVars = null; + IDictionary machineVars = null; + try + { + processVars = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Process); + } + catch (Exception e) + { + LOG.Error("Error retrieving EnvironmentVariableTarget.Process", e); + } + + try + { + userVars = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User); + } + catch (Exception e) + { + LOG.Error("Error retrieving EnvironmentVariableTarget.User", e); + } + + try + { + machineVars = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine); + } + catch (Exception e) + { + LOG.Error("Error retrieving EnvironmentVariableTarget.Machine", e); + } + + return CMD_VAR_REGEXP.Replace(pattern, + delegate (Match m) { + return MatchVarEvaluator(m, null, processVars, userVars, machineVars, filenameSafeMode); + } + ); + } + /// /// "Simply" fill the pattern with environment variables /// @@ -508,10 +554,10 @@ public static string FillVariables(string pattern, bool filenameSafeMode) } return VAR_REGEXP.Replace(pattern, - new MatchEvaluator(delegate (Match m) + delegate (Match m) { return MatchVarEvaluator(m, null, processVars, userVars, machineVars, filenameSafeMode); - }) + } ); } @@ -557,10 +603,10 @@ public static string FillPattern(string pattern, ICaptureDetails captureDetails, try { return VAR_REGEXP.Replace(pattern, - new MatchEvaluator(delegate (Match m) + delegate (Match m) { return MatchVarEvaluator(m, captureDetails, processVars, userVars, machineVars, filenameSafeMode); - }) + } ); } catch (Exception e) diff --git a/Greenshot.ImageEditor/Core/GreenshotResources.cs b/Greenshot.ImageEditor/Core/GreenshotResources.cs index 20f01ac86..c6918ecaf 100644 --- a/Greenshot.ImageEditor/Core/GreenshotResources.cs +++ b/Greenshot.ImageEditor/Core/GreenshotResources.cs @@ -29,7 +29,7 @@ namespace GreenshotPlugin.Core /// public static class GreenshotResources { - private static ComponentResourceManager greenshotResources = new ComponentResourceManager(typeof(GreenshotResources)); + private static readonly ComponentResourceManager greenshotResources = new ComponentResourceManager(typeof(GreenshotResources)); public static Image getImage(string imageName) { diff --git a/Greenshot.ImageEditor/Core/ImageHelper.cs b/Greenshot.ImageEditor/Core/ImageHelper.cs index ad86b9818..8d1d790d2 100644 --- a/Greenshot.ImageEditor/Core/ImageHelper.cs +++ b/Greenshot.ImageEditor/Core/ImageHelper.cs @@ -972,7 +972,7 @@ public static Bitmap CreateShadow(Image sourceBitmap, float darkness, int shadow { shadowSize++; } - bool useGDIBlur = GDIplus.isBlurPossible(shadowSize); + bool useGDIBlur = GDIplus.IsBlurPossible(shadowSize); // Create "mask" for the shadow ColorMatrix maskMatrix = new ColorMatrix(); maskMatrix.Matrix00 = 0; @@ -1195,12 +1195,12 @@ public static ImageAttributes CreateAdjustAttributes(float brightness, float con { float adjustedBrightness = brightness - 1.0f; ColorMatrix applyColorMatrix = new ColorMatrix( - new float[][] { - new float[] {contrast, 0, 0, 0, 0}, // scale red - new float[] {0, contrast, 0, 0, 0}, // scale green - new float[] {0, 0, contrast, 0, 0}, // scale blue - new float[] {0, 0, 0, 1.0f, 0}, // don't scale alpha - new float[] {adjustedBrightness, adjustedBrightness, adjustedBrightness, 0, 1} + new [] { + new[] {contrast, 0, 0, 0, 0}, // scale red + new[] {0, contrast, 0, 0, 0}, // scale green + new[] {0, 0, contrast, 0, 0}, // scale blue + new[] {0, 0, 0, 1.0f, 0}, // don't scale alpha + new[] {adjustedBrightness, adjustedBrightness, adjustedBrightness, 0, 1} }); //create some image attributes @@ -1240,10 +1240,10 @@ public static Image Adjust(Image sourceImage, float brightness, float contrast, public static Image CreateGrayscale(Image sourceImage) { Bitmap clone = (Bitmap)Clone(sourceImage); - ColorMatrix grayscaleMatrix = new ColorMatrix(new float[][] { - new float[] {.3f, .3f, .3f, 0, 0}, - new float[] {.59f, .59f, .59f, 0, 0}, - new float[] {.11f, .11f, .11f, 0, 0}, + ColorMatrix grayscaleMatrix = new ColorMatrix(new[] { + new[] {.3f, .3f, .3f, 0, 0}, + new[] {.59f, .59f, .59f, 0, 0}, + new[] {.11f, .11f, .11f, 0, 0}, new float[] {0, 0, 0, 1, 0}, new float[] {0, 0, 0, 0, 1} }); diff --git a/Greenshot.ImageEditor/Core/ImageOutput.cs b/Greenshot.ImageEditor/Core/ImageOutput.cs index 646f8ab52..cda7a4bcb 100644 --- a/Greenshot.ImageEditor/Core/ImageOutput.cs +++ b/Greenshot.ImageEditor/Core/ImageOutput.cs @@ -44,7 +44,7 @@ public static class ImageOutput { private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); private static readonly int PROPERTY_TAG_SOFTWARE_USED = 0x0131; - private static Cache tmpFileCache = new Cache(10 * 60 * 60, RemoveExpiredTmpFile); + private static readonly Cache tmpFileCache = new Cache(10 * 60 * 60, RemoveExpiredTmpFile); /// /// Creates a PropertyItem (Metadata) to store with the image. diff --git a/Greenshot.ImageEditor/Core/NetworkHelper.cs b/Greenshot.ImageEditor/Core/NetworkHelper.cs index 575c28c5b..a9045c78f 100644 --- a/Greenshot.ImageEditor/Core/NetworkHelper.cs +++ b/Greenshot.ImageEditor/Core/NetworkHelper.cs @@ -54,12 +54,17 @@ public static class NetworkHelper static NetworkHelper() { - // Disable certificate checking - ServicePointManager.ServerCertificateValidationCallback += - delegate + try { - return true; - }; + // Disable certificate checking + ServicePointManager.ServerCertificateValidationCallback += delegate { + return true; + }; + } + catch (Exception ex) + { + LOG.Warn("An error has occured while allowing self-signed certificates:", ex); + } } /// @@ -157,15 +162,18 @@ public static Image DownloadImage(string url) { content = streamReader.ReadLine(); } - Regex imageUrlRegex = new Regex(@"(http|https)://.*(\.png|\.gif|\.jpg|\.tiff|\.jpeg|\.bmp)"); - Match match = imageUrlRegex.Match(content); - if (match.Success) + if (!string.IsNullOrEmpty(content)) { - using (MemoryStream memoryStream2 = GetAsMemoryStream(match.Value)) + Regex imageUrlRegex = new Regex(@"(http|https)://.*(\.png|\.gif|\.jpg|\.tiff|\.jpeg|\.bmp)"); + Match match = imageUrlRegex.Match(content); + if (match.Success) { - using (Image image = Image.FromStream(memoryStream2)) + using (MemoryStream memoryStream2 = GetAsMemoryStream(match.Value)) { - return ImageHelper.Clone(image, PixelFormat.Format32bppArgb); + using (Image image = Image.FromStream(memoryStream2)) + { + return ImageHelper.Clone(image, PixelFormat.Format32bppArgb); + } } } } @@ -222,15 +230,7 @@ public static HttpWebRequest CreateWebRequest(Uri uri, HTTPMethod method) public static HttpWebRequest CreateWebRequest(Uri uri) { HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri); - if (Config.UseProxy) - { - webRequest.Proxy = CreateProxy(uri); - } - else - { - // BUG-1655: Fix that Greenshot always uses the default proxy even if the "use default proxy" checkbox is unset - webRequest.Proxy = null; - } + webRequest.Proxy = Config.UseProxy ? CreateProxy(uri) : null; // Make sure the default credentials are available webRequest.Credentials = CredentialCache.DefaultCredentials; @@ -463,10 +463,11 @@ public static void WriteMultipartFormData(Stream formDataStream, string boundary /// Post the parameters "x-www-form-urlencoded" /// /// + /// public static void UploadFormUrlEncoded(HttpWebRequest webRequest, IDictionary parameters) { webRequest.ContentType = "application/x-www-form-urlencoded"; - string urlEncoded = NetworkHelper.GenerateQueryParameters(parameters); + string urlEncoded = GenerateQueryParameters(parameters); byte[] data = Encoding.UTF8.GetBytes(urlEncoded); using (var requestStream = webRequest.GetRequestStream()) @@ -533,6 +534,7 @@ private static string GetResponseAsString(HttpWebResponse response) /// /// /// + /// /// public static string GetResponseAsString(HttpWebRequest webRequest, bool alsoReturnContentOnError) { @@ -639,10 +641,10 @@ public interface IBinaryContainer /// public class ByteContainer : IBinaryContainer { - private byte[] file; - private string fileName; - private string contentType; - private int fileSize; + private readonly byte[] _file; + private readonly string _fileName; + private readonly string _contentType; + private readonly int _fileSize; public ByteContainer(byte[] file) : this(file, null) { @@ -658,17 +660,10 @@ public ByteContainer(byte[] file, string filename, string contenttype) : this(fi public ByteContainer(byte[] file, string filename, string contenttype, int filesize) { - this.file = file; - fileName = filename; - contentType = contenttype; - if (filesize == 0) - { - fileSize = file.Length; - } - else - { - fileSize = filesize; - } + _file = file; + _fileName = filename; + _contentType = contenttype; + _fileSize = filesize == 0 ? file.Length : filesize; } /// @@ -677,7 +672,7 @@ public ByteContainer(byte[] file, string filename, string contenttype, int files /// string public string ToBase64String(Base64FormattingOptions formattingOptions) { - return Convert.ToBase64String(file, 0, fileSize, formattingOptions); + return Convert.ToBase64String(_file, 0, _fileSize, formattingOptions); } /// @@ -686,7 +681,7 @@ public string ToBase64String(Base64FormattingOptions formattingOptions) /// byte[] public byte[] ToByteArray() { - return file; + return _file; } /// @@ -701,13 +696,13 @@ public void WriteFormDataToStream(string boundary, string name, Stream formDataS string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n", boundary, name, - fileName ?? name, - contentType ?? "application/octet-stream"); + _fileName ?? name, + _contentType ?? "application/octet-stream"); formDataStream.Write(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header)); // Write the file data directly to the Stream, rather than serializing it to a string. - formDataStream.Write(file, 0, fileSize); + formDataStream.Write(_file, 0, _fileSize); } /// @@ -717,7 +712,7 @@ public void WriteFormDataToStream(string boundary, string name, Stream formDataS public void WriteToStream(Stream dataStream) { // Write the file data directly to the Stream, rather than serializing it to a string. - dataStream.Write(file, 0, fileSize); + dataStream.Write(_file, 0, _fileSize); } /// @@ -726,8 +721,8 @@ public void WriteToStream(Stream dataStream) /// public void Upload(HttpWebRequest webRequest) { - webRequest.ContentType = contentType; - webRequest.ContentLength = fileSize; + webRequest.ContentType = _contentType; + webRequest.ContentLength = _fileSize; using (var requestStream = webRequest.GetRequestStream()) { WriteToStream(requestStream); @@ -740,15 +735,15 @@ public void Upload(HttpWebRequest webRequest) /// public class BitmapContainer : IBinaryContainer { - private Bitmap bitmap; - private SurfaceOutputSettings outputSettings; - private string fileName; + private readonly Bitmap _bitmap; + private readonly SurfaceOutputSettings _outputSettings; + private readonly string _fileName; public BitmapContainer(Bitmap bitmap, SurfaceOutputSettings outputSettings, string filename) { - this.bitmap = bitmap; - this.outputSettings = outputSettings; - fileName = filename; + _bitmap = bitmap; + _outputSettings = outputSettings; + _fileName = filename; } /// @@ -760,7 +755,7 @@ public string ToBase64String(Base64FormattingOptions formattingOptions) { using (MemoryStream stream = new MemoryStream()) { - ImageOutput.SaveToStream(bitmap, null, stream, outputSettings); + ImageOutput.SaveToStream(_bitmap, null, stream, _outputSettings); return Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length, formattingOptions); } } @@ -774,7 +769,7 @@ public byte[] ToByteArray() { using (MemoryStream stream = new MemoryStream()) { - ImageOutput.SaveToStream(bitmap, null, stream, outputSettings); + ImageOutput.SaveToStream(_bitmap, null, stream, _outputSettings); return stream.ToArray(); } } @@ -791,11 +786,11 @@ public void WriteFormDataToStream(string boundary, string name, Stream formDataS string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n", boundary, name, - fileName ?? name, - "image/" + outputSettings.Format.ToString()); + _fileName ?? name, + "image/" + _outputSettings.Format); formDataStream.Write(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header)); - ImageOutput.SaveToStream(bitmap, null, formDataStream, outputSettings); + ImageOutput.SaveToStream(_bitmap, null, formDataStream, _outputSettings); } /// @@ -805,7 +800,7 @@ public void WriteFormDataToStream(string boundary, string name, Stream formDataS public void WriteToStream(Stream dataStream) { // Write the file data directly to the Stream, rather than serializing it to a string. - ImageOutput.SaveToStream(bitmap, null, dataStream, outputSettings); + ImageOutput.SaveToStream(_bitmap, null, dataStream, _outputSettings); } /// @@ -814,7 +809,7 @@ public void WriteToStream(Stream dataStream) /// public void Upload(HttpWebRequest webRequest) { - webRequest.ContentType = "image/" + outputSettings.Format.ToString(); + webRequest.ContentType = "image/" + _outputSettings.Format; using (var requestStream = webRequest.GetRequestStream()) { WriteToStream(requestStream); @@ -827,15 +822,15 @@ public void Upload(HttpWebRequest webRequest) /// public class SurfaceContainer : IBinaryContainer { - private ISurface surface; - private SurfaceOutputSettings outputSettings; - private string fileName; + private readonly ISurface _surface; + private readonly SurfaceOutputSettings _outputSettings; + private readonly string _fileName; public SurfaceContainer(ISurface surface, SurfaceOutputSettings outputSettings, string filename) { - this.surface = surface; - this.outputSettings = outputSettings; - fileName = filename; + _surface = surface; + _outputSettings = outputSettings; + _fileName = filename; } /// @@ -847,7 +842,7 @@ public string ToBase64String(Base64FormattingOptions formattingOptions) { using (MemoryStream stream = new MemoryStream()) { - ImageOutput.SaveToStream(surface, stream, outputSettings); + ImageOutput.SaveToStream(_surface, stream, _outputSettings); return Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length, formattingOptions); } } @@ -861,7 +856,7 @@ public byte[] ToByteArray() { using (MemoryStream stream = new MemoryStream()) { - ImageOutput.SaveToStream(surface, stream, outputSettings); + ImageOutput.SaveToStream(_surface, stream, _outputSettings); return stream.ToArray(); } } @@ -878,11 +873,11 @@ public void WriteFormDataToStream(string boundary, string name, Stream formDataS string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n", boundary, name, - fileName ?? name, - "image/" + outputSettings.Format); + _fileName ?? name, + "image/" + _outputSettings.Format); formDataStream.Write(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header)); - ImageOutput.SaveToStream(surface, formDataStream, outputSettings); + ImageOutput.SaveToStream(_surface, formDataStream, _outputSettings); } /// @@ -892,7 +887,7 @@ public void WriteFormDataToStream(string boundary, string name, Stream formDataS public void WriteToStream(Stream dataStream) { // Write the file data directly to the Stream, rather than serializing it to a string. - ImageOutput.SaveToStream(surface, dataStream, outputSettings); + ImageOutput.SaveToStream(_surface, dataStream, _outputSettings); } /// @@ -901,7 +896,7 @@ public void WriteToStream(Stream dataStream) /// public void Upload(HttpWebRequest webRequest) { - webRequest.ContentType = "image/" + outputSettings.Format.ToString(); + webRequest.ContentType = "image/" + _outputSettings.Format.ToString(); using (var requestStream = webRequest.GetRequestStream()) { WriteToStream(requestStream); diff --git a/Greenshot.ImageEditor/Core/OperatingSystemExtensions.cs b/Greenshot.ImageEditor/Core/OperatingSystemExtensions.cs new file mode 100644 index 000000000..9a4f7973e --- /dev/null +++ b/Greenshot.ImageEditor/Core/OperatingSystemExtensions.cs @@ -0,0 +1,92 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on GitHub: https://github.com/greenshot + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 1 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +using System; + +namespace GreenshotPlugin.Core +{ + /// + /// Extensions to help with querying the Operating System + /// + public static class OperatingSystemExtensions + { + /// + /// Test if the current OS is Windows 10 + /// + /// OperatingSystem from Environment.OSVersion + /// true if we are running on Windows 10 + public static bool IsWindows10(this OperatingSystem operatingSystem) + { + return operatingSystem.Version.Major == 10; + } + + /// + /// Test if the current OS is Windows 8(.1) + /// + /// OperatingSystem from Environment.OSVersion + /// true if we are running on Windows 8(.1) + public static bool IsWindows8(this OperatingSystem operatingSystem) + { + return operatingSystem.Version.Major == 6 && operatingSystem.Version.Minor >= 2; + } + + /// + /// Test if the current OS is Windows 8 or later + /// + /// OperatingSystem from Environment.OSVersion + /// true if we are running on Windows 8 or later + public static bool IsWindows8OrLater(this OperatingSystem operatingSystem) + { + return (operatingSystem.Version.Major == 6 && operatingSystem.Version.Minor >= 2) || operatingSystem.Version.Major >= 6; + } + + /// + /// Test if the current OS is Windows 7 or later + /// + /// OperatingSystem from Environment.OSVersion + /// true if we are running on Windows 7 or later + public static bool IsWindows7OrLater(this OperatingSystem operatingSystem) + { + return (operatingSystem.Version.Major == 6 && operatingSystem.Version.Minor >= 1) || operatingSystem.Version.Major >= 6; + } + + /// + /// Test if the current OS is Windows Vista or later + /// + /// OperatingSystem from Environment.OSVersion + /// true if we are running on Windows Vista or later + public static bool IsWindowsVistaOrLater(this OperatingSystem operatingSystem) + { + return operatingSystem.Version.Major >= 6; + } + + /// + /// Test if the current OS is Windows XP or later + /// + /// OperatingSystem from Environment.OSVersion + /// true if we are running on Windows XP or later + public static bool IsWindowsXpOrLater(this OperatingSystem operatingSystem) + { + // Windows 2000 is Major 5 minor 0 + return Environment.OSVersion.Version.Major > 5 || (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1); + } + } +} \ No newline at end of file diff --git a/Greenshot.ImageEditor/Core/PluginUtils.cs b/Greenshot.ImageEditor/Core/PluginUtils.cs index 9a1c5585f..525fa0ffb 100644 --- a/Greenshot.ImageEditor/Core/PluginUtils.cs +++ b/Greenshot.ImageEditor/Core/PluginUtils.cs @@ -37,9 +37,9 @@ namespace GreenshotPlugin.Core /// public static class PluginUtils { - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); private const string PATH_KEY = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\"; - private static IDictionary exeIconCache = new Dictionary(); + private static readonly IDictionary exeIconCache = new Dictionary(); static PluginUtils() { @@ -126,16 +126,19 @@ public static Image GetCachedExeIcon(string path, int index) { string cacheKey = string.Format("{0}:{1}", path, index); Image returnValue; - if (!exeIconCache.TryGetValue(cacheKey, out returnValue)) + lock (exeIconCache) { - lock (exeIconCache) + if (!exeIconCache.TryGetValue(cacheKey, out returnValue)) { - if (!exeIconCache.TryGetValue(cacheKey, out returnValue)) + lock (exeIconCache) { - returnValue = GetExeIcon(path, index); - if (returnValue != null) + if (!exeIconCache.TryGetValue(cacheKey, out returnValue)) { - exeIconCache.Add(cacheKey, returnValue); + returnValue = GetExeIcon(path, index); + if (returnValue != null) + { + exeIconCache.Add(cacheKey, returnValue); + } } } } diff --git a/Greenshot.ImageEditor/Core/QuantizerHelper.cs b/Greenshot.ImageEditor/Core/QuantizerHelper.cs index c920dc86e..c5ca60e11 100644 --- a/Greenshot.ImageEditor/Core/QuantizerHelper.cs +++ b/Greenshot.ImageEditor/Core/QuantizerHelper.cs @@ -83,23 +83,23 @@ public class WuQuantizer : IDisposable private const Int32 MAXVOLUME = SIDESIZE * SIDESIZE * SIDESIZE; // To count the colors - private int colorCount = 0; + private readonly int colorCount; private Int32[] reds; private Int32[] greens; private Int32[] blues; private Int32[] sums; - private Int64[,,] weights; - private Int64[,,] momentsRed; - private Int64[,,] momentsGreen; - private Int64[,,] momentsBlue; - private Single[,,] moments; + private readonly Int64[,,] weights; + private readonly Int64[,,] momentsRed; + private readonly Int64[,,] momentsGreen; + private readonly Int64[,,] momentsBlue; + private readonly Single[,,] moments; private byte[] tag; - private WuColorCube[] cubes; - private Bitmap sourceBitmap; + private readonly WuColorCube[] cubes; + private readonly Bitmap sourceBitmap; private Bitmap resultBitmap; public void Dispose() diff --git a/Greenshot.ImageEditor/Core/WindowCapture.cs b/Greenshot.ImageEditor/Core/WindowCapture.cs index 8a31d5540..384936323 100644 --- a/Greenshot.ImageEditor/Core/WindowCapture.cs +++ b/Greenshot.ImageEditor/Core/WindowCapture.cs @@ -68,7 +68,7 @@ public float DpiY set; } - private Dictionary metaData = new Dictionary(); + private readonly Dictionary metaData = new Dictionary(); public Dictionary MetaData { get { return metaData; } @@ -503,6 +503,7 @@ public class WindowCapture /// /// [DllImport("gdi32", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DeleteObject(IntPtr hObject); private WindowCapture() @@ -766,7 +767,7 @@ public static Bitmap CaptureRectangle(Rectangle captureBounds) // capture.Image = capturedBitmap; // capture.Location = captureBounds.Location; - using (SafeWindowDCHandle desktopDCHandle = SafeWindowDCHandle.fromDesktop()) + using (SafeWindowDCHandle desktopDCHandle = SafeWindowDCHandle.FromDesktop()) { if (desktopDCHandle.IsInvalid) { diff --git a/Greenshot.ImageEditor/Core/WindowsHelper.cs b/Greenshot.ImageEditor/Core/WindowsHelper.cs index fc0174f71..638c5bfd2 100644 --- a/Greenshot.ImageEditor/Core/WindowsHelper.cs +++ b/Greenshot.ImageEditor/Core/WindowsHelper.cs @@ -33,12 +33,6 @@ using System.Text.RegularExpressions; using System.Windows.Forms; -/// -/// Code for handling with "windows" -/// Main code is taken from vbAccelerator, location: -/// http://www.vbaccelerator.com/home/NET/Code/Libraries/Windows/Enumerating_Windows/article.asp -/// but a LOT of changes/enhancements were made to adapt it for Greenshot. -/// namespace GreenshotPlugin.Core { #region EnumWindows @@ -50,7 +44,7 @@ public class WindowsEnumerator { #region Member Variables - private List items = null; + private List items; #endregion Member Variables @@ -101,7 +95,7 @@ public WindowsEnumerator GetWindows(IntPtr hWndParent, string classname) { items = new List(); List windows = new List(); - User32.EnumChildWindows(hWndParent, new EnumWindowsProc(WindowEnum), IntPtr.Zero); + User32.EnumChildWindows(hWndParent, WindowEnum, IntPtr.Zero); bool hasParent = !IntPtr.Zero.Equals(hWndParent); string parentText = null; @@ -162,7 +156,7 @@ private int WindowEnum(IntPtr hWnd, int lParam) /// True to continue enumeration, False to stop protected virtual bool OnWindowEnum(IntPtr hWnd) { - if (!WindowDetails.isIgnoreHandle(hWnd)) + if (!WindowDetails.IsIgnoreHandle(hWnd)) { items.Add(new WindowDetails(hWnd)); } @@ -186,19 +180,24 @@ public WindowsEnumerator() #region WindowDetails /// + /// Code for handling with "windows" + /// Main code is taken from vbAccelerator, location: + /// http://www.vbaccelerator.com/home/NET/Code/Libraries/Windows/Enumerating_Windows/article.asp + /// but a LOT of changes/enhancements were made to adapt it for Greenshot. + /// /// Provides details about a Window returned by the /// enumeration /// public class WindowDetails : IEquatable { - private const string METRO_WINDOWS_CLASS = "Windows.UI.Core.CoreWindow"; + private const string METRO_WINDOWS_CLASS = "Windows.UI.Core.CoreWindow"; // Windows 10 uses ApplicationFrameWindow private const string METRO_APPLAUNCHER_CLASS = "ImmersiveLauncher"; private const string METRO_GUTTER_CLASS = "ImmersiveGutter"; - private static CoreConfiguration conf = IniConfig.GetIniSection(); - private static List ignoreHandles = new List(); - private static List excludeProcessesFromFreeze = new List(); - private static IAppVisibility appVisibility = null; + private static readonly CoreConfiguration Conf = IniConfig.GetIniSection(); + private static readonly List IgnoreHandles = new List(); + private static readonly List ExcludeProcessesFromFreeze = new List(); + private static readonly IAppVisibility appVisibility; static WindowDetails() { @@ -215,23 +214,27 @@ static WindowDetails() public static void AddProcessToExcludeFromFreeze(string processname) { - if (!excludeProcessesFromFreeze.Contains(processname)) + if (!ExcludeProcessesFromFreeze.Contains(processname)) { - excludeProcessesFromFreeze.Add(processname); + ExcludeProcessesFromFreeze.Add(processname); } } - internal static bool isIgnoreHandle(IntPtr handle) + internal static bool IsIgnoreHandle(IntPtr handle) { - return ignoreHandles.Contains(handle); + return IgnoreHandles.Contains(handle); } - private List childWindows = null; - private IntPtr parentHandle = IntPtr.Zero; - private WindowDetails parent = null; - private bool frozen = false; + private List _childWindows; + private IntPtr _parentHandle = IntPtr.Zero; + private WindowDetails _parent; + private bool _frozen; - public bool isApp + /// + /// This checks if the window is a Windows 8 App + /// For Windows 10 most normal code works, as it's hosted inside "ApplicationFrameWindow" + /// + public bool IsApp { get { @@ -239,7 +242,7 @@ public bool isApp } } - public bool isGutter + public bool IsGutter { get { @@ -247,7 +250,7 @@ public bool isGutter } } - public bool isAppLauncher + public bool IsAppLauncher { get { @@ -258,18 +261,18 @@ public bool isAppLauncher /// /// Check if this window is the window of a metro app /// - public bool isMetroApp + public bool IsMetroApp { get { - return isAppLauncher || isApp; + return IsAppLauncher || IsApp; } } /// /// The window handle. /// - private IntPtr hWnd = IntPtr.Zero; + private IntPtr _hWnd = IntPtr.Zero; /// /// To allow items to be compared, the hash code @@ -310,18 +313,18 @@ public bool HasChildren { get { - return (childWindows != null) && (childWindows.Count > 0); + return (_childWindows != null) && (_childWindows.Count > 0); } } public void FreezeDetails() { - frozen = true; + _frozen = true; } public void UnfreezeDetails() { - frozen = false; + _frozen = false; } public string ProcessPath @@ -362,7 +365,7 @@ public Image DisplayIcon LOG.WarnFormat("Couldn't get icon for window {0} due to: {1}", Text, ex.Message); LOG.Warn(ex); } - if (isMetroApp) + if (IsMetroApp) { // No method yet to get the metro icon return null; @@ -391,8 +394,8 @@ private static Icon GetAppIcon(IntPtr hwnd) IntPtr ICON_BIG = new IntPtr(1); IntPtr ICON_SMALL2 = new IntPtr(2); - IntPtr iconHandle = User32.SendMessage(hwnd, (int)WindowsMessages.WM_GETICON, ICON_BIG, IntPtr.Zero); - if (conf.UseLargeIcons) + IntPtr iconHandle; + if (Conf.UseLargeIcons) { iconHandle = User32.SendMessage(hwnd, (int)WindowsMessages.WM_GETICON, ICON_BIG, IntPtr.Zero); if (iconHandle == IntPtr.Zero) @@ -437,7 +440,7 @@ private static Icon GetAppIcon(IntPtr hwnd) /// public static void RegisterIgnoreHandle(IntPtr ignoreHandle) { - ignoreHandles.Add(ignoreHandle); + IgnoreHandles.Add(ignoreHandle); } /// @@ -446,24 +449,25 @@ public static void RegisterIgnoreHandle(IntPtr ignoreHandle) /// public static void UnregisterIgnoreHandle(IntPtr ignoreHandle) { - ignoreHandles.Remove(ignoreHandle); + IgnoreHandles.Remove(ignoreHandle); } public List Children { get { - if (childWindows == null) + if (_childWindows == null) { GetChildren(); } - return childWindows; + return _childWindows; } } /// /// Retrieve all windows with a certain title or classname /// + /// /// The regexp to look for in the title /// The regexp to look for in the classname /// List with all the found windows @@ -529,19 +533,19 @@ public IntPtr ParentHandle { get { - if (parentHandle == IntPtr.Zero) + if (_parentHandle == IntPtr.Zero) { - parentHandle = User32.GetParent(Handle); - parent = null; + _parentHandle = User32.GetParent(Handle); + _parent = null; } - return parentHandle; + return _parentHandle; } set { - if (parentHandle != value) + if (_parentHandle != value) { - parentHandle = value; - parent = null; + _parentHandle = value; + _parent = null; } } } @@ -552,18 +556,18 @@ public IntPtr ParentHandle /// WindowDetails of the parent, or null if none public WindowDetails GetParent() { - if (parent == null) + if (_parent == null) { - if (parentHandle == IntPtr.Zero) + if (_parentHandle == IntPtr.Zero) { - parentHandle = User32.GetParent(Handle); + _parentHandle = User32.GetParent(Handle); } - if (parentHandle != IntPtr.Zero) + if (_parentHandle != IntPtr.Zero) { - parent = new WindowDetails(parentHandle); + _parent = new WindowDetails(_parentHandle); } } - return parent; + return _parent; } /// @@ -572,11 +576,11 @@ public WindowDetails GetParent() /// public List GetChildren() { - if (childWindows == null) + if (_childWindows == null) { return GetChildren(0); } - return childWindows; + return _childWindows; } /// @@ -585,19 +589,19 @@ public List GetChildren() /// Specify how many levels we go in public List GetChildren(int levelsToGo) { - if (childWindows == null) + if (_childWindows == null) { - childWindows = new List(); - foreach (WindowDetails childWindow in new WindowsEnumerator().GetWindows(hWnd, null).Items) + _childWindows = new List(); + foreach (WindowDetails childWindow in new WindowsEnumerator().GetWindows(_hWnd, null).Items) { - childWindows.Add(childWindow); + _childWindows.Add(childWindow); if (levelsToGo > 0) { childWindow.GetChildren(levelsToGo - 1); } } } - return childWindows; + return _childWindows; } /// @@ -605,7 +609,7 @@ public List GetChildren(int levelsToGo) /// /// The regexp to look for in the title /// The regexp to look for in the classname - /// List with all the found windows, or an empty list + /// List WindowDetails with all the found windows, or an empty list public List FindChildren(string titlePattern, string classnamePattern) { return FindWindow(Children, titlePattern, classnamePattern); @@ -646,7 +650,7 @@ private WindowDetails FindPath(List classnames, int index) /// This method will find the child window according to a path of classnames. /// Usually used for finding a certain "content" window like for the IE Browser /// - /// List with classname "path" + /// List string with classname "path" /// true allows the search to skip a classname of the path /// WindowDetails if found public WindowDetails FindPath(List classnames, bool allowSkip) @@ -707,7 +711,7 @@ public WindowDetails GetWindow(GetWindowCommand gwCommand) return null; } WindowDetails windowDetails = new WindowDetails(tmphWnd); - windowDetails.parent = this; + windowDetails._parent = this; return windowDetails; } @@ -718,11 +722,11 @@ public IntPtr Handle { get { - return hWnd; + return _hWnd; } } - private string text = null; + private string _text; /// /// Gets the window's title (caption) /// @@ -730,21 +734,21 @@ public string Text { set { - text = value; + _text = value; } get { - if (text == null) + if (_text == null) { StringBuilder title = new StringBuilder(260, 260); - User32.GetWindowText(hWnd, title, title.Capacity); - text = title.ToString(); + User32.GetWindowText(_hWnd, title, title.Capacity); + _text = title.ToString(); } - return text; + return _text; } } - private string className = null; + private string _className; /// /// Gets the window's class name. /// @@ -752,11 +756,11 @@ public string ClassName { get { - if (className == null) + if (_className == null) { - className = GetClassName(hWnd); + _className = GetClassName(_hWnd); } - return className; + return _className; } } @@ -767,21 +771,21 @@ public bool Iconic { get { - if (isMetroApp) + if (IsMetroApp) { return !Visible; } - return User32.IsIconic(hWnd) || Location.X <= -32000; + return User32.IsIconic(_hWnd) || Location.X <= -32000; } set { if (value) { - User32.SendMessage(hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_MINIMIZE, IntPtr.Zero); + User32.SendMessage(_hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_MINIMIZE, IntPtr.Zero); } else { - User32.SendMessage(hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_RESTORE, IntPtr.Zero); + User32.SendMessage(_hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_RESTORE, IntPtr.Zero); } } } @@ -793,7 +797,7 @@ public bool Maximised { get { - if (isApp) + if (IsApp) { if (Visible) { @@ -811,17 +815,17 @@ public bool Maximised } return false; } - return User32.IsZoomed(hWnd); + return User32.IsZoomed(_hWnd); } set { if (value) { - User32.SendMessage(hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_MAXIMIZE, IntPtr.Zero); + User32.SendMessage(_hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_MAXIMIZE, IntPtr.Zero); } else { - User32.SendMessage(hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_MINIMIZE, IntPtr.Zero); + User32.SendMessage(_hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_MINIMIZE, IntPtr.Zero); } } } @@ -841,7 +845,7 @@ public bool Visible { get { - if (isApp) + if (IsApp) { Rectangle windowRectangle = WindowRectangle; foreach (Screen screen in Screen.AllScreens) @@ -876,16 +880,16 @@ public bool Visible } return false; } - if (isGutter) + if (IsGutter) { // gutter is only made available when it's visible return true; } - if (isAppLauncher) + if (IsAppLauncher) { return IsAppLauncherVisible; } - return User32.IsWindowVisible(hWnd); + return User32.IsWindowVisible(_hWnd); } } @@ -894,7 +898,7 @@ public bool HasParent get { GetParent(); - return parentHandle != IntPtr.Zero; + return _parentHandle != IntPtr.Zero; } } @@ -935,12 +939,12 @@ public Process Process /// public void Reset() { - previousWindowRectangle = Rectangle.Empty; + _previousWindowRectangle = Rectangle.Empty; } - private Rectangle previousWindowRectangle = Rectangle.Empty; - private long lastWindowRectangleRetrieveTime = 0; - private const long CACHE_TIME = TimeSpan.TicksPerSecond * 2; + private Rectangle _previousWindowRectangle = Rectangle.Empty; + private long _lastWindowRectangleRetrieveTime; + private const long CacheTime = TimeSpan.TicksPerSecond * 2; /// /// Gets the bounding rectangle of the window /// @@ -950,39 +954,64 @@ public Rectangle WindowRectangle { // Try to return a cached value long now = DateTime.Now.Ticks; - if (previousWindowRectangle.IsEmpty || !frozen) + if (_previousWindowRectangle.IsEmpty || !_frozen) { - if (previousWindowRectangle.IsEmpty || now - lastWindowRectangleRetrieveTime > CACHE_TIME) + if (_previousWindowRectangle.IsEmpty || now - _lastWindowRectangleRetrieveTime > CacheTime) { Rectangle windowRect = Rectangle.Empty; - if (DWM.isDWMEnabled()) + if (DWM.IsDwmEnabled()) { - GetExtendedFrameBounds(out windowRect); + bool gotFrameBounds = GetExtendedFrameBounds(out windowRect); + if (IsApp) + { + // Pre-Cache for Maximised call, this is only on Windows 8 apps (full screen) + if (gotFrameBounds) + { + _previousWindowRectangle = windowRect; + _lastWindowRectangleRetrieveTime = now; + } + } + if (gotFrameBounds && Environment.OSVersion.IsWindows10() && !Maximised) + { + // Somehow DWM doesn't calculate it corectly, there is a 1 pixel border around the capture + // Remove this border, currently it's fixed but TODO: Make it depend on the OS? + windowRect.Inflate(-1, -1); + _previousWindowRectangle = windowRect; + _lastWindowRectangleRetrieveTime = now; + return windowRect; + } } if (windowRect.IsEmpty) { - GetWindowRect(out windowRect); + if (GetWindowRect(out windowRect)) + { + Win32Error error = Win32.GetLastErrorCode(); + LOG.WarnFormat("Couldn't retrieve the windows rectangle: {0}", Win32.GetMessage(error)); + } } // Correction for maximized windows, only if it's not an app - if (!HasParent && !isApp && Maximised) + if (!HasParent && !IsApp && Maximised) { - Size size = Size.Empty; - GetBorderSize(out size); - windowRect = new Rectangle(windowRect.X + size.Width, windowRect.Y + size.Height, windowRect.Width - (2 * size.Width), windowRect.Height - (2 * size.Height)); + Size size; + // Only if the border size can be retrieved + if (GetBorderSize(out size)) + { + windowRect = new Rectangle(windowRect.X + size.Width, windowRect.Y + size.Height, windowRect.Width - (2 * size.Width), windowRect.Height - (2 * size.Height)); + } } - lastWindowRectangleRetrieveTime = now; + _lastWindowRectangleRetrieveTime = now; // Try to return something valid, by getting returning the previous size if the window doesn't have a Rectangle anymore if (windowRect.IsEmpty) { - return previousWindowRectangle; + return _previousWindowRectangle; } - previousWindowRectangle = windowRect; + _previousWindowRectangle = windowRect; return windowRect; } } - return previousWindowRectangle; + return _previousWindowRectangle; } } @@ -1017,8 +1046,12 @@ public Rectangle ClientRectangle { get { - Rectangle clientRect = Rectangle.Empty; - GetClientRect(out clientRect); + Rectangle clientRect; + if (GetClientRect(out clientRect)) + { + Win32Error error = Win32.GetLastErrorCode(); + LOG.WarnFormat("Couldn't retrieve the client rectangle: {0}", Win32.GetMessage(error)); + } return clientRect; } } @@ -1041,10 +1074,10 @@ public void Restore() { if (Iconic) { - User32.SendMessage(hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_RESTORE, IntPtr.Zero); + User32.SendMessage(_hWnd, (int)WindowsMessages.WM_SYSCOMMAND, (IntPtr)User32.SC_RESTORE, IntPtr.Zero); } - User32.BringWindowToTop(hWnd); - User32.SetForegroundWindow(hWnd); + User32.BringWindowToTop(_hWnd); + User32.SetForegroundWindow(_hWnd); // Make sure windows has time to perform the action while (Iconic) { @@ -1059,11 +1092,11 @@ public WindowStyleFlags WindowStyle { get { - return (WindowStyleFlags)User32.GetWindowLongWrapper(hWnd, (int)WindowLongIndex.GWL_STYLE); + return (WindowStyleFlags)User32.GetWindowLongWrapper(_hWnd, (int)WindowLongIndex.GWL_STYLE); } set { - User32.SetWindowLongWrapper(hWnd, (int)WindowLongIndex.GWL_STYLE, new IntPtr((long)value)); + User32.SetWindowLongWrapper(_hWnd, (int)WindowLongIndex.GWL_STYLE, new IntPtr((long)value)); } } @@ -1091,11 +1124,11 @@ public ExtendedWindowStyleFlags ExtendedWindowStyle { get { - return (ExtendedWindowStyleFlags)User32.GetWindowLongWrapper(hWnd, (int)WindowLongIndex.GWL_EXSTYLE); + return (ExtendedWindowStyleFlags)User32.GetWindowLongWrapper(_hWnd, (int)WindowLongIndex.GWL_EXSTYLE); } set { - User32.SetWindowLongWrapper(hWnd, (int)WindowLongIndex.GWL_EXSTYLE, new IntPtr((uint)value)); + User32.SetWindowLongWrapper(_hWnd, (int)WindowLongIndex.GWL_EXSTYLE, new IntPtr((uint)value)); } } @@ -1104,7 +1137,7 @@ public ExtendedWindowStyleFlags ExtendedWindowStyle /// /// The capture to fill /// ICapture - public ICapture CaptureGDIWindow(ICapture capture) + public ICapture CaptureGdiWindow(ICapture capture) { Image capturedImage = PrintWindow(); if (capturedImage != null) @@ -1123,17 +1156,19 @@ public ICapture CaptureGDIWindow(ICapture capture) /// Wanted WindowCaptureMode /// True if auto modus is used /// ICapture with the capture - public ICapture CaptureDWMWindow(ICapture capture, WindowCaptureMode windowCaptureMode, bool autoMode) + public ICapture CaptureDwmWindow(ICapture capture, WindowCaptureMode windowCaptureMode, bool autoMode) { IntPtr thumbnailHandle = IntPtr.Zero; Form tempForm = null; bool tempFormShown = false; try { - tempForm = new Form(); - tempForm.ShowInTaskbar = false; - tempForm.FormBorderStyle = FormBorderStyle.None; - tempForm.TopMost = true; + tempForm = new Form + { + ShowInTaskbar = false, + FormBorderStyle = FormBorderStyle.None, + TopMost = true + }; // Register the Thumbnail DWM.DwmRegisterThumbnail(tempForm.Handle, Handle, out thumbnailHandle); @@ -1142,14 +1177,14 @@ public ICapture CaptureDWMWindow(ICapture capture, WindowCaptureMode windowCaptu SIZE sourceSize; DWM.DwmQueryThumbnailSourceSize(thumbnailHandle, out sourceSize); - if (sourceSize.width <= 0 || sourceSize.height <= 0) + if (sourceSize.Width <= 0 || sourceSize.Height <= 0) { return null; } // Calculate the location of the temp form - Point formLocation; Rectangle windowRectangle = WindowRectangle; + Point formLocation = windowRectangle.Location; Size borderSize = new Size(); bool doesCaptureFit = false; if (!Maximised) @@ -1161,7 +1196,7 @@ public ICapture CaptureDWMWindow(ICapture capture, WindowCaptureMode windowCaptu // Find the screen where the window is and check if it fits foreach (Screen screen in Screen.AllScreens) { - if (screen != Screen.PrimaryScreen) + if (!Equals(screen, Screen.PrimaryScreen)) { workingArea.Union(screen.Bounds); } @@ -1188,7 +1223,7 @@ public ICapture CaptureDWMWindow(ICapture capture, WindowCaptureMode windowCaptu } } } - else + else if (!Environment.OSVersion.IsWindows8OrLater()) { //GetClientRect(out windowRectangle); GetBorderSize(out borderSize); @@ -1199,38 +1234,42 @@ public ICapture CaptureDWMWindow(ICapture capture, WindowCaptureMode windowCaptu tempForm.Size = sourceSize.ToSize(); // Prepare rectangle to capture from the screen. - Rectangle captureRectangle = new Rectangle(formLocation.X, formLocation.Y, sourceSize.width, sourceSize.height); + Rectangle captureRectangle = new Rectangle(formLocation.X, formLocation.Y, sourceSize.Width, sourceSize.Height); if (Maximised) { // Correct capture size for maximized window by offsetting the X,Y with the border size - captureRectangle.X += borderSize.Width; - captureRectangle.Y += borderSize.Height; // and subtracting the border from the size (2 times, as we move right/down for the capture without resizing) - captureRectangle.Width -= 2 * borderSize.Width; - captureRectangle.Height -= 2 * borderSize.Height; + captureRectangle.Inflate(borderSize.Width, borderSize.Height); } - else if (autoMode) + else { - // check if the capture fits - if (!doesCaptureFit) + captureRectangle.Inflate(-1, -1); + + if (autoMode) { - // if GDI is allowed.. (a screenshot won't be better than we comes if we continue) - using (Process thisWindowProcess = Process) + // check if the capture fits + if (!doesCaptureFit) { - if (!isMetroApp && WindowCapture.IsGdiAllowed(thisWindowProcess)) + // if GDI is allowed.. (a screenshot won't be better than we comes if we continue) + using (Process thisWindowProcess = Process) { - // we return null which causes the capturing code to try another method. - return null; + if (!IsMetroApp && WindowCapture.IsGdiAllowed(thisWindowProcess)) + { + // we return null which causes the capturing code to try another method. + return null; + } } } } } // Prepare the displaying of the Thumbnail - DWM_THUMBNAIL_PROPERTIES props = new DWM_THUMBNAIL_PROPERTIES(); - props.Opacity = (byte)255; - props.Visible = true; - props.Destination = new RECT(0, 0, sourceSize.width, sourceSize.height); + DWM_THUMBNAIL_PROPERTIES props = new DWM_THUMBNAIL_PROPERTIES + { + Opacity = 255, + Visible = true, + Destination = new RECT(0, 0, sourceSize.Width, sourceSize.Height) + }; DWM.DwmUpdateThumbnailProperties(thumbnailHandle, ref props); tempForm.Show(); tempFormShown = true; @@ -1261,7 +1300,7 @@ public ICapture CaptureDWMWindow(ICapture capture, WindowCaptureMode windowCaptu tempForm.BackColor = Color.Black; // Make sure everything is visible tempForm.Refresh(); - if (!isMetroApp) + if (!IsMetroApp) { // Make sure the application window is active, so the colors & buttons are right ToForeground(); @@ -1291,7 +1330,7 @@ public ICapture CaptureDWMWindow(ICapture capture, WindowCaptureMode windowCaptu // Remove transparency, this will break the capturing if (!autoMode) { - tempForm.BackColor = Color.FromArgb(255, conf.DWMBackgroundColor.R, conf.DWMBackgroundColor.G, conf.DWMBackgroundColor.B); + tempForm.BackColor = Color.FromArgb(255, Conf.DWMBackgroundColor.R, Conf.DWMBackgroundColor.G, Conf.DWMBackgroundColor.B); } else { @@ -1302,7 +1341,7 @@ public ICapture CaptureDWMWindow(ICapture capture, WindowCaptureMode windowCaptu } // Make sure everything is visible tempForm.Refresh(); - if (!isMetroApp) + if (!IsMetroApp) { // Make sure the application window is active, so the colors & buttons are right ToForeground(); @@ -1315,10 +1354,10 @@ public ICapture CaptureDWMWindow(ICapture capture, WindowCaptureMode windowCaptu if (capturedBitmap != null) { // Not needed for Windows 8 - if (!(Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor >= 2)) + if (!Environment.OSVersion.IsWindows8OrLater()) { // Only if the Inivalue is set, not maximized and it's not a tool window. - if (conf.WindowCaptureRemoveCorners && !Maximised && (ExtendedWindowStyle & ExtendedWindowStyleFlags.WS_EX_TOOLWINDOW) == 0) + if (Conf.WindowCaptureRemoveCorners && !Maximised && (ExtendedWindowStyle & ExtendedWindowStyleFlags.WS_EX_TOOLWINDOW) == 0) { // Remove corners if (!Image.IsAlphaPixelFormat(capturedBitmap.PixelFormat)) @@ -1375,9 +1414,9 @@ private void RemoveCorners(Bitmap image) { using (IFastBitmap fastBitmap = FastBitmap.Create(image)) { - for (int y = 0; y < conf.WindowCornerCutShape.Count; y++) + for (int y = 0; y < Conf.WindowCornerCutShape.Count; y++) { - for (int x = 0; x < conf.WindowCornerCutShape[y]; x++) + for (int x = 0; x < Conf.WindowCornerCutShape[y]; x++) { fastBitmap.SetColorAt(x, y, Color.Transparent); fastBitmap.SetColorAt(image.Width - 1 - x, y, Color.Transparent); @@ -1506,7 +1545,7 @@ private bool GetWindowRect(out Rectangle rectangle) /// /// Helper method to get the Border size for GDI Windows /// - /// out Rectangle + /// out Size /// bool true if it worked private bool GetBorderSize(out Size size) { @@ -1570,7 +1609,7 @@ private bool CanFreezeOrUnfreeze(string titleOrProcessname) return false; } - foreach (string excludeProcess in excludeProcessesFromFreeze) + foreach (string excludeProcess in ExcludeProcessesFromFreeze) { if (titleOrProcessname.ToLower().Contains(excludeProcess)) { @@ -1722,7 +1761,7 @@ public Image PrintWindow() /// The Window Handle public WindowDetails(IntPtr hWnd) { - this.hWnd = hWnd; + this._hWnd = hWnd; } /// @@ -1734,7 +1773,7 @@ public static WindowDetails GetActiveWindow() IntPtr hWnd = User32.GetForegroundWindow(); if (hWnd != null && hWnd != IntPtr.Zero) { - if (ignoreHandles.Contains(hWnd)) + if (IgnoreHandles.Contains(hWnd)) { return GetDesktopWindow(); } @@ -1759,7 +1798,7 @@ public bool IsGreenshot { try { - if (!isMetroApp) + if (!IsMetroApp) { using (Process thisWindowProcess = Process) { @@ -1796,7 +1835,7 @@ public static List GetAllWindows() /// /// Get all the top level windows, with matching classname /// - /// List with all the top level windows + /// List WindowDetails with all the top level windows public static List GetAllWindows(string classname) { return new WindowsEnumerator().GetWindows(IntPtr.Zero, classname).Items; @@ -1805,7 +1844,6 @@ public static List GetAllWindows(string classname) /// /// Recursive "find children which" /// - /// Window to look into /// point to check for /// public WindowDetails FindChildUnderPoint(Point point) @@ -1839,7 +1877,7 @@ public static string GetClassName(IntPtr hWnd) /// /// Get all the visible top level windows /// - /// List with all the visible top level windows + /// List WindowDetails with all the visible top level windows public static List GetVisibleWindows() { List windows = new List(); @@ -1859,7 +1897,7 @@ public static List GetVisibleWindows() continue; } // Ignore some classes - List ignoreClasses = new List(new string[] { "Progman", "XLMAIN", "Button", "Dwm" }); //"MS-SDIa" + List ignoreClasses = new List(new[] { "Progman", "XLMAIN", "Button", "Dwm" }); //"MS-SDIa" if (ignoreClasses.Contains(window.ClassName)) { continue; @@ -1880,7 +1918,7 @@ public static List GetVisibleWindows() /// Get the WindowDetails for all Metro Apps /// These are all Windows with Classname "Windows.UI.Core.CoreWindow" /// - /// List with visible metro apps + /// List WindowDetails with visible metro apps public static List GetMetroApps() { List metroApps = new List(); @@ -1939,7 +1977,7 @@ public static List GetTopLevelWindows() continue; } // Ignore some classes - List ignoreClasses = new List(new string[] { "Progman", "XLMAIN", "Button", "Dwm" }); //"MS-SDIa" + List ignoreClasses = new List(new[] { "Progman", "XLMAIN", "Button", "Dwm" }); //"MS-SDIa" if (ignoreClasses.Contains(window.ClassName)) { continue; @@ -2020,7 +2058,7 @@ public static WindowDetails GetLinkedWindow(WindowDetails windowToLinkTo) /// Helper method to "active" all windows that are not in the supplied list. /// One should preferably call "GetVisibleWindows" for the oldWindows. /// - /// List with old windows + /// List WindowDetails with old windows public static void ActiveNewerWindows(List oldWindows) { List windowsAfter = GetVisibleWindows(); diff --git a/Greenshot.ImageEditor/Drawing/ArrowContainer.cs b/Greenshot.ImageEditor/Drawing/ArrowContainer.cs index fa61d14e3..e08a2b91f 100644 --- a/Greenshot.ImageEditor/Drawing/ArrowContainer.cs +++ b/Greenshot.ImageEditor/Drawing/ArrowContainer.cs @@ -89,7 +89,7 @@ public override void Draw(Graphics graphics, RenderMode rm) Top + currentStep + Height); currentStep++; - alpha = alpha - (basealpha / steps); + alpha = alpha - basealpha / steps; } } } diff --git a/Greenshot.ImageEditor/Drawing/DrawableContainer.cs b/Greenshot.ImageEditor/Drawing/DrawableContainer.cs index 236842c8d..c23ce8eee 100644 --- a/Greenshot.ImageEditor/Drawing/DrawableContainer.cs +++ b/Greenshot.ImageEditor/Drawing/DrawableContainer.cs @@ -50,10 +50,8 @@ public abstract class DrawableContainer : AbstractFieldHolderWithChildren, IDraw protected static readonly Color DefaultLineColor = Color.FromArgb(0, 150, 255); - private bool isMadeUndoable; + private bool _isMadeUndoable; private const int M11 = 0; - private const int M12 = 1; - private const int M21 = 2; private const int M22 = 3; protected EditStatus _defaultEditMode = EditStatus.DRAWING; @@ -383,7 +381,7 @@ public void AlignToParent(HorizontalAlignment horizontalAlignment, VerticalAlign } if (horizontalAlignment == HorizontalAlignment.Center) { - Left = (_parent.Width / 2) - (Width / 2) - lineThickness / 2; + Left = _parent.Width / 2 - Width / 2 - lineThickness / 2; } if (verticalAlignment == VerticalAlignment.TOP) @@ -396,7 +394,7 @@ public void AlignToParent(HorizontalAlignment horizontalAlignment, VerticalAlign } if (verticalAlignment == VerticalAlignment.CENTER) { - Top = (_parent.Height / 2) - (Height / 2) - lineThickness / 2; + Top = _parent.Height / 2 - Height / 2 - lineThickness / 2; } } @@ -569,7 +567,7 @@ private void GripperMouseDown(object sender, MouseEventArgs e) { Status = EditStatus.MOVING; } - isMadeUndoable = false; + _isMadeUndoable = false; } private void GripperMouseUp(object sender, MouseEventArgs e) @@ -579,7 +577,7 @@ private void GripperMouseUp(object sender, MouseEventArgs e) { _boundsBeforeResize = Rectangle.Empty; _boundsAfterResize = RectangleF.Empty; - isMadeUndoable = false; + _isMadeUndoable = false; } Status = EditStatus.IDLE; Invalidate(); @@ -598,10 +596,10 @@ private void GripperMouseMove(object sender, MouseEventArgs e) else if (Status.Equals(EditStatus.RESIZING)) { // check if we already made this undoable - if (!isMadeUndoable) + if (!_isMadeUndoable) { // don't allow another undo until we are finished with this move - isMadeUndoable = true; + _isMadeUndoable = true; // Make undo-able MakeBoundsChangeUndoable(false); } @@ -871,6 +869,8 @@ public override bool Equals(object obj) public override int GetHashCode() { + // TODO: This actually doesn't make sense... + // Place the container in a list, and you can't find it :) return left.GetHashCode() ^ top.GetHashCode() ^ width.GetHashCode() ^ height.GetHashCode() ^ GetFields().GetHashCode(); } diff --git a/Greenshot.ImageEditor/Drawing/DrawableContainerList.cs b/Greenshot.ImageEditor/Drawing/DrawableContainerList.cs index 9c2b91da2..96727d200 100644 --- a/Greenshot.ImageEditor/Drawing/DrawableContainerList.cs +++ b/Greenshot.ImageEditor/Drawing/DrawableContainerList.cs @@ -383,7 +383,7 @@ public void PullElementsUp(DrawableContainerList elements) { continue; } - if (Count > (i + 1) && !elements.Contains(this[i + 1])) + if (Count > i + 1 && !elements.Contains(this[i + 1])) { SwapElements(i, i + 1); } @@ -554,7 +554,7 @@ public virtual void AddContextMenuItems(ContextMenuStrip menu, Surface surface) // Copy item = new ToolStripMenuItem("Copy"); - item.Image = ((Image)(editorFormResources.GetObject("copyToolStripMenuItem.Image"))); + item.Image = (Image)editorFormResources.GetObject("copyToolStripMenuItem.Image"); item.Click += delegate { ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), this); @@ -563,7 +563,7 @@ public virtual void AddContextMenuItems(ContextMenuStrip menu, Surface surface) // Cut item = new ToolStripMenuItem("Cut"); - item.Image = ((Image)(editorFormResources.GetObject("btnCut.Image"))); + item.Image = (Image)editorFormResources.GetObject("btnCut.Image"); item.Click += delegate { ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), this); @@ -582,7 +582,7 @@ public virtual void AddContextMenuItems(ContextMenuStrip menu, Surface surface) // Delete item = new ToolStripMenuItem("Delete"); - item.Image = ((Image)(editorFormResources.GetObject("removeObjectToolStripMenuItem.Image"))); + item.Image = (Image)editorFormResources.GetObject("removeObjectToolStripMenuItem.Image"); item.Click += delegate { List containersToDelete = new List(); diff --git a/Greenshot.ImageEditor/Drawing/EllipseContainer.cs b/Greenshot.ImageEditor/Drawing/EllipseContainer.cs index 906ef0c4e..44b1a8d98 100644 --- a/Greenshot.ImageEditor/Drawing/EllipseContainer.cs +++ b/Greenshot.ImageEditor/Drawing/EllipseContainer.cs @@ -65,11 +65,16 @@ public override void Draw(Graphics graphics, RenderMode renderMode) /// This allows another container to draw an ellipse /// /// + /// /// /// + /// + /// + /// + /// public static void DrawEllipse(Rectangle rect, Graphics graphics, RenderMode renderMode, int lineThickness, Color lineColor, Color fillColor, bool shadow) { - bool lineVisible = (lineThickness > 0 && Colors.IsVisible(lineColor)); + bool lineVisible = lineThickness > 0 && Colors.IsVisible(lineColor); // draw shadow before anything else if (shadow && (lineVisible || Colors.IsVisible(fillColor))) { diff --git a/Greenshot.ImageEditor/Drawing/Fields/AbstractFieldHolder.cs b/Greenshot.ImageEditor/Drawing/Fields/AbstractFieldHolder.cs index ee290df28..dc7ebfdcf 100644 --- a/Greenshot.ImageEditor/Drawing/Fields/AbstractFieldHolder.cs +++ b/Greenshot.ImageEditor/Drawing/Fields/AbstractFieldHolder.cs @@ -35,7 +35,7 @@ namespace Greenshot.Drawing.Fields [Serializable] public abstract class AbstractFieldHolder : IFieldHolder { - private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); + private static readonly EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); /// /// called when a field's value has changed @@ -52,11 +52,7 @@ public event FieldChangedEventHandler FieldChanged // this allows us to use default serialization [NonSerialized] private Dictionary fieldsByType = new Dictionary(); - private List fields = new List(); - - public AbstractFieldHolder() - { - } + private readonly List fields = new List(); [OnDeserialized] private void OnDeserialized(StreamingContext context) diff --git a/Greenshot.ImageEditor/Drawing/Fields/AbstractFieldHolderWithChildren.cs b/Greenshot.ImageEditor/Drawing/Fields/AbstractFieldHolderWithChildren.cs index f29921be8..f8364d4cb 100644 --- a/Greenshot.ImageEditor/Drawing/Fields/AbstractFieldHolderWithChildren.cs +++ b/Greenshot.ImageEditor/Drawing/Fields/AbstractFieldHolderWithChildren.cs @@ -33,7 +33,7 @@ namespace Greenshot.Drawing.Fields [Serializable()] public abstract class AbstractFieldHolderWithChildren : AbstractFieldHolder { - private FieldChangedEventHandler fieldChangedEventHandler; + private readonly FieldChangedEventHandler fieldChangedEventHandler; [NonSerialized] private EventHandler childrenChanged; diff --git a/Greenshot.ImageEditor/Drawing/Fields/Binding/AbstractBindingConverter.cs b/Greenshot.ImageEditor/Drawing/Fields/Binding/AbstractBindingConverter.cs index b7a843221..77a4ad207 100644 --- a/Greenshot.ImageEditor/Drawing/Fields/Binding/AbstractBindingConverter.cs +++ b/Greenshot.ImageEditor/Drawing/Fields/Binding/AbstractBindingConverter.cs @@ -28,10 +28,6 @@ namespace Greenshot.Drawing.Fields.Binding /// public abstract class AbstractBindingConverter : IBindingConverter { - public AbstractBindingConverter() - { - } - public object convert(object o) { if (o == null) diff --git a/Greenshot.ImageEditor/Drawing/Fields/Binding/BidirectionalBinding.cs b/Greenshot.ImageEditor/Drawing/Fields/Binding/BidirectionalBinding.cs index d50de7c29..f5fdcb492 100644 --- a/Greenshot.ImageEditor/Drawing/Fields/Binding/BidirectionalBinding.cs +++ b/Greenshot.ImageEditor/Drawing/Fields/Binding/BidirectionalBinding.cs @@ -32,14 +32,14 @@ namespace Greenshot.Drawing.Fields.Binding /// public class BidirectionalBinding { - private INotifyPropertyChanged controlObject; - private INotifyPropertyChanged fieldObject; - private string controlPropertyName; - private string fieldPropertyName; - private bool updatingControl = false; - private bool updatingField = false; - private IBindingConverter converter; - private IBindingValidator validator; + private readonly INotifyPropertyChanged _controlObject; + private readonly INotifyPropertyChanged _fieldObject; + private readonly string _controlPropertyName; + private readonly string _fieldPropertyName; + private bool _updatingControl = false; + private bool _updatingField = false; + private IBindingConverter _converter; + private readonly IBindingValidator _validator; /// /// Whether or not null values are passed on to the other object. @@ -49,19 +49,19 @@ public class BidirectionalBinding /// /// Bind properties of two objects bidirectionally /// - /// Object containing 1st property to bind - /// Property of 1st object to bind - /// Object containing 2nd property to bind - /// Property of 2nd object to bind + /// Object containing 1st property to bind + /// Property of 1st object to bind + /// Object containing 2nd property to bind + /// Property of 2nd object to bind public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName) { - this.controlObject = controlObject; - this.fieldObject = fieldObject; - this.controlPropertyName = controlPropertyName; - this.fieldPropertyName = fieldPropertyName; + _controlObject = controlObject; + _fieldObject = fieldObject; + _controlPropertyName = controlPropertyName; + _fieldPropertyName = fieldPropertyName; - this.controlObject.PropertyChanged += ControlPropertyChanged; - this.fieldObject.PropertyChanged += FieldPropertyChanged; + _controlObject.PropertyChanged += ControlPropertyChanged; + _fieldObject.PropertyChanged += FieldPropertyChanged; } /// @@ -74,7 +74,7 @@ public BidirectionalBinding(INotifyPropertyChanged controlObject, string control /// taking care of converting the synchronized value to the correct target format and back public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingConverter converter) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) { - this.converter = converter; + _converter = converter; } /// @@ -88,7 +88,7 @@ public BidirectionalBinding(INotifyPropertyChanged controlObject, string control /// validator to intercept synchronization if the value does not match certain criteria public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) { - this.validator = validator; + _validator = validator; } /// @@ -103,56 +103,56 @@ public BidirectionalBinding(INotifyPropertyChanged controlObject, string control /// validator to intercept synchronization if the value does not match certain criteria public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingConverter converter, IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName, converter) { - this.validator = validator; + _validator = validator; } public void ControlPropertyChanged(object sender, PropertyChangedEventArgs e) { - if (!updatingControl && e.PropertyName.Equals(controlPropertyName)) + if (!_updatingControl && e.PropertyName.Equals(_controlPropertyName)) { - updatingField = true; - synchronize(controlObject, controlPropertyName, fieldObject, fieldPropertyName); - updatingField = false; + _updatingField = true; + Synchronize(_controlObject, _controlPropertyName, _fieldObject, _fieldPropertyName); + _updatingField = false; } } public void FieldPropertyChanged(object sender, PropertyChangedEventArgs e) { - if (!updatingField && e.PropertyName.Equals(fieldPropertyName)) + if (!_updatingField && e.PropertyName.Equals(_fieldPropertyName)) { - updatingControl = true; - synchronize(fieldObject, fieldPropertyName, controlObject, controlPropertyName); - updatingControl = false; + _updatingControl = true; + Synchronize(_fieldObject, _fieldPropertyName, _controlObject, _controlPropertyName); + _updatingControl = false; } } - private void synchronize(INotifyPropertyChanged sourceObject, string sourceProperty, INotifyPropertyChanged targetObject, string targetProperty) + private void Synchronize(INotifyPropertyChanged sourceObject, string sourceProperty, INotifyPropertyChanged targetObject, string targetProperty) { - PropertyInfo targetPropertyInfo = resolvePropertyInfo(targetObject, targetProperty); - PropertyInfo sourcePropertyInfo = resolvePropertyInfo(sourceObject, sourceProperty); + PropertyInfo targetPropertyInfo = ResolvePropertyInfo(targetObject, targetProperty); + PropertyInfo sourcePropertyInfo = ResolvePropertyInfo(sourceObject, sourceProperty); if (sourcePropertyInfo != null && targetPropertyInfo != null && targetPropertyInfo.CanWrite) { object bValue = sourcePropertyInfo.GetValue(sourceObject, null); - if (converter != null && bValue != null) + if (_converter != null && bValue != null) { - bValue = converter.convert(bValue); + bValue = _converter.convert(bValue); } try { - if (validator == null || validator.validate(bValue)) + if (_validator == null || _validator.validate(bValue)) { targetPropertyInfo.SetValue(targetObject, bValue, null); } } catch (Exception e) { - throw new MemberAccessException("Could not set property '" + targetProperty + "' to '" + bValue + "' [" + ((bValue != null) ? bValue.GetType().Name : "") + "] on " + targetObject + ". Probably other type than expected, IBindingCoverter to the rescue.", e); + throw new MemberAccessException("Could not set property '" + targetProperty + "' to '" + bValue + "' [" + (bValue != null ? bValue.GetType().Name : "") + "] on " + targetObject + ". Probably other type than expected, IBindingCoverter to the rescue.", e); } } } - private PropertyInfo resolvePropertyInfo(object obj, string property) + private static PropertyInfo ResolvePropertyInfo(object obj, string property) { PropertyInfo ret = null; string[] properties = property.Split(".".ToCharArray()); @@ -170,8 +170,8 @@ private PropertyInfo resolvePropertyInfo(object obj, string property) public IBindingConverter Converter { - get { return converter; } - set { converter = value; } + get { return _converter; } + set { _converter = value; } } } } \ No newline at end of file diff --git a/Greenshot.ImageEditor/Drawing/Fields/FieldAggregator.cs b/Greenshot.ImageEditor/Drawing/Fields/FieldAggregator.cs index eaa1da956..197ded39c 100644 --- a/Greenshot.ImageEditor/Drawing/Fields/FieldAggregator.cs +++ b/Greenshot.ImageEditor/Drawing/Fields/FieldAggregator.cs @@ -40,13 +40,10 @@ namespace Greenshot.Drawing.Fields /// public class FieldAggregator : AbstractFieldHolder { - private List boundContainers; - private bool internalUpdateRunning = false; + private readonly List boundContainers; + private bool internalUpdateRunning; - private enum Status - { IDLE, BINDING, UPDATING }; - - private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); + private static readonly EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); public FieldAggregator() { diff --git a/Greenshot.ImageEditor/Drawing/FilterContainer.cs b/Greenshot.ImageEditor/Drawing/FilterContainer.cs index 6798ef6f6..7c84f7067 100644 --- a/Greenshot.ImageEditor/Drawing/FilterContainer.cs +++ b/Greenshot.ImageEditor/Drawing/FilterContainer.cs @@ -58,7 +58,7 @@ public override void Draw(Graphics graphics, RenderMode rm) int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS); Color lineColor = GetFieldValueAsColor(FieldType.LINE_COLOR); bool shadow = GetFieldValueAsBool(FieldType.SHADOW); - bool lineVisible = (lineThickness > 0 && Colors.IsVisible(lineColor)); + bool lineVisible = lineThickness > 0 && Colors.IsVisible(lineColor); if (lineVisible) { graphics.SmoothingMode = SmoothingMode.HighSpeed; @@ -79,7 +79,7 @@ public override void Draw(Graphics graphics, RenderMode rm) Rectangle shadowRect = GuiRectangle.GetGuiRectangle(Left + currentStep, Top + currentStep, Width, Height); graphics.DrawRectangle(shadowPen, shadowRect); currentStep++; - alpha = alpha - (basealpha / steps); + alpha = alpha - basealpha / steps; } } } diff --git a/Greenshot.ImageEditor/Drawing/Filters/AbstractFilter.cs b/Greenshot.ImageEditor/Drawing/Filters/AbstractFilter.cs index 060b439cc..a336a08ac 100644 --- a/Greenshot.ImageEditor/Drawing/Filters/AbstractFilter.cs +++ b/Greenshot.ImageEditor/Drawing/Filters/AbstractFilter.cs @@ -43,7 +43,7 @@ public event PropertyChangedEventHandler PropertyChanged remove { propertyChanged -= value; } } - private bool invert = false; + private bool invert; public bool Invert { get diff --git a/Greenshot.ImageEditor/Drawing/Filters/BlurFilter.cs b/Greenshot.ImageEditor/Drawing/Filters/BlurFilter.cs index dd86cd437..00b4bb279 100644 --- a/Greenshot.ImageEditor/Drawing/Filters/BlurFilter.cs +++ b/Greenshot.ImageEditor/Drawing/Filters/BlurFilter.cs @@ -45,7 +45,7 @@ public BlurFilter(DrawableContainer parent) : base(parent) AddField(GetType(), FieldType.PREVIEW_QUALITY, 1.0d); } - public unsafe override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode) + public override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode) { int blurRadius = GetFieldValueAsInt(FieldType.BLUR_RADIUS); Rectangle applyRect = ImageHelper.CreateIntersectRectangle(applyBitmap.Size, rect, Invert); @@ -59,7 +59,7 @@ public unsafe override void Apply(Graphics graphics, Bitmap applyBitmap, Rectang graphics.SetClip(applyRect); graphics.ExcludeClip(rect); } - if (GDIplus.isBlurPossible(blurRadius)) + if (GDIplus.IsBlurPossible(blurRadius)) { GDIplus.DrawWithBlur(graphics, applyBitmap, applyRect, null, null, blurRadius, false); } @@ -72,7 +72,6 @@ public unsafe override void Apply(Graphics graphics, Bitmap applyBitmap, Rectang } } graphics.Restore(state); - return; } } } \ No newline at end of file diff --git a/Greenshot.ImageEditor/Drawing/Filters/MagnifierFilter.cs b/Greenshot.ImageEditor/Drawing/Filters/MagnifierFilter.cs index 6a1b7d506..e60b7cb6d 100644 --- a/Greenshot.ImageEditor/Drawing/Filters/MagnifierFilter.cs +++ b/Greenshot.ImageEditor/Drawing/Filters/MagnifierFilter.cs @@ -60,7 +60,7 @@ public override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect int halfHeight = rect.Height / 2; int newWidth = rect.Width / magnificationFactor; int newHeight = rect.Height / magnificationFactor; - Rectangle source = new Rectangle(rect.X + halfWidth - (newWidth / 2), rect.Y + halfHeight - (newHeight / 2), newWidth, newHeight); + Rectangle source = new Rectangle(rect.X + halfWidth - newWidth / 2, rect.Y + halfHeight - newHeight / 2, newWidth, newHeight); graphics.DrawImage(applyBitmap, rect, source, GraphicsUnit.Pixel); graphics.Restore(state); } diff --git a/Greenshot.ImageEditor/Drawing/Filters/PixelizationFilter.cs b/Greenshot.ImageEditor/Drawing/Filters/PixelizationFilter.cs index 4860200a2..7f29f3ea8 100644 --- a/Greenshot.ImageEditor/Drawing/Filters/PixelizationFilter.cs +++ b/Greenshot.ImageEditor/Drawing/Filters/PixelizationFilter.cs @@ -40,7 +40,7 @@ public PixelizationFilter(DrawableContainer parent) : base(parent) public override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode) { int pixelSize = GetFieldValueAsInt(FieldType.PIXEL_SIZE); - Rectangle applyRect = ImageHelper.CreateIntersectRectangle(applyBitmap.Size, rect, Invert); + ImageHelper.CreateIntersectRectangle(applyBitmap.Size, rect, Invert); if (pixelSize <= 1 || rect.Width == 0 || rect.Height == 0) { // Nothing to do diff --git a/Greenshot.ImageEditor/Drawing/FreehandContainer.cs b/Greenshot.ImageEditor/Drawing/FreehandContainer.cs index c57610435..08452680b 100644 --- a/Greenshot.ImageEditor/Drawing/FreehandContainer.cs +++ b/Greenshot.ImageEditor/Drawing/FreehandContainer.cs @@ -42,8 +42,8 @@ public class FreehandContainer : DrawableContainer private GraphicsPath freehandPath = new GraphicsPath(); private Rectangle myBounds = Rectangle.Empty; private Point lastMouse = Point.Empty; - private List capturePoints = new List(); - private bool isRecalculated = false; + private readonly List capturePoints = new List(); + private bool isRecalculated; /// /// Constructor @@ -130,7 +130,7 @@ public override bool HandleMouseMove(int mouseX, int mouseY) { Point previousPoint = capturePoints[capturePoints.Count - 1]; - if (GeometryHelper.Distance2D(previousPoint.X, previousPoint.Y, mouseX, mouseY) >= (2 * EditorConfig.FreehandSensitivity)) + if (GeometryHelper.Distance2D(previousPoint.X, previousPoint.Y, mouseX, mouseY) >= 2 * EditorConfig.FreehandSensitivity) { capturePoints.Add(new Point(mouseX, mouseY)); } @@ -263,7 +263,7 @@ public override Rectangle DrawingBounds { int lineThickness = Math.Max(10, GetFieldValueAsInt(FieldType.LINE_THICKNESS)); int safetymargin = 10; - return new Rectangle((myBounds.Left + Left) - (safetymargin + lineThickness), (myBounds.Top + Top) - (safetymargin + lineThickness), myBounds.Width + (2 * (lineThickness + safetymargin)), myBounds.Height + (2 * (lineThickness + safetymargin))); + return new Rectangle(myBounds.Left + Left - (safetymargin + lineThickness), myBounds.Top + Top - (safetymargin + lineThickness), myBounds.Width + 2 * (lineThickness + safetymargin), myBounds.Height + 2 * (lineThickness + safetymargin)); } return new Rectangle(0, 0, _parent.Width, _parent.Height); } diff --git a/Greenshot.ImageEditor/Drawing/LineContainer.cs b/Greenshot.ImageEditor/Drawing/LineContainer.cs index 6d49e4f06..6114697e5 100644 --- a/Greenshot.ImageEditor/Drawing/LineContainer.cs +++ b/Greenshot.ImageEditor/Drawing/LineContainer.cs @@ -99,7 +99,7 @@ public override void Draw(Graphics graphics, RenderMode rm) Top + currentStep + Height); currentStep++; - alpha = alpha - (basealpha / steps); + alpha = alpha - basealpha / steps; } } } diff --git a/Greenshot.ImageEditor/Drawing/RectangleContainer.cs b/Greenshot.ImageEditor/Drawing/RectangleContainer.cs index 8b6843c2d..3dbdd5812 100644 --- a/Greenshot.ImageEditor/Drawing/RectangleContainer.cs +++ b/Greenshot.ImageEditor/Drawing/RectangleContainer.cs @@ -74,7 +74,7 @@ public static void DrawRectangle(Rectangle rect, Graphics graphics, RenderMode r graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.None; - bool lineVisible = (lineThickness > 0 && Colors.IsVisible(lineColor)); + bool lineVisible = lineThickness > 0 && Colors.IsVisible(lineColor); if (shadow && (lineVisible || Colors.IsVisible(fillColor))) { //draw shadow first @@ -94,7 +94,7 @@ public static void DrawRectangle(Rectangle rect, Graphics graphics, RenderMode r rect.Height); graphics.DrawRectangle(shadowPen, shadowRect); currentStep++; - alpha = alpha - (basealpha / steps); + alpha = alpha - basealpha / steps; } } } diff --git a/Greenshot.ImageEditor/Drawing/SpeechbubbleContainer.cs b/Greenshot.ImageEditor/Drawing/SpeechbubbleContainer.cs index 66431931e..369d5c388 100644 --- a/Greenshot.ImageEditor/Drawing/SpeechbubbleContainer.cs +++ b/Greenshot.ImageEditor/Drawing/SpeechbubbleContainer.cs @@ -200,7 +200,7 @@ private GraphicsPath CreateTail() { Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); - int tailLength = GeometryHelper.Distance2D(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2), TargetGripper.Left, TargetGripper.Top); + int tailLength = GeometryHelper.Distance2D(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2, TargetGripper.Left, TargetGripper.Top); int tailWidth = (Math.Abs(rect.Width) + Math.Abs(rect.Height)) / 20; // This should fix a problem with the tail being to wide @@ -212,11 +212,11 @@ private GraphicsPath CreateTail() tail.AddLine(tailWidth, 0, 0, -tailLength); tail.CloseFigure(); - int tailAngle = 90 + (int)GeometryHelper.Angle2D(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2), TargetGripper.Left, TargetGripper.Top); + int tailAngle = 90 + (int)GeometryHelper.Angle2D(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2, TargetGripper.Left, TargetGripper.Top); using (Matrix tailMatrix = new Matrix()) { - tailMatrix.Translate(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2)); + tailMatrix.Translate(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2); tailMatrix.Rotate(tailAngle); tail.Transform(tailMatrix); } @@ -246,7 +246,7 @@ public override void Draw(Graphics graphics, RenderMode renderMode) bool shadow = GetFieldValueAsBool(FieldType.SHADOW); int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS); - bool lineVisible = (lineThickness > 0 && Colors.IsVisible(lineColor)); + bool lineVisible = lineThickness > 0 && Colors.IsVisible(lineColor); Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); if (Selected && renderMode == RenderMode.EDIT) @@ -281,7 +281,7 @@ public override void Draw(Graphics graphics, RenderMode renderMode) graphics.DrawPath(shadowPen, bubbleClone); } currentStep++; - alpha = alpha - (basealpha / steps); + alpha = alpha - basealpha / steps; } } } diff --git a/Greenshot.ImageEditor/Drawing/StepLabelContainer.cs b/Greenshot.ImageEditor/Drawing/StepLabelContainer.cs index 8160401a7..1c1c41766 100644 --- a/Greenshot.ImageEditor/Drawing/StepLabelContainer.cs +++ b/Greenshot.ImageEditor/Drawing/StepLabelContainer.cs @@ -136,7 +136,7 @@ public override bool InitContent() /// public override bool HandleMouseDown(int mouseX, int mouseY) { - return base.HandleMouseDown(mouseX - (Width / 2), mouseY - (Height / 2)); + return base.HandleMouseDown(mouseX - Width / 2, mouseY - Height / 2); } /// @@ -169,8 +169,8 @@ protected override void Dispose(bool disposing) public override bool HandleMouseMove(int x, int y) { Invalidate(); - Left = x - (Width / 2); - Top = y - (Height / 2); + Left = x - Width / 2; + Top = y - Height / 2; Invalidate(); return true; } @@ -191,7 +191,7 @@ public override void Transform(Matrix matrix) int widthAfter = rect.Width; int heightAfter = rect.Height; - float factor = (((float)widthAfter / widthBefore) + ((float)heightAfter / heightBefore)) / 2; + float factor = ((float)widthAfter / widthBefore + (float)heightAfter / heightBefore) / 2; fontSize *= factor; } diff --git a/Greenshot.ImageEditor/Drawing/Surface.cs b/Greenshot.ImageEditor/Drawing/Surface.cs index 178a83045..fe56164f4 100644 --- a/Greenshot.ImageEditor/Drawing/Surface.cs +++ b/Greenshot.ImageEditor/Drawing/Surface.cs @@ -46,8 +46,8 @@ namespace Greenshot.Drawing /// public class Surface : Control, ISurface { - public static int Count = 0; - private static CoreConfiguration conf = IniConfig.GetIniSection(); + public static int Count; + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); // Property to identify the Surface ID private Guid _uniqueId = Guid.NewGuid(); @@ -183,7 +183,7 @@ public event SurfaceMessageEventHandler SurfaceMessage /// all selected elements, do not serialize /// [NonSerialized] - private DrawableContainerList selectedElements; + private readonly DrawableContainerList selectedElements; /// /// the element we are drawing with, do not serialize @@ -222,7 +222,7 @@ public event SurfaceMessageEventHandler SurfaceMessage /// /// all stepLabels for the surface, needed with serialization /// - private List _stepLabels = new List(); + private readonly List _stepLabels = new List(); public void AddStepLabel(StepLabelContainer stepLabel) { @@ -244,7 +244,7 @@ public int CountStepLabels(IDrawableContainer stopAtContainer) int number = 1; foreach (var possibleThis in _stepLabels) { - if (possibleThis == stopAtContainer) + if (possibleThis.Equals(stopAtContainer)) { break; } @@ -1180,7 +1180,10 @@ private void SurfaceMouseDown(object sender, MouseEventArgs e) // if a new element has been drawn, set location and register it if (_drawingElement != null) { - _drawingElement.Status = _undrawnElement.DefaultEditMode; + if (_undrawnElement != null) + { + _drawingElement.Status = _undrawnElement.DefaultEditMode; + } _drawingElement.PropertyChanged += ElementPropertyChanged; if (!_drawingElement.HandleMouseDown(_mouseStart.X, _mouseStart.Y)) { @@ -1540,7 +1543,7 @@ public bool HasSelectedElements { get { - return (selectedElements != null && selectedElements.Count > 0); + return selectedElements != null && selectedElements.Count > 0; } } @@ -1606,6 +1609,10 @@ public void ConfirmSelectedConfirmableElements(bool confirm) { // create new collection so that we can iterate safely (selectedElements might change due with confirm/cancel) List selectedDCs = new List(selectedElements); + if (_cropContainer == null) + { + return; + } foreach (IDrawableContainer dc in selectedDCs) { if (dc.Equals(_cropContainer)) @@ -1619,6 +1626,7 @@ public void ConfirmSelectedConfirmableElements(bool confirm) } _cropContainer.Dispose(); _cropContainer = null; + break; } } } @@ -1652,7 +1660,7 @@ public void PasteElementFromClipboard() { // Make element(s) only move 10,10 if the surface is the same Point moveOffset; - bool isSameSurface = (dcs.ParentID == _uniqueId); + bool isSameSurface = dcs.ParentID == _uniqueId; dcs.Parent = this; if (isSameSurface) { diff --git a/Greenshot.ImageEditor/Drawing/TextContainer.cs b/Greenshot.ImageEditor/Drawing/TextContainer.cs index 6f7398636..2544d0a35 100644 --- a/Greenshot.ImageEditor/Drawing/TextContainer.cs +++ b/Greenshot.ImageEditor/Drawing/TextContainer.cs @@ -77,7 +77,7 @@ public string Text internal void ChangeText(string newText, bool allowUndoable) { - if ((text == null && newText != null) || (text != null && !text.Equals(newText))) + if ((text == null && newText != null) || (text != null && !string.Equals(text, newText))) { if (makeUndoable && allowUndoable) { @@ -139,8 +139,10 @@ protected override void Dispose(bool disposing) private void Init() { - _stringFormat = new StringFormat(); - _stringFormat.Trimming = StringTrimming.EllipsisWord; + _stringFormat = new StringFormat + { + Trimming = StringTrimming.EllipsisWord + }; CreateTextBox(); @@ -208,8 +210,11 @@ private void TextContainer_FieldChanged(object sender, FieldChangedEventArgs e) // Only dispose the font, and re-create it, when a font field has changed. if (e.Field.FieldType.Name.StartsWith("FONT")) { - _font.Dispose(); - _font = null; + if (_font != null) + { + _font.Dispose(); + _font = null; + } UpdateFormat(); } else @@ -218,7 +223,7 @@ private void TextContainer_FieldChanged(object sender, FieldChangedEventArgs e) } UpdateTextBoxFormat(); - if (_textBox.Visible) + if (_textBox != null && _textBox.Visible) { _textBox.Invalidate(); } @@ -231,17 +236,19 @@ public override void OnDoubleClick() private void CreateTextBox() { - _textBox = new TextBox(); + _textBox = new TextBox + { + ImeMode = ImeMode.On, + Multiline = true, + AcceptsTab = true, + AcceptsReturn = true, + BorderStyle = BorderStyle.None, + Visible = false + }; - _textBox.ImeMode = ImeMode.On; - _textBox.Multiline = true; - _textBox.AcceptsTab = true; - _textBox.AcceptsReturn = true; _textBox.DataBindings.Add("Text", this, "Text", false, DataSourceUpdateMode.OnPropertyChanged); _textBox.LostFocus += textBox_LostFocus; _textBox.KeyDown += textBox_KeyDown; - _textBox.BorderStyle = BorderStyle.None; - _textBox.Visible = false; } private void ShowTextBox() @@ -348,6 +355,7 @@ protected void UpdateFormat() } } } + _font?.Dispose(); _font = new Font(fam, fontSize, fs, GraphicsUnit.Pixel); _textBox.Font = _font; } @@ -392,8 +400,8 @@ private void UpdateTextBoxPosition() { lineWidth = 0; } - _textBox.Width = absRectangle.Width - (2 * lineWidth) + correction; - _textBox.Height = absRectangle.Height - (2 * lineWidth) + correction; + _textBox.Width = absRectangle.Width - 2 * lineWidth + correction; + _textBox.Height = absRectangle.Height - 2 * lineWidth + correction; } public override void ApplyBounds(RectangleF newBounds) @@ -459,7 +467,7 @@ public override void Draw(Graphics graphics, RenderMode rm) DrawSelectionBorder(graphics, rect); } - if (text == null || text.Length == 0) + if (string.IsNullOrEmpty(text)) { return; } @@ -481,12 +489,13 @@ public override void Draw(Graphics graphics, RenderMode rm) /// /// /// + /// /// /// /// public static void DrawText(Graphics graphics, Rectangle drawingRectange, int lineThickness, Color fontColor, bool drawShadow, StringFormat stringFormat, string text, Font font) { - int textOffset = (lineThickness > 0) ? (int)Math.Ceiling(lineThickness / 2d) : 0; + int textOffset = lineThickness > 0 ? (int)Math.Ceiling(lineThickness / 2d) : 0; // draw shadow before anything else if (drawShadow) { diff --git a/Greenshot.ImageEditor/Forms/ColorDialog.cs b/Greenshot.ImageEditor/Forms/ColorDialog.cs index f557acae7..f0ca56dcc 100644 --- a/Greenshot.ImageEditor/Forms/ColorDialog.cs +++ b/Greenshot.ImageEditor/Forms/ColorDialog.cs @@ -37,7 +37,7 @@ namespace Greenshot public partial class ColorDialog : BaseForm { private static ColorDialog uniqueInstance; - private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); + private static readonly EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); private ColorDialog() { @@ -62,7 +62,7 @@ public static ColorDialog GetInstance() private readonly List /// /// - private void propertiesToolStrip_Paint(object sender, PaintEventArgs e) + private void PropertiesToolStrip_Paint(object sender, PaintEventArgs e) { using (Pen cbBorderPen = new Pen(SystemColors.ActiveBorder)) { @@ -244,10 +247,13 @@ private void propertiesToolStrip_Paint(object sender, PaintEventArgs e) continue; } // Calculate the rectangle - Rectangle r = new Rectangle(cb.ComboBox.Location.X - 1, cb.ComboBox.Location.Y - 1, cb.ComboBox.Size.Width + 1, cb.ComboBox.Size.Height + 1); + if (cb.ComboBox != null) + { + Rectangle r = new Rectangle(cb.ComboBox.Location.X - 1, cb.ComboBox.Location.Y - 1, cb.ComboBox.Size.Width + 1, cb.ComboBox.Size.Height + 1); - // Draw the rectangle - e.Graphics.DrawRectangle(cbBorderPen, r); + // Draw the rectangle + e.Graphics.DrawRectangle(cbBorderPen, r); + } } } } @@ -282,7 +288,7 @@ private void SurfaceMessageReceived(object sender, SurfaceMessageEventArgs event { if (InvokeRequired) { - this.Invoke(new SurfaceMessageReceivedThreadSafeDelegate(SurfaceMessageReceived), new object[] { sender, eventArgs }); + Invoke(new SurfaceMessageReceivedThreadSafeDelegate(SurfaceMessageReceived), new object[] { sender, eventArgs }); } else { @@ -310,10 +316,11 @@ private void SurfaceMessageReceived(object sender, SurfaceMessageEventArgs event /// /// This is called when the size of the surface chances, used for resizing and displaying the size information /// - /// + /// + /// private void SurfaceSizeChanged(object sender, EventArgs e) { - if (editorConfiguration.MatchSizeToCapture) + if (EditorConfiguration.MatchSizeToCapture) { // Set editor's initial size to the size of the surface plus the size of the chrome Size imageSize = Surface.Image.Size; @@ -321,8 +328,8 @@ private void SurfaceSizeChanged(object sender, EventArgs e) Size currentImageClientSize = panel1.ClientSize; int minimumFormWidth = 650; int minimumFormHeight = 530; - int newWidth = Math.Max(minimumFormWidth, (currentFormSize.Width - currentImageClientSize.Width) + imageSize.Width); - int newHeight = Math.Max(minimumFormHeight, (currentFormSize.Height - currentImageClientSize.Height) + imageSize.Height); + int newWidth = Math.Max(minimumFormWidth, currentFormSize.Width - currentImageClientSize.Width + imageSize.Width); + int newHeight = Math.Max(minimumFormHeight, currentFormSize.Height - currentImageClientSize.Height + imageSize.Height); Size = new Size(newWidth, newHeight); } UpdateTitle(); @@ -334,9 +341,9 @@ private void ReloadConfiguration(object source, FileSystemEventArgs e) Invoke((MethodInvoker)delegate { // Fix title - if (surface != null && surface.CaptureDetails != null && surface.CaptureDetails.Title != null) + if (_surface != null && _surface.CaptureDetails != null && _surface.CaptureDetails.Title != null) { - SetTitle(surface.CaptureDetails.Title); + SetTitle(_surface.CaptureDetails.Title); } }); } @@ -362,7 +369,7 @@ public ISurface Surface { get { - return surface; + return _surface; } set { @@ -377,7 +384,7 @@ public void SetImagePath(string fullpath) { fullpath = null; } - surface.LastSaveFullPath = fullpath; + _surface.LastSaveFullPath = fullpath; if (fullpath == null) { @@ -386,7 +393,7 @@ public void SetImagePath(string fullpath) //updateStatusLabel(string.Format("Image saved to {0}.", fullpath), fileSavedStatusContextMenu); SetTitle(Path.GetFileName(fullpath)); - tsbSaveImage.Enabled = tsmiSaveImage.Enabled = File.Exists(surface.LastSaveFullPath); + tsbSaveImage.Enabled = tsmiSaveImage.Enabled = File.Exists(_surface.LastSaveFullPath); } private void surface_DrawingModeChanged(object source, SurfaceDrawingModeEventArgs eventArgs) @@ -440,12 +447,12 @@ private void surface_DrawingModeChanged(object source, SurfaceDrawingModeEventAr public Image GetImageForExport() { - return surface.GetImageForExport(); + return _surface.GetImageForExport(); } public ICaptureDetails CaptureDetails { - get { return surface.CaptureDetails; } + get { return _surface.CaptureDetails; } } public ToolStripMenuItem GetPluginMenuItem() @@ -464,74 +471,74 @@ public ToolStripMenuItem GetFileMenuItem() private void BtnEllipseClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Ellipse; - refreshFieldControls(); + _surface.DrawingMode = DrawingModes.Ellipse; + RefreshFieldControls(); } private void BtnCursorClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.None; - refreshFieldControls(); + _surface.DrawingMode = DrawingModes.None; + RefreshFieldControls(); } private void BtnRectClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Rect; - refreshFieldControls(); + _surface.DrawingMode = DrawingModes.Rect; + RefreshFieldControls(); } private void BtnTextClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Text; - refreshFieldControls(); + _surface.DrawingMode = DrawingModes.Text; + RefreshFieldControls(); } private void BtnSpeechBubbleClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.SpeechBubble; - refreshFieldControls(); + _surface.DrawingMode = DrawingModes.SpeechBubble; + RefreshFieldControls(); } private void BtnStepLabelClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.StepLabel; - refreshFieldControls(); + _surface.DrawingMode = DrawingModes.StepLabel; + RefreshFieldControls(); } private void BtnLineClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Line; - refreshFieldControls(); + _surface.DrawingMode = DrawingModes.Line; + RefreshFieldControls(); } private void BtnArrowClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Arrow; - refreshFieldControls(); + _surface.DrawingMode = DrawingModes.Arrow; + RefreshFieldControls(); } private void BtnCropClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Crop; - refreshFieldControls(); + _surface.DrawingMode = DrawingModes.Crop; + RefreshFieldControls(); } private void BtnHighlightClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Highlight; - refreshFieldControls(); + _surface.DrawingMode = DrawingModes.Highlight; + RefreshFieldControls(); } private void BtnObfuscateClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Obfuscate; - refreshFieldControls(); + _surface.DrawingMode = DrawingModes.Obfuscate; + RefreshFieldControls(); } private void BtnFreehandClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Path; - refreshFieldControls(); + _surface.DrawingMode = DrawingModes.Path; + RefreshFieldControls(); } private void SetButtonChecked(ToolStripButton btn) @@ -542,9 +549,9 @@ private void SetButtonChecked(ToolStripButton btn) private void UncheckAllToolButtons() { - if (toolbarButtons != null) + if (_toolbarButtons != null) { - foreach (ToolStripButton butt in toolbarButtons) + foreach (GreenshotToolStripButton butt in _toolbarButtons) { butt.Checked = false; } @@ -553,13 +560,13 @@ private void UncheckAllToolButtons() private void RemoveObjectToolStripMenuItemClick(object sender, EventArgs e) { - surface.RemoveSelectedElements(); + _surface.RemoveSelectedElements(); } private void clearToolStripMenuItem_Click(object sender, EventArgs e) { - surface.SelectAllElements(); - surface.RemoveSelectedElements(); + _surface.SelectAllElements(); + _surface.RemoveSelectedElements(); } #endregion drawing options @@ -568,38 +575,38 @@ private void clearToolStripMenuItem_Click(object sender, EventArgs e) private void CutToolStripMenuItemClick(object sender, EventArgs e) { - surface.CutSelectedElements(); - updateClipboardSurfaceDependencies(); + _surface.CutSelectedElements(); + UpdateClipboardSurfaceDependencies(); } private void CopyToolStripMenuItemClick(object sender, EventArgs e) { - surface.CopySelectedElements(); - updateClipboardSurfaceDependencies(); + _surface.CopySelectedElements(); + UpdateClipboardSurfaceDependencies(); } private void PasteToolStripMenuItemClick(object sender, EventArgs e) { - surface.PasteElementFromClipboard(); - updateClipboardSurfaceDependencies(); + _surface.PasteElementFromClipboard(); + UpdateClipboardSurfaceDependencies(); } private void UndoToolStripMenuItemClick(object sender, EventArgs e) { - surface.Undo(); - updateUndoRedoSurfaceDependencies(); + _surface.Undo(); + UpdateUndoRedoSurfaceDependencies(); } private void RedoToolStripMenuItemClick(object sender, EventArgs e) { - surface.Redo(); - updateUndoRedoSurfaceDependencies(); + _surface.Redo(); + UpdateUndoRedoSurfaceDependencies(); } private void DuplicateToolStripMenuItemClick(object sender, EventArgs e) { - surface.DuplicateSelectedElements(); - updateClipboardSurfaceDependencies(); + _surface.DuplicateSelectedElements(); + UpdateClipboardSurfaceDependencies(); } #endregion copy&paste options @@ -608,22 +615,22 @@ private void DuplicateToolStripMenuItemClick(object sender, EventArgs e) private void UpOneLevelToolStripMenuItemClick(object sender, EventArgs e) { - surface.PullElementsUp(); + _surface.PullElementsUp(); } private void DownOneLevelToolStripMenuItemClick(object sender, EventArgs e) { - surface.PushElementsDown(); + _surface.PushElementsDown(); } private void UpToTopToolStripMenuItemClick(object sender, EventArgs e) { - surface.PullElementsToTop(); + _surface.PullElementsToTop(); } private void DownToBottomToolStripMenuItemClick(object sender, EventArgs e) { - surface.PushElementsToBottom(); + _surface.PushElementsToBottom(); } #endregion element properties @@ -632,17 +639,17 @@ private void DownToBottomToolStripMenuItemClick(object sender, EventArgs e) private void ImageEditorFormActivated(object sender, EventArgs e) { - updateClipboardSurfaceDependencies(); - updateUndoRedoSurfaceDependencies(); + UpdateClipboardSurfaceDependencies(); + UpdateUndoRedoSurfaceDependencies(); - tsbSaveImage.Enabled = tsmiSaveImage.Enabled = surface != null ? File.Exists(surface.LastSaveFullPath) : false; + tsbSaveImage.Enabled = tsmiSaveImage.Enabled = _surface != null ? File.Exists(_surface.LastSaveFullPath) : false; } private void ImageEditorFormFormClosing(object sender, FormClosingEventArgs e) { - if (!forceClose && surface.Modified) + if (!forceClose && _surface.Modified) { - if (!editorConfiguration.SuppressSaveDialogAtClose) + if (!EditorConfiguration.SuppressSaveDialogAtClose) { // Make sure the editor is visible WindowDetails.ToForeground(Handle); @@ -675,11 +682,11 @@ private void ImageEditorFormFormClosing(object sender, FormClosingEventArgs e) } // persist our geometry string. - editorConfiguration.SetEditorPlacement(new WindowDetails(Handle).WindowPlacement); + EditorConfiguration.SetEditorPlacement(new WindowDetails(Handle).WindowPlacement); IniConfig.Save(); // remove from the editor list - editorList.Remove(this); + EditorList.Remove(this); } private void ImageEditorFormKeyDown(object sender, KeyEventArgs e) @@ -687,7 +694,7 @@ private void ImageEditorFormKeyDown(object sender, KeyEventArgs e) // LOG.Debug("Got key event "+e.KeyCode + ", " + e.Modifiers); // avoid conflict with other shortcuts and // make sure there's no selected element claiming input focus - if (e.Modifiers.Equals(Keys.None) && !surface.KeysLocked) + if (e.Modifiers.Equals(Keys.None) && !_surface.KeysLocked) { switch (e.KeyCode) { @@ -808,7 +815,7 @@ private void PanelMouseWheel(object sender, MouseEventArgs e) protected override bool ProcessKeyPreview(ref Message msg) { // disable default key handling if surface has requested a lock - if (!surface.KeysLocked) + if (!_surface.KeysLocked) { return base.ProcessKeyPreview(ref msg); } @@ -818,9 +825,9 @@ protected override bool ProcessKeyPreview(ref Message msg) protected override bool ProcessCmdKey(ref Message msg, Keys keys) { // disable default key handling if surface has requested a lock - if (!surface.KeysLocked) + if (!_surface.KeysLocked) { - if (!surface.ProcessCmdKey(keys)) + if (!_surface.ProcessCmdKey(keys)) { return base.ProcessCmdKey(ref msg, keys); } @@ -832,20 +839,20 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keys) #region helpers - private void updateUndoRedoSurfaceDependencies() + private void UpdateUndoRedoSurfaceDependencies() { - if (surface == null) + if (_surface == null) { return; } - bool canUndo = surface.CanUndo; + bool canUndo = _surface.CanUndo; btnUndo.Enabled = canUndo; undoToolStripMenuItem.Enabled = canUndo; string undoText = "Undo"; btnUndo.Text = undoText; undoToolStripMenuItem.Text = undoText; - bool canRedo = surface.CanRedo; + bool canRedo = _surface.CanRedo; btnRedo.Enabled = canRedo; redoToolStripMenuItem.Enabled = canRedo; string redoText = "Redo"; @@ -853,15 +860,15 @@ private void updateUndoRedoSurfaceDependencies() redoToolStripMenuItem.Text = redoText; } - private void updateClipboardSurfaceDependencies() + private void UpdateClipboardSurfaceDependencies() { - if (surface == null) + if (_surface == null) { return; } // check dependencies for the Surface - bool hasItems = surface.HasSelectedElements; - bool actionAllowedForSelection = hasItems && !controlsDisabledDueToConfirmable; + bool hasItems = _surface.HasSelectedElements; + bool actionAllowedForSelection = hasItems && !_controlsDisabledDueToConfirmable; // buttons btnCut.Enabled = actionAllowedForSelection; @@ -875,9 +882,9 @@ private void updateClipboardSurfaceDependencies() duplicateToolStripMenuItem.Enabled = actionAllowedForSelection; // check dependencies for the Clipboard - bool hasClipboard = ClipboardHelper.ContainsFormat(SUPPORTED_CLIPBOARD_FORMATS) || ClipboardHelper.ContainsImage(); - btnPaste.Enabled = hasClipboard && !controlsDisabledDueToConfirmable; - pasteToolStripMenuItem.Enabled = hasClipboard && !controlsDisabledDueToConfirmable; + bool hasClipboard = ClipboardHelper.ContainsFormat(SupportedClipboardFormats) || ClipboardHelper.ContainsImage(); + btnPaste.Enabled = hasClipboard && !_controlsDisabledDueToConfirmable; + pasteToolStripMenuItem.Enabled = hasClipboard && !_controlsDisabledDueToConfirmable; } #endregion helpers @@ -895,7 +902,7 @@ private void updateStatusLabel(string text) updateStatusLabel(text, null); } - private void clearStatusLabel() + private void ClearStatusLabel() { updateStatusLabel(null, null); } @@ -911,38 +918,38 @@ private void StatusLabelClicked(object sender, MouseEventArgs e) #endregion status label handling - private void bindFieldControls() + private void BindFieldControls() { - new BidirectionalBinding(btnFillColor, "SelectedColor", surface.FieldAggregator.GetField(FieldType.FILL_COLOR), "Value", NotNullValidator.GetInstance()); - new BidirectionalBinding(btnLineColor, "SelectedColor", surface.FieldAggregator.GetField(FieldType.LINE_COLOR), "Value", NotNullValidator.GetInstance()); - new BidirectionalBinding(lineThicknessUpDown, "Value", surface.FieldAggregator.GetField(FieldType.LINE_THICKNESS), "Value", DecimalIntConverter.GetInstance(), NotNullValidator.GetInstance()); - new BidirectionalBinding(blurRadiusUpDown, "Value", surface.FieldAggregator.GetField(FieldType.BLUR_RADIUS), "Value", DecimalIntConverter.GetInstance(), NotNullValidator.GetInstance()); - new BidirectionalBinding(magnificationFactorUpDown, "Value", surface.FieldAggregator.GetField(FieldType.MAGNIFICATION_FACTOR), "Value", DecimalIntConverter.GetInstance(), NotNullValidator.GetInstance()); - new BidirectionalBinding(pixelSizeUpDown, "Value", surface.FieldAggregator.GetField(FieldType.PIXEL_SIZE), "Value", DecimalIntConverter.GetInstance(), NotNullValidator.GetInstance()); - new BidirectionalBinding(brightnessUpDown, "Value", surface.FieldAggregator.GetField(FieldType.BRIGHTNESS), "Value", DecimalDoublePercentageConverter.GetInstance(), NotNullValidator.GetInstance()); - new BidirectionalBinding(fontFamilyComboBox, "Text", surface.FieldAggregator.GetField(FieldType.FONT_FAMILY), "Value", NotNullValidator.GetInstance()); - new BidirectionalBinding(fontSizeUpDown, "Value", surface.FieldAggregator.GetField(FieldType.FONT_SIZE), "Value", DecimalFloatConverter.GetInstance(), NotNullValidator.GetInstance()); - new BidirectionalBinding(fontBoldButton, "Checked", surface.FieldAggregator.GetField(FieldType.FONT_BOLD), "Value", NotNullValidator.GetInstance()); - new BidirectionalBinding(fontItalicButton, "Checked", surface.FieldAggregator.GetField(FieldType.FONT_ITALIC), "Value", NotNullValidator.GetInstance()); - new BidirectionalBinding(textHorizontalAlignmentButton, "SelectedTag", surface.FieldAggregator.GetField(FieldType.TEXT_HORIZONTAL_ALIGNMENT), "Value", NotNullValidator.GetInstance()); - new BidirectionalBinding(textVerticalAlignmentButton, "SelectedTag", surface.FieldAggregator.GetField(FieldType.TEXT_VERTICAL_ALIGNMENT), "Value", NotNullValidator.GetInstance()); - new BidirectionalBinding(shadowButton, "Checked", surface.FieldAggregator.GetField(FieldType.SHADOW), "Value", NotNullValidator.GetInstance()); - new BidirectionalBinding(previewQualityUpDown, "Value", surface.FieldAggregator.GetField(FieldType.PREVIEW_QUALITY), "Value", DecimalDoublePercentageConverter.GetInstance(), NotNullValidator.GetInstance()); - new BidirectionalBinding(obfuscateModeButton, "SelectedTag", surface.FieldAggregator.GetField(FieldType.PREPARED_FILTER_OBFUSCATE), "Value"); - new BidirectionalBinding(highlightModeButton, "SelectedTag", surface.FieldAggregator.GetField(FieldType.PREPARED_FILTER_HIGHLIGHT), "Value"); + new BidirectionalBinding(btnFillColor, "SelectedColor", _surface.FieldAggregator.GetField(FieldType.FILL_COLOR), "Value", NotNullValidator.GetInstance()); + new BidirectionalBinding(btnLineColor, "SelectedColor", _surface.FieldAggregator.GetField(FieldType.LINE_COLOR), "Value", NotNullValidator.GetInstance()); + new BidirectionalBinding(lineThicknessUpDown, "Value", _surface.FieldAggregator.GetField(FieldType.LINE_THICKNESS), "Value", DecimalIntConverter.GetInstance(), NotNullValidator.GetInstance()); + new BidirectionalBinding(blurRadiusUpDown, "Value", _surface.FieldAggregator.GetField(FieldType.BLUR_RADIUS), "Value", DecimalIntConverter.GetInstance(), NotNullValidator.GetInstance()); + new BidirectionalBinding(magnificationFactorUpDown, "Value", _surface.FieldAggregator.GetField(FieldType.MAGNIFICATION_FACTOR), "Value", DecimalIntConverter.GetInstance(), NotNullValidator.GetInstance()); + new BidirectionalBinding(pixelSizeUpDown, "Value", _surface.FieldAggregator.GetField(FieldType.PIXEL_SIZE), "Value", DecimalIntConverter.GetInstance(), NotNullValidator.GetInstance()); + new BidirectionalBinding(brightnessUpDown, "Value", _surface.FieldAggregator.GetField(FieldType.BRIGHTNESS), "Value", DecimalDoublePercentageConverter.GetInstance(), NotNullValidator.GetInstance()); + new BidirectionalBinding(fontFamilyComboBox, "Text", _surface.FieldAggregator.GetField(FieldType.FONT_FAMILY), "Value", NotNullValidator.GetInstance()); + new BidirectionalBinding(fontSizeUpDown, "Value", _surface.FieldAggregator.GetField(FieldType.FONT_SIZE), "Value", DecimalFloatConverter.GetInstance(), NotNullValidator.GetInstance()); + new BidirectionalBinding(fontBoldButton, "Checked", _surface.FieldAggregator.GetField(FieldType.FONT_BOLD), "Value", NotNullValidator.GetInstance()); + new BidirectionalBinding(fontItalicButton, "Checked", _surface.FieldAggregator.GetField(FieldType.FONT_ITALIC), "Value", NotNullValidator.GetInstance()); + new BidirectionalBinding(textHorizontalAlignmentButton, "SelectedTag", _surface.FieldAggregator.GetField(FieldType.TEXT_HORIZONTAL_ALIGNMENT), "Value", NotNullValidator.GetInstance()); + new BidirectionalBinding(textVerticalAlignmentButton, "SelectedTag", _surface.FieldAggregator.GetField(FieldType.TEXT_VERTICAL_ALIGNMENT), "Value", NotNullValidator.GetInstance()); + new BidirectionalBinding(shadowButton, "Checked", _surface.FieldAggregator.GetField(FieldType.SHADOW), "Value", NotNullValidator.GetInstance()); + new BidirectionalBinding(previewQualityUpDown, "Value", _surface.FieldAggregator.GetField(FieldType.PREVIEW_QUALITY), "Value", DecimalDoublePercentageConverter.GetInstance(), NotNullValidator.GetInstance()); + new BidirectionalBinding(obfuscateModeButton, "SelectedTag", _surface.FieldAggregator.GetField(FieldType.PREPARED_FILTER_OBFUSCATE), "Value"); + new BidirectionalBinding(highlightModeButton, "SelectedTag", _surface.FieldAggregator.GetField(FieldType.PREPARED_FILTER_HIGHLIGHT), "Value"); } /// /// shows/hides field controls (2nd toolbar on top) depending on fields of selected elements /// - private void refreshFieldControls() + private void RefreshFieldControls() { propertiesToolStrip.SuspendLayout(); - if (surface.HasSelectedElements || surface.DrawingMode != DrawingModes.None) + if (_surface.HasSelectedElements || _surface.DrawingMode != DrawingModes.None) { toolStripSeparator5.Visible = true; - FieldAggregator props = surface.FieldAggregator; + FieldAggregator props = _surface.FieldAggregator; btnFillColor.Visible = props.HasFieldValue(FieldType.FILL_COLOR); btnLineColor.Visible = props.HasFieldValue(FieldType.LINE_COLOR); lineThicknessLabel.Visible = lineThicknessUpDown.Visible = props.HasFieldValue(FieldType.LINE_THICKNESS); @@ -966,13 +973,13 @@ private void refreshFieldControls() } else { - hideToolstripItems(); + HideToolstripItems(); } propertiesToolStrip.ResumeLayout(); } - private void hideToolstripItems() + private void HideToolstripItems() { btnFillColor.Visible = btnLineColor.Visible = lineThicknessLabel.Visible = lineThicknessUpDown.Visible = blurRadiusLabel.Visible = blurRadiusUpDown.Visible = previewQualityLabel.Visible = previewQualityUpDown.Visible = magnificationFactorLabel.Visible = @@ -986,53 +993,53 @@ private void hideToolstripItems() /// /// refreshes all editor controls depending on selected elements and their fields /// - private void refreshEditorControls() + private void RefreshEditorControls() { - int stepLabels = surface.CountStepLabels(null); + int stepLabels = _surface.CountStepLabels(null); Image icon; if (stepLabels <= 20) { - icon = ((System.Drawing.Image)(Resources.ResourceManager.GetObject(string.Format("notification_counter_{0:00}", stepLabels)))); + icon = (Image)Resources.ResourceManager.GetObject(string.Format("notification_counter_{0:00}", stepLabels)); } else { - icon = ((System.Drawing.Image)(Resources.ResourceManager.GetObject("notification_counter_20_plus"))); + icon = (Image)Resources.ResourceManager.GetObject("notification_counter_20_plus"); } - this.btnStepLabel.Image = icon; + btnStepLabel.Image = icon; - FieldAggregator props = surface.FieldAggregator; + FieldAggregator props = _surface.FieldAggregator; // if a confirmable element is selected, we must disable most of the controls // since we demand confirmation or cancel for confirmable element if (props.HasFieldValue(FieldType.FLAGS) && ((FieldType.Flag)props.GetFieldValue(FieldType.FLAGS) & FieldType.Flag.CONFIRMABLE) == FieldType.Flag.CONFIRMABLE) { // disable most controls - if (!controlsDisabledDueToConfirmable) + if (!_controlsDisabledDueToConfirmable) { ToolStripItemEndisabler.Disable(menuStrip1); //ToolStripItemEndisabler.Disable(propertiesToolStrip); ToolStripItemEndisabler.Disable(toolsToolStrip); ToolStripItemEndisabler.Enable(closeToolStripMenuItem); - controlsDisabledDueToConfirmable = true; + _controlsDisabledDueToConfirmable = true; } } - else if (controlsDisabledDueToConfirmable) + else if (_controlsDisabledDueToConfirmable) { // re-enable disabled controls, confirmable element has either been confirmed or cancelled ToolStripItemEndisabler.Enable(menuStrip1); //ToolStripItemEndisabler.Enable(propertiesToolStrip); ToolStripItemEndisabler.Enable(toolsToolStrip); - controlsDisabledDueToConfirmable = false; + _controlsDisabledDueToConfirmable = false; } // en/disable controls depending on whether an element is selected at all - updateClipboardSurfaceDependencies(); - updateUndoRedoSurfaceDependencies(); + UpdateClipboardSurfaceDependencies(); + UpdateUndoRedoSurfaceDependencies(); // en/disablearrage controls depending on hierarchy of selected elements - bool actionAllowedForSelection = surface.HasSelectedElements && !controlsDisabledDueToConfirmable; - bool push = actionAllowedForSelection && surface.CanPushSelectionDown(); - bool pull = actionAllowedForSelection && surface.CanPullSelectionUp(); - arrangeToolStripMenuItem.Enabled = (push || pull); + bool actionAllowedForSelection = _surface.HasSelectedElements && !_controlsDisabledDueToConfirmable; + bool push = actionAllowedForSelection && _surface.CanPushSelectionDown(); + bool pull = actionAllowedForSelection && _surface.CanPullSelectionUp(); + arrangeToolStripMenuItem.Enabled = push || pull; if (arrangeToolStripMenuItem.Enabled) { upToTopToolStripMenuItem.Enabled = pull; @@ -1042,26 +1049,32 @@ private void refreshEditorControls() } // finally show/hide field controls depending on the fields of selected elements - refreshFieldControls(); + RefreshFieldControls(); } private void ArrowHeadsToolStripMenuItemClick(object sender, EventArgs e) { - surface.FieldAggregator.GetField(FieldType.ARROWHEADS).Value = (ArrowContainer.ArrowHeadCombination)((ToolStripMenuItem)sender).Tag; + _surface.FieldAggregator.GetField(FieldType.ARROWHEADS).Value = (ArrowContainer.ArrowHeadCombination)((ToolStripMenuItem)sender).Tag; } private void FontPropertyChanged(object sender, EventArgs e) { // in case we forced another FontStyle before, reset it first. - if (originalBoldCheckState != fontBoldButton.Checked) fontBoldButton.Checked = originalBoldCheckState; - if (originalItalicCheckState != fontItalicButton.Checked) fontItalicButton.Checked = originalItalicCheckState; + if (fontBoldButton != null && _originalBoldCheckState != fontBoldButton.Checked) + { + fontBoldButton.Checked = _originalBoldCheckState; + } + if (fontItalicButton != null && _originalItalicCheckState != fontItalicButton.Checked) + { + fontItalicButton.Checked = _originalItalicCheckState; + } FontFamily fam = fontFamilyComboBox.FontFamily; bool boldAvailable = fam.IsStyleAvailable(FontStyle.Bold); if (!boldAvailable) { - originalBoldCheckState = fontBoldButton.Checked; + _originalBoldCheckState = fontBoldButton.Checked; fontBoldButton.Checked = false; } fontBoldButton.Enabled = boldAvailable; @@ -1090,41 +1103,41 @@ private void FieldAggregatorFieldChanged(object sender, FieldChangedEventArgs e) // refresh toolbar if prepared filter mode is changed if (e.Field.FieldType == FieldType.PREPARED_FILTER_HIGHLIGHT) { - refreshFieldControls(); + RefreshFieldControls(); } } private void FontBoldButtonClick(object sender, EventArgs e) { - originalBoldCheckState = fontBoldButton.Checked; + _originalBoldCheckState = fontBoldButton.Checked; } private void FontItalicButtonClick(object sender, EventArgs e) { - originalItalicCheckState = fontItalicButton.Checked; + _originalItalicCheckState = fontItalicButton.Checked; } private void ToolBarFocusableElementGotFocus(object sender, EventArgs e) { - surface.KeysLocked = true; + _surface.KeysLocked = true; } private void ToolBarFocusableElementLostFocus(object sender, EventArgs e) { - surface.KeysLocked = false; + _surface.KeysLocked = false; } private void SaveElementsToolStripMenuItemClick(object sender, EventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Greenshot templates (*.gst)|*.gst"; - saveFileDialog.FileName = FilenameHelper.GetFilenameWithoutExtensionFromPattern(coreConfiguration.OutputFileFilenamePattern, surface.CaptureDetails); + saveFileDialog.FileName = FilenameHelper.GetFilenameWithoutExtensionFromPattern(coreConfiguration.OutputFileFilenamePattern, _surface.CaptureDetails); DialogResult dialogResult = saveFileDialog.ShowDialog(); if (dialogResult.Equals(DialogResult.OK)) { using (Stream streamWrite = File.OpenWrite(saveFileDialog.FileName)) { - surface.SaveElementsToStream(streamWrite); + _surface.SaveElementsToStream(streamWrite); } } } @@ -1137,47 +1150,47 @@ private void LoadElementsToolStripMenuItemClick(object sender, EventArgs e) { using (Stream streamRead = File.OpenRead(openFileDialog.FileName)) { - surface.LoadElementsFromStream(streamRead); + _surface.LoadElementsFromStream(streamRead); } - surface.Refresh(); + _surface.Refresh(); } } protected void FilterPresetDropDownItemClicked(object sender, ToolStripItemClickedEventArgs e) { - refreshFieldControls(); + RefreshFieldControls(); Invalidate(true); } private void SelectAllToolStripMenuItemClick(object sender, EventArgs e) { - surface.SelectAllElements(); + _surface.SelectAllElements(); } private void BtnConfirmClick(object sender, EventArgs e) { - surface.ConfirmSelectedConfirmableElements(true); - refreshFieldControls(); + _surface.ConfirmSelectedConfirmableElements(true); + RefreshFieldControls(); } private void BtnCancelClick(object sender, EventArgs e) { - surface.ConfirmSelectedConfirmableElements(false); - refreshFieldControls(); + _surface.ConfirmSelectedConfirmableElements(false); + RefreshFieldControls(); } private void AutoCropToolStripMenuItemClick(object sender, EventArgs e) { - if (surface.AutoCrop()) + if (_surface.AutoCrop()) { - refreshFieldControls(); + RefreshFieldControls(); } } private void AddBorderToolStripMenuItemClick(object sender, EventArgs e) { - surface.ApplyBitmapEffect(new BorderEffect()); - updateUndoRedoSurfaceDependencies(); + _surface.ApplyBitmapEffect(new BorderEffect()); + UpdateUndoRedoSurfaceDependencies(); } /// @@ -1187,13 +1200,13 @@ private void AddBorderToolStripMenuItemClick(object sender, EventArgs e) /// private void AddDropshadowToolStripMenuItemClick(object sender, EventArgs e) { - DropShadowEffect dropShadowEffect = editorConfiguration.DropShadowEffectSettings; + DropShadowEffect dropShadowEffect = EditorConfiguration.DropShadowEffectSettings; // Use the dropshadow settings form to make it possible to change the default values DialogResult result = new DropShadowSettingsForm(dropShadowEffect).ShowDialog(this); if (result == DialogResult.OK) { - surface.ApplyBitmapEffect(dropShadowEffect); - updateUndoRedoSurfaceDependencies(); + _surface.ApplyBitmapEffect(dropShadowEffect); + UpdateUndoRedoSurfaceDependencies(); } } @@ -1204,13 +1217,13 @@ private void AddDropshadowToolStripMenuItemClick(object sender, EventArgs e) /// private void BtnResizeClick(object sender, EventArgs e) { - ResizeEffect resizeEffect = new ResizeEffect(surface.Image.Width, surface.Image.Height, true); + ResizeEffect resizeEffect = new ResizeEffect(_surface.Image.Width, _surface.Image.Height, true); // Use the Resize SettingsForm to make it possible to change the default values DialogResult result = new ResizeSettingsForm(resizeEffect).ShowDialog(this); if (result == DialogResult.OK) { - surface.ApplyBitmapEffect(resizeEffect); - updateUndoRedoSurfaceDependencies(); + _surface.ApplyBitmapEffect(resizeEffect); + UpdateUndoRedoSurfaceDependencies(); } } @@ -1221,11 +1234,11 @@ private void BtnResizeClick(object sender, EventArgs e) /// private void ResizeToolStripMenuItemClick(object sender, EventArgs e) { - ResizeEffect resizeEffect = new ResizeEffect(surface.Image.Width, surface.Image.Height, true); + ResizeEffect resizeEffect = new ResizeEffect(_surface.Image.Width, _surface.Image.Height, true); // DialogResult result = new ResizeSettingsForm(resizeEffect).ShowDialog(this); // if (result == DialogResult.OK) { - surface.ApplyBitmapEffect(resizeEffect); - updateUndoRedoSurfaceDependencies(); + _surface.ApplyBitmapEffect(resizeEffect); + UpdateUndoRedoSurfaceDependencies(); //} } @@ -1236,44 +1249,44 @@ private void ResizeToolStripMenuItemClick(object sender, EventArgs e) /// private void TornEdgesToolStripMenuItemClick(object sender, EventArgs e) { - TornEdgeEffect tornEdgeEffect = editorConfiguration.TornEdgeEffectSettings; + TornEdgeEffect tornEdgeEffect = EditorConfiguration.TornEdgeEffectSettings; // Use the dropshadow settings form to make it possible to change the default values DialogResult result = new TornEdgeSettingsForm(tornEdgeEffect).ShowDialog(this); if (result == DialogResult.OK) { - surface.ApplyBitmapEffect(tornEdgeEffect); - updateUndoRedoSurfaceDependencies(); + _surface.ApplyBitmapEffect(tornEdgeEffect); + UpdateUndoRedoSurfaceDependencies(); } } private void GrayscaleToolStripMenuItemClick(object sender, EventArgs e) { - surface.ApplyBitmapEffect(new GrayscaleEffect()); - updateUndoRedoSurfaceDependencies(); + _surface.ApplyBitmapEffect(new GrayscaleEffect()); + UpdateUndoRedoSurfaceDependencies(); } private void ClearToolStripMenuItemClick(object sender, EventArgs e) { - surface.Clear(Color.Transparent); - updateUndoRedoSurfaceDependencies(); + _surface.Clear(Color.Transparent); + UpdateUndoRedoSurfaceDependencies(); } private void RotateCwToolstripButtonClick(object sender, EventArgs e) { - surface.ApplyBitmapEffect(new RotateEffect(90)); - updateUndoRedoSurfaceDependencies(); + _surface.ApplyBitmapEffect(new RotateEffect(90)); + UpdateUndoRedoSurfaceDependencies(); } private void RotateCcwToolstripButtonClick(object sender, EventArgs e) { - surface.ApplyBitmapEffect(new RotateEffect(270)); - updateUndoRedoSurfaceDependencies(); + _surface.ApplyBitmapEffect(new RotateEffect(270)); + UpdateUndoRedoSurfaceDependencies(); } private void InvertToolStripMenuItemClick(object sender, EventArgs e) { - surface.ApplyBitmapEffect(new InvertEffect()); - updateUndoRedoSurfaceDependencies(); + _surface.ApplyBitmapEffect(new InvertEffect()); + UpdateUndoRedoSurfaceDependencies(); } private void ImageEditorFormResize(object sender, EventArgs e) @@ -1285,6 +1298,10 @@ private void ImageEditorFormResize(object sender, EventArgs e) Size imageSize = Surface.Image.Size; Size currentClientSize = panel1.ClientSize; var canvas = Surface as Control; + if (canvas == null) + { + return; + } Panel panel = (Panel)canvas.Parent; if (panel == null) { @@ -1292,38 +1309,32 @@ private void ImageEditorFormResize(object sender, EventArgs e) } int offsetX = -panel.HorizontalScroll.Value; int offsetY = -panel.VerticalScroll.Value; - if (canvas != null) + if (currentClientSize.Width > imageSize.Width) { - if (currentClientSize.Width > imageSize.Width) - { - canvas.Left = offsetX + ((currentClientSize.Width - imageSize.Width) / 2); - } - else - { - canvas.Left = offsetX + 0; - } + canvas.Left = offsetX + ((currentClientSize.Width - imageSize.Width) / 2); } - if (canvas != null) + else { - if (currentClientSize.Height > imageSize.Height) - { - canvas.Top = offsetY + ((currentClientSize.Height - imageSize.Height) / 2); - } - else - { - canvas.Top = offsetY + 0; - } + canvas.Left = offsetX + 0; + } + if (currentClientSize.Height > imageSize.Height) + { + canvas.Top = offsetY + ((currentClientSize.Height - imageSize.Height) / 2); + } + else + { + canvas.Top = offsetY + 0; } } public void OnImageSaveRequested() { - if (ImageSaveRequested != null && File.Exists(surface.LastSaveFullPath)) + if (ImageSaveRequested != null && File.Exists(_surface.LastSaveFullPath)) { - using (Image img = surface.GetImageForExport()) + using (Image img = _surface.GetImageForExport()) { - ImageSaveRequested(img, surface.LastSaveFullPath); - surface.Modified = false; + ImageSaveRequested(img, _surface.LastSaveFullPath); + _surface.Modified = false; } } } @@ -1332,10 +1343,10 @@ public void OnImageSaveAsRequested() { if (ImageSaveAsRequested != null) { - using (Image img = surface.GetImageForExport()) + using (Image img = _surface.GetImageForExport()) { - string newFilePath = ImageSaveAsRequested(img, surface.LastSaveFullPath); - surface.Modified = false; + string newFilePath = ImageSaveAsRequested(img, _surface.LastSaveFullPath); + _surface.Modified = false; if (!string.IsNullOrEmpty(newFilePath)) { SetImagePath(newFilePath); @@ -1348,7 +1359,7 @@ public void OnClipboardCopyRequested() { if (ClipboardCopyRequested != null) { - using (Image img = surface.GetImageForExport()) + using (Image img = _surface.GetImageForExport()) { ClipboardCopyRequested(img); } @@ -1360,7 +1371,7 @@ public void OnImageUploadRequested() if (ImageUploadRequested != null) { // Image will be disposed in upload task - Image img = surface.GetImageForExport(); + Image img = _surface.GetImageForExport(); ImageUploadRequested(img); } } @@ -1369,7 +1380,7 @@ public void OnPrintImageRequested() { if (PrintImageRequested != null) { - using (Image img = surface.GetImageForExport()) + using (Image img = _surface.GetImageForExport()) { PrintImageRequested(img); } @@ -1425,8 +1436,8 @@ private void tsbPrintImage_Click(object sender, EventArgs e) private void menuStrip1_Click(object sender, EventArgs e) { - updateClipboardSurfaceDependencies(); - updateUndoRedoSurfaceDependencies(); + UpdateClipboardSurfaceDependencies(); + UpdateUndoRedoSurfaceDependencies(); } private void tsmiSettings_Click(object sender, EventArgs e) diff --git a/Greenshot.ImageEditor/Forms/MovableShowColorForm.cs b/Greenshot.ImageEditor/Forms/MovableShowColorForm.cs index 2485b6dd8..540d8f1a1 100644 --- a/Greenshot.ImageEditor/Forms/MovableShowColorForm.cs +++ b/Greenshot.ImageEditor/Forms/MovableShowColorForm.cs @@ -100,9 +100,9 @@ public void MoveTo(Point screenCoordinates) /// /// Point with the coordinates /// Color at the specified screenCoordinates - static private Color GetPixelColor(Point screenCoordinates) + private static Color GetPixelColor(Point screenCoordinates) { - using (SafeWindowDCHandle screenDC = SafeWindowDCHandle.fromDesktop()) + using (SafeWindowDCHandle screenDC = SafeWindowDCHandle.FromDesktop()) { try { diff --git a/Greenshot.ImageEditor/Forms/ResizeSettingsForm.cs b/Greenshot.ImageEditor/Forms/ResizeSettingsForm.cs index 6d6de8177..65777ce60 100644 --- a/Greenshot.ImageEditor/Forms/ResizeSettingsForm.cs +++ b/Greenshot.ImageEditor/Forms/ResizeSettingsForm.cs @@ -32,9 +32,9 @@ namespace Greenshot /// public partial class ResizeSettingsForm : BaseForm { - private ResizeEffect effect; - private string value_pixel; - private string value_percent; + private readonly ResizeEffect effect; + private readonly string value_pixel; + private readonly string value_percent; private double newWidth, newHeight; public ResizeSettingsForm(ResizeEffect effect) @@ -55,8 +55,8 @@ public ResizeSettingsForm(ResizeEffect effect) textbox_height.Text = effect.Height.ToString(); newWidth = effect.Width; newHeight = effect.Height; - combobox_width.SelectedIndexChanged += new System.EventHandler(this.combobox_SelectedIndexChanged); - combobox_height.SelectedIndexChanged += new System.EventHandler(this.combobox_SelectedIndexChanged); + combobox_width.SelectedIndexChanged += new EventHandler(combobox_SelectedIndexChanged); + combobox_height.SelectedIndexChanged += new EventHandler(combobox_SelectedIndexChanged); checkbox_aspectratio.Checked = effect.MaintainAspectRatio; } @@ -96,7 +96,7 @@ private void displayWidth() double displayValue; if (value_percent.Equals(combobox_width.SelectedItem)) { - displayValue = ((double)newWidth / (double)effect.Width) * 100d; + displayValue = (double)newWidth / (double)effect.Width * 100d; } else { @@ -110,7 +110,7 @@ private void displayHeight() double displayValue; if (value_percent.Equals(combobox_height.SelectedItem)) { - displayValue = ((double)newHeight / (double)effect.Height) * 100d; + displayValue = (double)newHeight / (double)effect.Height * 100d; } else { @@ -158,16 +158,16 @@ private void textbox_KeyUp(object sender, KeyEventArgs e) if (isPercent) { percent = double.Parse(textbox_width.Text); - newWidth = ((double)effect.Width / 100d) * percent; + newWidth = (double)effect.Width / 100d * percent; } else { newWidth = double.Parse(textbox_width.Text); - percent = ((double)double.Parse(textbox_width.Text) / (double)effect.Width) * 100d; + percent = (double)double.Parse(textbox_width.Text) / (double)effect.Width * 100d; } if (checkbox_aspectratio.Checked) { - newHeight = ((double)effect.Height / 100d) * percent; + newHeight = (double)effect.Height / 100d * percent; displayHeight(); } } @@ -176,16 +176,16 @@ private void textbox_KeyUp(object sender, KeyEventArgs e) if (isPercent) { percent = double.Parse(textbox_height.Text); - newHeight = ((double)effect.Height / 100d) * percent; + newHeight = (double)effect.Height / 100d * percent; } else { newHeight = double.Parse(textbox_height.Text); - percent = ((double)double.Parse(textbox_height.Text) / (double)effect.Height) * 100d; + percent = (double)double.Parse(textbox_height.Text) / (double)effect.Height * 100d; } if (checkbox_aspectratio.Checked) { - newWidth = ((double)effect.Width / 100d) * percent; + newWidth = (double)effect.Width / 100d * percent; displayWidth(); } } diff --git a/Greenshot.ImageEditor/Forms/TornEdgeSettingsForm.cs b/Greenshot.ImageEditor/Forms/TornEdgeSettingsForm.cs index 1c8255062..7ce104e40 100644 --- a/Greenshot.ImageEditor/Forms/TornEdgeSettingsForm.cs +++ b/Greenshot.ImageEditor/Forms/TornEdgeSettingsForm.cs @@ -29,7 +29,7 @@ namespace Greenshot.Forms { public partial class TornEdgeSettingsForm : BaseForm { - private TornEdgeEffect effect; + private readonly TornEdgeEffect effect; public TornEdgeSettingsForm(TornEdgeEffect effect) { diff --git a/Greenshot.ImageEditor/Greenshot.ImageEditor.csproj b/Greenshot.ImageEditor/Greenshot.ImageEditor.csproj index d6112e99c..e44dfe7a5 100644 --- a/Greenshot.ImageEditor/Greenshot.ImageEditor.csproj +++ b/Greenshot.ImageEditor/Greenshot.ImageEditor.csproj @@ -168,6 +168,7 @@ Component + diff --git a/Greenshot.ImageEditor/Helpers/GeometryHelper.cs b/Greenshot.ImageEditor/Helpers/GeometryHelper.cs index 7e2aafe40..ad5b4a48b 100644 --- a/Greenshot.ImageEditor/Helpers/GeometryHelper.cs +++ b/Greenshot.ImageEditor/Helpers/GeometryHelper.cs @@ -41,9 +41,9 @@ public static int Distance2D(int x1, int y1, int x2, int y2) //Our end result int result = 0; //Take x2-x1, then square it - double part1 = Math.Pow((x2 - x1), 2); + double part1 = Math.Pow(x2 - x1, 2); //Take y2-y1, then square it - double part2 = Math.Pow((y2 - y1), 2); + double part2 = Math.Pow(y2 - y1, 2); //Add both of the parts together double underRadical = part1 + part2; //Get the square root of the parts diff --git a/Greenshot.ImageEditor/Helpers/ScaleHelper.cs b/Greenshot.ImageEditor/Helpers/ScaleHelper.cs index e2f7c436b..f2d76b7dd 100644 --- a/Greenshot.ImageEditor/Helpers/ScaleHelper.cs +++ b/Greenshot.ImageEditor/Helpers/ScaleHelper.cs @@ -80,7 +80,7 @@ public static RectangleF GetAlignedRectangle(RectangleF currentRect, RectangleF newRect.X = (targetRect.Width - currentRect.Width) / 2; break; case ContentAlignment.TopRight: - newRect.X = (targetRect.Width - currentRect.Width); + newRect.X = targetRect.Width - currentRect.Width; break; case ContentAlignment.MiddleLeft: newRect.Y = (targetRect.Height - currentRect.Height) / 2; @@ -91,18 +91,18 @@ public static RectangleF GetAlignedRectangle(RectangleF currentRect, RectangleF break; case ContentAlignment.MiddleRight: newRect.Y = (targetRect.Height - currentRect.Height) / 2; - newRect.X = (targetRect.Width - currentRect.Width); + newRect.X = targetRect.Width - currentRect.Width; break; case ContentAlignment.BottomLeft: - newRect.Y = (targetRect.Height - currentRect.Height); + newRect.Y = targetRect.Height - currentRect.Height; break; case ContentAlignment.BottomCenter: - newRect.Y = (targetRect.Height - currentRect.Height); + newRect.Y = targetRect.Height - currentRect.Height; newRect.X = (targetRect.Width - currentRect.Width) / 2; break; case ContentAlignment.BottomRight: - newRect.Y = (targetRect.Height - currentRect.Height); - newRect.X = (targetRect.Width - currentRect.Width); + newRect.Y = targetRect.Height - currentRect.Height; + newRect.X = targetRect.Width - currentRect.Width; break; } return newRect; @@ -351,7 +351,7 @@ public static void Scale(Rectangle boundsBeforeResize, int gripperPosition, int public static ScaleOptions GetScaleOptions() { bool anchorAtCenter = (Control.ModifierKeys & Keys.Control) != 0; - bool maintainAspectRatio = ((Control.ModifierKeys & Keys.Shift) != 0); + bool maintainAspectRatio = (Control.ModifierKeys & Keys.Shift) != 0; ScaleOptions opts = ScaleOptions.Default; if (anchorAtCenter) opts |= ScaleOptions.Centered; if (maintainAspectRatio) opts |= ScaleOptions.Rational; @@ -393,7 +393,7 @@ public double Process(double angle) public class FixedAngleRoundBehavior : IDoubleProcessor { - private double fixedAngle; + private readonly double fixedAngle; public FixedAngleRoundBehavior(double fixedAngle) { diff --git a/Greenshot.ImageEditor/IniFile/IniConfig.cs b/Greenshot.ImageEditor/IniFile/IniConfig.cs index 03b753fea..252431951 100644 --- a/Greenshot.ImageEditor/IniFile/IniConfig.cs +++ b/Greenshot.ImageEditor/IniFile/IniConfig.cs @@ -38,24 +38,24 @@ public class IniConfig /// /// A lock object for the ini file saving /// - private static object iniLock = new object(); + private static readonly object iniLock = new object(); /// /// As the ini implementation is kept someone generic, for reusing, this holds the name of the application /// - private static string applicationName = null; + private static string applicationName; /// /// As the ini implementation is kept someone generic, for reusing, this holds the name of the configuration /// - private static string configName = null; + private static string configName; private static string configFolderPath = null; /// /// A Dictionary with all the sections stored by section name /// - private static Dictionary sectionMap = new Dictionary(); + private static readonly Dictionary sectionMap = new Dictionary(); /// /// A Dictionary with the properties for a section stored by section name @@ -65,7 +65,7 @@ public class IniConfig /// /// A Dictionary with the fixed-properties for a section stored by section name /// - private static Dictionary> fixedProperties = null; + private static Dictionary> fixedProperties; /// /// Is the configuration portable (meaning we don't store it in the AppData directory) diff --git a/Greenshot.ImageEditor/IniFile/IniReader.cs b/Greenshot.ImageEditor/IniFile/IniReader.cs index cde741425..723ddb0db 100644 --- a/Greenshot.ImageEditor/IniFile/IniReader.cs +++ b/Greenshot.ImageEditor/IniFile/IniReader.cs @@ -30,7 +30,7 @@ public static class IniReader private const string SECTION_START = "["; private const string SECTION_END = "]"; private const string COMMENT = ";"; - private static char[] ASSIGNMENT = new char[] { '=' }; + private static readonly char[] ASSIGNMENT = new[] { '=' }; /** * Read an ini file to a Dictionary, each key is a section and the value is a Dictionary with name and values. diff --git a/Greenshot.ImageEditor/IniFile/IniSection.cs b/Greenshot.ImageEditor/IniFile/IniSection.cs index dfb7f71e4..6a6776d36 100644 --- a/Greenshot.ImageEditor/IniFile/IniSection.cs +++ b/Greenshot.ImageEditor/IniFile/IniSection.cs @@ -35,9 +35,9 @@ namespace Greenshot.IniFile public abstract class IniSection { [NonSerialized] - private IDictionary values = new Dictionary(); + private readonly IDictionary values = new Dictionary(); [NonSerialized] - private IniSectionAttribute iniSectionAttribute = null; + private IniSectionAttribute iniSectionAttribute; public IniSectionAttribute IniSectionAttribute { get diff --git a/Greenshot.ImageEditor/IniFile/IniValue.cs b/Greenshot.ImageEditor/IniFile/IniValue.cs index b3f069fff..fd02b0e09 100644 --- a/Greenshot.ImageEditor/IniFile/IniValue.cs +++ b/Greenshot.ImageEditor/IniFile/IniValue.cs @@ -34,10 +34,10 @@ namespace Greenshot.IniFile /// public class IniValue { - private PropertyInfo propertyInfo; - private FieldInfo fieldInfo; - private IniSection containingIniSection; - private IniPropertyAttribute attributes; + private readonly PropertyInfo propertyInfo; + private readonly FieldInfo fieldInfo; + private readonly IniSection containingIniSection; + private readonly IniPropertyAttribute attributes; public IniValue(IniSection containingIniSection, PropertyInfo propertyInfo, IniPropertyAttribute iniPropertyAttribute) { @@ -226,7 +226,7 @@ public void Write(TextWriter writer, bool onlyProperties) while ((bool)moveNext.Invoke(enumerator, null)) { var key = current.Invoke(enumerator, null); - var valueObject = item.GetValue(myValue, new object[] { key }); + var valueObject = item.GetValue(myValue, new[] { key }); // Write to ini file! writer.WriteLine("{0}.{1}={2}", attributes.Name, ConvertValueToString(valueType1, key, attributes.Separator), ConvertValueToString(valueType2, valueObject, attributes.Separator)); } @@ -324,7 +324,7 @@ public void UseValueOrDefault(string propertyValue) LOG.Warn(ex); //LOG.Error("Problem converting " + stringValue + " to type " + type2.FullName, e); } - addMethodInfo.Invoke(dictionary, new object[] { newValue1, newValue2 }); + addMethodInfo.Invoke(dictionary, new[] { newValue1, newValue2 }); addedElements = true; } } @@ -428,7 +428,7 @@ private static object ConvertStringToValueType(Type valueType, string valueStrin string arraySeparator = separator; object list = Activator.CreateInstance(valueType); // Logic for List<> - string[] arrayValues = valueString.Split(new string[] { arraySeparator }, StringSplitOptions.None); + string[] arrayValues = valueString.Split(new[] { arraySeparator }, StringSplitOptions.None); if (arrayValues == null || arrayValues.Length == 0) { return list; @@ -450,7 +450,7 @@ private static object ConvertStringToValueType(Type valueType, string valueStrin } if (newValue != null) { - addMethodInfo.Invoke(list, new object[] { newValue }); + addMethodInfo.Invoke(list, new[] { newValue }); } } } @@ -460,7 +460,7 @@ private static object ConvertStringToValueType(Type valueType, string valueStrin if (valueType == typeof(object) && valueString.Length > 0) { //LOG.Debug("Parsing: " + valueString); - string[] values = valueString.Split(new Char[] { ':' }); + string[] values = valueString.Split(new[] { ':' }); //LOG.Debug("Type: " + values[0]); //LOG.Debug("Value: " + values[1]); Type fieldTypeForValue = Type.GetType(values[0], true); diff --git a/Greenshot.ImageEditor/Interfaces/IDestination.cs b/Greenshot.ImageEditor/Interfaces/IDestination.cs index 92ee06497..7f0b1bd84 100644 --- a/Greenshot.ImageEditor/Interfaces/IDestination.cs +++ b/Greenshot.ImageEditor/Interfaces/IDestination.cs @@ -28,14 +28,14 @@ namespace Greenshot.Plugin { public class ExportInformation { - private string uri = null; - private string filepath = null; + private string uri; + private string filepath; - private bool exportMade = false; - private string destinationDesignation = null; - private string destinationDescription = null; + private bool exportMade; + private readonly string destinationDesignation; + private string destinationDescription; - private string errorMessage = null; + private string errorMessage; public ExportInformation(string destinationDesignation, string destinationDescription) { diff --git a/Greenshot.ImageEditor/Interfaces/Plugin/PluginInterfaces.cs b/Greenshot.ImageEditor/Interfaces/Plugin/PluginInterfaces.cs index 21387120a..185cca02e 100644 --- a/Greenshot.ImageEditor/Interfaces/Plugin/PluginInterfaces.cs +++ b/Greenshot.ImageEditor/Interfaces/Plugin/PluginInterfaces.cs @@ -87,10 +87,10 @@ public int CompareTo(object obj) public class SurfaceOutputSettings { - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); private bool reduceColors; private bool disableReduceColors; - private List effects = new List(); + private readonly List effects = new List(); public SurfaceOutputSettings() { diff --git a/Greenshot.ImageEditor/Interop/COMWrapper.cs b/Greenshot.ImageEditor/Interop/COMWrapper.cs index c3845d96b..6a5999b9f 100644 --- a/Greenshot.ImageEditor/Interop/COMWrapper.cs +++ b/Greenshot.ImageEditor/Interop/COMWrapper.cs @@ -55,12 +55,12 @@ public sealed class COMWrapper : RealProxy, IDisposable, IRemotingTypeInfo /// /// The type of which method calls are intercepted and executed on the COM object. /// - private Type _InterceptType; + private Type _interceptType; /// /// The humanly readable target name /// - private string _TargetName; + private string _targetName; #endregion Private Data @@ -437,8 +437,8 @@ private COMWrapper(object comObject, Type type, string targetName) { _COMObject = comObject; _COMType = comObject.GetType(); - _InterceptType = type; - _TargetName = targetName; + _interceptType = type; + _targetName = targetName; } #endregion Construction @@ -451,7 +451,7 @@ private COMWrapper(object comObject, Type type, string targetName) /// ~COMWrapper() { - LOG.DebugFormat("Finalize {0}", _InterceptType.ToString()); + LOG.DebugFormat("Finalize {0}", _interceptType); Dispose(false); } @@ -475,7 +475,7 @@ private void Dispose(bool disposing) { if (null != _COMObject) { - LOG.DebugFormat("Disposing {0}", _InterceptType.ToString()); + LOG.DebugFormat("Disposing {0}", _interceptType); if (Marshal.IsComObject(_COMObject)) { try @@ -484,7 +484,7 @@ private void Dispose(bool disposing) do { count = Marshal.ReleaseComObject(_COMObject); - LOG.DebugFormat("RCW count for {0} now is {1}", _InterceptType.ToString(), count); + LOG.DebugFormat("RCW count for {0} now is {1}", _interceptType, count); } while (count > 0); } catch (Exception ex) @@ -514,7 +514,7 @@ private void Dispose(bool disposing) /// public override string ToString() { - return _InterceptType.FullName; + return _interceptType.FullName; } /// @@ -603,12 +603,12 @@ public static T Cast(object wrapperProxy) { throw new ArgumentException("wrapper proxy was no COMWrapper"); } - if (oldWrapper._InterceptType.IsAssignableFrom(newType)) + if (oldWrapper._interceptType.IsAssignableFrom(newType)) { - COMWrapper newWrapper = new COMWrapper(oldWrapper._COMObject, newType, oldWrapper._TargetName); + COMWrapper newWrapper = new COMWrapper(oldWrapper._COMObject, newType, oldWrapper._targetName); return (T)newWrapper.GetTransparentProxy(); } - throw new InvalidCastException(string.Format("{0} is not assignable from {1}", oldWrapper._InterceptType, newType)); + throw new InvalidCastException(string.Format("{0} is not assignable from {1}", oldWrapper._interceptType, newType)); } /// @@ -665,7 +665,7 @@ public static void DumpTypeInfo(Type type) { foreach (MemberInfo memberInfo in type.GetMembers()) { - LOG.InfoFormat("Member: {0};", memberInfo.ToString()); + LOG.InfoFormat("Member: {0};", memberInfo); } } catch (Exception memberException) @@ -676,7 +676,7 @@ public static void DumpTypeInfo(Type type) { foreach (PropertyInfo propertyInfo in type.GetProperties()) { - LOG.InfoFormat("Property: {0};", propertyInfo.ToString()); + LOG.InfoFormat("Property: {0};", propertyInfo); } } catch (Exception propertyException) @@ -687,7 +687,7 @@ public static void DumpTypeInfo(Type type) { foreach (FieldInfo fieldInfo in type.GetFields()) { - LOG.InfoFormat("Field: {0};", fieldInfo.ToString()); + LOG.InfoFormat("Field: {0};", fieldInfo); } } catch (Exception fieldException) @@ -711,14 +711,14 @@ public override IMessage Invoke(IMessage myMessage) IMethodCallMessage callMessage = myMessage as IMethodCallMessage; if (null == callMessage) { - LOG.DebugFormat("Message type not implemented: {0}", myMessage.GetType().ToString()); + LOG.DebugFormat("Message type not implemented: {0}", myMessage.GetType()); return null; } MethodInfo method = callMessage.MethodBase as MethodInfo; if (null == method) { - LOG.DebugFormat("Unrecognized Invoke call: {0}", callMessage.MethodBase.ToString()); + LOG.DebugFormat("Unrecognized Invoke call: {0}", callMessage.MethodBase); return null; } @@ -731,18 +731,8 @@ public override IMessage Invoke(IMessage myMessage) BindingFlags flags = BindingFlags.InvokeMethod; int argCount = callMessage.ArgCount; - object invokeObject; - Type invokeType; - Type byValType; - - object[] args; - object arg; - COMWrapper[] originalArgs; - COMWrapper wrapper; - ParameterModifier[] argModifiers = null; ParameterInfo[] parameters = null; - ParameterInfo parameter; if ("Dispose" == methodName && 0 == argCount && typeof(void) == returnType) { @@ -754,7 +744,7 @@ public override IMessage Invoke(IMessage myMessage) } else if ("GetType" == methodName && 0 == argCount && typeof(Type) == returnType) { - returnValue = _InterceptType; + returnValue = _interceptType; } else if ("GetHashCode" == methodName && 0 == argCount && typeof(int) == returnType) { @@ -777,9 +767,11 @@ public override IMessage Invoke(IMessage myMessage) } else { - invokeObject = _COMObject; - invokeType = _COMType; + var invokeObject = _COMObject; + var invokeType = _COMType; + object[] args; + ParameterInfo parameter; if (methodName.StartsWith("get_")) { // Property Get @@ -822,6 +814,9 @@ public override IMessage Invoke(IMessage myMessage) } // Un-wrap wrapped COM objects before passing to the method + Type byValType; + COMWrapper wrapper; + COMWrapper[] originalArgs; if (null == args || 0 == args.Length) { originalArgs = null; @@ -853,7 +848,7 @@ public override IMessage Invoke(IMessage myMessage) args[i] = new DispatchWrapper(null); } } - else if (typeof(Decimal) == byValType) + else if (typeof(decimal) == byValType) { // If we're passing a decimal value by reference, // we need to pass a CurrencyWrapper to avoid a @@ -875,7 +870,7 @@ public override IMessage Invoke(IMessage myMessage) catch (InvalidComObjectException icoEx) { // Should assist BUG-1616 and others - LOG.WarnFormat("COM object {0} has been separated from its underlying RCW cannot be used. The COM object was released while it was still in use on another thread.", _InterceptType.FullName); + LOG.WarnFormat("COM object {0} has been separated from its underlying RCW cannot be used. The COM object was released while it was still in use on another thread.", _interceptType.FullName); return new ReturnMessage(icoEx, callMessage); } catch (Exception ex) @@ -888,7 +883,7 @@ public override IMessage Invoke(IMessage myMessage) } if (comEx != null && (comEx.ErrorCode == RPC_E_CALL_REJECTED || comEx.ErrorCode == RPC_E_FAIL)) { - string destinationName = _TargetName; + string destinationName = _targetName; // Try to find a "catchy" name for the rejecting application if (destinationName != null && destinationName.Contains(".")) { @@ -896,7 +891,7 @@ public override IMessage Invoke(IMessage myMessage) } if (destinationName == null) { - destinationName = _InterceptType.FullName; + destinationName = _interceptType.FullName; } DialogResult result = MessageBox.Show(string.Format("The destination {0} rejected Greenshot access, probably a dialog is open. Close the dialog and try again.", destinationName), "Greenshot access rejected", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation); @@ -918,7 +913,7 @@ public override IMessage Invoke(IMessage myMessage) // Wrap the returned value in an intercepting COM wrapper if (Marshal.IsComObject(returnValue)) { - returnValue = Wrap(returnValue, returnType, _TargetName); + returnValue = Wrap(returnValue, returnType, _targetName); } } else if (returnType.IsEnum) @@ -939,7 +934,7 @@ public override IMessage Invoke(IMessage myMessage) continue; } - arg = args[i]; + var arg = args[i]; if (null == arg) { continue; @@ -949,7 +944,7 @@ public override IMessage Invoke(IMessage myMessage) wrapper = null; byValType = GetByValType(parameter.ParameterType); - if (typeof(Decimal) == byValType) + if (typeof(decimal) == byValType) { if (arg is CurrencyWrapper) { @@ -973,7 +968,7 @@ public override IMessage Invoke(IMessage myMessage) if (null == wrapper) { - wrapper = new COMWrapper(arg, byValType, _TargetName); + wrapper = new COMWrapper(arg, byValType, _targetName); } arg = wrapper.GetTransparentProxy(); } @@ -995,7 +990,7 @@ public override IMessage Invoke(IMessage myMessage) /// public bool CanCastTo(Type toType, object o) { - bool returnValue = _InterceptType.IsAssignableFrom(toType); + bool returnValue = _interceptType.IsAssignableFrom(toType); return returnValue; } diff --git a/Greenshot.ImageEditor/Interop/ComProgIdAttribute.cs b/Greenshot.ImageEditor/Interop/ComProgIdAttribute.cs index 8eaccb939..ae4d0ac45 100644 --- a/Greenshot.ImageEditor/Interop/ComProgIdAttribute.cs +++ b/Greenshot.ImageEditor/Interop/ComProgIdAttribute.cs @@ -29,7 +29,7 @@ namespace Greenshot.Interop [AttributeUsage(AttributeTargets.Interface, Inherited = false, AllowMultiple = false)] public sealed class ComProgIdAttribute : Attribute { - private string _value; + private readonly string _value; /// /// Extracts the attribute from the specified type. diff --git a/Greenshot.ImageEditor/Memento/AddElementMemento.cs b/Greenshot.ImageEditor/Memento/AddElementMemento.cs index 95565f60b..2068d2be8 100644 --- a/Greenshot.ImageEditor/Memento/AddElementMemento.cs +++ b/Greenshot.ImageEditor/Memento/AddElementMemento.cs @@ -30,13 +30,13 @@ namespace Greenshot.Memento /// public class AddElementMemento : IMemento { - private IDrawableContainer drawableContainer; - private Surface surface; + private IDrawableContainer _drawableContainer; + private Surface _surface; public AddElementMemento(Surface surface, IDrawableContainer drawableContainer) { - this.surface = surface; - this.drawableContainer = drawableContainer; + _surface = surface; + _drawableContainer = drawableContainer; } public void Dispose() @@ -48,8 +48,8 @@ public void Dispose() protected virtual void Dispose(bool disposing) { //if (disposing) { } - drawableContainer = null; - surface = null; + _drawableContainer = null; + _surface = null; } public bool Merge(IMemento otherMemento) @@ -60,16 +60,15 @@ public bool Merge(IMemento otherMemento) public IMemento Restore() { // Before - drawableContainer.Invalidate(); + _drawableContainer.Invalidate(); // Store the selected state, as it's overwritten by the RemoveElement - bool selected = drawableContainer.Selected; - DeleteElementMemento oldState = new DeleteElementMemento(surface, drawableContainer); - surface.RemoveElement(drawableContainer, false); - drawableContainer.Selected = true; + DeleteElementMemento oldState = new DeleteElementMemento(_surface, _drawableContainer); + _surface.RemoveElement(_drawableContainer, false); + _drawableContainer.Selected = true; // After - drawableContainer.Invalidate(); + _drawableContainer.Invalidate(); return oldState; } } diff --git a/Greenshot.ImageEditor/Memento/ChangeFieldHolderMemento.cs b/Greenshot.ImageEditor/Memento/ChangeFieldHolderMemento.cs index 65873f620..91acedc7b 100644 --- a/Greenshot.ImageEditor/Memento/ChangeFieldHolderMemento.cs +++ b/Greenshot.ImageEditor/Memento/ChangeFieldHolderMemento.cs @@ -31,8 +31,8 @@ namespace Greenshot.Memento public class ChangeFieldHolderMemento : IMemento { private IDrawableContainer drawableContainer; - private Field fieldToBeChanged; - private object oldValue; + private readonly Field fieldToBeChanged; + private readonly object oldValue; public ChangeFieldHolderMemento(IDrawableContainer drawableContainer, Field fieldToBeChanged) { diff --git a/Greenshot.ImageEditor/Memento/DeleteElementMemento.cs b/Greenshot.ImageEditor/Memento/DeleteElementMemento.cs index 21efca51b..4f8e0768a 100644 --- a/Greenshot.ImageEditor/Memento/DeleteElementMemento.cs +++ b/Greenshot.ImageEditor/Memento/DeleteElementMemento.cs @@ -31,7 +31,7 @@ namespace Greenshot.Memento public class DeleteElementMemento : IMemento { private IDrawableContainer drawableContainer; - private Surface surface; + private readonly Surface surface; public DeleteElementMemento(Surface surface, IDrawableContainer drawableContainer) { diff --git a/Greenshot.ImageEditor/Memento/DrawableContainerBoundsChangeMemento.cs b/Greenshot.ImageEditor/Memento/DrawableContainerBoundsChangeMemento.cs index 9541c08f9..342c445a4 100644 --- a/Greenshot.ImageEditor/Memento/DrawableContainerBoundsChangeMemento.cs +++ b/Greenshot.ImageEditor/Memento/DrawableContainerBoundsChangeMemento.cs @@ -32,8 +32,8 @@ namespace Greenshot.Memento /// public class DrawableContainerBoundsChangeMemento : IMemento { - private List points = new List(); - private List sizes = new List(); + private readonly List points = new List(); + private readonly List sizes = new List(); private List listOfdrawableContainer; private void StoreBounds() diff --git a/Greenshot.ImageEditor/Memento/TextChangeMemento.cs b/Greenshot.ImageEditor/Memento/TextChangeMemento.cs index 127e77485..3724e2914 100644 --- a/Greenshot.ImageEditor/Memento/TextChangeMemento.cs +++ b/Greenshot.ImageEditor/Memento/TextChangeMemento.cs @@ -30,7 +30,7 @@ namespace Greenshot.Memento public class TextChangeMemento : IMemento { private TextContainer textContainer; - private string oldText; + private readonly string oldText; public TextChangeMemento(TextContainer textContainer) { diff --git a/Greenshot.ImageEditor/UnmanagedHelpers/DWM.cs b/Greenshot.ImageEditor/UnmanagedHelpers/DWM.cs index cd558ac59..4739d81ce 100644 --- a/Greenshot.ImageEditor/UnmanagedHelpers/DWM.cs +++ b/Greenshot.ImageEditor/UnmanagedHelpers/DWM.cs @@ -154,7 +154,7 @@ public static void DisableComposition() /// Helper method for an easy DWM check /// /// bool true if DWM is available AND active - public static bool isDWMEnabled() + public static bool IsDwmEnabled() { // According to: http://technet.microsoft.com/en-us/subscriptions/aa969538%28v=vs.85%29.aspx // And: http://msdn.microsoft.com/en-us/library/windows/desktop/aa969510%28v=vs.85%29.aspx diff --git a/Greenshot.ImageEditor/UnmanagedHelpers/Enumerations.cs b/Greenshot.ImageEditor/UnmanagedHelpers/Enumerations.cs index ee83de09a..4e2396268 100644 --- a/Greenshot.ImageEditor/UnmanagedHelpers/Enumerations.cs +++ b/Greenshot.ImageEditor/UnmanagedHelpers/Enumerations.cs @@ -20,6 +20,7 @@ */ using System; +using System.Diagnostics.CodeAnalysis; namespace GreenshotPlugin.UnmanagedHelpers { @@ -27,6 +28,7 @@ namespace GreenshotPlugin.UnmanagedHelpers /// Window Style Flags /// [Flags] + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum WindowStyleFlags : long { //WS_OVERLAPPED = 0x00000000, @@ -79,6 +81,7 @@ public enum WindowStyleFlags : long } [Flags] + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum ExtendedWindowStyleFlags : uint { WS_EX_DLGMODALFRAME = 0x00000001, @@ -116,6 +119,7 @@ public enum ExtendedWindowStyleFlags : uint } [Flags] + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum WindowPlacementFlags : uint { // The coordinates of the minimized window may be specified. @@ -128,6 +132,7 @@ public enum WindowPlacementFlags : uint WPF_RESTORETOMAXIMIZED = 0x0002 } + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum ShowWindowCommand : uint { /// @@ -155,7 +160,7 @@ public enum ShowWindowCommand : uint ShowMaximized = 3, /// /// Displays a window in its most recent size and position. This value - /// is similar to , except + /// is similar to , except /// the window is not actived. /// ShowNoActivate = 4, @@ -170,13 +175,13 @@ public enum ShowWindowCommand : uint Minimize = 6, /// /// Displays the window as a minimized window. This value is similar to - /// , except the + /// , except the /// window is not activated. /// ShowMinNoActive = 7, /// /// Displays the window in its current size and position. This value is - /// similar to , except the + /// similar to , except the /// window is not activated. /// ShowNA = 8, @@ -200,7 +205,8 @@ public enum ShowWindowCommand : uint ForceMinimize = 11 } - public enum SYSCOLOR : int + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum SYSCOLOR { SCROLLBAR = 0, BACKGROUND = 1, @@ -241,7 +247,8 @@ public enum SYSCOLOR : int /// ai_productions@verizon.net or osirisgothra@hotmail.com /// Obtained on pinvoke.net, please contribute your code to support the wiki! /// - public enum SystemMetric : int + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum SystemMetric { /// /// Width of the screen of the primary display monitor, in pixels. This is the same values obtained by calling GetDeviceCaps as follows: GetDeviceCaps( hdcPrimaryMonitor, HORZRES). @@ -621,6 +628,7 @@ public enum SystemMetric : int SM_REMOTECONTROL = 0x2001 } + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum RegionResult { REGION_ERROR = 0, @@ -630,6 +638,7 @@ public enum RegionResult } // See http://msdn.microsoft.com/en-us/library/aa969530(v=vs.85).aspx + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum DWMWINDOWATTRIBUTE { DWMWA_NCRENDERING_ENABLED = 1, @@ -650,6 +659,7 @@ public enum DWMWINDOWATTRIBUTE DWMWA_LAST } + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum GetWindowCommand : uint { GW_HWNDFIRST = 0, @@ -662,6 +672,7 @@ public enum GetWindowCommand : uint } [Flags] + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum DWM_BB { Enable = 1, @@ -669,7 +680,8 @@ public enum DWM_BB TransitionMaximized = 4 } - public enum ClassLongIndex : int + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum ClassLongIndex { GCL_CBCLSEXTRA = -20, // the size, in bytes, of the extra memory associated with the class. Setting this value does not change the number of extra bytes already allocated. GCL_CBWNDEXTRA = -18, // the size, in bytes, of the extra window memory associated with each window in the class. Setting this value does not change the number of extra bytes already allocated. For information on how to access this memory, see SetWindowLong. @@ -683,7 +695,8 @@ public enum ClassLongIndex : int GCL_WNDPROC = -24, // the address of the window procedure, or a handle representing the address of the window procedure. You must use the CallWindowProc function to call the window procedure. } - public enum WindowsMessages : int + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum WindowsMessages { WM_NULL = 0x0000, WM_CREATE = 0x0001, @@ -891,7 +904,8 @@ public enum WindowsMessages : int } // Get/Set WindowLong Enum See: http://msdn.microsoft.com/en-us/library/ms633591.aspx - public enum WindowLongIndex : int + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum WindowLongIndex { GWL_EXSTYLE = -20, // Sets a new extended window style. GWL_HINSTANCE = -6, // Sets a new application instance handle. @@ -903,7 +917,8 @@ public enum WindowLongIndex : int // See: http://msdn.microsoft.com/en-us/library/ms633545.aspx [Flags] - public enum WindowPos : int + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum WindowPos { SWP_ASYNCWINDOWPOS = 0x4000, // If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request. SWP_DEFERERASE = 0x2000, // Prevents generation of the WM_SYNCPAINT message. @@ -922,14 +937,17 @@ public enum WindowPos : int SWP_SHOWWINDOW = 0x0040 //Displays the window. } - public enum ScrollBarDirection : int + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum ScrollBarDirection { SB_HORZ = 0, SB_VERT = 1, SB_CTL = 2, SB_BOTH = 3 } - public enum ScrollbarCommand : int + + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum ScrollbarCommand { SB_LINEUP = 0, // Scrolls one line up. SB_LINEDOWN = 1, // Scrolls one line down. @@ -942,6 +960,7 @@ public enum ScrollbarCommand : int SB_ENDSCROLL = 8 // Ends scroll. } + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum ScrollInfoMask { SIF_RANGE = 0x1, @@ -956,6 +975,7 @@ public enum ScrollInfoMask /// See: http://www.pinvoke.net/default.aspx/Enums/SendMessageTimeoutFlags.html /// [Flags] + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum SendMessageTimeoutFlags : uint { SMTO_NORMAL = 0x0, @@ -965,6 +985,7 @@ public enum SendMessageTimeoutFlags : uint } [Flags] + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum ProcessAccessFlags : uint { All = 0x001F0FFF, @@ -983,7 +1004,8 @@ public enum ProcessAccessFlags : uint /// See: http://msdn.microsoft.com/en-us/library/aa909766.aspx /// [Flags] - public enum SoundFlags : int + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum SoundFlags { SND_SYNC = 0x0000, // play synchronously (default) SND_ASYNC = 0x0001, // play asynchronously @@ -1001,6 +1023,7 @@ public enum SoundFlags : int /// Used by GDI32.GetDeviceCaps /// See: http://msdn.microsoft.com/en-us/library/windows/desktop/dd144877%28v=vs.85%29.aspx /// + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum DeviceCaps { /// @@ -1170,7 +1193,8 @@ public enum DeviceCaps /// Used for User32.SetWinEventHook /// See: http://msdn.microsoft.com/en-us/library/windows/desktop/dd373640%28v=vs.85%29.aspx /// - public enum WinEventHookFlags : int + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum WinEventHookFlags { WINEVENT_SKIPOWNTHREAD = 1, WINEVENT_SKIPOWNPROCESS = 2, @@ -1182,6 +1206,7 @@ public enum WinEventHookFlags : int /// Used for User32.SetWinEventHook /// See MSDN: http://msdn.microsoft.com/en-us/library/windows/desktop/dd318066%28v=vs.85%29.aspx /// + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum WinEvent : uint { EVENT_OBJECT_ACCELERATORCHANGE = 32786, @@ -1232,7 +1257,8 @@ public enum WinEvent : uint /// Used for User32.SetWinEventHook /// See: http://msdn.microsoft.com/en-us/library/windows/desktop/dd373606%28v=vs.85%29.aspx#OBJID_WINDOW /// - public enum EventObjects : int + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum EventObjects { OBJID_ALERT = -10, OBJID_CARET = -8, @@ -1249,6 +1275,7 @@ public enum EventObjects : int } [Flags] + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum DesktopAccessRight : uint { DESKTOP_READOBJECTS = 0x00000001, diff --git a/Greenshot.ImageEditor/UnmanagedHelpers/GDI32.cs b/Greenshot.ImageEditor/UnmanagedHelpers/GDI32.cs index b5fcf3ba5..47fa3f1ec 100644 --- a/Greenshot.ImageEditor/UnmanagedHelpers/GDI32.cs +++ b/Greenshot.ImageEditor/UnmanagedHelpers/GDI32.cs @@ -57,7 +57,7 @@ public static bool AreRectangleCornersVisisble(this Region region, Rectangle rec /// SafeDeviceContextHandle public static SafeDeviceContextHandle GetSafeDeviceContext(this Graphics graphics) { - return SafeDeviceContextHandle.fromGraphics(graphics); + return SafeDeviceContextHandle.FromGraphics(graphics); } } @@ -67,6 +67,7 @@ public static SafeDeviceContextHandle GetSafeDeviceContext(this Graphics graphic public abstract class SafeObjectHandle : SafeHandleZeroOrMinusOneIsInvalid { [DllImport("gdi32", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DeleteObject(IntPtr hObject); protected SafeObjectHandle(bool ownsHandle) : base(ownsHandle) @@ -84,9 +85,13 @@ protected override bool ReleaseHandle() /// public class SafeHBitmapHandle : SafeObjectHandle { + /// + /// Needed for marshalling return values + /// [SecurityCritical] - private SafeHBitmapHandle() : base(true) + public SafeHBitmapHandle() : base(true) { + } [SecurityCritical] @@ -101,8 +106,11 @@ public SafeHBitmapHandle(IntPtr preexistingHandle) : base(true) /// public class SafeRegionHandle : SafeObjectHandle { + /// + /// Needed for marshalling return values + /// [SecurityCritical] - private SafeRegionHandle() : base(true) + public SafeRegionHandle() : base(true) { } @@ -118,8 +126,11 @@ public SafeRegionHandle(IntPtr preexistingHandle) : base(true) /// public class SafeDibSectionHandle : SafeObjectHandle { + /// + /// Needed for marshalling return values + /// [SecurityCritical] - private SafeDibSectionHandle() : base(true) + public SafeDibSectionHandle() : base(true) { } @@ -139,23 +150,26 @@ public class SafeSelectObjectHandle : SafeHandleZeroOrMinusOneIsInvalid [DllImport("gdi32", SetLastError = true)] private static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject); - private SafeHandle hdc; + private readonly SafeHandle _hdc; + /// + /// Needed for marshalling return values + /// [SecurityCritical] - private SafeSelectObjectHandle() : base(true) + public SafeSelectObjectHandle() : base(true) { } [SecurityCritical] public SafeSelectObjectHandle(SafeDCHandle hdc, SafeHandle newHandle) : base(true) { - this.hdc = hdc; + _hdc = hdc; SetHandle(SelectObject(hdc.DangerousGetHandle(), newHandle.DangerousGetHandle())); } protected override bool ReleaseHandle() { - SelectObject(hdc.DangerousGetHandle(), handle); + SelectObject(_hdc.DangerousGetHandle(), handle); return true; } } @@ -173,10 +187,14 @@ protected SafeDCHandle(bool ownsHandle) : base(ownsHandle) public class SafeCompatibleDCHandle : SafeDCHandle { [DllImport("gdi32", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DeleteDC(IntPtr hDC); + /// + /// Needed for marshalling return values + /// [SecurityCritical] - private SafeCompatibleDCHandle() : base(true) + public SafeCompatibleDCHandle() : base(true) { } @@ -202,23 +220,26 @@ protected override bool ReleaseHandle() /// public class SafeDeviceContextHandle : SafeDCHandle { - private Graphics graphics = null; + private readonly Graphics _graphics; + /// + /// Needed for marshalling return values + /// [SecurityCritical] - private SafeDeviceContextHandle() : base(true) + public SafeDeviceContextHandle() : base(true) { } [SecurityCritical] public SafeDeviceContextHandle(Graphics graphics, IntPtr preexistingHandle) : base(true) { - this.graphics = graphics; + _graphics = graphics; SetHandle(preexistingHandle); } protected override bool ReleaseHandle() { - graphics.ReleaseHdc(handle); + _graphics.ReleaseHdc(handle); return true; } @@ -227,7 +248,7 @@ public SafeSelectObjectHandle SelectObject(SafeHandle newHandle) return new SafeSelectObjectHandle(this, newHandle); } - public static SafeDeviceContextHandle fromGraphics(Graphics graphics) + public static SafeDeviceContextHandle FromGraphics(Graphics graphics) { return new SafeDeviceContextHandle(graphics, graphics.GetHdc()); } @@ -261,51 +282,6 @@ public static class GDI32 [DllImport("gdi32", SetLastError = true)] public static extern int GetDeviceCaps(SafeHandle hdc, DeviceCaps nIndex); - - /// - /// StretchBlt extension for the graphics object - /// Doesn't work? - /// - /// - /// - public static void StretchBlt(this Graphics target, Bitmap sourceBitmap, Rectangle source, Rectangle destination) - { - using (SafeDeviceContextHandle targetDC = target.GetSafeDeviceContext()) - { - using (SafeCompatibleDCHandle safeCompatibleDCHandle = CreateCompatibleDC(targetDC)) - { - using (SafeHBitmapHandle hBitmapHandle = new SafeHBitmapHandle(sourceBitmap.GetHbitmap())) - { - using (safeCompatibleDCHandle.SelectObject(hBitmapHandle)) - { - StretchBlt(targetDC, destination.X, destination.Y, destination.Width, destination.Height, safeCompatibleDCHandle, source.Left, source.Top, source.Width, source.Height, CopyPixelOperation.SourceCopy); - } - } - } - } - } - - /// - /// Bitblt extension for the graphics object - /// - /// - /// - public static void BitBlt(this Graphics target, Bitmap sourceBitmap, Rectangle source, Point destination, CopyPixelOperation rop) - { - using (SafeDeviceContextHandle targetDC = target.GetSafeDeviceContext()) - { - using (SafeCompatibleDCHandle safeCompatibleDCHandle = CreateCompatibleDC(targetDC)) - { - using (SafeHBitmapHandle hBitmapHandle = new SafeHBitmapHandle(sourceBitmap.GetHbitmap())) - { - using (safeCompatibleDCHandle.SelectObject(hBitmapHandle)) - { - BitBlt(targetDC, destination.X, destination.Y, source.Width, source.Height, safeCompatibleDCHandle, source.Left, source.Top, rop); - } - } - } - } - } } [StructLayout(LayoutKind.Sequential, Pack = 2)] @@ -441,10 +417,12 @@ public BITMAPINFOHEADER(int width, int height, ushort bpp) bV5BlueMask = (uint)255; bV5AlphaMask = (uint)255 << 24; bV5CSType = 1934772034; // sRGB - bV5Endpoints = new CIEXYZTRIPLE(); - bV5Endpoints.ciexyzBlue = new CIEXYZ(0); - bV5Endpoints.ciexyzGreen = new CIEXYZ(0); - bV5Endpoints.ciexyzRed = new CIEXYZ(0); + bV5Endpoints = new CIEXYZTRIPLE + { + ciexyzBlue = new CIEXYZ(0), + ciexyzGreen = new CIEXYZ(0), + ciexyzRed = new CIEXYZ(0) + }; bV5GammaRed = 0; bV5GammaGreen = 0; bV5GammaBlue = 0; diff --git a/Greenshot.ImageEditor/UnmanagedHelpers/GDIplus.cs b/Greenshot.ImageEditor/UnmanagedHelpers/GDIplus.cs index 699beb510..8d5c4d80a 100644 --- a/Greenshot.ImageEditor/UnmanagedHelpers/GDIplus.cs +++ b/Greenshot.ImageEditor/UnmanagedHelpers/GDIplus.cs @@ -111,7 +111,7 @@ public static class GDIplus [DllImport("gdiplus.dll", SetLastError = true, ExactSpelling = true)] private static extern int GdipDeleteEffect(IntPtr effect); - private static Guid BlurEffectGuid = new Guid("{633C80A4-1843-482B-9EF2-BE2834C5FDD4}"); + private static readonly Guid BlurEffectGuid = new Guid("{633C80A4-1843-482B-9EF2-BE2834C5FDD4}"); // Constant "FieldInfo" for getting the nativeImage from the Bitmap private static readonly FieldInfo FIELD_INFO_NATIVE_IMAGE = typeof(Bitmap).GetField("nativeImage", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic); @@ -122,7 +122,7 @@ public static class GDIplus // Constant "FieldInfo" for getting the nativeImageAttributes from the ImageAttributes private static readonly FieldInfo FIELD_INFO_NATIVE_IMAGEATTRIBUTES = typeof(ImageAttributes).GetField("nativeImageAttributes", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic); - private static bool isBlurEnabled = Environment.OSVersion.Version.Major >= 6; + private static bool _isBlurEnabled = Environment.OSVersion.Version.Major >= 6; /// /// Get the nativeImage field from the bitmap @@ -186,9 +186,9 @@ private static IntPtr GetNativeImageAttributes(ImageAttributes imageAttributes) /// /// /// - public static bool isBlurPossible(int radius) + public static bool IsBlurPossible(int radius) { - if (!isBlurEnabled) + if (!_isBlurEnabled) { return false; } @@ -209,7 +209,7 @@ public static bool isBlurPossible(int radius) /// false if there is no GDI+ available or an exception occured public static bool ApplyBlur(Bitmap destinationBitmap, Rectangle area, int radius, bool expandEdges) { - if (!isBlurPossible(radius)) + if (!IsBlurPossible(radius)) { return false; } @@ -248,7 +248,7 @@ public static bool ApplyBlur(Bitmap destinationBitmap, Rectangle area, int radiu } catch (Exception ex) { - isBlurEnabled = false; + _isBlurEnabled = false; LOG.Error("Problem using GdipBitmapApplyEffect: ", ex); return false; } @@ -269,7 +269,7 @@ public static bool ApplyBlur(Bitmap destinationBitmap, Rectangle area, int radiu } catch (Exception ex) { - isBlurEnabled = false; + _isBlurEnabled = false; LOG.Error("Problem cleaning up ApplyBlur: ", ex); } } @@ -281,7 +281,7 @@ public static bool ApplyBlur(Bitmap destinationBitmap, Rectangle area, int radiu /// false if there is no GDI+ available or an exception occured public static bool DrawWithBlur(Graphics graphics, Bitmap image, Rectangle source, Matrix transform, ImageAttributes imageAttributes, int radius, bool expandEdges) { - if (!isBlurPossible(radius)) + if (!IsBlurPossible(radius)) { return false; } @@ -325,7 +325,7 @@ public static bool DrawWithBlur(Graphics graphics, Bitmap image, Rectangle sourc } catch (Exception ex) { - isBlurEnabled = false; + _isBlurEnabled = false; LOG.Error("Problem using GdipDrawImageFX: ", ex); return false; } @@ -346,7 +346,7 @@ public static bool DrawWithBlur(Graphics graphics, Bitmap image, Rectangle sourc } catch (Exception ex) { - isBlurEnabled = false; + _isBlurEnabled = false; LOG.Error("Problem cleaning up DrawWithBlur: ", ex); } } diff --git a/Greenshot.ImageEditor/UnmanagedHelpers/Kernel32.cs b/Greenshot.ImageEditor/UnmanagedHelpers/Kernel32.cs index 381515910..45d21da5d 100644 --- a/Greenshot.ImageEditor/UnmanagedHelpers/Kernel32.cs +++ b/Greenshot.ImageEditor/UnmanagedHelpers/Kernel32.cs @@ -67,6 +67,7 @@ public class Kernel32 public static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess, bool bInheritHandle, int dwProcessId); [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] public static extern bool QueryFullProcessImageName(IntPtr hProcess, uint dwFlags, StringBuilder lpExeName, ref uint lpdwSize); [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)] @@ -76,6 +77,7 @@ public class Kernel32 public static extern IntPtr GetModuleHandle(string lpModuleName); [DllImport("kernel32", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CloseHandle(IntPtr hObject); /// diff --git a/Greenshot.ImageEditor/UnmanagedHelpers/Shell32.cs b/Greenshot.ImageEditor/UnmanagedHelpers/Shell32.cs index 29807a45e..eda15379f 100644 --- a/Greenshot.ImageEditor/UnmanagedHelpers/Shell32.cs +++ b/Greenshot.ImageEditor/UnmanagedHelpers/Shell32.cs @@ -43,44 +43,16 @@ public static class Shell32 #region Structs - [StructLayout(LayoutKind.Sequential)] - private struct SHITEMID - { - public ushort cb; - [MarshalAs(UnmanagedType.LPArray)] - public byte[] abID; - } - - [StructLayout(LayoutKind.Sequential)] - private struct ITEMIDLIST - { - public SHITEMID mkid; - } - - [StructLayout(LayoutKind.Sequential)] - private struct BROWSEINFO - { - public IntPtr hwndOwner; - public IntPtr pidlRoot; - public IntPtr pszDisplayName; - [MarshalAs(UnmanagedType.LPTStr)] - public string lpszTitle; - public uint ulFlags; - public IntPtr lpfn; - public int lParam; - public IntPtr iImage; - } - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private struct SHFILEINFO { - public IntPtr hIcon; - public int iIcon; - public uint dwAttributes; + public readonly IntPtr hIcon; + public readonly int iIcon; + public readonly uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] - public string szDisplayName; + public readonly string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] - public string szTypeName; + public readonly string szTypeName; }; #endregion Structs @@ -160,7 +132,7 @@ public enum FolderType /// Returns an icon for a given file extension - indicated by the name parameter. /// See: http://msdn.microsoft.com/en-us/library/windows/desktop/bb762179(v=vs.85).aspx /// - /// Filename + /// Filename /// Large or small /// Whether to include the link icon /// System.Drawing.Icon @@ -168,24 +140,24 @@ public static Icon GetFileIcon(string filename, IconSize size, bool linkOverlay) { SHFILEINFO shfi = new SHFILEINFO(); // SHGFI_USEFILEATTRIBUTES makes it simulate, just gets the icon for the extension - uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES; + uint flags = SHGFI_ICON | SHGFI_USEFILEATTRIBUTES; - if (true == linkOverlay) + if (linkOverlay) { - flags += Shell32.SHGFI_LINKOVERLAY; + flags += SHGFI_LINKOVERLAY; } // Check the size specified for return. if (IconSize.Small == size) { - flags += Shell32.SHGFI_SMALLICON; + flags += SHGFI_SMALLICON; } else { - flags += Shell32.SHGFI_LARGEICON; + flags += SHGFI_LARGEICON; } - SHGetFileInfo(Path.GetFileName(filename), Shell32.FILE_ATTRIBUTE_NORMAL, ref shfi, (uint)Marshal.SizeOf(shfi), flags); + SHGetFileInfo(Path.GetFileName(filename), FILE_ATTRIBUTE_NORMAL, ref shfi, (uint)Marshal.SizeOf(shfi), flags); // Only return an icon if we really got one if (shfi.hIcon != IntPtr.Zero) diff --git a/Greenshot.ImageEditor/UnmanagedHelpers/Structs.cs b/Greenshot.ImageEditor/UnmanagedHelpers/Structs.cs index 2737780f0..c8c1f2698 100644 --- a/Greenshot.ImageEditor/UnmanagedHelpers/Structs.cs +++ b/Greenshot.ImageEditor/UnmanagedHelpers/Structs.cs @@ -28,8 +28,8 @@ namespace GreenshotPlugin.UnmanagedHelpers [StructLayout(LayoutKind.Sequential), Serializable()] public struct SIZE { - public int width; - public int height; + public int Width; + public int Height; public SIZE(Size size) : this(size.Width, size.Height) { @@ -37,13 +37,13 @@ public SIZE(Size size) : this(size.Width, size.Height) public SIZE(int width, int height) { - this.width = width; - this.height = height; + Width = width; + Height = height; } public Size ToSize() { - return new Size(width, height); + return new Size(Width, Height); } } diff --git a/Greenshot.ImageEditor/UnmanagedHelpers/User32.cs b/Greenshot.ImageEditor/UnmanagedHelpers/User32.cs index 460b90852..b7f439b6b 100644 --- a/Greenshot.ImageEditor/UnmanagedHelpers/User32.cs +++ b/Greenshot.ImageEditor/UnmanagedHelpers/User32.cs @@ -64,7 +64,7 @@ public static class User32 [DllImport("user32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] - public extern static bool IsWindowVisible(IntPtr hWnd); + public static extern bool IsWindowVisible(IntPtr hWnd); [DllImport("user32", SetLastError = true)] public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId); @@ -82,10 +82,10 @@ public static class User32 public static extern int ShowWindow(IntPtr hWnd, ShowWindowCommand nCmdShow); [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - public extern static int GetWindowText(IntPtr hWnd, StringBuilder lpString, int cch); + public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int cch); [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - public extern static int GetWindowTextLength(IntPtr hWnd); + public static extern int GetWindowTextLength(IntPtr hWnd); [DllImport("user32", SetLastError = true)] public static extern uint GetSysColor(int nIndex); @@ -114,16 +114,16 @@ public static class User32 [DllImport("user32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] - public extern static bool IsIconic(IntPtr hWnd); + public static extern bool IsIconic(IntPtr hWnd); [DllImport("user32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] - public extern static bool IsZoomed(IntPtr hwnd); + public static extern bool IsZoomed(IntPtr hwnd); [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - public extern static int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); + public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); - [DllImport("user32", SetLastError = true)] + [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] public static extern uint GetClassLong(IntPtr hWnd, int nIndex); [DllImport("user32", SetLastError = true, EntryPoint = "GetClassLongPtr")] @@ -133,17 +133,17 @@ public static class User32 [return: MarshalAs(UnmanagedType.Bool)] public static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags); - [DllImport("user32", SetLastError = true)] - public extern static IntPtr SendMessage(IntPtr hWnd, uint wMsg, IntPtr wParam, IntPtr lParam); + [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern IntPtr SendMessage(IntPtr hWnd, uint wMsg, IntPtr wParam, IntPtr lParam); [DllImport("user32", SetLastError = true)] - public extern static IntPtr SendMessage(IntPtr hWnd, uint wMsg, IntPtr wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam); + public static extern IntPtr SendMessage(IntPtr hWnd, uint wMsg, IntPtr wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam); [DllImport("user32", SetLastError = true, EntryPoint = "GetWindowLong")] - public extern static int GetWindowLong(IntPtr hwnd, int index); + public static extern int GetWindowLong(IntPtr hwnd, int index); [DllImport("user32", SetLastError = true, EntryPoint = "GetWindowLongPtr")] - public extern static IntPtr GetWindowLongPtr(IntPtr hwnd, int nIndex); + public static extern IntPtr GetWindowLongPtr(IntPtr hwnd, int nIndex); [DllImport("user32", SetLastError = true)] public static extern int SetWindowLong(IntPtr hWnd, int index, int styleFlags); @@ -162,10 +162,10 @@ public static class User32 public static extern bool GetWindowInfo(IntPtr hwnd, ref WindowInfo pwi); [DllImport("user32", SetLastError = true)] - public extern static int EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam); + public static extern int EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam); [DllImport("user32", SetLastError = true)] - public extern static int EnumChildWindows(IntPtr hWndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam); + public static extern int EnumChildWindows(IntPtr hWndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam); [DllImport("user32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] @@ -173,10 +173,10 @@ public static class User32 [DllImport("user32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool ShowScrollBar(IntPtr hwnd, ScrollBarDirection scrollBar, bool show); + public static extern bool ShowScrollBar(IntPtr hwnd, ScrollBarDirection scrollBar, [MarshalAs(UnmanagedType.Bool)] bool show); [DllImport("user32", SetLastError = true)] - public static extern int SetScrollPos(IntPtr hWnd, Orientation nBar, int nPos, bool bRedraw); + public static extern int SetScrollPos(IntPtr hWnd, Orientation nBar, int nPos, [MarshalAs(UnmanagedType.Bool)] bool bRedraw); [DllImport("user32", SetLastError = true)] public static extern RegionResult GetWindowRgn(IntPtr hWnd, SafeHandle hRgn); @@ -231,7 +231,7 @@ public static class User32 public static extern uint RegisterWindowMessage(string lpString); [DllImport("user32", SetLastError = true, CharSet = CharSet.Unicode)] - public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam, SendMessageTimeoutFlags fuFlags, uint uTimeout, out UIntPtr lpdwResult); + public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam, SendMessageTimeoutFlags fuFlags, uint uTimeout, out UIntPtr lpdwResult); [DllImport("user32", SetLastError = true)] private static extern bool GetPhysicalCursorPos(out POINT cursorLocation); @@ -446,7 +446,11 @@ protected override bool ReleaseHandle() /// public class SafeIconHandle : SafeHandleZeroOrMinusOneIsInvalid { - private SafeIconHandle() : base(true) + /// + /// Needed for marshalling return values + /// + [SecurityCritical] + public SafeIconHandle() : base(true) { } @@ -473,28 +477,30 @@ public class SafeWindowDCHandle : SafeHandleZeroOrMinusOneIsInvalid [DllImport("user32", SetLastError = true)] private static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC); - private IntPtr hWnd; + private readonly IntPtr _hWnd; - [SecurityCritical] - private SafeWindowDCHandle() : base(true) + /// + /// Needed for marshalling return values + /// + public SafeWindowDCHandle() : base(true) { } [SecurityCritical] public SafeWindowDCHandle(IntPtr hWnd, IntPtr preexistingHandle) : base(true) { - this.hWnd = hWnd; + _hWnd = hWnd; SetHandle(preexistingHandle); } [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] protected override bool ReleaseHandle() { - bool returnValue = ReleaseDC(hWnd, handle); + bool returnValue = ReleaseDC(_hWnd, handle); return returnValue; } - public static SafeWindowDCHandle fromDesktop() + public static SafeWindowDCHandle FromDesktop() { IntPtr hWndDesktop = User32.GetDesktopWindow(); IntPtr hDCDesktop = GetWindowDC(hWndDesktop); diff --git a/ShareX.HelpersLib/Helpers/ImageHelpers.cs b/ShareX.HelpersLib/Helpers/ImageHelpers.cs index 01310dee1..77d3544c2 100644 --- a/ShareX.HelpersLib/Helpers/ImageHelpers.cs +++ b/ShareX.HelpersLib/Helpers/ImageHelpers.cs @@ -853,7 +853,7 @@ public static Bitmap AddShadow(Image sourceImage, float opacity, int size, float public static void Blur(Bitmap sourceImage, int radius) { - if (GDIplus.isBlurPossible(radius)) + if (GDIplus.IsBlurPossible(radius)) { GDIplus.ApplyBlur(sourceImage, new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), radius, false); }