From d780d337e419f6e821e26754bd07c138939ebc09 Mon Sep 17 00:00:00 2001 From: David Bremner Date: Sat, 16 Apr 2016 18:28:44 -0700 Subject: [PATCH 01/19] marshal return types, add CharSet.Unicode to functions that lack it, marshal BOOL parameters --- Greenshot/Helpers/EnvironmentInfo.cs | 4 +++- GreenshotPlugin/Core/CredentialsHelper.cs | 3 ++- GreenshotPlugin/Core/WindowCapture.cs | 1 + GreenshotPlugin/UnmanagedHelpers/GDI32.cs | 4 +++- GreenshotPlugin/UnmanagedHelpers/Kernel32.cs | 2 ++ GreenshotPlugin/UnmanagedHelpers/Shell32.cs | 4 ++-- GreenshotPlugin/UnmanagedHelpers/User32.cs | 10 +++++----- 7 files changed, 18 insertions(+), 10 deletions(-) diff --git a/Greenshot/Helpers/EnvironmentInfo.cs b/Greenshot/Helpers/EnvironmentInfo.cs index 443fe3321..4aa2e9bf7 100644 --- a/Greenshot/Helpers/EnvironmentInfo.cs +++ b/Greenshot/Helpers/EnvironmentInfo.cs @@ -645,6 +645,7 @@ namespace Greenshot.Helpers #region GET #region PRODUCT INFO [DllImport("Kernel32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetProductInfo( int osMajorVersion, int osMinorVersion, @@ -654,7 +655,8 @@ namespace Greenshot.Helpers #endregion PRODUCT INFO #region VERSION - [DllImport("kernel32.dll")] + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetVersionEx(ref OSVERSIONINFOEX osVersionInfo); #endregion VERSION #endregion GET diff --git a/GreenshotPlugin/Core/CredentialsHelper.cs b/GreenshotPlugin/Core/CredentialsHelper.cs index 539ab244a..5c9474b55 100644 --- a/GreenshotPlugin/Core/CredentialsHelper.cs +++ b/GreenshotPlugin/Core/CredentialsHelper.cs @@ -59,6 +59,7 @@ namespace GreenshotPlugin.Core { /// Encapsulates dialog functionality from the Credential Management API. public sealed class CredentialsDialog { [DllImport("gdi32.dll", SetLastError=true)] + [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DeleteObject(IntPtr hObject); /// The only valid bitmap height (in pixels) of a user-defined banner. @@ -602,6 +603,6 @@ namespace GreenshotPlugin.Core { /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/secauthn/security/creduiconfirmcredentials.asp /// [DllImport("credui.dll", CharSet=CharSet.Unicode)] - public static extern ReturnCodes CredUIConfirmCredentials(string targetName, bool confirm); + public static extern ReturnCodes CredUIConfirmCredentials(string targetName, [MarshalAs(UnmanagedType.Bool)] bool confirm); } } \ No newline at end of file diff --git a/GreenshotPlugin/Core/WindowCapture.cs b/GreenshotPlugin/Core/WindowCapture.cs index 733aa12f0..a85792162 100644 --- a/GreenshotPlugin/Core/WindowCapture.cs +++ b/GreenshotPlugin/Core/WindowCapture.cs @@ -423,6 +423,7 @@ namespace GreenshotPlugin.Core { /// /// [DllImport("gdi32", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DeleteObject(IntPtr hObject); private WindowCapture() { diff --git a/GreenshotPlugin/UnmanagedHelpers/GDI32.cs b/GreenshotPlugin/UnmanagedHelpers/GDI32.cs index 2d12a4a81..f3e2aff3e 100644 --- a/GreenshotPlugin/UnmanagedHelpers/GDI32.cs +++ b/GreenshotPlugin/UnmanagedHelpers/GDI32.cs @@ -62,6 +62,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// 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) { @@ -149,7 +150,8 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// public class SafeCompatibleDCHandle : SafeDCHandle { [DllImport("gdi32", SetLastError = true)] - private static extern bool DeleteDC(IntPtr hDC); + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool DeleteDC(IntPtr hDC); [SecurityCritical] private SafeCompatibleDCHandle() : base(true) { diff --git a/GreenshotPlugin/UnmanagedHelpers/Kernel32.cs b/GreenshotPlugin/UnmanagedHelpers/Kernel32.cs index 677e1a0f4..c2b347b06 100644 --- a/GreenshotPlugin/UnmanagedHelpers/Kernel32.cs +++ b/GreenshotPlugin/UnmanagedHelpers/Kernel32.cs @@ -58,12 +58,14 @@ namespace GreenshotPlugin.UnmanagedHelpers { [DllImport("kernel32", SetLastError = true)] 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)] public static extern uint QueryDosDevice(string lpDeviceName, StringBuilder lpTargetPath, uint uuchMax); [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)] 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/GreenshotPlugin/UnmanagedHelpers/Shell32.cs b/GreenshotPlugin/UnmanagedHelpers/Shell32.cs index 945c3b292..e74d38310 100644 --- a/GreenshotPlugin/UnmanagedHelpers/Shell32.cs +++ b/GreenshotPlugin/UnmanagedHelpers/Shell32.cs @@ -49,12 +49,12 @@ namespace GreenshotPlugin.UnmanagedHelpers { public SHITEMID mkid; } - [StructLayout(LayoutKind.Sequential)] + [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] private struct BROWSEINFO { public IntPtr hwndOwner; public IntPtr pidlRoot; public IntPtr pszDisplayName; - [MarshalAs(UnmanagedType.LPTStr)] + [MarshalAs(UnmanagedType.LPWStr)] public string lpszTitle; public uint ulFlags; public IntPtr lpfn; diff --git a/GreenshotPlugin/UnmanagedHelpers/User32.cs b/GreenshotPlugin/UnmanagedHelpers/User32.cs index 416a38823..b3335a204 100644 --- a/GreenshotPlugin/UnmanagedHelpers/User32.cs +++ b/GreenshotPlugin/UnmanagedHelpers/User32.cs @@ -104,14 +104,14 @@ namespace GreenshotPlugin.UnmanagedHelpers { public extern static bool IsZoomed(IntPtr hwnd); [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] public extern static 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")] public static extern IntPtr GetClassLongPtr(IntPtr hWnd, int nIndex); [DllImport("user32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags); - [DllImport("user32", SetLastError=true)] + [DllImport("user32", CharSet=CharSet.Unicode, SetLastError=true)] public extern static 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); @@ -119,7 +119,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { public extern static int GetWindowLong(IntPtr hwnd, int index); [DllImport("user32", SetLastError = true, EntryPoint = "GetWindowLongPtr")] public extern static IntPtr GetWindowLongPtr(IntPtr hwnd, int nIndex); - [DllImport("user32", SetLastError = true)] + [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] public static extern int SetWindowLong(IntPtr hWnd, int index, int styleFlags); [DllImport("user32", SetLastError = true, EntryPoint = "SetWindowLongPtr")] public static extern IntPtr SetWindowLongPtr(IntPtr hWnd, int index, IntPtr styleFlags); @@ -139,9 +139,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { public static extern bool GetScrollInfo(IntPtr hwnd, int fnBar, ref SCROLLINFO lpsi); [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); [DllImport("user32", SetLastError = true)] From 98e6be5eb6218ff47b9ae41884629a1885b78015 Mon Sep 17 00:00:00 2001 From: Robin Date: Sun, 17 Apr 2016 23:32:22 +0200 Subject: [PATCH 02/19] Small cleanups [skip ci] --- .../Configuration/EditorConfiguration.cs | 2 +- Greenshot/Controls/BindableToolStripButton.cs | 3 +- .../Controls/BindableToolStripComboBox.cs | 3 +- .../BindableToolStripDropDownButton.cs | 3 - ...ontextMenuToolStripProfessionalRenderer.cs | 2 +- Greenshot/Controls/FontFamilyComboBox.cs | 30 +- Greenshot/Controls/MenuStripEx.cs | 10 +- Greenshot/Controls/NonJumpingPanel.cs | 7 +- Greenshot/Controls/Pipette.cs | 10 +- Greenshot/Controls/ToolStripEx.cs | 10 +- .../Destinations/ClipboardDestination.cs | 4 - Greenshot/Destinations/EditorDestination.cs | 12 +- Greenshot/Destinations/EmailDestination.cs | 6 +- Greenshot/Destinations/FileDestination.cs | 13 +- .../Destinations/FileWithDialogDestination.cs | 2 +- Greenshot/Destinations/PrinterDestination.cs | 6 +- Greenshot/Drawing/ArrowContainer.cs | 2 +- Greenshot/Drawing/CursorContainer.cs | 2 +- Greenshot/Drawing/DrawableContainer.cs | 18 +- Greenshot/Drawing/DrawableContainerList.cs | 8 +- Greenshot/Drawing/EllipseContainer.cs | 9 +- .../Drawing/Fields/AbstractFieldHolder.cs | 8 +- .../Fields/AbstractFieldHolderWithChildren.cs | 3 +- .../Binding/AbstractBindingConverter.cs | 2 - .../Fields/Binding/BidirectionalBinding.cs | 80 +- Greenshot/Drawing/Fields/FieldAggregator.cs | 12 +- Greenshot/Drawing/FilterContainer.cs | 4 +- Greenshot/Drawing/Filters/AbstractFilter.cs | 2 +- Greenshot/Drawing/Filters/BlurFilter.cs | 9 +- Greenshot/Drawing/Filters/MagnifierFilter.cs | 2 +- .../Drawing/Filters/PixelizationFilter.cs | 2 +- Greenshot/Drawing/FreehandContainer.cs | 10 +- Greenshot/Drawing/IconContainer.cs | 2 +- Greenshot/Drawing/ImageContainer.cs | 2 +- Greenshot/Drawing/LineContainer.cs | 2 +- Greenshot/Drawing/RectangleContainer.cs | 4 +- Greenshot/Drawing/RoundedRectangle.cs | 14 +- Greenshot/Drawing/SpeechbubbleContainer.cs | 10 +- Greenshot/Drawing/StepLabelContainer.cs | 8 +- Greenshot/Drawing/Surface.cs | 26 +- Greenshot/Drawing/TextContainer.cs | 6 +- Greenshot/Forms/AboutForm.cs | 110 +-- Greenshot/Forms/CaptureForm.cs | 38 +- Greenshot/Forms/ColorDialog.cs | 4 +- Greenshot/Forms/DropShadowSettingsForm.cs | 7 +- Greenshot/Forms/ImageEditorForm.Designer.cs | 2 +- Greenshot/Forms/ImageEditorForm.cs | 818 +++++++++--------- Greenshot/Forms/LanguageDialog.cs | 4 +- Greenshot/Forms/MainForm.cs | 6 +- Greenshot/Forms/MovableShowColorForm.cs | 4 +- Greenshot/Forms/ResizeSettingsForm.cs | 26 +- Greenshot/Forms/SettingsForm.cs | 7 +- Greenshot/Forms/ToolStripMenuSelectList.cs | 6 +- Greenshot/Forms/TornEdgeSettingsForm.cs | 7 +- Greenshot/Helpers/CaptureHelper.cs | 8 +- Greenshot/Helpers/CopyData.cs | 174 ++-- Greenshot/Helpers/DestinationHelper.cs | 6 +- Greenshot/Helpers/EnvironmentInfo.cs | 84 +- Greenshot/Helpers/GeometryHelper.cs | 4 +- Greenshot/Helpers/IECaptureHelper.cs | 29 +- Greenshot/Helpers/IEInterop/IEContainer.cs | 219 +++-- Greenshot/Helpers/MailHelper.cs | 27 +- Greenshot/Helpers/PluginHelper.cs | 12 +- Greenshot/Helpers/PrintHelper.cs | 6 +- Greenshot/Helpers/ProcessorHelper.cs | 4 +- Greenshot/Helpers/ScaleHelper.cs | 21 +- Greenshot/Helpers/SoundHelper.cs | 24 +- Greenshot/Helpers/UpdateHelper.cs | 2 +- Greenshot/Helpers/WindowWrapper.cs | 2 +- Greenshot/Memento/AddElementMemento.cs | 23 +- Greenshot/Memento/ChangeFieldHolderMemento.cs | 4 +- Greenshot/Memento/DeleteElementMemento.cs | 2 +- .../DrawableContainerBoundsChangeMemento.cs | 4 +- Greenshot/Memento/TextChangeMemento.cs | 2 +- Greenshot/Processors/TitleFixProcessor.cs | 4 +- GreenshotBoxPlugin/BoxCredentials.cs | 1 - GreenshotBoxPlugin/BoxDestination.cs | 3 - GreenshotBoxPlugin/Forms/SettingsForm.cs | 6 - GreenshotPlugin/Controls/AnimatingForm.cs | 36 +- GreenshotPlugin/Controls/BackgroundForm.cs | 12 +- .../Controls/ExtendedWebBrowser.cs | 4 +- .../Controls/FormWithoutActivation.cs | 2 +- GreenshotPlugin/Controls/GreenshotButton.cs | 2 +- GreenshotPlugin/Controls/GreenshotCheckBox.cs | 12 +- .../Controls/GreenshotColumnSorter.cs | 53 +- GreenshotPlugin/Controls/GreenshotComboBox.cs | 35 +- GreenshotPlugin/Controls/GreenshotForm.cs | 21 +- GreenshotPlugin/Controls/GreenshotGroupBox.cs | 2 +- GreenshotPlugin/Controls/GreenshotLabel.cs | 2 +- .../Controls/GreenshotRadioButton.cs | 2 +- GreenshotPlugin/Controls/GreenshotTabPage.cs | 2 +- GreenshotPlugin/Controls/GreenshotTextBox.cs | 12 +- .../Controls/GreenshotToolDropDownButton.cs | 2 +- .../Controls/GreenshotToolStripButton.cs | 2 +- .../Controls/GreenshotToolStripLabel.cs | 2 +- .../Controls/GreenshotToolStripMenuItem.cs | 2 +- GreenshotPlugin/Controls/HotkeyControl.cs | 23 +- .../Controls/IGreenshotConfigBindable.cs | 1 - .../Controls/IGreenshotLanguageBindable.cs | 1 - GreenshotPlugin/Controls/OAuthLoginForm.cs | 8 +- GreenshotPlugin/Controls/PleaseWaitForm.cs | 5 +- GreenshotPlugin/Controls/QualityDialog.cs | 3 +- .../Controls/SaveImageFileDialog.cs | 124 ++- GreenshotPlugin/Controls/ThumbnailForm.cs | 31 +- GreenshotPlugin/Core/AbstractDestination.cs | 5 +- GreenshotPlugin/Core/AccessibleHelper.cs | 2 +- GreenshotPlugin/Core/AnimationHelpers.cs | 178 ++-- GreenshotPlugin/Core/Cache.cs | 10 +- GreenshotPlugin/Core/ClipboardHelper.cs | 8 +- GreenshotPlugin/Core/CoreConfiguration.cs | 3 + GreenshotPlugin/Core/CredentialsHelper.cs | 10 +- GreenshotPlugin/Core/Effects.cs | 35 +- GreenshotPlugin/Core/EventDelay.cs | 4 +- GreenshotPlugin/Core/FastBitmap.cs | 6 +- GreenshotPlugin/Core/FilenameHelper.cs | 20 +- GreenshotPlugin/Core/GreenshotResources.cs | 2 +- GreenshotPlugin/Core/ImageHelper.cs | 30 +- GreenshotPlugin/Core/ImageOutput.cs | 2 +- GreenshotPlugin/Core/InterfaceUtils.cs | 2 +- GreenshotPlugin/Core/JSONHelper.cs | 1 - GreenshotPlugin/Core/Language.cs | 22 +- GreenshotPlugin/Core/LogHelper.cs | 2 +- GreenshotPlugin/Core/NetworkHelper.cs | 20 +- GreenshotPlugin/Core/OAuthHelper.cs | 5 +- GreenshotPlugin/Core/PluginUtils.cs | 4 +- GreenshotPlugin/Core/QuantizerHelper.cs | 18 +- GreenshotPlugin/Core/SourceForgeHelper.cs | 3 +- GreenshotPlugin/Core/StringExtensions.cs | 1 - GreenshotPlugin/Core/WindowCapture.cs | 4 +- GreenshotPlugin/Core/WindowsHelper.cs | 32 +- GreenshotPlugin/IEInterop/IHTMLBodyElement.cs | 2 +- .../IEInterop/IHTMLCurrentStyle.cs | 2 +- GreenshotPlugin/IEInterop/IHTMLDocument.cs | 2 +- GreenshotPlugin/IEInterop/IHTMLDocument2.cs | 2 +- GreenshotPlugin/IEInterop/IHTMLDocument3.cs | 2 +- GreenshotPlugin/IEInterop/IHTMLDocument4.cs | 2 +- GreenshotPlugin/IEInterop/IHTMLDocument5.cs | 2 +- GreenshotPlugin/IEInterop/IHTMLElement.cs | 2 +- GreenshotPlugin/IEInterop/IHTMLElement2.cs | 2 +- .../IEInterop/IHTMLElementCollection.cs | 2 +- GreenshotPlugin/IEInterop/IHTMLFrameBase.cs | 2 +- .../IEInterop/IHTMLFramesCollection2.cs | 2 +- GreenshotPlugin/IEInterop/IHTMLRect.cs | 2 +- GreenshotPlugin/IEInterop/IHTMLScreen.cs | 2 +- GreenshotPlugin/IEInterop/IHTMLScreen2.cs | 2 +- .../IEInterop/IHTMLSelectionObject.cs | 2 +- GreenshotPlugin/IEInterop/IHTMLStyle.cs | 2 +- GreenshotPlugin/IEInterop/IHTMLTxtRange.cs | 2 +- GreenshotPlugin/IEInterop/IHTMLWindow2.cs | 2 +- GreenshotPlugin/IEInterop/IHTMLWindow3.cs | 2 +- GreenshotPlugin/IEInterop/IHTMLWindow4.cs | 2 +- GreenshotPlugin/IEInterop/IWebBrowser2.cs | 2 +- GreenshotPlugin/IniFile/IniConfig.cs | 16 +- GreenshotPlugin/IniFile/IniReader.cs | 4 +- GreenshotPlugin/IniFile/IniSection.cs | 4 +- GreenshotPlugin/IniFile/IniValue.cs | 20 +- .../Interfaces/Forms/ImageEditor.cs | 7 +- GreenshotPlugin/Interfaces/Generic.cs | 1 - GreenshotPlugin/Interfaces/IDestination.cs | 12 +- GreenshotPlugin/Interfaces/IProcessor.cs | 3 - .../Interfaces/Plugin/PluginInterfaces.cs | 5 +- GreenshotPlugin/Interop/Base.cs | 2 - GreenshotPlugin/Interop/COMWrapper.cs | 73 +- GreenshotPlugin/Interop/ComProgIdAttribute.cs | 2 +- GreenshotPlugin/Interop/IAppVisibility.cs | 1 - GreenshotPlugin/Properties/AssemblyInfo.cs | 1 - .../UnmanagedHelpers/Enumerations.cs | 74 +- GreenshotPlugin/UnmanagedHelpers/GDI32.cs | 81 +- GreenshotPlugin/UnmanagedHelpers/GDIplus.cs | 27 +- GreenshotPlugin/UnmanagedHelpers/Shell32.cs | 47 +- GreenshotPlugin/UnmanagedHelpers/User32.cs | 42 +- 171 files changed, 1607 insertions(+), 1769 deletions(-) diff --git a/Greenshot/Configuration/EditorConfiguration.cs b/Greenshot/Configuration/EditorConfiguration.cs index 4c805e5ce..3d3240273 100644 --- a/Greenshot/Configuration/EditorConfiguration.cs +++ b/Greenshot/Configuration/EditorConfiguration.cs @@ -73,7 +73,7 @@ namespace Greenshot.Configuration { /// Type of the class for which to create the field /// 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) { string requestingTypeName = requestingType.Name; diff --git a/Greenshot/Controls/BindableToolStripButton.cs b/Greenshot/Controls/BindableToolStripButton.cs index 5641a9c27..a9f41b1a3 100644 --- a/Greenshot/Controls/BindableToolStripButton.cs +++ b/Greenshot/Controls/BindableToolStripButton.cs @@ -36,7 +36,8 @@ namespace Greenshot.Controls { set; } - public BindableToolStripButton() :base() { + public BindableToolStripButton() + { CheckedChanged += BindableToolStripButton_CheckedChanged; } diff --git a/Greenshot/Controls/BindableToolStripComboBox.cs b/Greenshot/Controls/BindableToolStripComboBox.cs index 192e25ecb..f65188a11 100644 --- a/Greenshot/Controls/BindableToolStripComboBox.cs +++ b/Greenshot/Controls/BindableToolStripComboBox.cs @@ -36,7 +36,8 @@ namespace Greenshot.Controls { set; } - public BindableToolStripComboBox() :base() { + public BindableToolStripComboBox() + { SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged; } diff --git a/Greenshot/Controls/BindableToolStripDropDownButton.cs b/Greenshot/Controls/BindableToolStripDropDownButton.cs index d32b2453d..57cb593b4 100644 --- a/Greenshot/Controls/BindableToolStripDropDownButton.cs +++ b/Greenshot/Controls/BindableToolStripDropDownButton.cs @@ -38,9 +38,6 @@ namespace Greenshot.Controls { set; } - public BindableToolStripDropDownButton() { - } - public object SelectedTag { get { if(Tag==null && DropDownItems.Count>0) Tag=DropDownItems[0].Tag; return Tag; } set { AdoptFromTag(value); } diff --git a/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs b/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs index 6c18554da..d8c8ef68c 100644 --- a/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs +++ b/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs @@ -30,7 +30,7 @@ namespace Greenshot.Controls { /// ToolStripProfessionalRenderer which draws the Check correctly when the icons are larger /// public class ContextMenuToolStripProfessionalRenderer : ToolStripProfessionalRenderer { - private static CoreConfiguration coreConfiguration = IniConfig.GetIniSection(); + private static readonly CoreConfiguration coreConfiguration = IniConfig.GetIniSection(); private static Image scaledCheckbox; protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) { diff --git a/Greenshot/Controls/FontFamilyComboBox.cs b/Greenshot/Controls/FontFamilyComboBox.cs index 410c87402..b832247c4 100644 --- a/Greenshot/Controls/FontFamilyComboBox.cs +++ b/Greenshot/Controls/FontFamilyComboBox.cs @@ -41,12 +41,16 @@ namespace Greenshot.Controls { } } - public FontFamilyComboBox() : base() { - ComboBox.DataSource = FontFamily.Families; - ComboBox.DisplayMember = "Name"; - SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged; - ComboBox.DrawMode = DrawMode.OwnerDrawFixed; - ComboBox.DrawItem += ComboBox_DrawItem; + public FontFamilyComboBox() + { + if (ComboBox != null) + { + ComboBox.DataSource = FontFamily.Families; + ComboBox.DisplayMember = "Name"; + SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged; + ComboBox.DrawMode = DrawMode.OwnerDrawFixed; + ComboBox.DrawItem += ComboBox_DrawItem; + } } void ComboBox_DrawItem(object sender, DrawItemEventArgs e) { @@ -58,7 +62,7 @@ namespace Greenshot.Controls { if (e.Index > -1) { 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)) { fontStyle = FontStyle.Bold; } else if (fontFamily.IsStyleAvailable(FontStyle.Italic)) { @@ -70,10 +74,16 @@ namespace Greenshot.Controls { } } 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) + { + DrawText(e.Graphics, FontFamily.GenericSansSerif, FontStyle.Regular, e.Bounds, fontFamily.Name); + } } } // Uncomment this if you actually like the way the focus rectangle looks @@ -89,7 +99,7 @@ namespace Greenshot.Controls { /// /// 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()) { stringFormat.LineAlignment = StringAlignment.Center; diff --git a/Greenshot/Controls/MenuStripEx.cs b/Greenshot/Controls/MenuStripEx.cs index aa880f06e..5400260a0 100644 --- a/Greenshot/Controls/MenuStripEx.cs +++ b/Greenshot/Controls/MenuStripEx.cs @@ -32,11 +32,9 @@ namespace Greenshot.Controls { 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. /// @@ -45,17 +43,17 @@ namespace Greenshot.Controls { /// 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/Controls/NonJumpingPanel.cs b/Greenshot/Controls/NonJumpingPanel.cs index 8392b9219..93f2f713c 100644 --- a/Greenshot/Controls/NonJumpingPanel.cs +++ b/Greenshot/Controls/NonJumpingPanel.cs @@ -19,14 +19,13 @@ * 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/ + /// public class NonJumpingPanel : Panel { protected override Point ScrollToControl(Control activeControl) { // Returning the current location prevents the panel from diff --git a/Greenshot/Controls/Pipette.cs b/Greenshot/Controls/Pipette.cs index 6aeccf9b5..5a730c4b4 100644 --- a/Greenshot/Controls/Pipette.cs +++ b/Greenshot/Controls/Pipette.cs @@ -34,7 +34,7 @@ namespace Greenshot.Controls { 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; @@ -111,10 +111,14 @@ namespace Greenshot.Controls { /// /// MouseEventArgs protected override void OnMouseUp(MouseEventArgs e) { - if (e.Button == MouseButtons.Left) { + if (e.Button == MouseButtons.Left) + { //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/Controls/ToolStripEx.cs b/Greenshot/Controls/ToolStripEx.cs index 3a32224c3..2ce378d3f 100644 --- a/Greenshot/Controls/ToolStripEx.cs +++ b/Greenshot/Controls/ToolStripEx.cs @@ -32,11 +32,9 @@ namespace Greenshot.Controls { 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. /// @@ -46,17 +44,17 @@ namespace Greenshot.Controls { 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/Destinations/ClipboardDestination.cs b/Greenshot/Destinations/ClipboardDestination.cs index 25476f64e..5638b7fd1 100644 --- a/Greenshot/Destinations/ClipboardDestination.cs +++ b/Greenshot/Destinations/ClipboardDestination.cs @@ -25,16 +25,12 @@ using System.Windows.Forms; using Greenshot.Configuration; using GreenshotPlugin.Core; using Greenshot.Plugin; -using Greenshot.IniFile; -using log4net; namespace Greenshot.Destinations { /// /// Description of ClipboardDestination. /// public class ClipboardDestination : AbstractDestination { - private static ILog LOG = LogManager.GetLogger(typeof(ClipboardDestination)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); public const string DESIGNATION = "Clipboard"; public override string Designation { diff --git a/Greenshot/Destinations/EditorDestination.cs b/Greenshot/Destinations/EditorDestination.cs index 0aaed76a2..2f5234705 100644 --- a/Greenshot/Destinations/EditorDestination.cs +++ b/Greenshot/Destinations/EditorDestination.cs @@ -32,11 +32,11 @@ namespace Greenshot.Destinations { /// Description of EditorDestination. /// public class EditorDestination : AbstractDestination { - private static ILog LOG = LogManager.GetLogger(typeof(EditorDestination)); - private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); + private static readonly ILog LOG = LogManager.GetLogger(typeof(EditorDestination)); + private static readonly EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); public const string DESIGNATION = "Editor"; - private IImageEditor editor = null; - private static Image greenshotIcon = GreenshotResources.getGreenshotIcon().ToBitmap(); + private readonly IImageEditor editor; + private static readonly Image greenshotIcon = GreenshotResources.getGreenshotIcon().ToBitmap(); public EditorDestination() { } @@ -79,8 +79,8 @@ namespace Greenshot.Destinations { } public override IEnumerable DynamicDestinations() { - foreach (IImageEditor editor in ImageEditorForm.Editors) { - yield return new EditorDestination(editor); + foreach (IImageEditor someEditor in ImageEditorForm.Editors) { + yield return new EditorDestination(someEditor); } } diff --git a/Greenshot/Destinations/EmailDestination.cs b/Greenshot/Destinations/EmailDestination.cs index b82b233b0..16dcf0866 100644 --- a/Greenshot/Destinations/EmailDestination.cs +++ b/Greenshot/Destinations/EmailDestination.cs @@ -36,9 +36,9 @@ namespace Greenshot.Destinations { public class EmailDestination : AbstractDestination { private static ILog LOG = LogManager.GetLogger(typeof(EmailDestination)); private static CoreConfiguration conf = IniConfig.GetIniSection(); - private static Image mailIcon = GreenshotResources.getImage("Email.Image"); - private static bool isActiveFlag = false; - private static string mapiClient = null; + private static readonly Image mailIcon = GreenshotResources.getImage("Email.Image"); + private static bool isActiveFlag; + private static string mapiClient; public const string DESIGNATION = "EMail"; static EmailDestination() { diff --git a/Greenshot/Destinations/FileDestination.cs b/Greenshot/Destinations/FileDestination.cs index 24af9bd1d..6b2c0b24d 100644 --- a/Greenshot/Destinations/FileDestination.cs +++ b/Greenshot/Destinations/FileDestination.cs @@ -35,8 +35,8 @@ namespace Greenshot.Destinations { /// Description of FileSaveAsDestination. /// public class FileDestination : AbstractDestination { - private static ILog LOG = LogManager.GetLogger(typeof(FileDestination)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly ILog LOG = LogManager.GetLogger(typeof(FileDestination)); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); public const string DESIGNATION = "FileNoDialog"; public override string Designation { @@ -103,20 +103,23 @@ namespace Greenshot.Destinations { LOG.InfoFormat("Not overwriting: {0}", ex1.Message); // when we don't allow to overwrite present a new SaveWithDialog fullPath = ImageOutput.SaveWithDialog(surface, captureDetails); - outputMade = (fullPath != null); + outputMade = fullPath != null; } catch (Exception ex2) { LOG.Error("Error saving screenshot!", ex2); // Show the problem MessageBox.Show(Language.GetString(LangKey.error_save), Language.GetString(LangKey.error)); // when save failed we present a SaveWithDialog fullPath = ImageOutput.SaveWithDialog(surface, captureDetails); - outputMade = (fullPath != null); + outputMade = fullPath != null; } // Don't overwrite filename if no output is made if (outputMade) { exportInformation.ExportMade = outputMade; exportInformation.Filepath = fullPath; - captureDetails.Filename = fullPath; + if (captureDetails != null) + { + captureDetails.Filename = fullPath; + } conf.OutputFileAsFullpath = fullPath; } diff --git a/Greenshot/Destinations/FileWithDialogDestination.cs b/Greenshot/Destinations/FileWithDialogDestination.cs index e14b804b6..d5e76ebfb 100644 --- a/Greenshot/Destinations/FileWithDialogDestination.cs +++ b/Greenshot/Destinations/FileWithDialogDestination.cs @@ -34,7 +34,7 @@ namespace Greenshot.Destinations { /// public class FileWithDialogDestination : AbstractDestination { private static ILog LOG = LogManager.GetLogger(typeof(FileWithDialogDestination)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); public const string DESIGNATION = "FileDialog"; public override string Designation { diff --git a/Greenshot/Destinations/PrinterDestination.cs b/Greenshot/Destinations/PrinterDestination.cs index bc4ce8af0..ec37b8bcf 100644 --- a/Greenshot/Destinations/PrinterDestination.cs +++ b/Greenshot/Destinations/PrinterDestination.cs @@ -28,18 +28,14 @@ using Greenshot.Configuration; using GreenshotPlugin.Core; using Greenshot.Plugin; using Greenshot.Helpers; -using Greenshot.IniFile; -using log4net; namespace Greenshot.Destinations { /// /// Description of PrinterDestination. /// public class PrinterDestination : AbstractDestination { - private static ILog LOG = LogManager.GetLogger(typeof(PrinterDestination)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); public const string DESIGNATION = "Printer"; - public string printerName = null; + public string printerName; public PrinterDestination() { } diff --git a/Greenshot/Drawing/ArrowContainer.cs b/Greenshot/Drawing/ArrowContainer.cs index f1c65ff53..57c2fe8c1 100644 --- a/Greenshot/Drawing/ArrowContainer.cs +++ b/Greenshot/Drawing/ArrowContainer.cs @@ -79,7 +79,7 @@ namespace Greenshot.Drawing { Top + currentStep + Height); currentStep++; - alpha = alpha - (basealpha / steps); + alpha = alpha - basealpha / steps; } } diff --git a/Greenshot/Drawing/CursorContainer.cs b/Greenshot/Drawing/CursorContainer.cs index 3911d5940..2b5969c92 100644 --- a/Greenshot/Drawing/CursorContainer.cs +++ b/Greenshot/Drawing/CursorContainer.cs @@ -33,7 +33,7 @@ namespace Greenshot.Drawing { /// [Serializable] public class CursorContainer : DrawableContainer, ICursorContainer { - private static ILog LOG = LogManager.GetLogger(typeof(CursorContainer)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(CursorContainer)); protected Cursor cursor; diff --git a/Greenshot/Drawing/DrawableContainer.cs b/Greenshot/Drawing/DrawableContainer.cs index aa4ffce43..9b3a10952 100644 --- a/Greenshot/Drawing/DrawableContainer.cs +++ b/Greenshot/Drawing/DrawableContainer.cs @@ -46,10 +46,8 @@ namespace Greenshot.Drawing { public abstract class DrawableContainer : AbstractFieldHolderWithChildren, IDrawableContainer { private static readonly ILog LOG = LogManager.GetLogger(typeof(DrawableContainer)); protected static readonly EditorConfiguration EditorConfig = IniConfig.GetIniSection(); - 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; @@ -305,7 +303,7 @@ namespace Greenshot.Drawing { Left = _parent.Width - Width - lineThickness/2; } if (horizontalAlignment == HorizontalAlignment.Center) { - Left = (_parent.Width / 2) - (Width / 2) - lineThickness/2; + Left = _parent.Width / 2 - Width / 2 - lineThickness/2; } if (verticalAlignment == VerticalAlignment.TOP) { @@ -315,7 +313,7 @@ namespace Greenshot.Drawing { Top = _parent.Height - Height - lineThickness/2; } if (verticalAlignment == VerticalAlignment.CENTER) { - Top = (_parent.Height / 2) - (Height / 2) - lineThickness/2; + Top = _parent.Height / 2 - Height / 2 - lineThickness/2; } } @@ -455,7 +453,7 @@ namespace Greenshot.Drawing { } else { Status = EditStatus.MOVING; } - isMadeUndoable = false; + _isMadeUndoable = false; } private void GripperMouseUp(object sender, MouseEventArgs e) { @@ -463,7 +461,7 @@ namespace Greenshot.Drawing { if (originatingGripper != _targetGripper) { _boundsBeforeResize = Rectangle.Empty; _boundsAfterResize = RectangleF.Empty; - isMadeUndoable = false; + _isMadeUndoable = false; } Status = EditStatus.IDLE; Invalidate(); @@ -478,9 +476,9 @@ namespace Greenshot.Drawing { TargetGripperMove(absX, absY); } 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); } @@ -699,6 +697,8 @@ namespace Greenshot.Drawing { } 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/Drawing/DrawableContainerList.cs b/Greenshot/Drawing/DrawableContainerList.cs index 570949a40..46daf9773 100644 --- a/Greenshot/Drawing/DrawableContainerList.cs +++ b/Greenshot/Drawing/DrawableContainerList.cs @@ -322,7 +322,7 @@ namespace Greenshot.Drawing { if (!elements.Contains(dc)) { continue; } - if (Count > (i+1) && !elements.Contains(this[i+1])) { + if (Count > i+1 && !elements.Contains(this[i+1])) { SwapElements(i,i+1); } } @@ -468,7 +468,7 @@ namespace Greenshot.Drawing { // Copy item = new ToolStripMenuItem(Language.GetString(LangKey.editor_copytoclipboard)); - item.Image = ((Image)(editorFormResources.GetObject("copyToolStripMenuItem.Image"))); + item.Image = (Image)editorFormResources.GetObject("copyToolStripMenuItem.Image"); item.Click += delegate { ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), this); }; @@ -476,7 +476,7 @@ namespace Greenshot.Drawing { // Cut item = new ToolStripMenuItem(Language.GetString(LangKey.editor_cuttoclipboard)); - item.Image = ((Image)(editorFormResources.GetObject("btnCut.Image"))); + item.Image = (Image)editorFormResources.GetObject("btnCut.Image"); item.Click += delegate { ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), this); List containersToDelete = new List(); @@ -492,7 +492,7 @@ namespace Greenshot.Drawing { // Delete item = new ToolStripMenuItem(Language.GetString(LangKey.editor_deleteelement)); - item.Image = ((Image)(editorFormResources.GetObject("removeObjectToolStripMenuItem.Image"))); + item.Image = (Image)editorFormResources.GetObject("removeObjectToolStripMenuItem.Image"); item.Click += delegate { List containersToDelete = new List(); foreach(var drawableContainer in this) { diff --git a/Greenshot/Drawing/EllipseContainer.cs b/Greenshot/Drawing/EllipseContainer.cs index caf41824b..c4fe278e1 100644 --- a/Greenshot/Drawing/EllipseContainer.cs +++ b/Greenshot/Drawing/EllipseContainer.cs @@ -59,12 +59,15 @@ namespace Greenshot.Drawing { /// /// 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))) { int basealpha = 100; diff --git a/Greenshot/Drawing/Fields/AbstractFieldHolder.cs b/Greenshot/Drawing/Fields/AbstractFieldHolder.cs index 0f8df4937..4bb0316fb 100644 --- a/Greenshot/Drawing/Fields/AbstractFieldHolder.cs +++ b/Greenshot/Drawing/Fields/AbstractFieldHolder.cs @@ -34,7 +34,7 @@ namespace Greenshot.Drawing.Fields { [Serializable] public abstract class AbstractFieldHolder : IFieldHolder { private static readonly ILog LOG = LogManager.GetLogger(typeof(AbstractFieldHolder)); - private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); + private static readonly EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); /// /// called when a field's value has changed @@ -50,10 +50,8 @@ namespace Greenshot.Drawing.Fields { // 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) { fieldsByType = new Dictionary(); diff --git a/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs b/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs index b919edd9b..3114ffc46 100644 --- a/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs +++ b/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs @@ -30,8 +30,7 @@ namespace Greenshot.Drawing.Fields { /// [Serializable()] public abstract class AbstractFieldHolderWithChildren : AbstractFieldHolder { - - FieldChangedEventHandler fieldChangedEventHandler; + readonly FieldChangedEventHandler fieldChangedEventHandler; [NonSerialized] private EventHandler childrenChanged; diff --git a/Greenshot/Drawing/Fields/Binding/AbstractBindingConverter.cs b/Greenshot/Drawing/Fields/Binding/AbstractBindingConverter.cs index da43dd6f3..5c31e0286 100644 --- a/Greenshot/Drawing/Fields/Binding/AbstractBindingConverter.cs +++ b/Greenshot/Drawing/Fields/Binding/AbstractBindingConverter.cs @@ -26,8 +26,6 @@ namespace Greenshot.Drawing.Fields.Binding { /// public abstract class AbstractBindingConverter : IBindingConverter { - public AbstractBindingConverter() {} - public object convert(object o) { if(o == null) { return null; diff --git a/Greenshot/Drawing/Fields/Binding/BidirectionalBinding.cs b/Greenshot/Drawing/Fields/Binding/BidirectionalBinding.cs index 21ebeb1ef..ca109731a 100644 --- a/Greenshot/Drawing/Fields/Binding/BidirectionalBinding.cs +++ b/Greenshot/Drawing/Fields/Binding/BidirectionalBinding.cs @@ -29,35 +29,35 @@ namespace Greenshot.Drawing.Fields.Binding { /// behavior (e.g. when binding to a /// 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; + private bool _updatingField; + private IBindingConverter _converter; + private readonly IBindingValidator _validator; /// /// Whether or not null values are passed on to the other object. /// protected bool AllowSynchronizeNull = true; - + /// /// 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; } /// @@ -69,7 +69,7 @@ namespace Greenshot.Drawing.Fields.Binding { /// Property of 2nd object to bind /// 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; } /// @@ -82,7 +82,7 @@ namespace Greenshot.Drawing.Fields.Binding { /// Property of 2nd object to bind /// 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; } /// @@ -96,46 +96,46 @@ namespace Greenshot.Drawing.Fields.Binding { /// taking care of converting the synchronized value to the correct target format and back /// 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)) { - updatingField = true; - synchronize(controlObject, controlPropertyName, fieldObject, fieldPropertyName); - updatingField = false; + if (!_updatingControl && e.PropertyName.Equals(_controlPropertyName)) { + _updatingField = true; + Synchronize(_controlObject, _controlPropertyName, _fieldObject, _fieldPropertyName); + _updatingField = false; } } public void FieldPropertyChanged(object sender, PropertyChangedEventArgs e) { - if (!updatingField && e.PropertyName.Equals(fieldPropertyName)) { - updatingControl = true; - synchronize(fieldObject, fieldPropertyName, controlObject, controlPropertyName); - updatingControl = false; + if (!_updatingField && e.PropertyName.Equals(_fieldPropertyName)) { + _updatingControl = true; + Synchronize(_fieldObject, _fieldPropertyName, _controlObject, _controlPropertyName); + _updatingControl = false; } } - private void synchronize(INotifyPropertyChanged sourceObject, string sourceProperty, INotifyPropertyChanged targetObject, string targetProperty) { - PropertyInfo targetPropertyInfo = resolvePropertyInfo(targetObject, targetProperty); - PropertyInfo sourcePropertyInfo = resolvePropertyInfo(sourceObject, sourceProperty); + private void Synchronize(INotifyPropertyChanged sourceObject, string sourceProperty, INotifyPropertyChanged targetObject, string targetProperty) { + 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) { - bValue = converter.convert(bValue); + if (_converter != null && bValue != null) { + 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()); for(int i=0; i @@ -41,13 +40,10 @@ namespace Greenshot.Drawing.Fields { /// public class FieldAggregator : AbstractFieldHolder { - private List boundContainers; - private bool internalUpdateRunning = false; - - enum Status {IDLE, BINDING, UPDATING}; - - private static readonly ILog LOG = LogManager.GetLogger(typeof(FieldAggregator)); - private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); + private readonly List boundContainers; + private bool internalUpdateRunning; + + private static readonly EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); public FieldAggregator() { foreach(FieldType fieldType in FieldType.Values) { diff --git a/Greenshot/Drawing/FilterContainer.cs b/Greenshot/Drawing/FilterContainer.cs index 630c5c35d..7e6b2336e 100644 --- a/Greenshot/Drawing/FilterContainer.cs +++ b/Greenshot/Drawing/FilterContainer.cs @@ -52,7 +52,7 @@ namespace Greenshot.Drawing { 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; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; @@ -69,7 +69,7 @@ namespace Greenshot.Drawing { 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/Drawing/Filters/AbstractFilter.cs b/Greenshot/Drawing/Filters/AbstractFilter.cs index cd1be85a2..e34f61008 100644 --- a/Greenshot/Drawing/Filters/AbstractFilter.cs +++ b/Greenshot/Drawing/Filters/AbstractFilter.cs @@ -41,7 +41,7 @@ namespace Greenshot.Drawing.Filters { remove{ propertyChanged -= value; } } - private bool invert = false; + private bool invert; public bool Invert { get { return invert; diff --git a/Greenshot/Drawing/Filters/BlurFilter.cs b/Greenshot/Drawing/Filters/BlurFilter.cs index 1b2e6ab68..1b9ddf5a0 100644 --- a/Greenshot/Drawing/Filters/BlurFilter.cs +++ b/Greenshot/Drawing/Filters/BlurFilter.cs @@ -18,6 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ + using System; using System.Drawing; using Greenshot.Drawing.Fields; @@ -25,13 +26,10 @@ using Greenshot.Plugin.Drawing; using GreenshotPlugin.Core; using GreenshotPlugin.UnmanagedHelpers; using System.Drawing.Drawing2D; -using log4net; namespace Greenshot.Drawing.Filters { [Serializable()] public class BlurFilter : AbstractFilter { - private static ILog LOG = LogManager.GetLogger(typeof(BlurFilter)); - public double previewQuality; public double PreviewQuality { get { return previewQuality; } @@ -43,7 +41,7 @@ namespace Greenshot.Drawing.Filters { 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); if (applyRect.Width == 0 || applyRect.Height == 0) { @@ -54,7 +52,7 @@ namespace Greenshot.Drawing.Filters { graphics.SetClip(applyRect); graphics.ExcludeClip(rect); } - if (GDIplus.isBlurPossible(blurRadius)) { + if (GDIplus.IsBlurPossible(blurRadius)) { GDIplus.DrawWithBlur(graphics, applyBitmap, applyRect, null, null, blurRadius, false); } else { using (IFastBitmap fastBitmap = FastBitmap.CreateCloneOf(applyBitmap, applyRect)) { @@ -63,7 +61,6 @@ namespace Greenshot.Drawing.Filters { } } graphics.Restore(state); - return; } } } diff --git a/Greenshot/Drawing/Filters/MagnifierFilter.cs b/Greenshot/Drawing/Filters/MagnifierFilter.cs index 23359546e..c9944b7c3 100644 --- a/Greenshot/Drawing/Filters/MagnifierFilter.cs +++ b/Greenshot/Drawing/Filters/MagnifierFilter.cs @@ -53,7 +53,7 @@ namespace Greenshot.Drawing.Filters { 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/Drawing/Filters/PixelizationFilter.cs b/Greenshot/Drawing/Filters/PixelizationFilter.cs index a7f13c096..78e49253f 100644 --- a/Greenshot/Drawing/Filters/PixelizationFilter.cs +++ b/Greenshot/Drawing/Filters/PixelizationFilter.cs @@ -37,7 +37,7 @@ namespace Greenshot.Drawing.Filters { 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 return; diff --git a/Greenshot/Drawing/FreehandContainer.cs b/Greenshot/Drawing/FreehandContainer.cs index b30937c2b..5294f5bd5 100644 --- a/Greenshot/Drawing/FreehandContainer.cs +++ b/Greenshot/Drawing/FreehandContainer.cs @@ -22,7 +22,6 @@ using Greenshot.Drawing.Fields; using Greenshot.Helpers; using Greenshot.Plugin.Drawing; -using log4net; using System; using System.Collections.Generic; using System.Drawing; @@ -35,15 +34,14 @@ namespace Greenshot.Drawing { /// [Serializable] public class FreehandContainer : DrawableContainer { - private static readonly ILog LOG = LogManager.GetLogger(typeof(FreehandContainer)); private static readonly float [] POINT_OFFSET = new float[]{0.5f, 0.25f, 0.75f}; [NonSerialized] 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 @@ -119,7 +117,7 @@ namespace Greenshot.Drawing { 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)); } if (GeometryHelper.Distance2D(lastMouse.X, lastMouse.Y, mouseX, mouseY) >= EditorConfig.FreehandSensitivity) { @@ -232,7 +230,7 @@ namespace Greenshot.Drawing { if (!myBounds.IsEmpty) { 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/Drawing/IconContainer.cs b/Greenshot/Drawing/IconContainer.cs index 86b82a46f..846ee3cde 100644 --- a/Greenshot/Drawing/IconContainer.cs +++ b/Greenshot/Drawing/IconContainer.cs @@ -31,7 +31,7 @@ namespace Greenshot.Drawing { /// [Serializable] public class IconContainer : DrawableContainer, IIconContainer { - private static ILog LOG = LogManager.GetLogger(typeof(IconContainer)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(IconContainer)); protected Icon icon; diff --git a/Greenshot/Drawing/ImageContainer.cs b/Greenshot/Drawing/ImageContainer.cs index b9f9c6dc3..25894af74 100644 --- a/Greenshot/Drawing/ImageContainer.cs +++ b/Greenshot/Drawing/ImageContainer.cs @@ -34,7 +34,7 @@ namespace Greenshot.Drawing { /// [Serializable] public class ImageContainer : DrawableContainer, IImageContainer { - private static ILog LOG = LogManager.GetLogger(typeof(ImageContainer)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(ImageContainer)); private Image image; diff --git a/Greenshot/Drawing/LineContainer.cs b/Greenshot/Drawing/LineContainer.cs index 4189134ac..b11486901 100644 --- a/Greenshot/Drawing/LineContainer.cs +++ b/Greenshot/Drawing/LineContainer.cs @@ -86,7 +86,7 @@ namespace Greenshot.Drawing { Top + currentStep + Height); currentStep++; - alpha = alpha - (basealpha / steps); + alpha = alpha - basealpha / steps; } } } diff --git a/Greenshot/Drawing/RectangleContainer.cs b/Greenshot/Drawing/RectangleContainer.cs index c235346c5..933adb180 100644 --- a/Greenshot/Drawing/RectangleContainer.cs +++ b/Greenshot/Drawing/RectangleContainer.cs @@ -69,7 +69,7 @@ namespace Greenshot.Drawing { 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 int basealpha = 100; @@ -86,7 +86,7 @@ namespace Greenshot.Drawing { rect.Height); graphics.DrawRectangle(shadowPen, shadowRect); currentStep++; - alpha = alpha - (basealpha / steps); + alpha = alpha - basealpha / steps; } } } diff --git a/Greenshot/Drawing/RoundedRectangle.cs b/Greenshot/Drawing/RoundedRectangle.cs index 51ea777ff..1eaa7485f 100644 --- a/Greenshot/Drawing/RoundedRectangle.cs +++ b/Greenshot/Drawing/RoundedRectangle.cs @@ -35,13 +35,13 @@ namespace Greenshot.Drawing { public static GraphicsPath Create2(int x, int y, int width, int height, int radius) { GraphicsPath gp = new GraphicsPath(); - gp.AddLine(x + radius, y, x + width - (radius * 2), y); // Line - gp.AddArc(x + width - (radius * 2), y, radius * 2, radius * 2, 270, 90); // Corner - gp.AddLine(x + width, y + radius, x + width, y + height - (radius * 2)); // Line - gp.AddArc(x + width - (radius * 2), y + height - (radius * 2), radius * 2, radius * 2, 0, 90); // Corner - gp.AddLine(x + width - (radius * 2), y + height, x + radius, y + height); // Line - gp.AddArc(x, y + height - (radius * 2), radius * 2, radius * 2, 90, 90); // Corner - gp.AddLine(x, y + height - (radius * 2), x, y + radius); // Line + gp.AddLine(x + radius, y, x + width - radius * 2, y); // Line + gp.AddArc(x + width - radius * 2, y, radius * 2, radius * 2, 270, 90); // Corner + gp.AddLine(x + width, y + radius, x + width, y + height - radius * 2); // Line + gp.AddArc(x + width - radius * 2, y + height - radius * 2, radius * 2, radius * 2, 0, 90); // Corner + gp.AddLine(x + width - radius * 2, y + height, x + radius, y + height); // Line + gp.AddArc(x, y + height - radius * 2, radius * 2, radius * 2, 90, 90); // Corner + gp.AddLine(x, y + height - radius * 2, x, y + radius); // Line gp.AddArc(x, y, radius * 2, radius * 2, 180, 90); // Corner gp.CloseFigure(); diff --git a/Greenshot/Drawing/SpeechbubbleContainer.cs b/Greenshot/Drawing/SpeechbubbleContainer.cs index 64ede51e8..eef5e8ef6 100644 --- a/Greenshot/Drawing/SpeechbubbleContainer.cs +++ b/Greenshot/Drawing/SpeechbubbleContainer.cs @@ -180,7 +180,7 @@ namespace Greenshot.Drawing { 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 @@ -192,10 +192,10 @@ namespace Greenshot.Drawing { 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); } @@ -223,7 +223,7 @@ namespace Greenshot.Drawing { 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) { @@ -253,7 +253,7 @@ namespace Greenshot.Drawing { graphics.DrawPath(shadowPen, bubbleClone); } currentStep++; - alpha = alpha - (basealpha / steps); + alpha = alpha - basealpha / steps; } } } diff --git a/Greenshot/Drawing/StepLabelContainer.cs b/Greenshot/Drawing/StepLabelContainer.cs index 79583c5ab..e42076c82 100644 --- a/Greenshot/Drawing/StepLabelContainer.cs +++ b/Greenshot/Drawing/StepLabelContainer.cs @@ -118,7 +118,7 @@ namespace Greenshot.Drawing { /// This makes it possible for the label to be placed exactly in the middle of the pointer. /// 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); } /// @@ -146,8 +146,8 @@ namespace Greenshot.Drawing { 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; } @@ -167,7 +167,7 @@ namespace Greenshot.Drawing { 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/Drawing/Surface.cs b/Greenshot/Drawing/Surface.cs index b28e2a86f..22c1aea93 100644 --- a/Greenshot/Drawing/Surface.cs +++ b/Greenshot/Drawing/Surface.cs @@ -46,9 +46,9 @@ namespace Greenshot.Drawing { /// Description of Surface. /// public class Surface : Control, ISurface { - private static ILog LOG = LogManager.GetLogger(typeof(Surface)); - public static int Count = 0; - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly ILog LOG = LogManager.GetLogger(typeof(Surface)); + public static int Count; + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); // Property to identify the Surface ID private Guid _uniqueId = Guid.NewGuid(); @@ -169,7 +169,7 @@ namespace Greenshot.Drawing { /// all selected elements, do not serialize /// [NonSerialized] - private DrawableContainerList selectedElements; + private readonly DrawableContainerList selectedElements; /// /// the element we are drawing with, do not serialize @@ -208,7 +208,7 @@ namespace Greenshot.Drawing { /// /// all stepLabels for the surface, needed with serialization /// - private List _stepLabels = new List(); + private readonly List _stepLabels = new List(); public void AddStepLabel(StepLabelContainer stepLabel) { _stepLabels.Add(stepLabel); @@ -225,7 +225,7 @@ namespace Greenshot.Drawing { public int CountStepLabels(IDrawableContainer stopAtContainer) { int number = 1; foreach (var possibleThis in _stepLabels) { - if (possibleThis == stopAtContainer) { + if (possibleThis.Equals(stopAtContainer)) { break; } if (IsOnSurface(possibleThis)) { @@ -1037,7 +1037,10 @@ namespace Greenshot.Drawing { _drawingElement = _undrawnElement; // 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)) { _drawingElement.Left = _mouseStart.X; @@ -1331,7 +1334,7 @@ namespace Greenshot.Drawing { /// public bool HasSelectedElements { get { - return (selectedElements != null && selectedElements.Count > 0); + return selectedElements != null && selectedElements.Count > 0; } } @@ -1387,6 +1390,10 @@ namespace Greenshot.Drawing { 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)){ DrawingMode = DrawingModes.None; @@ -1397,6 +1404,7 @@ namespace Greenshot.Drawing { } _cropContainer.Dispose(); _cropContainer = null; + break; } } } @@ -1423,7 +1431,7 @@ namespace Greenshot.Drawing { if (dcs != null) { // 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) { moveOffset = new Point(10, 10); diff --git a/Greenshot/Drawing/TextContainer.cs b/Greenshot/Drawing/TextContainer.cs index 110c40775..f02ecbf39 100644 --- a/Greenshot/Drawing/TextContainer.cs +++ b/Greenshot/Drawing/TextContainer.cs @@ -332,8 +332,8 @@ namespace Greenshot.Drawing { if (lineThickness <= 1) { 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) { @@ -415,7 +415,7 @@ namespace Greenshot.Drawing { /// /// 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) { int basealpha = 100; diff --git a/Greenshot/Forms/AboutForm.cs b/Greenshot/Forms/AboutForm.cs index 64934dea0..f330dcfd6 100644 --- a/Greenshot/Forms/AboutForm.cs +++ b/Greenshot/Forms/AboutForm.cs @@ -41,21 +41,21 @@ namespace Greenshot { /// The about form /// public partial class AboutForm : AnimatingBaseForm { - private static ILog LOG = LogManager.GetLogger(typeof(AboutForm)); - private Bitmap gBitmap; - private ColorAnimator backgroundAnimation; - private List pixels = new List(); - private List colorFlow = new List(); - private List pixelColors = new List(); - private Random rand = new Random(); - private readonly Color backColor = Color.FromArgb(61, 61, 61); - private readonly Color pixelColor = Color.FromArgb(138, 255, 0); + private static readonly ILog LOG = LogManager.GetLogger(typeof(AboutForm)); + private Bitmap _bitmap; + private readonly ColorAnimator _backgroundAnimation; + private readonly IList _pixels = new List(); + private readonly IList _colorFlow = new List(); + private readonly IList _pixelColors = new List(); + private readonly Random _rand = new Random(); + private readonly Color _backColor = Color.FromArgb(61, 61, 61); + private readonly Color _pixelColor = Color.FromArgb(138, 255, 0); // Variables used for the color-cycle - private int waitFrames = 0; - private int colorIndex = 0; - private int scrollCount = 0; - private bool hasAnimationsLeft; + private int _waitFrames; + private int _colorIndex; + private int _scrollCount; + private bool _hasAnimationsLeft; // Variables are used to define the location of the dots private const int w = 13; @@ -70,7 +70,7 @@ namespace Greenshot { /// /// The location of every dot in the "G" /// - private List gSpots = new List() { + private readonly List gSpots = new List() { // Top row new Point(p2, p1), // 0 new Point(p3, p1), // 1 @@ -116,15 +116,15 @@ namespace Greenshot { // 18 19 20 21 22 23 // The order in which we draw the dots & flow the collors. - List flowOrder = new List() { 4, 3, 2, 1, 0, 5, 6, 7, 8, 9, 10, 14, 15, 18, 19, 20, 21, 22, 23, 16, 17, 13, 12, 11 }; + readonly List flowOrder = new List() { 4, 3, 2, 1, 0, 5, 6, 7, 8, 9, 10, 14, 15, 18, 19, 20, 21, 22, 23, 16, 17, 13, 12, 11 }; /// /// Cleanup all the allocated resources /// private void Cleanup(object sender, EventArgs e) { - if (gBitmap != null) { - gBitmap.Dispose(); - gBitmap = null; + if (_bitmap != null) { + _bitmap.Dispose(); + _bitmap = null; } } @@ -144,22 +144,22 @@ namespace Greenshot { InitializeComponent(); // Only use double-buffering when we are NOT in a Terminal Server session - DoubleBuffered = !isTerminalServerSession; + DoubleBuffered = !IsTerminalServerSession; // Use the self drawn image, first we create the background to be the backcolor (as we animate from this) - gBitmap = ImageHelper.CreateEmpty(90, 90, PixelFormat.Format24bppRgb, BackColor, 96, 96); - pictureBox1.Image = gBitmap; + _bitmap = ImageHelper.CreateEmpty(90, 90, PixelFormat.Format24bppRgb, BackColor, 96, 96); + pictureBox1.Image = _bitmap; Version v = Assembly.GetExecutingAssembly().GetName().Version; // Format is like this: AssemblyVersion("Major.Minor.Build.Revision")] - lblTitle.Text = "Greenshot " + v.Major + "." + v.Minor + "." + v.Build + " Build " + v.Revision + (IniConfig.IsPortable ? " Portable" : "") + (" (" + OSInfo.Bits + " bit)"); + lblTitle.Text = "Greenshot " + v.Major + "." + v.Minor + "." + v.Build + " Build " + v.Revision + (IniConfig.IsPortable ? " Portable" : "") + (" (" + OSInfo.Bits) + " bit)"; //Random rand = new Random(); // Number of frames the pixel animation takes int frames = FramesForMillis(2000); // The number of frames the color-cycle waits before it starts - waitFrames = FramesForMillis(6000); + _waitFrames = FramesForMillis(6000); // Every pixel is created after pixelWaitFrames frames, which is increased in the loop. int pixelWaitFrames = FramesForMillis(2000); @@ -174,7 +174,7 @@ namespace Greenshot { int offset = (w - 2) / 2; // If the optimize for Terminal Server is set we make the animation without much ado - if (isTerminalServerSession) { + if (IsTerminalServerSession) { // No animation pixelAnimation = new RectangleAnimator(new Rectangle(gSpot.X, gSpot.Y, w - 2, w - 2), new Rectangle(gSpot.X, gSpot.Y, w - 2, w - 2), 1, EasingType.Cubic, EasingMode.EaseIn); } else { @@ -187,23 +187,23 @@ namespace Greenshot { // Increase the wait frames pixelWaitFrames += FramesForMillis(100); // Add to the list of to be animated pixels - pixels.Add(pixelAnimation); + _pixels.Add(pixelAnimation); // Add a color to the list for this pixel. - pixelColors.Add(pixelColor); + _pixelColors.Add(_pixelColor); } // Make sure the frame "loop" knows we have to animate - hasAnimationsLeft = true; + _hasAnimationsLeft = true; // Pixel Color cycle colors, here we use a pre-animated loop which stores the values. - ColorAnimator pixelColorAnimator = new ColorAnimator(pixelColor, Color.FromArgb(255, 255, 255), 6, EasingType.Quadratic, EasingMode.EaseIn); - pixelColorAnimator.QueueDestinationLeg(pixelColor, 6, EasingType.Quadratic, EasingMode.EaseOut); + ColorAnimator pixelColorAnimator = new ColorAnimator(_pixelColor, Color.FromArgb(255, 255, 255), 6, EasingType.Quadratic, EasingMode.EaseIn); + pixelColorAnimator.QueueDestinationLeg(_pixelColor, 6, EasingType.Quadratic, EasingMode.EaseOut); do { - colorFlow.Add(pixelColorAnimator.Current); + _colorFlow.Add(pixelColorAnimator.Current); pixelColorAnimator.Next(); - } while (pixelColorAnimator.hasNext); + } while (pixelColorAnimator.HasNext); // color animation for the background - backgroundAnimation = new ColorAnimator(BackColor, backColor, FramesForMillis(5000), EasingType.Linear, EasingMode.EaseIn); + _backgroundAnimation = new ColorAnimator(BackColor, _backColor, FramesForMillis(5000), EasingType.Linear, EasingMode.EaseIn); } /// @@ -227,63 +227,63 @@ namespace Greenshot { /// Called from the AnimatingForm, for every frame /// protected override void Animate() { - if (gBitmap == null) { + if (_bitmap == null) { return; } - if (!isTerminalServerSession) { + if (!IsTerminalServerSession) { // Color cycle - if (waitFrames != 0) { - waitFrames--; + if (_waitFrames != 0) { + _waitFrames--; // Check if there is something else to do, if not we return so we don't occupy the CPU - if (!hasAnimationsLeft) { + if (!_hasAnimationsLeft) { return; } - } else if (scrollCount < (pixelColors.Count + colorFlow.Count)) { + } else if (_scrollCount < _pixelColors.Count + _colorFlow.Count) { // Scroll colors, the scrollCount is the amount of pixels + the amount of colors to cycle. - for (int index = pixelColors.Count - 1; index > 0; index--) { - pixelColors[index] = pixelColors[index - 1]; + for (int index = _pixelColors.Count - 1; index > 0; index--) { + _pixelColors[index] = _pixelColors[index - 1]; } // Keep adding from the colors to cycle until there is nothing left - if (colorIndex < colorFlow.Count) { - pixelColors[0] = colorFlow[colorIndex++]; + if (_colorIndex < _colorFlow.Count) { + _pixelColors[0] = _colorFlow[_colorIndex++]; } - scrollCount++; + _scrollCount++; } else { // Reset values, wait X time for the next one - waitFrames = FramesForMillis(3000 + rand.Next(35000)); - colorIndex = 0; - scrollCount = 0; + _waitFrames = FramesForMillis(3000 + _rand.Next(35000)); + _colorIndex = 0; + _scrollCount = 0; // Check if there is something else to do, if not we return so we don't occupy the CPU - if (!hasAnimationsLeft) { + if (!_hasAnimationsLeft) { return; } } - } else if (!hasAnimationsLeft) { + } else if (!_hasAnimationsLeft) { return; } // Draw the "G" - using (Graphics graphics = Graphics.FromImage(gBitmap)) { + using (Graphics graphics = Graphics.FromImage(_bitmap)) { graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBilinear; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; - graphics.Clear(backgroundAnimation.Next()); + graphics.Clear(_backgroundAnimation.Next()); graphics.TranslateTransform(2, -2); graphics.RotateTransform(20); - using (SolidBrush brush = new SolidBrush(pixelColor)) { + using (SolidBrush brush = new SolidBrush(_pixelColor)) { int index = 0; // We asume there is nothing to animate in the next Animate loop - hasAnimationsLeft = false; + _hasAnimationsLeft = false; // Pixels of the G - foreach (RectangleAnimator pixel in pixels) { - brush.Color = pixelColors[index++]; + foreach (RectangleAnimator pixel in _pixels) { + brush.Color = _pixelColors[index++]; graphics.FillEllipse(brush, pixel.Current); // If a pixel still has frames left, the hasAnimationsLeft will be true - hasAnimationsLeft = hasAnimationsLeft | pixel.hasNext; + _hasAnimationsLeft = _hasAnimationsLeft | pixel.HasNext; pixel.Next(); } } diff --git a/Greenshot/Forms/CaptureForm.cs b/Greenshot/Forms/CaptureForm.cs index 528cd6515..3c6398ac5 100644 --- a/Greenshot/Forms/CaptureForm.cs +++ b/Greenshot/Forms/CaptureForm.cs @@ -61,9 +61,9 @@ namespace Greenshot.Forms { private int _mX; private int _mY; private Point _mouseMovePos = Point.Empty; - private Point _cursorPos = Point.Empty; - private CaptureMode _captureMode = CaptureMode.None; - private readonly List _windows = new List(); + private Point _cursorPos; + private CaptureMode _captureMode; + private readonly List _windows; private WindowDetails _selectedCaptureWindow; private bool _mouseDown; private Rectangle _captureRect = Rectangle.Empty; @@ -73,7 +73,7 @@ namespace Greenshot.Forms { private RectangleAnimator _windowAnimator; private RectangleAnimator _zoomAnimator; private readonly bool _isZoomerTransparent = Conf.ZoomerOpacity < 1; - private bool _isCtrlPressed = false; + private bool _isCtrlPressed; /// /// Property to access the selected capture rectangle @@ -153,7 +153,7 @@ namespace Greenshot.Forms { // InitializeComponent(); // Only double-buffer when we are not in a TerminalServerSession - DoubleBuffered = !isTerminalServerSession; + DoubleBuffered = !IsTerminalServerSession; Text = "Greenshot capture form"; // Make sure we never capture the captureform @@ -398,7 +398,7 @@ namespace Greenshot.Forms { if (animator == null) { return false; } - return animator.hasNext; + return animator.HasNext; } /// @@ -486,7 +486,7 @@ namespace Greenshot.Forms { invalidateRectangle = new Rectangle(x1,y1, x2-x1, y2-y1); Invalidate(invalidateRectangle); } else if (_captureMode != CaptureMode.Window) { - if (!isTerminalServerSession) { + if (!IsTerminalServerSession) { Rectangle allScreenBounds = WindowCapture.GetScreenBounds(); allScreenBounds.Location = WindowCapture.GetLocationRelativeToScreenBounds(allScreenBounds.Location); if (verticalMove) { @@ -570,7 +570,7 @@ namespace Greenshot.Forms { screenBounds.Location = WindowCapture.GetLocationRelativeToScreenBounds(screenBounds.Location); int relativeZoomSize = Math.Min(screenBounds.Width, screenBounds.Height) / 5; // Make sure the final size is a plural of 4, this makes it look better - relativeZoomSize = relativeZoomSize - (relativeZoomSize % 4); + relativeZoomSize = relativeZoomSize - relativeZoomSize % 4; Size zoomSize = new Size(relativeZoomSize, relativeZoomSize); Point zoomOffset = new Point(20, 20); @@ -652,9 +652,9 @@ namespace Greenshot.Forms { // Calculate some values int pixelThickness = destinationRectangle.Width / sourceRectangle.Width; int halfWidth = destinationRectangle.Width / 2; - int halfWidthEnd = (destinationRectangle.Width / 2) - (pixelThickness / 2); + int halfWidthEnd = destinationRectangle.Width / 2 - pixelThickness / 2; int halfHeight = destinationRectangle.Height / 2; - int halfHeightEnd = (destinationRectangle.Height / 2) - (pixelThickness / 2); + int halfHeightEnd = destinationRectangle.Height / 2 - pixelThickness / 2; int drawAtHeight = destinationRectangle.Y + halfHeight; int drawAtWidth = destinationRectangle.X + halfWidth; @@ -673,8 +673,8 @@ namespace Greenshot.Forms { graphics.DrawLine(pen, destinationRectangle.X + halfWidthEnd + 2 * padding, drawAtHeight, destinationRectangle.X + destinationRectangle.Width - padding, drawAtHeight); // Fix offset for drawing the white rectangle around the crosshair-lines - drawAtHeight -= (pixelThickness / 2); - drawAtWidth -= (pixelThickness / 2); + drawAtHeight -= pixelThickness / 2; + drawAtWidth -= pixelThickness / 2; // Fix off by one error with the DrawRectangle pixelThickness -= 1; // Change the color and the pen width @@ -762,7 +762,7 @@ namespace Greenshot.Forms { graphics.DrawPath(rulerPen, p); graphics.DrawString(captureWidth, rulerFont, rulerPen.Brush, fixedRect.X + (fixedRect.Width / 2 - hSpace / 2) + 3, fixedRect.Y - dist - 7); graphics.DrawLine(rulerPen, fixedRect.X, fixedRect.Y - dist, fixedRect.X + (fixedRect.Width / 2 - hSpace / 2), fixedRect.Y - dist); - graphics.DrawLine(rulerPen, fixedRect.X + (fixedRect.Width / 2 + hSpace / 2), fixedRect.Y - dist, fixedRect.X + fixedRect.Width, fixedRect.Y - dist); + graphics.DrawLine(rulerPen, fixedRect.X + fixedRect.Width / 2 + hSpace / 2, fixedRect.Y - dist, fixedRect.X + fixedRect.Width, fixedRect.Y - dist); graphics.DrawLine(rulerPen, fixedRect.X, fixedRect.Y - dist - 3, fixedRect.X, fixedRect.Y - dist + 3); graphics.DrawLine(rulerPen, fixedRect.X + fixedRect.Width, fixedRect.Y - dist - 3, fixedRect.X + fixedRect.Width, fixedRect.Y - dist + 3); } @@ -780,7 +780,7 @@ namespace Greenshot.Forms { graphics.DrawPath(rulerPen, p); graphics.DrawString(captureHeight, rulerFont, rulerPen.Brush, fixedRect.X - measureHeight.Width + 1, fixedRect.Y + (fixedRect.Height / 2 - vSpace / 2) + 2); graphics.DrawLine(rulerPen, fixedRect.X - dist, fixedRect.Y, fixedRect.X - dist, fixedRect.Y + (fixedRect.Height / 2 - vSpace / 2)); - graphics.DrawLine(rulerPen, fixedRect.X - dist, fixedRect.Y + (fixedRect.Height / 2 + vSpace / 2), fixedRect.X - dist, fixedRect.Y + fixedRect.Height); + graphics.DrawLine(rulerPen, fixedRect.X - dist, fixedRect.Y + fixedRect.Height / 2 + vSpace / 2, fixedRect.X - dist, fixedRect.Y + fixedRect.Height); graphics.DrawLine(rulerPen, fixedRect.X - dist - 3, fixedRect.Y, fixedRect.X - dist + 3, fixedRect.Y); graphics.DrawLine(rulerPen, fixedRect.X - dist - 3, fixedRect.Y + fixedRect.Height, fixedRect.X - dist + 3, fixedRect.Y + fixedRect.Height); } @@ -797,7 +797,7 @@ namespace Greenshot.Forms { string sizeText; if (_captureMode == CaptureMode.Region) { // correct the GUI width to real width for the shown size - sizeText = (_captureRect.Width + 1) + " x " + (_captureRect.Height + 1); + sizeText = _captureRect.Width + 1 + " x " + (_captureRect.Height + 1); } else { sizeText = _captureRect.Width + " x " + _captureRect.Height; } @@ -806,7 +806,7 @@ namespace Greenshot.Forms { SizeF extent = graphics.MeasureString( sizeText, sizeFont ); float hRatio = _captureRect.Height / (extent.Height * 2); float wRatio = _captureRect.Width / (extent.Width * 2); - float ratio = ( hRatio < wRatio ? hRatio : wRatio ); + float ratio = hRatio < wRatio ? hRatio : wRatio; float newSize = sizeFont.Size * ratio; if ( newSize >= 4 ) { @@ -816,13 +816,13 @@ namespace Greenshot.Forms { } // Draw the size. using (Font newSizeFont = new Font(FontFamily.GenericSansSerif, newSize, FontStyle.Bold)) { - PointF sizeLocation = new PointF(fixedRect.X + (_captureRect.Width / 2) - (extent.Width / 2), fixedRect.Y + (_captureRect.Height / 2) - (newSizeFont.GetHeight() / 2)); + PointF sizeLocation = new PointF(fixedRect.X + _captureRect.Width / 2 - extent.Width / 2, fixedRect.Y + _captureRect.Height / 2 - newSizeFont.GetHeight() / 2); graphics.DrawString(sizeText, newSizeFont, Brushes.LightSeaGreen, sizeLocation); } } } } else { - if (!isTerminalServerSession) { + if (!IsTerminalServerSession) { using (Pen pen = new Pen(Color.LightSeaGreen)) { pen.DashStyle = DashStyle.Dot; Rectangle screenBounds = _capture.ScreenBounds; @@ -852,7 +852,7 @@ namespace Greenshot.Forms { const int zoomSourceWidth = 25; const int zoomSourceHeight = 25; - Rectangle sourceRectangle = new Rectangle(_cursorPos.X - (zoomSourceWidth / 2), _cursorPos.Y - (zoomSourceHeight / 2), zoomSourceWidth, zoomSourceHeight); + Rectangle sourceRectangle = new Rectangle(_cursorPos.X - zoomSourceWidth / 2, _cursorPos.Y - zoomSourceHeight / 2, zoomSourceWidth, zoomSourceHeight); Rectangle destinationRectangle = _zoomAnimator.Current; destinationRectangle.Offset(_cursorPos); diff --git a/Greenshot/Forms/ColorDialog.cs b/Greenshot/Forms/ColorDialog.cs index 2f630d064..00f756317 100644 --- a/Greenshot/Forms/ColorDialog.cs +++ b/Greenshot/Forms/ColorDialog.cs @@ -35,7 +35,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() { SuspendLayout(); @@ -57,7 +57,7 @@ namespace Greenshot { private readonly List public partial class ImageEditorForm : BaseForm, IImageEditor { private static readonly ILog LOG = LogManager.GetLogger(typeof(ImageEditorForm)); - private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); - private static List ignoreDestinations = new List() { PickerDestination.DESIGNATION, EditorDestination.DESIGNATION }; - private static List editorList = new List(); + private static readonly EditorConfiguration EditorConfiguration = IniConfig.GetIniSection(); + private static readonly List IgnoreDestinations = new List() { PickerDestination.DESIGNATION, EditorDestination.DESIGNATION }; + private static readonly List EditorList = new List(); - private Surface surface; - private GreenshotToolStripButton[] toolbarButtons; + private Surface _surface; + private GreenshotToolStripButton[] _toolbarButtons; - private static string[] SUPPORTED_CLIPBOARD_FORMATS = {typeof(string).FullName, "Text", typeof(DrawableContainerList).FullName}; + private static readonly string[] SupportedClipboardFormats = {typeof(string).FullName, "Text", typeof(DrawableContainerList).FullName}; - private bool originalBoldCheckState = false; - private bool originalItalicCheckState = false; + private bool _originalBoldCheckState; + private bool _originalItalicCheckState; // whether part of the editor controls are disabled depending on selected item(s) - private bool controlsDisabledDueToConfirmable = false; + private bool _controlsDisabledDueToConfirmable; /// /// An Implementation for the IImageEditor, this way Plugins have access to the HWND handles wich can be used with Win32 API calls. @@ -74,54 +74,58 @@ namespace Greenshot { public static List Editors { get { try { - editorList.Sort(delegate(IImageEditor e1, IImageEditor e2) { - return e1.Surface.CaptureDetails.Title.CompareTo(e2.Surface.CaptureDetails.Title); + EditorList.Sort(delegate(IImageEditor e1, IImageEditor e2) { + return String.Compare(e1.Surface.CaptureDetails.Title, e2.Surface.CaptureDetails.Title, StringComparison.Ordinal); }); } catch(Exception ex) { LOG.Warn("Sorting of editors failed.", ex); } - return editorList; + return EditorList; } } public ImageEditorForm(ISurface iSurface, bool outputMade) { - editorList.Add(this); + EditorList.Add(this); // // The InitializeComponent() call is required for Windows Forms designer support. // ManualLanguageApply = true; InitializeComponent(); - + Load += delegate { - var thread = new Thread(delegate() {AddDestinations();}); - thread.Name = "add destinations"; + var thread = new Thread(AddDestinations) + { + Name = "add destinations" + }; thread.Start(); }; // Make sure the editor is placed on the same location as the last editor was on close - WindowDetails thisForm = new WindowDetails(Handle); - thisForm.WindowPlacement = editorConfiguration.GetEditorPlacement(); + WindowDetails thisForm = new WindowDetails(Handle) + { + WindowPlacement = EditorConfiguration.GetEditorPlacement() + }; // init surface Surface = iSurface; // Intial "saved" flag for asking if the image needs to be save - surface.Modified = !outputMade; + _surface.Modified = !outputMade; - updateUI(); + UpdateUi(); // Workaround: As the cursor is (mostly) selected on the surface a funny artifact is visible, this fixes it. - hideToolstripItems(); + HideToolstripItems(); } /// /// Remove the current surface /// private void RemoveSurface() { - if (surface != null) { - panel1.Controls.Remove(surface as Control); - surface.Dispose(); - surface = null; + if (_surface != null) { + panel1.Controls.Remove(_surface); + _surface.Dispose(); + _surface = null; } } @@ -138,30 +142,33 @@ namespace Greenshot { panel1.Height = 10; panel1.Width = 10; - surface = newSurface as Surface; - panel1.Controls.Add(surface as Surface); + _surface = newSurface as Surface; + panel1.Controls.Add(_surface); Image backgroundForTransparency = GreenshotResources.getImage("Checkerboard.Image"); - surface.TransparencyBackgroundBrush = new TextureBrush(backgroundForTransparency, WrapMode.Tile); + if (_surface != null) + { + _surface.TransparencyBackgroundBrush = new TextureBrush(backgroundForTransparency, WrapMode.Tile); - surface.MovingElementChanged += delegate { - refreshEditorControls(); - }; - surface.DrawingModeChanged += surface_DrawingModeChanged; - surface.SurfaceSizeChanged += SurfaceSizeChanged; - surface.SurfaceMessage += SurfaceMessageReceived; - surface.FieldAggregator.FieldChanged += FieldAggregatorFieldChanged; - SurfaceSizeChanged(Surface, null); + _surface.MovingElementChanged += delegate { + RefreshEditorControls(); + }; + _surface.DrawingModeChanged += surface_DrawingModeChanged; + _surface.SurfaceSizeChanged += SurfaceSizeChanged; + _surface.SurfaceMessage += SurfaceMessageReceived; + _surface.FieldAggregator.FieldChanged += FieldAggregatorFieldChanged; + SurfaceSizeChanged(Surface, null); - bindFieldControls(); - refreshEditorControls(); - // Fix title - if (surface != null && surface.CaptureDetails != null && surface.CaptureDetails.Title != null) { - Text = surface.CaptureDetails.Title + " - " + Language.GetString(LangKey.editor_title); + BindFieldControls(); + RefreshEditorControls(); + // Fix title + if (_surface != null && _surface.CaptureDetails != null && _surface.CaptureDetails.Title != null) { + Text = _surface.CaptureDetails.Title + " - " + Language.GetString(LangKey.editor_title); + } } WindowDetails.ToForeground(Handle); } - private void updateUI() { + private void UpdateUi() { // Disable access to the settings, for feature #3521446 preferencesToolStripMenuItem.Visible = !coreConfiguration.DisableSettings; toolStripSeparator12.Visible = !coreConfiguration.DisableSettings; @@ -181,7 +188,7 @@ namespace Greenshot { obfuscateModeButton.DropDownItemClicked += FilterPresetDropDownItemClicked; highlightModeButton.DropDownItemClicked += FilterPresetDropDownItemClicked; - toolbarButtons = new[] { btnCursor, btnRect, btnEllipse, btnText, btnLine, btnArrow, btnFreehand, btnHighlight, btnObfuscate, btnCrop, btnStepLabel, btnSpeechBubble }; + _toolbarButtons = new[] { btnCursor, btnRect, btnEllipse, btnText, btnLine, btnArrow, btnFreehand, btnHighlight, btnObfuscate, btnCrop, btnStepLabel, btnSpeechBubble }; //toolbarDropDownButtons = new ToolStripDropDownButton[]{btnBlur, btnPixeliate, btnTextHighlighter, btnAreaHighlighter, btnMagnifier}; pluginToolStripMenuItem.Visible = pluginToolStripMenuItem.DropDownItems.Count > 0; @@ -198,7 +205,7 @@ namespace Greenshot { /// /// /// - void propertiesToolStrip_Paint(object sender, PaintEventArgs e) { + private void PropertiesToolStrip_Paint(object sender, PaintEventArgs e) { using (Pen cbBorderPen = new Pen(SystemColors.ActiveBorder)) { // Loop over all items in the propertiesToolStrip foreach (ToolStripItem item in propertiesToolStrip.Items) { @@ -208,10 +215,13 @@ namespace Greenshot { 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); + } } } } @@ -219,7 +229,7 @@ namespace Greenshot { /// /// Get all the destinations and display them in the file menu and the buttons /// - void AddDestinations() { + private void AddDestinations() { Invoke((MethodInvoker)delegate { // Create export buttons foreach(IDestination destination in DestinationHelper.GetAllDestinations()) { @@ -242,29 +252,34 @@ namespace Greenshot { }); } - void AddDestinationButton(IDestination toolstripDestination) { + private void AddDestinationButton(IDestination toolstripDestination) { if (toolstripDestination.isDynamic) { - ToolStripSplitButton destinationButton = new ToolStripSplitButton(); + ToolStripSplitButton destinationButton = new ToolStripSplitButton + { + DisplayStyle = ToolStripItemDisplayStyle.Image, + Size = new Size(23, 22), + Text = toolstripDestination.Description, + Image = toolstripDestination.DisplayIcon + }; //ToolStripDropDownButton destinationButton = new ToolStripDropDownButton(); - destinationButton.DisplayStyle = ToolStripItemDisplayStyle.Image; - destinationButton.Size = new Size(23, 22); - destinationButton.Text = toolstripDestination.Description; - destinationButton.Image = toolstripDestination.DisplayIcon; - ToolStripMenuItem defaultItem = new ToolStripMenuItem(toolstripDestination.Description); - defaultItem.Tag = toolstripDestination; - defaultItem.Image = toolstripDestination.DisplayIcon; + ToolStripMenuItem defaultItem = new ToolStripMenuItem(toolstripDestination.Description) + { + Tag = toolstripDestination, + Image = toolstripDestination.DisplayIcon + }; defaultItem.Click += delegate { - toolstripDestination.ExportCapture(true, surface, surface.CaptureDetails); + toolstripDestination.ExportCapture(true, _surface, _surface.CaptureDetails); }; // The ButtonClick, this is for the icon, gets the current default item - destinationButton.ButtonClick += delegate(object sender, EventArgs e) { - toolstripDestination.ExportCapture(true, surface, surface.CaptureDetails); + destinationButton.ButtonClick += delegate { + toolstripDestination.ExportCapture(true, _surface, _surface.CaptureDetails); }; // Generate the entries for the drop down - destinationButton.DropDownOpening += delegate(object sender, EventArgs e) { + destinationButton.DropDownOpening += delegate + { ClearItems(destinationButton.DropDownItems); destinationButton.DropDownItems.Add(defaultItem); @@ -278,7 +293,7 @@ namespace Greenshot { destinationMenuItem.Tag = closureFixedDestination; destinationMenuItem.Image = closureFixedDestination.DisplayIcon; destinationMenuItem.Click += delegate { - closureFixedDestination.ExportCapture(true, surface, surface.CaptureDetails); + closureFixedDestination.ExportCapture(true, _surface, _surface.CaptureDetails); }; destinationButton.DropDownItems.Add(destinationMenuItem); } @@ -294,8 +309,8 @@ namespace Greenshot { destinationButton.Size = new Size(23, 22); destinationButton.Text = toolstripDestination.Description; destinationButton.Image = toolstripDestination.DisplayIcon; - destinationButton.Click += delegate(object sender, EventArgs e) { - toolstripDestination.ExportCapture(true, surface, surface.CaptureDetails); + destinationButton.Click += delegate { + toolstripDestination.ExportCapture(true, _surface, _surface.CaptureDetails); }; } } @@ -315,12 +330,12 @@ namespace Greenshot { items.Clear(); } - void FileMenuDropDownOpening(object sender, EventArgs eventArgs) { + private void FileMenuDropDownOpening(object sender, EventArgs eventArgs) { ClearItems(fileStripMenuItem.DropDownItems); // Add the destinations foreach(IDestination destination in DestinationHelper.GetAllDestinations()) { - if (ignoreDestinations.Contains(destination.Designation)) { + if (IgnoreDestinations.Contains(destination.Designation)) { continue; } if (!destination.isActive) { @@ -347,7 +362,7 @@ namespace Greenshot { /// private void SurfaceMessageReceived(object sender, SurfaceMessageEventArgs eventArgs) { if (InvokeRequired) { - this.Invoke(new SurfaceMessageReceivedThreadSafeDelegate(SurfaceMessageReceived), new object[] { sender, eventArgs }); + Invoke(new SurfaceMessageReceivedThreadSafeDelegate(SurfaceMessageReceived), new object[] { sender, eventArgs }); } else { string dateTime = DateTime.Now.ToLongTimeString(); // TODO: Fix that we only open files, like in the tooltip @@ -372,17 +387,18 @@ namespace Greenshot { /// /// 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; Size currentFormSize = Size; 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); } dimensionsLabel.Text = Surface.Image.Width + "x" + Surface.Image.Height; @@ -391,7 +407,7 @@ namespace Greenshot { public ISurface Surface { get { - return surface; + return _surface; } set { SetSurface(value); @@ -403,7 +419,7 @@ namespace Greenshot { if (fullpath != null && (fullpath.EndsWith(".ico") || fullpath.EndsWith(".wmf"))) { fullpath = null; } - surface.LastSaveFullPath = fullpath; + _surface.LastSaveFullPath = fullpath; if (fullpath == null) { return; @@ -411,8 +427,8 @@ namespace Greenshot { updateStatusLabel(Language.GetFormattedString(LangKey.editor_imagesaved, fullpath), fileSavedStatusContextMenu); Text = Path.GetFileName(fullpath) + " - " + Language.GetString(LangKey.editor_title); } - - void surface_DrawingModeChanged(object source, SurfaceDrawingModeEventArgs eventArgs) { + + private void surface_DrawingModeChanged(object source, SurfaceDrawingModeEventArgs eventArgs) { switch (eventArgs.DrawingMode) { case DrawingModes.None: SetButtonChecked(btnCursor); @@ -460,11 +476,11 @@ namespace Greenshot { */ public Image GetImageForExport() { - return surface.GetImageForExport(); + return _surface.GetImageForExport(); } public ICaptureDetails CaptureDetails { - get { return surface.CaptureDetails; } + get { return _surface.CaptureDetails; } } public ToolStripMenuItem GetPluginMenuItem() { @@ -477,254 +493,253 @@ namespace Greenshot { #endregion #region filesystem options - void BtnSaveClick(object sender, EventArgs e) { + + private void BtnSaveClick(object sender, EventArgs e) { string destinationDesignation = FileDestination.DESIGNATION; - if (surface.LastSaveFullPath == null) { + if (_surface.LastSaveFullPath == null) { destinationDesignation = FileWithDialogDestination.DESIGNATION; } - DestinationHelper.ExportCapture(true, destinationDesignation, surface, surface.CaptureDetails); - } - - void BtnClipboardClick(object sender, EventArgs e) { - DestinationHelper.ExportCapture(true, ClipboardDestination.DESIGNATION, surface, surface.CaptureDetails); + DestinationHelper.ExportCapture(true, destinationDesignation, _surface, _surface.CaptureDetails); } - void BtnPrintClick(object sender, EventArgs e) { + private void BtnClipboardClick(object sender, EventArgs e) { + DestinationHelper.ExportCapture(true, ClipboardDestination.DESIGNATION, _surface, _surface.CaptureDetails); + } + + private void BtnPrintClick(object sender, EventArgs e) { // The BeginInvoke is a solution for the printdialog not having focus BeginInvoke((MethodInvoker) delegate { - DestinationHelper.ExportCapture(true, PrinterDestination.DESIGNATION, surface, surface.CaptureDetails); + DestinationHelper.ExportCapture(true, PrinterDestination.DESIGNATION, _surface, _surface.CaptureDetails); }); } - void CloseToolStripMenuItemClick(object sender, EventArgs e) { + private void CloseToolStripMenuItemClick(object sender, EventArgs e) { Close(); } #endregion #region drawing options - void BtnEllipseClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Ellipse; - refreshFieldControls(); - } - - void BtnCursorClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.None; - refreshFieldControls(); - } - - void BtnRectClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Rect; - refreshFieldControls(); - } - - void BtnTextClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Text; - refreshFieldControls(); + + private void BtnEllipseClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.Ellipse; + RefreshFieldControls(); } - void BtnSpeechBubbleClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.SpeechBubble; - refreshFieldControls(); - } - void BtnStepLabelClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.StepLabel; - refreshFieldControls(); - } - - void BtnLineClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Line; - refreshFieldControls(); - } - - void BtnArrowClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Arrow; - refreshFieldControls(); - } - - void BtnCropClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Crop; - refreshFieldControls(); - } - - void BtnHighlightClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Highlight; - refreshFieldControls(); - } - - void BtnObfuscateClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Obfuscate; - refreshFieldControls(); + private void BtnCursorClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.None; + RefreshFieldControls(); } - void BtnFreehandClick(object sender, EventArgs e) { - surface.DrawingMode = DrawingModes.Path; - refreshFieldControls(); + private void BtnRectClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.Rect; + RefreshFieldControls(); } - - void SetButtonChecked(ToolStripButton btn) { + + private void BtnTextClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.Text; + RefreshFieldControls(); + } + + private void BtnSpeechBubbleClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.SpeechBubble; + RefreshFieldControls(); + } + + private void BtnStepLabelClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.StepLabel; + RefreshFieldControls(); + } + + private void BtnLineClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.Line; + RefreshFieldControls(); + } + + private void BtnArrowClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.Arrow; + RefreshFieldControls(); + } + + private void BtnCropClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.Crop; + RefreshFieldControls(); + } + + private void BtnHighlightClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.Highlight; + RefreshFieldControls(); + } + + private void BtnObfuscateClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.Obfuscate; + RefreshFieldControls(); + } + + private void BtnFreehandClick(object sender, EventArgs e) { + _surface.DrawingMode = DrawingModes.Path; + RefreshFieldControls(); + } + + private void SetButtonChecked(ToolStripButton btn) { UncheckAllToolButtons(); btn.Checked = true; } private void UncheckAllToolButtons() { - if (toolbarButtons != null) { - foreach (ToolStripButton butt in toolbarButtons) { + if (_toolbarButtons != null) { + foreach (GreenshotToolStripButton butt in _toolbarButtons) { butt.Checked = false; } } } - - void AddRectangleToolStripMenuItemClick(object sender, EventArgs e) { + + private void AddRectangleToolStripMenuItemClick(object sender, EventArgs e) { BtnRectClick(sender, e); } - void DrawFreehandToolStripMenuItemClick(object sender, EventArgs e) { + private void DrawFreehandToolStripMenuItemClick(object sender, EventArgs e) { BtnFreehandClick(sender, e); } - - void AddEllipseToolStripMenuItemClick(object sender, EventArgs e) { + + private void AddEllipseToolStripMenuItemClick(object sender, EventArgs e) { BtnEllipseClick(sender, e); } - - void AddTextBoxToolStripMenuItemClick(object sender, EventArgs e) { + + private void AddTextBoxToolStripMenuItemClick(object sender, EventArgs e) { BtnTextClick(sender, e); } - - void AddSpeechBubbleToolStripMenuItemClick(object sender, EventArgs e) { + + private void AddSpeechBubbleToolStripMenuItemClick(object sender, EventArgs e) { BtnSpeechBubbleClick(sender, e); } - - void AddCounterToolStripMenuItemClick(object sender, EventArgs e) { + + private void AddCounterToolStripMenuItemClick(object sender, EventArgs e) { BtnStepLabelClick(sender, e); } - - void DrawLineToolStripMenuItemClick(object sender, EventArgs e) { + + private void DrawLineToolStripMenuItemClick(object sender, EventArgs e) { BtnLineClick(sender, e); } - - void DrawArrowToolStripMenuItemClick(object sender, EventArgs e) { + + private void DrawArrowToolStripMenuItemClick(object sender, EventArgs e) { BtnArrowClick(sender, e); } - - void DrawHighlightToolStripMenuItemClick(object sender, EventArgs e) { - BtnHighlightClick(sender, e); - } - - void BlurToolStripMenuItemClick(object sender, EventArgs e) { - BtnObfuscateClick(sender, e); - } - - void RemoveObjectToolStripMenuItemClick(object sender, EventArgs e) { - surface.RemoveSelectedElements(); + + private void RemoveObjectToolStripMenuItemClick(object sender, EventArgs e) { + _surface.RemoveSelectedElements(); } - void BtnDeleteClick(object sender, EventArgs e) { + private void BtnDeleteClick(object sender, EventArgs e) { RemoveObjectToolStripMenuItemClick(sender, e); } #endregion #region copy&paste options - void CutToolStripMenuItemClick(object sender, EventArgs e) { - surface.CutSelectedElements(); - updateClipboardSurfaceDependencies(); + + private void CutToolStripMenuItemClick(object sender, EventArgs e) { + _surface.CutSelectedElements(); + UpdateClipboardSurfaceDependencies(); } - void BtnCutClick(object sender, EventArgs e) { + private void BtnCutClick(object sender, EventArgs e) { CutToolStripMenuItemClick(sender, e); } - - void CopyToolStripMenuItemClick(object sender, EventArgs e) { - surface.CopySelectedElements(); - updateClipboardSurfaceDependencies(); + + private void CopyToolStripMenuItemClick(object sender, EventArgs e) { + _surface.CopySelectedElements(); + UpdateClipboardSurfaceDependencies(); } - void BtnCopyClick(object sender, EventArgs e) { + private void BtnCopyClick(object sender, EventArgs e) { CopyToolStripMenuItemClick(sender, e); } - - void PasteToolStripMenuItemClick(object sender, EventArgs e) { - surface.PasteElementFromClipboard(); - updateClipboardSurfaceDependencies(); + + private void PasteToolStripMenuItemClick(object sender, EventArgs e) { + _surface.PasteElementFromClipboard(); + UpdateClipboardSurfaceDependencies(); } - void BtnPasteClick(object sender, EventArgs e) { + private void BtnPasteClick(object sender, EventArgs e) { PasteToolStripMenuItemClick(sender, e); } - void UndoToolStripMenuItemClick(object sender, EventArgs e) { - surface.Undo(); - updateUndoRedoSurfaceDependencies(); + private void UndoToolStripMenuItemClick(object sender, EventArgs e) { + _surface.Undo(); + UpdateUndoRedoSurfaceDependencies(); } - void BtnUndoClick(object sender, EventArgs e) { + private void BtnUndoClick(object sender, EventArgs e) { UndoToolStripMenuItemClick(sender, e); } - void RedoToolStripMenuItemClick(object sender, EventArgs e) { - surface.Redo(); - updateUndoRedoSurfaceDependencies(); + private void RedoToolStripMenuItemClick(object sender, EventArgs e) { + _surface.Redo(); + UpdateUndoRedoSurfaceDependencies(); } - void BtnRedoClick(object sender, EventArgs e) { + private void BtnRedoClick(object sender, EventArgs e) { RedoToolStripMenuItemClick(sender, e); } - void DuplicateToolStripMenuItemClick(object sender, EventArgs e) { - surface.DuplicateSelectedElements(); - updateClipboardSurfaceDependencies(); + private void DuplicateToolStripMenuItemClick(object sender, EventArgs e) { + _surface.DuplicateSelectedElements(); + UpdateClipboardSurfaceDependencies(); } #endregion #region element properties - void UpOneLevelToolStripMenuItemClick(object sender, EventArgs e) { - surface.PullElementsUp(); + + private void UpOneLevelToolStripMenuItemClick(object sender, EventArgs e) { + _surface.PullElementsUp(); } - - void DownOneLevelToolStripMenuItemClick(object sender, EventArgs e) { - surface.PushElementsDown(); + + private void DownOneLevelToolStripMenuItemClick(object sender, EventArgs e) { + _surface.PushElementsDown(); } - - void UpToTopToolStripMenuItemClick(object sender, EventArgs e) { - surface.PullElementsToTop(); + + private void UpToTopToolStripMenuItemClick(object sender, EventArgs e) { + _surface.PullElementsToTop(); } - - void DownToBottomToolStripMenuItemClick(object sender, EventArgs e) { - surface.PushElementsToBottom(); + + private void DownToBottomToolStripMenuItemClick(object sender, EventArgs e) { + _surface.PushElementsToBottom(); } #endregion #region help - void HelpToolStripMenuItem1Click(object sender, EventArgs e) { + + private void HelpToolStripMenuItem1Click(object sender, EventArgs e) { HelpFileLoader.LoadHelp(); } - void AboutToolStripMenuItemClick(object sender, EventArgs e) { + private void AboutToolStripMenuItemClick(object sender, EventArgs e) { MainForm.Instance.ShowAbout(); } - void PreferencesToolStripMenuItemClick(object sender, EventArgs e) { + private void PreferencesToolStripMenuItemClick(object sender, EventArgs e) { MainForm.Instance.ShowSetting(); } - void BtnSettingsClick(object sender, EventArgs e) { + private void BtnSettingsClick(object sender, EventArgs e) { PreferencesToolStripMenuItemClick(sender, e); } - void BtnHelpClick(object sender, EventArgs e) { + private void BtnHelpClick(object sender, EventArgs e) { HelpToolStripMenuItem1Click(sender, e); } #endregion #region image editor event handlers - void ImageEditorFormActivated(object sender, EventArgs e) { - updateClipboardSurfaceDependencies(); - updateUndoRedoSurfaceDependencies(); + + private void ImageEditorFormActivated(object sender, EventArgs e) { + UpdateClipboardSurfaceDependencies(); + UpdateUndoRedoSurfaceDependencies(); } - void ImageEditorFormFormClosing(object sender, FormClosingEventArgs e) { - if (surface.Modified && !editorConfiguration.SuppressSaveDialogAtClose) { + private void ImageEditorFormFormClosing(object sender, FormClosingEventArgs e) { + if (_surface.Modified && !EditorConfiguration.SuppressSaveDialogAtClose) { // Make sure the editor is visible WindowDetails.ToForeground(Handle); @@ -741,20 +756,20 @@ namespace Greenshot { if (result.Equals(DialogResult.Yes)) { BtnSaveClick(sender,e); // Check if the save was made, if not it was cancelled so we cancel the closing - if (surface.Modified) { + if (_surface.Modified) { e.Cancel = true; return; } } } // 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); - surface.Dispose(); + _surface.Dispose(); GC.Collect(); if (coreConfiguration.MinimizeWorkingSetSize) { @@ -762,11 +777,11 @@ namespace Greenshot { } } - void ImageEditorFormKeyDown(object sender, KeyEventArgs e) { + 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) { case Keys.Escape: BtnCursorClick(sender, e); @@ -854,7 +869,7 @@ namespace Greenshot { #region key handling 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); } return false; @@ -862,13 +877,13 @@ namespace Greenshot { 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) { // Go through the destinations to check the EditorShortcut Keys // this way the menu entries don't need to be enabled. // This also fixes bugs #3526974 & #3527020 foreach (IDestination destination in DestinationHelper.GetAllDestinations()) { - if (ignoreDestinations.Contains(destination.Designation)) { + if (IgnoreDestinations.Contains(destination.Designation)) { continue; } if (!destination.isActive) { @@ -876,11 +891,11 @@ namespace Greenshot { } if (destination.EditorShortcutKeys == keys) { - destination.ExportCapture(true, surface, surface.CaptureDetails); + destination.ExportCapture(true, _surface, _surface.CaptureDetails); return true; } } - if (!surface.ProcessCmdKey(keys)) { + if (!_surface.ProcessCmdKey(keys)) { return base.ProcessCmdKey(ref msg, keys); } } @@ -890,30 +905,30 @@ namespace Greenshot { #region helpers - private void updateUndoRedoSurfaceDependencies() { - if (surface == null) { + private void UpdateUndoRedoSurfaceDependencies() { + if (_surface == null) { return; } - bool canUndo = surface.CanUndo; + bool canUndo = _surface.CanUndo; btnUndo.Enabled = canUndo; undoToolStripMenuItem.Enabled = canUndo; string undoAction = ""; if (canUndo) { - if (surface.UndoActionLanguageKey != LangKey.none) { - undoAction = Language.GetString(surface.UndoActionLanguageKey); + if (_surface.UndoActionLanguageKey != LangKey.none) { + undoAction = Language.GetString(_surface.UndoActionLanguageKey); } } string undoText = Language.GetFormattedString(LangKey.editor_undo, undoAction); btnUndo.Text = undoText; undoToolStripMenuItem.Text = undoText; - bool canRedo = surface.CanRedo; + bool canRedo = _surface.CanRedo; btnRedo.Enabled = canRedo; redoToolStripMenuItem.Enabled = canRedo; string redoAction = ""; if (canRedo) { - if (surface.RedoActionLanguageKey != LangKey.none) { - redoAction = Language.GetString(surface.RedoActionLanguageKey); + if (_surface.RedoActionLanguageKey != LangKey.none) { + redoAction = Language.GetString(_surface.RedoActionLanguageKey); } } string redoText = Language.GetFormattedString(LangKey.editor_redo, redoAction); @@ -922,13 +937,13 @@ namespace Greenshot { } - private void updateClipboardSurfaceDependencies() { - if (surface == null) { + private void UpdateClipboardSurfaceDependencies() { + 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; @@ -942,9 +957,9 @@ namespace Greenshot { 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 @@ -958,25 +973,27 @@ namespace Greenshot { private void updateStatusLabel(string text) { updateStatusLabel(text, null); } - private void clearStatusLabel() { + private void ClearStatusLabel() { updateStatusLabel(null, null); } - - void StatusLabelClicked(object sender, MouseEventArgs e) { + + private void StatusLabelClicked(object sender, MouseEventArgs e) { ToolStrip ss = (StatusStrip)((ToolStripStatusLabel)sender).Owner; if(ss.ContextMenuStrip != null) { ss.ContextMenuStrip.Show(ss, e.X, e.Y); } } - - void CopyPathMenuItemClick(object sender, EventArgs e) { - ClipboardHelper.SetClipboardData(surface.LastSaveFullPath); + + private void CopyPathMenuItemClick(object sender, EventArgs e) { + ClipboardHelper.SetClipboardData(_surface.LastSaveFullPath); } - - void OpenDirectoryMenuItemClick(object sender, EventArgs e) { - ProcessStartInfo psi = new ProcessStartInfo("explorer"); - psi.Arguments = Path.GetDirectoryName(surface.LastSaveFullPath); - psi.UseShellExecute = false; + + private void OpenDirectoryMenuItemClick(object sender, EventArgs e) { + ProcessStartInfo psi = new ProcessStartInfo("explorer") + { + Arguments = Path.GetDirectoryName(_surface.LastSaveFullPath), + UseShellExecute = false + }; using (Process p = new Process()) { p.StartInfo = psi; p.Start(); @@ -984,33 +1001,33 @@ namespace Greenshot { } #endregion - 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"); + 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"); } /// /// 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) { - FieldAggregator props = surface.FieldAggregator; + if(_surface.HasSelectedElements || _surface.DrawingMode != DrawingModes.None) { + 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); @@ -1033,12 +1050,12 @@ namespace Greenshot { obfuscateModeButton.Visible = props.HasFieldValue(FieldType.PREPARED_FILTER_OBFUSCATE); highlightModeButton.Visible = props.HasFieldValue(FieldType.PREPARED_FILTER_HIGHLIGHT); } else { - hideToolstripItems(); + HideToolstripItems(); } propertiesToolStrip.ResumeLayout(); } - private void hideToolstripItems() { + private void HideToolstripItems() { foreach(ToolStripItem toolStripItem in propertiesToolStrip.Items) { toolStripItem.Visible = false; } @@ -1047,23 +1064,23 @@ namespace Greenshot { /// /// refreshes all editor controls depending on selected elements and their fields /// - private void refreshEditorControls() { - int stepLabels = surface.CountStepLabels(null); + private void RefreshEditorControls() { + int stepLabels = _surface.CountStepLabels(null); Image icon; if (stepLabels <= 20) { - icon = ((System.Drawing.Image)(resources.GetObject(string.Format("btnStepLabel{0:00}.Image", stepLabels)))); + icon = (Image)resources.GetObject(string.Format("btnStepLabel{0:00}.Image", stepLabels)); } else { - icon = ((System.Drawing.Image)(resources.GetObject("btnStepLabel20+.Image"))); + icon = (Image)resources.GetObject("btnStepLabel20+.Image"); } - this.btnStepLabel.Image = icon; - this.addCounterToolStripMenuItem.Image = icon; + btnStepLabel.Image = icon; + addCounterToolStripMenuItem.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(destinationsToolStrip); ToolStripItemEndisabler.Disable(toolsToolStrip); @@ -1071,25 +1088,25 @@ namespace Greenshot { ToolStripItemEndisabler.Enable(helpToolStripMenuItem); ToolStripItemEndisabler.Enable(aboutToolStripMenuItem); ToolStripItemEndisabler.Enable(preferencesToolStripMenuItem); - 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(destinationsToolStrip); 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; upOneLevelToolStripMenuItem.Enabled = pull; @@ -1098,29 +1115,35 @@ namespace Greenshot { } // finally show/hide field controls depending on the fields of selected elements - refreshFieldControls(); - } - - - void ArrowHeadsToolStripMenuItemClick(object sender, EventArgs e) { - surface.FieldAggregator.GetField(FieldType.ARROWHEADS).Value = (ArrowContainer.ArrowHeadCombination)((ToolStripMenuItem)sender).Tag; - } - - void EditToolStripMenuItemClick(object sender, EventArgs e) { - updateClipboardSurfaceDependencies(); - updateUndoRedoSurfaceDependencies(); + RefreshFieldControls(); } - void FontPropertyChanged(object sender, EventArgs e) { + + private void ArrowHeadsToolStripMenuItemClick(object sender, EventArgs e) { + _surface.FieldAggregator.GetField(FieldType.ARROWHEADS).Value = (ArrowContainer.ArrowHeadCombination)((ToolStripMenuItem)sender).Tag; + } + + private void EditToolStripMenuItemClick(object sender, EventArgs e) { + UpdateClipboardSurfaceDependencies(); + UpdateUndoRedoSurfaceDependencies(); + } + + 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; @@ -1137,55 +1160,56 @@ namespace Greenshot { fontItalicButton.Checked = true; } } - } - - void FieldAggregatorFieldChanged(object sender, FieldChangedEventArgs e) { + } + + private void FieldAggregatorFieldChanged(object sender, FieldChangedEventArgs e) { // in addition to selection, deselection of elements, we need to // refresh toolbar if prepared filter mode is changed if(e.Field.FieldType == FieldType.PREPARED_FILTER_HIGHLIGHT) { - refreshFieldControls(); + RefreshFieldControls(); } } - - void FontBoldButtonClick(object sender, EventArgs e) { - originalBoldCheckState = fontBoldButton.Checked; + + private void FontBoldButtonClick(object sender, EventArgs e) { + _originalBoldCheckState = fontBoldButton.Checked; } - void FontItalicButtonClick(object sender, EventArgs e) { - originalItalicCheckState = fontItalicButton.Checked; + private void FontItalicButtonClick(object sender, EventArgs e) { + _originalItalicCheckState = fontItalicButton.Checked; } - - void ToolBarFocusableElementGotFocus(object sender, EventArgs e) { - surface.KeysLocked = true; + + private void ToolBarFocusableElementGotFocus(object sender, EventArgs e) { + _surface.KeysLocked = true; } - void ToolBarFocusableElementLostFocus(object sender, EventArgs e) { - surface.KeysLocked = false; + + private void ToolBarFocusableElementLostFocus(object sender, EventArgs e) { + _surface.KeysLocked = false; } - - void SaveElementsToolStripMenuItemClick(object sender, EventArgs e) { + + 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); } } } - - void LoadElementsToolStripMenuItemClick(object sender, EventArgs e) { + + private void LoadElementsToolStripMenuItemClick(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Greenshot templates (*.gst)|*.gst"; if (openFileDialog.ShowDialog() == DialogResult.OK) { using (Stream streamRead = File.OpenRead(openFileDialog.FileName)) { - surface.LoadElementsFromStream(streamRead); + _surface.LoadElementsFromStream(streamRead); } - surface.Refresh(); + _surface.Refresh(); } } - void DestinationToolStripMenuItemClick(object sender, EventArgs e) { + private void DestinationToolStripMenuItemClick(object sender, EventArgs e) { IDestination clickedDestination = null; if (sender is Control) { Control clickedControl = sender as Control; @@ -1199,39 +1223,39 @@ namespace Greenshot { clickedDestination = (IDestination)clickedMenuItem.Tag; } if (clickedDestination != null) { - ExportInformation exportInformation = clickedDestination.ExportCapture(true, surface, surface.CaptureDetails); + ExportInformation exportInformation = clickedDestination.ExportCapture(true, _surface, _surface.CaptureDetails); if (exportInformation != null && exportInformation.ExportMade) { - surface.Modified = false; + _surface.Modified = false; } } } protected void FilterPresetDropDownItemClicked(object sender, ToolStripItemClickedEventArgs e) { - refreshFieldControls(); + RefreshFieldControls(); Invalidate(true); } - - void SelectAllToolStripMenuItemClick(object sender, EventArgs e) { - surface.SelectAllElements(); + + private void SelectAllToolStripMenuItemClick(object sender, EventArgs e) { + _surface.SelectAllElements(); } - - void BtnConfirmClick(object sender, EventArgs e) { - surface.ConfirmSelectedConfirmableElements(true); - refreshFieldControls(); + + private void BtnConfirmClick(object sender, EventArgs e) { + _surface.ConfirmSelectedConfirmableElements(true); + RefreshFieldControls(); } - - void BtnCancelClick(object sender, EventArgs e) { - surface.ConfirmSelectedConfirmableElements(false); - refreshFieldControls(); + + private void BtnCancelClick(object sender, EventArgs e) { + _surface.ConfirmSelectedConfirmableElements(false); + RefreshFieldControls(); } - - void Insert_window_toolstripmenuitemMouseEnter(object sender, EventArgs e) { + + private void Insert_window_toolstripmenuitemMouseEnter(object sender, EventArgs e) { ToolStripMenuItem captureWindowMenuItem = (ToolStripMenuItem)sender; MainForm.Instance.AddCaptureWindowMenuItems(captureWindowMenuItem, Contextmenu_window_Click); } - void Contextmenu_window_Click(object sender, EventArgs e) { + private void Contextmenu_window_Click(object sender, EventArgs e) { ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender; try { WindowDetails windowToCapture = (WindowDetails)clickedItem.Tag; @@ -1245,7 +1269,7 @@ namespace Greenshot { capture = CaptureHelper.CaptureWindow(windowToCapture, capture, coreConfiguration.WindowCaptureMode); if (capture != null && capture.CaptureDetails != null && capture.Image != null) { ((Bitmap)capture.Image).SetResolution(capture.CaptureDetails.DpiX, capture.CaptureDetails.DpiY); - surface.AddImageContainer((Bitmap)capture.Image, 100, 100); + _surface.AddImageContainer((Bitmap)capture.Image, 100, 100); } Activate(); WindowDetails.ToForeground(Handle); @@ -1259,15 +1283,15 @@ namespace Greenshot { } } - void AutoCropToolStripMenuItemClick(object sender, EventArgs e) { - if (surface.AutoCrop()) { - refreshFieldControls(); + private void AutoCropToolStripMenuItemClick(object sender, EventArgs e) { + if (_surface.AutoCrop()) { + RefreshFieldControls(); } } - void AddBorderToolStripMenuItemClick(object sender, EventArgs e) { - surface.ApplyBitmapEffect(new BorderEffect()); - updateUndoRedoSurfaceDependencies(); + private void AddBorderToolStripMenuItemClick(object sender, EventArgs e) { + _surface.ApplyBitmapEffect(new BorderEffect()); + UpdateUndoRedoSurfaceDependencies(); } /// @@ -1275,13 +1299,13 @@ namespace Greenshot { /// /// /// - void AddDropshadowToolStripMenuItemClick(object sender, EventArgs e) { - DropShadowEffect dropShadowEffect = editorConfiguration.DropShadowEffectSettings; + private void AddDropshadowToolStripMenuItemClick(object sender, EventArgs e) { + DropShadowEffect dropShadowEffect = EditorConfiguration.DropShadowEffectSettings; // TODO: 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(); } } @@ -1290,13 +1314,13 @@ namespace Greenshot { /// /// /// - void BtnResizeClick(object sender, EventArgs e) { - ResizeEffect resizeEffect = new ResizeEffect(surface.Image.Width, surface.Image.Height, true); + private void BtnResizeClick(object sender, EventArgs e) { + ResizeEffect resizeEffect = new ResizeEffect(_surface.Image.Width, _surface.Image.Height, true); // TODO: 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(); } } @@ -1305,39 +1329,39 @@ namespace Greenshot { /// /// /// - void TornEdgesToolStripMenuItemClick(object sender, EventArgs e) { - TornEdgeEffect tornEdgeEffect = editorConfiguration.TornEdgeEffectSettings; + private void TornEdgesToolStripMenuItemClick(object sender, EventArgs e) { + TornEdgeEffect tornEdgeEffect = EditorConfiguration.TornEdgeEffectSettings; // TODO: 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(); } } - void GrayscaleToolStripMenuItemClick(object sender, EventArgs e) { - surface.ApplyBitmapEffect(new GrayscaleEffect()); - updateUndoRedoSurfaceDependencies(); + private void GrayscaleToolStripMenuItemClick(object sender, EventArgs e) { + _surface.ApplyBitmapEffect(new GrayscaleEffect()); + UpdateUndoRedoSurfaceDependencies(); } - void ClearToolStripMenuItemClick(object sender, EventArgs e) { - surface.Clear(Color.Transparent); - updateUndoRedoSurfaceDependencies(); + private void ClearToolStripMenuItemClick(object sender, EventArgs e) { + _surface.Clear(Color.Transparent); + UpdateUndoRedoSurfaceDependencies(); } - void RotateCwToolstripButtonClick(object sender, EventArgs e) { - surface.ApplyBitmapEffect(new RotateEffect(90)); - updateUndoRedoSurfaceDependencies(); + private void RotateCwToolstripButtonClick(object sender, EventArgs e) { + _surface.ApplyBitmapEffect(new RotateEffect(90)); + UpdateUndoRedoSurfaceDependencies(); } - - void RotateCcwToolstripButtonClick(object sender, EventArgs e) { - surface.ApplyBitmapEffect(new RotateEffect(270)); - updateUndoRedoSurfaceDependencies(); + + private void RotateCcwToolstripButtonClick(object sender, EventArgs e) { + _surface.ApplyBitmapEffect(new RotateEffect(270)); + UpdateUndoRedoSurfaceDependencies(); } - - void InvertToolStripMenuItemClick(object sender, EventArgs e) { - surface.ApplyBitmapEffect(new InvertEffect()); - updateUndoRedoSurfaceDependencies(); + + private void InvertToolStripMenuItemClick(object sender, EventArgs e) { + _surface.ApplyBitmapEffect(new InvertEffect()); + UpdateUndoRedoSurfaceDependencies(); } private void ImageEditorFormResize(object sender, EventArgs e) { @@ -1347,25 +1371,25 @@ namespace Greenshot { 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) { return; } int offsetX = -panel.HorizontalScroll.Value; int offsetY = -panel.VerticalScroll.Value; - if (canvas != null) { - if (currentClientSize.Width > imageSize.Width) { - canvas.Left = offsetX + ((currentClientSize.Width - imageSize.Width) / 2); - } else { - canvas.Left = offsetX + 0; - } + if (currentClientSize.Width > imageSize.Width) { + canvas.Left = offsetX + (currentClientSize.Width - imageSize.Width) / 2; + } else { + canvas.Left = offsetX + 0; } - if (canvas != null) { - if (currentClientSize.Height > imageSize.Height) { - canvas.Top = offsetY + ((currentClientSize.Height - imageSize.Height) / 2); - } else { - canvas.Top = offsetY + 0; - } + if (currentClientSize.Height > imageSize.Height) { + canvas.Top = offsetY + (currentClientSize.Height - imageSize.Height) / 2; + } else { + canvas.Top = offsetY + 0; } } } diff --git a/Greenshot/Forms/LanguageDialog.cs b/Greenshot/Forms/LanguageDialog.cs index ee0fb7549..4de13156a 100644 --- a/Greenshot/Forms/LanguageDialog.cs +++ b/Greenshot/Forms/LanguageDialog.cs @@ -29,9 +29,9 @@ namespace Greenshot.Forms { /// Description of LanguageDialog. /// public partial class LanguageDialog : Form { - private static ILog LOG = LogManager.GetLogger(typeof(LanguageDialog)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(LanguageDialog)); private static LanguageDialog uniqueInstance; - private bool properOkPressed = false; + private bool properOkPressed; private LanguageDialog() { // diff --git a/Greenshot/Forms/MainForm.cs b/Greenshot/Forms/MainForm.cs index e58af6640..686f507d4 100644 --- a/Greenshot/Forms/MainForm.cs +++ b/Greenshot/Forms/MainForm.cs @@ -54,7 +54,7 @@ namespace Greenshot { private static ILog LOG; private static Mutex _applicationMutex; private static CoreConfiguration _conf; - public static string LogFileLocation = null; + public static string LogFileLocation; public static void Start(string[] args) { bool isAlreadyRunning = false; @@ -258,7 +258,7 @@ namespace Greenshot { using (Form dummyForm = new Form()) { dummyForm.Icon = GreenshotResources.getGreenshotIcon(); dummyForm.ShowInTaskbar = true; - dummyForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; + dummyForm.FormBorderStyle = FormBorderStyle.None; dummyForm.Location = new Point(int.MinValue, int.MinValue); dummyForm.Load += delegate { dummyForm.Size = Size.Empty; }; dummyForm.Show(); @@ -581,7 +581,7 @@ namespace Greenshot { contextMenu.ImageScalingSize = coreConfiguration.IconSize; string ieExePath = PluginUtils.GetExePath("iexplore.exe"); if (!string.IsNullOrEmpty(ieExePath)) { - this.contextmenu_captureie.Image = PluginUtils.GetCachedExeIcon(ieExePath, 0); + contextmenu_captureie.Image = PluginUtils.GetCachedExeIcon(ieExePath, 0); } } } diff --git a/Greenshot/Forms/MovableShowColorForm.cs b/Greenshot/Forms/MovableShowColorForm.cs index 6173a4b4e..3b378894a 100644 --- a/Greenshot/Forms/MovableShowColorForm.cs +++ b/Greenshot/Forms/MovableShowColorForm.cs @@ -85,8 +85,8 @@ namespace Greenshot.Forms { /// /// Point with the coordinates /// Color at the specified screenCoordinates - static private Color GetPixelColor(Point screenCoordinates) { - using (SafeWindowDCHandle screenDC = SafeWindowDCHandle.fromDesktop()) { + private static Color GetPixelColor(Point screenCoordinates) { + using (SafeWindowDCHandle screenDC = SafeWindowDCHandle.FromDesktop()) { try { uint pixel = GDI32.GetPixel(screenDC, screenCoordinates.X, screenCoordinates.Y); Color color = Color.FromArgb(255, (int)(pixel & 0xFF), (int)(pixel & 0xFF00) >> 8, (int)(pixel & 0xFF0000) >> 16); diff --git a/Greenshot/Forms/ResizeSettingsForm.cs b/Greenshot/Forms/ResizeSettingsForm.cs index db8cac328..84c8bd31f 100644 --- a/Greenshot/Forms/ResizeSettingsForm.cs +++ b/Greenshot/Forms/ResizeSettingsForm.cs @@ -29,9 +29,9 @@ namespace Greenshot.Forms { /// A form to set the resize settings /// 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) { @@ -50,8 +50,8 @@ namespace Greenshot.Forms { 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; } @@ -82,7 +82,7 @@ namespace Greenshot.Forms { 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 { displayValue = newWidth; } @@ -92,7 +92,7 @@ namespace Greenshot.Forms { 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 { displayValue = newHeight; } @@ -126,25 +126,25 @@ namespace Greenshot.Forms { if (isWidth) { 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(); } } else { 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/Forms/SettingsForm.cs b/Greenshot/Forms/SettingsForm.cs index b64fdfaf0..10b8cec7a 100644 --- a/Greenshot/Forms/SettingsForm.cs +++ b/Greenshot/Forms/SettingsForm.cs @@ -43,7 +43,7 @@ namespace Greenshot { /// Description of SettingsForm. /// public partial class SettingsForm : BaseForm { - private static ILog LOG = LogManager.GetLogger(typeof(SettingsForm)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(SettingsForm)); private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); private readonly ToolTip _toolTip = new ToolTip(); private bool _inHotkey; @@ -237,7 +237,7 @@ namespace Greenshot { string filenamePart = pathParts[pathParts.Length-1]; settingsOk = FilenameHelper.IsFilenameValid(filenamePart); - for (int i = 0; (settingsOk && i public class ToolStripMenuSelectList : ToolStripMenuItem { - private static CoreConfiguration coreConfiguration = IniConfig.GetIniSection(); - private bool multiCheckAllowed = false; - private bool updateInProgress = false; + private static readonly CoreConfiguration coreConfiguration = IniConfig.GetIniSection(); + private readonly bool multiCheckAllowed; + private bool updateInProgress; private static Image defaultImage; /// diff --git a/Greenshot/Forms/TornEdgeSettingsForm.cs b/Greenshot/Forms/TornEdgeSettingsForm.cs index 63bae471a..707ea5c32 100644 --- a/Greenshot/Forms/TornEdgeSettingsForm.cs +++ b/Greenshot/Forms/TornEdgeSettingsForm.cs @@ -26,7 +26,7 @@ using GreenshotPlugin.Core; namespace Greenshot.Forms { public partial class TornEdgeSettingsForm : BaseForm { - private TornEdgeEffect effect; + private readonly TornEdgeEffect effect; public TornEdgeSettingsForm(TornEdgeEffect effect) { this.effect = effect; InitializeComponent(); @@ -60,11 +60,6 @@ namespace Greenshot.Forms { DialogResult = DialogResult.OK; } - private void ButtonReset_Click(object sender, EventArgs e) { - effect.Reset(); - ShowSettings(); - } - private void ShadowCheckbox_CheckedChanged(object sender, EventArgs e) { thickness.Enabled = shadowCheckbox.Checked; offsetX.Enabled = shadowCheckbox.Checked; diff --git a/Greenshot/Helpers/CaptureHelper.cs b/Greenshot/Helpers/CaptureHelper.cs index 301b97c14..5d3868194 100644 --- a/Greenshot/Helpers/CaptureHelper.cs +++ b/Greenshot/Helpers/CaptureHelper.cs @@ -42,7 +42,7 @@ namespace Greenshot.Helpers { /// public class CaptureHelper : IDisposable { private static readonly ILog LOG = LogManager.GetLogger(typeof(CaptureHelper)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); // TODO: when we get the screen capture code working correctly, this needs to be enabled //private static ScreenCaptureHelper screenCapture = null; private List _windows = new List(); @@ -404,7 +404,7 @@ namespace Greenshot.Helpers { // Set capture title, fixing bug #3569703 foreach (WindowDetails window in WindowDetails.GetVisibleWindows()) { - Point estimatedLocation = new Point(conf.LastCapturedRegion.X + (conf.LastCapturedRegion.Width / 2), conf.LastCapturedRegion.Y + (conf.LastCapturedRegion.Height / 2)); + Point estimatedLocation = new Point(conf.LastCapturedRegion.X + conf.LastCapturedRegion.Width / 2, conf.LastCapturedRegion.Y + conf.LastCapturedRegion.Height / 2); if (window.Contains(estimatedLocation)) { _selectedCaptureWindow = window; _capture.CaptureDetails.Title = _selectedCaptureWindow.Text; @@ -850,14 +850,14 @@ namespace Greenshot.Helpers { // check if GDI capture any good, by comparing it with the screen content int blackCountGDI = ImageHelper.CountColor(tmpCapture.Image, Color.Black, false); int GDIPixels = tmpCapture.Image.Width * tmpCapture.Image.Height; - int blackPercentageGDI = (blackCountGDI * 100) / GDIPixels; + int blackPercentageGDI = blackCountGDI * 100 / GDIPixels; if (blackPercentageGDI >= 1) { int screenPixels = windowRectangle.Width * windowRectangle.Height; using (ICapture screenCapture = new Capture()) { screenCapture.CaptureDetails = captureForWindow.CaptureDetails; if (WindowCapture.CaptureRectangleFromDesktopScreen(screenCapture, windowRectangle) != null) { int blackCountScreen = ImageHelper.CountColor(screenCapture.Image, Color.Black, false); - int blackPercentageScreen = (blackCountScreen * 100) / screenPixels; + int blackPercentageScreen = blackCountScreen * 100 / screenPixels; if (screenPixels == GDIPixels) { // "easy compare", both have the same size // If GDI has more black, use the screen capture. diff --git a/Greenshot/Helpers/CopyData.cs b/Greenshot/Helpers/CopyData.cs index ab695822d..776de7a99 100644 --- a/Greenshot/Helpers/CopyData.cs +++ b/Greenshot/Helpers/CopyData.cs @@ -18,6 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ + using System; using System.Collections; using System.Collections.Generic; @@ -28,21 +29,21 @@ using System.Windows.Forms; using GreenshotPlugin.Core; -/// -/// Code from vbAccelerator, location: -/// http://www.vbaccelerator.com/home/NET/Code/Libraries/Windows_Messages/Simple_Interprocess_Communication/WM_COPYDATA_Demo_zip_SimpleInterprocessCommunicationsCS_CopyData_cs.asp -/// namespace Greenshot.Helpers { public enum CommandEnum { OpenFile, Exit, FirstLaunch, ReloadConfig }; + /// + /// Code from vbAccelerator, location: + /// http://www.vbaccelerator.com/home/NET/Code/Libraries/Windows_Messages/Simple_Interprocess_Communication/WM_COPYDATA_Demo_zip_SimpleInterprocessCommunicationsCS_CopyData_cs.asp + /// [Serializable()] public class CopyDataTransport { - List> commands; + private readonly List> _commands; public List> Commands { - get {return commands;} + get {return _commands;} } public CopyDataTransport() { - commands = new List>(); + _commands = new List>(); } public CopyDataTransport(CommandEnum command) : this() { @@ -53,10 +54,10 @@ namespace Greenshot.Helpers { AddCommand(command, commandData); } public void AddCommand(CommandEnum command) { - commands.Add(new KeyValuePair(command, null)); + _commands.Add(new KeyValuePair(command, null)); } public void AddCommand(CommandEnum command, string commandData) { - commands.Add(new KeyValuePair(command, commandData)); + _commands.Add(new KeyValuePair(command, commandData)); } } @@ -81,16 +82,16 @@ namespace Greenshot.Helpers { [StructLayout(LayoutKind.Sequential)] private struct COPYDATASTRUCT { - public IntPtr dwData; - public int cbData; - public IntPtr lpData; + public readonly IntPtr dwData; + public readonly int cbData; + public readonly IntPtr lpData; } private const int WM_COPYDATA = 0x4A; private const int WM_DESTROY = 0x2; #region Member Variables - private CopyDataChannels channels = null; + private CopyDataChannels _channels; #endregion /// @@ -109,7 +110,7 @@ namespace Greenshot.Helpers { BinaryFormatter b = new BinaryFormatter(); CopyDataObjectData cdo = (CopyDataObjectData) b.Deserialize(stream); - if (channels != null && channels.Contains(cdo.Channel)) { + if (_channels != null && _channels.Contains(cdo.Channel)) { CopyDataReceivedEventArgs d = new CopyDataReceivedEventArgs(cdo.Channel, cdo.Data, cdo.Sent); OnCopyDataReceived(d); m.Result = (IntPtr) 1; @@ -119,8 +120,8 @@ namespace Greenshot.Helpers { // WM_DESTROY fires before OnHandleChanged and is // a better place to ensure that we've cleared // everything up. - if (channels != null) { - channels.OnHandleChange(); + if (_channels != null) { + _channels.OnHandleChange(); } base.OnHandleChange(); } @@ -131,8 +132,12 @@ namespace Greenshot.Helpers { /// Raises the DataReceived event from this class. /// /// The data which has been received. - protected void OnCopyDataReceived(CopyDataReceivedEventArgs e) { - CopyDataReceived(this, e); + protected void OnCopyDataReceived(CopyDataReceivedEventArgs e) + { + if (CopyDataReceived != null) + { + CopyDataReceived(this, e); + } } /// @@ -144,8 +149,8 @@ namespace Greenshot.Helpers { /// protected override void OnHandleChange () { // need to clear up everything we had set. - if (channels != null) { - channels.OnHandleChange(); + if (_channels != null) { + _channels.OnHandleChange(); } base.OnHandleChange(); } @@ -155,7 +160,7 @@ namespace Greenshot.Helpers { /// public CopyDataChannels Channels { get { - return channels; + return _channels; } } @@ -168,9 +173,9 @@ namespace Greenshot.Helpers { /// Clears up any resources associated with this object. /// protected virtual void Dispose(bool disposing) { - if (disposing && channels != null) { - channels.Clear(); - channels = null; + if (disposing && _channels != null) { + _channels.Clear(); + _channels = null; } } @@ -178,7 +183,7 @@ namespace Greenshot.Helpers { /// Constructs a new instance of the CopyData class /// public CopyData() { - channels = new CopyDataChannels(this); + _channels = new CopyDataChannels(this); } /// @@ -196,45 +201,28 @@ namespace Greenshot.Helpers { /// which has been sent from another application. /// public class CopyDataReceivedEventArgs : EventArgs { - private string channelName = ""; - private object data = null; - private DateTime sent; - private DateTime received; - /// /// Gets the channel name that this data was sent on. /// - public string ChannelName { - get { - return channelName; - } - } + public string ChannelName { get; } = ""; + /// /// Gets the data object which was sent. /// - public Object Data { - get { - return data; - } - } + public object Data { get; } + /// /// Gets the date and time which at the data was sent /// by the sending application. /// - public DateTime Sent { - get { - return sent; - } - } + public DateTime Sent { get; } + /// /// Gets the date and time which this data item as /// received. /// - public DateTime Received { - get { - return received; - } - } + public DateTime Received { get; } + /// /// Constructs an instance of this class. /// @@ -242,10 +230,10 @@ namespace Greenshot.Helpers { /// The data which was sent /// The date and time the data was sent internal CopyDataReceivedEventArgs(string channelName, object data, DateTime sent) { - this.channelName = channelName; - this.data = data; - this.sent = sent; - received = DateTime.Now; + ChannelName = channelName; + Data = data; + Sent = sent; + Received = DateTime.Now; } } @@ -254,7 +242,7 @@ namespace Greenshot.Helpers { /// class. /// public class CopyDataChannels : DictionaryBase { - private NativeWindow owner = null; + private readonly NativeWindow _owner; /// /// Returns an enumerator for each of the CopyDataChannel objects @@ -296,7 +284,7 @@ namespace Greenshot.Helpers { /// receive messages. /// public void Add(string channelName) { - CopyDataChannel cdc = new CopyDataChannel(owner, channelName); + CopyDataChannel cdc = new CopyDataChannel(_owner, channelName); Dictionary.Add(channelName , cdc); } /// @@ -334,7 +322,7 @@ namespace Greenshot.Helpers { /// just been removed protected override void OnRemoveComplete ( Object key , Object data ) { ( (CopyDataChannel) data).Dispose(); - base.OnRemove(key, data); + OnRemove(key, data); } /// @@ -357,7 +345,7 @@ namespace Greenshot.Helpers { /// The NativeWindow this collection /// will be associated with internal CopyDataChannels(NativeWindow owner) { - this.owner = owner; + _owner = owner; } } @@ -367,14 +355,14 @@ namespace Greenshot.Helpers { public class CopyDataChannel : IDisposable { #region Unmanaged Code [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - private extern static IntPtr GetProp(IntPtr hwnd, string lpString); + private static extern IntPtr GetProp(IntPtr hwnd, string lpString); [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - private extern static bool SetProp(IntPtr hwnd, string lpString, IntPtr hData); + private static extern bool SetProp(IntPtr hwnd, string lpString, IntPtr hData); [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - private extern static IntPtr RemoveProp(IntPtr hwnd, string lpString); + private static extern IntPtr RemoveProp(IntPtr hwnd, string lpString); [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - private extern static IntPtr SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, ref COPYDATASTRUCT lParam); + private static extern IntPtr SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, ref COPYDATASTRUCT lParam); [StructLayout(LayoutKind.Sequential)] private struct COPYDATASTRUCT { @@ -387,19 +375,15 @@ namespace Greenshot.Helpers { #endregion #region Member Variables - private string channelName = ""; - private NativeWindow owner = null; - private bool recreateChannel = false; + + private readonly NativeWindow _owner; + private bool _recreateChannel; #endregion /// /// Gets the name associated with this channel. /// - public string ChannelName { - get { - return channelName; - } - } + public string ChannelName { get; private set; } /// /// Sends the specified object on this channel to any other @@ -411,12 +395,12 @@ namespace Greenshot.Helpers { public int Send(object obj) { int recipients = 0; - if (recreateChannel) { + if (_recreateChannel) { // handle has changed - addChannel(); + AddChannel(); } - CopyDataObjectData cdo = new CopyDataObjectData(obj, channelName); + CopyDataObjectData cdo = new CopyDataObjectData(obj, ChannelName); // Try to do a binary serialization on obj. @@ -446,14 +430,16 @@ namespace Greenshot.Helpers { // Send the data to each window identified on // the channel: foreach(WindowDetails window in WindowDetails.GetAllWindows()) { - if (!window.Handle.Equals(owner.Handle)) { - if (GetProp(window.Handle, channelName) != IntPtr.Zero) { - COPYDATASTRUCT cds = new COPYDATASTRUCT(); - cds.cbData = dataSize; - cds.dwData = IntPtr.Zero; - cds.lpData = ptrData; - SendMessage(window.Handle, WM_COPYDATA, owner.Handle, ref cds); - recipients += (Marshal.GetLastWin32Error() == 0 ? 1 : 0); + if (!window.Handle.Equals(_owner.Handle)) { + if (GetProp(window.Handle, ChannelName) != IntPtr.Zero) { + COPYDATASTRUCT cds = new COPYDATASTRUCT + { + cbData = dataSize, + dwData = IntPtr.Zero, + lpData = ptrData + }; + SendMessage(window.Handle, WM_COPYDATA, _owner.Handle, ref cds); + recipients += Marshal.GetLastWin32Error() == 0 ? 1 : 0; } } } @@ -466,14 +452,14 @@ namespace Greenshot.Helpers { return recipients; } - private void addChannel() { + private void AddChannel() { // Tag this window with property "channelName" - SetProp(owner.Handle, channelName, owner.Handle); + SetProp(_owner.Handle, ChannelName, _owner.Handle); } - private void removeChannel() { + private void RemoveChannel() { // Remove the "channelName" property from this window - RemoveProp(owner.Handle, channelName); + RemoveProp(_owner.Handle, ChannelName); } /// @@ -484,8 +470,8 @@ namespace Greenshot.Helpers { /// the new handle has been assigned. /// public void OnHandleChange() { - removeChannel(); - recreateChannel = true; + RemoveChannel(); + _recreateChannel = true; } public void Dispose() { @@ -498,10 +484,10 @@ namespace Greenshot.Helpers { /// protected virtual void Dispose(bool disposing) { if (disposing) { - if (channelName.Length > 0) { - removeChannel(); + if (ChannelName.Length > 0) { + RemoveChannel(); } - channelName = ""; + ChannelName = ""; } } @@ -513,9 +499,9 @@ namespace Greenshot.Helpers { /// The name of the channel to /// send messages on internal CopyDataChannel(NativeWindow owner, string channelName) { - this.owner = owner; - this.channelName = channelName; - addChannel(); + _owner = owner; + ChannelName = channelName; + AddChannel(); } ~CopyDataChannel() { @@ -552,7 +538,7 @@ namespace Greenshot.Helpers { Data = data; if (!data.GetType().IsSerializable) { throw new ArgumentException("Data object must be serializable.", - "data"); + nameof(data)); } Channel = channel; Sent = DateTime.Now; diff --git a/Greenshot/Helpers/DestinationHelper.cs b/Greenshot/Helpers/DestinationHelper.cs index 5d69c99d3..fd5f35095 100644 --- a/Greenshot/Helpers/DestinationHelper.cs +++ b/Greenshot/Helpers/DestinationHelper.cs @@ -31,9 +31,9 @@ namespace Greenshot.Helpers { /// Description of DestinationHelper. /// public static class DestinationHelper { - private static ILog LOG = LogManager.GetLogger(typeof(DestinationHelper)); - private static Dictionary RegisteredDestinations = new Dictionary(); - private static CoreConfiguration coreConfig = IniConfig.GetIniSection(); + private static readonly ILog LOG = LogManager.GetLogger(typeof(DestinationHelper)); + private static readonly Dictionary RegisteredDestinations = new Dictionary(); + private static readonly CoreConfiguration coreConfig = IniConfig.GetIniSection(); /// Initialize the destinations static DestinationHelper() { diff --git a/Greenshot/Helpers/EnvironmentInfo.cs b/Greenshot/Helpers/EnvironmentInfo.cs index 4aa2e9bf7..1da8b4e55 100644 --- a/Greenshot/Helpers/EnvironmentInfo.cs +++ b/Greenshot/Helpers/EnvironmentInfo.cs @@ -20,14 +20,12 @@ */ using System; -using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; using Greenshot.IniFile; using GreenshotPlugin.UnmanagedHelpers; -using log4net; namespace Greenshot.Helpers { @@ -36,19 +34,18 @@ namespace Greenshot.Helpers /// public static class EnvironmentInfo { - private static readonly ILog LOG = LogManager.GetLogger(typeof(EnvironmentInfo)); - private static bool? isWindows = null; + private static bool? _isWindows; public static bool IsWindows { get { - if (isWindows.HasValue) + if (_isWindows.HasValue) { - return isWindows.Value; + return _isWindows.Value; } - isWindows = Environment.OSVersion.Platform.ToString().StartsWith("Win"); - return isWindows.Value; + _isWindows = Environment.OSVersion.Platform.ToString().StartsWith("Win"); + return _isWindows.Value; } } @@ -101,7 +98,7 @@ namespace Greenshot.Helpers { environment.Append(", "); } - environment.Append(String.Format("OS: {0} {1} {2} (x{3}) {4}", OSInfo.Name, OSInfo.Edition, OSInfo.ServicePack, OSInfo.Bits, OSInfo.VersionString)); + environment.Append(string.Format("OS: {0} {1} {2} (x{3}) {4}", OSInfo.Name, OSInfo.Edition, OSInfo.ServicePack, OSInfo.Bits, OSInfo.VersionString)); if (newline) { environment.AppendLine(); @@ -201,11 +198,6 @@ namespace Greenshot.Helpers exceptionText.AppendLine(EnvironmentToString(true)); exceptionText.AppendLine(ExceptionToString(exception)); exceptionText.AppendLine("Configuration dump:"); - using (TextWriter writer = new StringWriter(exceptionText)) - { - // TODO: Create summary of properties - //var iniConfig = IniConfig.Current.WriteToStreamAsync(); - } return exceptionText.ToString(); } @@ -215,13 +207,13 @@ namespace Greenshot.Helpers /// Provides detailed information about the host operating system. /// Code is available at: http://www.csharp411.com/determine-windows-version-and-edition-with-c/ /// - static public class OSInfo + public static class OSInfo { #region BITS /// /// Determines if the current application is 32 or 64-bit. /// - static public int Bits + public static int Bits { get { @@ -231,24 +223,26 @@ namespace Greenshot.Helpers #endregion BITS #region EDITION - static private string s_Edition; + private static string _sEdition; /// /// Gets the edition of the operating system running on this computer. /// - static public string Edition + public static string Edition { get { - if (s_Edition != null) + if (_sEdition != null) { - return s_Edition; //***** RETURN *****// + return _sEdition; //***** RETURN *****// } - string edition = String.Empty; + string edition = string.Empty; OperatingSystem osVersion = Environment.OSVersion; - OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX(); - osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf(typeof(OSVERSIONINFOEX)); + OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX + { + dwOSVersionInfoSize = Marshal.SizeOf(typeof (OSVERSIONINFOEX)) + }; if (GetVersionEx(ref osVersionInfo)) { @@ -469,18 +463,18 @@ namespace Greenshot.Helpers #endregion VERSION 6 } - s_Edition = edition; + _sEdition = edition; return edition; } } #endregion EDITION #region NAME - static private string s_Name; + private static string s_Name; /// /// Gets the name of the operating system running on this computer. /// - static public string Name + public static string Name { get { @@ -666,17 +660,17 @@ namespace Greenshot.Helpers private struct OSVERSIONINFOEX { public int dwOSVersionInfoSize; - public int dwMajorVersion; - public int dwMinorVersion; - public int dwBuildNumber; - public int dwPlatformId; + public readonly int dwMajorVersion; + public readonly int dwMinorVersion; + public readonly int dwBuildNumber; + public readonly int dwPlatformId; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] - public string szCSDVersion; - public short wServicePackMajor; - public short wServicePackMinor; - public short wSuiteMask; - public byte wProductType; - public byte wReserved; + public readonly string szCSDVersion; + public readonly short wServicePackMajor; + public readonly short wServicePackMinor; + public readonly short wSuiteMask; + public readonly byte wProductType; + public readonly byte wReserved; } #endregion OSVERSIONINFOEX @@ -724,13 +718,9 @@ namespace Greenshot.Helpers #region VERSIONS private const int VER_NT_WORKSTATION = 1; - private const int VER_NT_DOMAIN_CONTROLLER = 2; private const int VER_NT_SERVER = 3; - private const int VER_SUITE_SMALLBUSINESS = 1; private const int VER_SUITE_ENTERPRISE = 2; - private const int VER_SUITE_TERMINAL = 16; private const int VER_SUITE_DATACENTER = 128; - private const int VER_SUITE_SINGLEUSERTS = 256; private const int VER_SUITE_PERSONAL = 512; private const int VER_SUITE_BLADE = 1024; #endregion VERSIONS @@ -740,11 +730,11 @@ namespace Greenshot.Helpers /// /// Gets the service pack information of the operating system running on this computer. /// - static public string ServicePack + public static string ServicePack { get { - string servicePack = String.Empty; + string servicePack = string.Empty; OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX(); osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf(typeof(OSVERSIONINFOEX)); @@ -778,7 +768,7 @@ namespace Greenshot.Helpers /// /// Gets the full version string of the operating system running on this computer. /// - static public string VersionString + public static string VersionString { get { @@ -791,7 +781,7 @@ namespace Greenshot.Helpers /// /// Gets the full version of the operating system running on this computer. /// - static public Version Version + public static Version Version { get { @@ -805,7 +795,7 @@ namespace Greenshot.Helpers /// /// Gets the major version number of the operating system running on this computer. /// - static public int MajorVersion + public static int MajorVersion { get { @@ -818,7 +808,7 @@ namespace Greenshot.Helpers /// /// Gets the minor version number of the operating system running on this computer. /// - static public int MinorVersion + public static int MinorVersion { get { @@ -831,7 +821,7 @@ namespace Greenshot.Helpers /// /// Gets the revision version number of the operating system running on this computer. /// - static public int RevisionVersion + public static int RevisionVersion { get { diff --git a/Greenshot/Helpers/GeometryHelper.cs b/Greenshot/Helpers/GeometryHelper.cs index 98534a2df..ff6ec0191 100644 --- a/Greenshot/Helpers/GeometryHelper.cs +++ b/Greenshot/Helpers/GeometryHelper.cs @@ -37,9 +37,9 @@ namespace Greenshot.Helpers { //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/Helpers/IECaptureHelper.cs b/Greenshot/Helpers/IECaptureHelper.cs index 1786106c9..78ceb3913 100644 --- a/Greenshot/Helpers/IECaptureHelper.cs +++ b/Greenshot/Helpers/IECaptureHelper.cs @@ -42,7 +42,7 @@ namespace Greenshot.Helpers { /// Many thanks to all the people who contributed here! /// public static class IECaptureHelper { - private static ILog LOG = LogManager.GetLogger(typeof(IECaptureHelper)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(IECaptureHelper)); private static readonly CoreConfiguration configuration = IniConfig.GetIniSection(); // Helper method to activate a certain IE Tab @@ -69,7 +69,7 @@ namespace Greenshot.Helpers { if (ieWindow != null) { Rectangle wholeClient = someWindow.ClientRectangle; Rectangle partClient = ieWindow.ClientRectangle; - int percentage = (int)(100*((float)(partClient.Width * partClient.Height)) / ((float)(wholeClient.Width * wholeClient.Height))); + int percentage = (int)(100*(float)(partClient.Width * partClient.Height) / (float)(wholeClient.Width * wholeClient.Height)); LOG.InfoFormat("Window {0}, ie part {1}, percentage {2}", wholeClient, partClient, percentage); if (percentage > minimumPercentage) { return true; @@ -143,7 +143,7 @@ namespace Greenshot.Helpers { } else if (configuration.WindowClassesToCheckForIE != null && configuration.WindowClassesToCheckForIE.Contains(ieWindow.ClassName)) { List singleWindowText = new List(); try { - IHTMLDocument2 document2 = getHTMLDocument(ieWindow); + IHTMLDocument2 document2 = GetHtmlDocument(ieWindow); string title = document2.title; Marshal.ReleaseComObject(document2); if (string.IsNullOrEmpty(title)) { @@ -177,7 +177,7 @@ namespace Greenshot.Helpers { /// /// /// - private static IHTMLDocument2 getHTMLDocument(WindowDetails mainWindow) { + private static IHTMLDocument2 GetHtmlDocument(WindowDetails mainWindow) { WindowDetails ieServer; if ("Internet Explorer_Server".Equals(mainWindow.ClassName)) { ieServer = mainWindow; @@ -249,7 +249,7 @@ namespace Greenshot.Helpers { try { // Get the Document - IHTMLDocument2 document2 = getHTMLDocument(ieWindow); + IHTMLDocument2 document2 = GetHtmlDocument(ieWindow); if (document2 == null) { continue; } @@ -371,7 +371,7 @@ namespace Greenshot.Helpers { Bitmap returnBitmap = null; try { Size pageSize = PrepareCapture(documentContainer, capture); - returnBitmap = capturePage(documentContainer, capture, pageSize); + returnBitmap = CapturePage(documentContainer, pageSize); } catch (Exception captureException) { LOG.Error("Exception found, ignoring and returning nothing! Error was: ", captureException); } @@ -554,8 +554,9 @@ namespace Greenshot.Helpers { /// Capture the actual page (document) /// /// The document wrapped in a container + /// /// Bitmap with the page content as an image - private static Bitmap capturePage(DocumentContainer documentContainer, ICapture capture, Size pageSize) { + private static Bitmap CapturePage(DocumentContainer documentContainer, Size pageSize) { WindowDetails contentWindowDetails = documentContainer.ContentWindow; //Create a target bitmap to draw into with the calculated page size @@ -567,7 +568,7 @@ namespace Greenshot.Helpers { graphicsTarget.Clear(clearColor); // Get the base document & draw it - drawDocument(documentContainer, contentWindowDetails, graphicsTarget); + DrawDocument(documentContainer, contentWindowDetails, graphicsTarget); // Loop over the frames and clear their source area so we don't see any artefacts foreach(DocumentContainer frameDocument in documentContainer.Frames) { @@ -577,7 +578,7 @@ namespace Greenshot.Helpers { } // Loop over the frames and capture their content foreach(DocumentContainer frameDocument in documentContainer.Frames) { - drawDocument(frameDocument, contentWindowDetails, graphicsTarget); + DrawDocument(frameDocument, contentWindowDetails, graphicsTarget); } } return returnBitmap; @@ -586,11 +587,11 @@ namespace Greenshot.Helpers { /// /// This method takes the actual capture of the document (frame) /// - /// + /// /// Needed for referencing the location of the frame /// Bitmap with the capture - private static void drawDocument(DocumentContainer documentContainer, WindowDetails contentWindowDetails, Graphics graphicsTarget) { - documentContainer.setAttribute("scroll", 1); + private static void DrawDocument(DocumentContainer documentContainer, WindowDetails contentWindowDetails, Graphics graphicsTarget) { + documentContainer.SetAttribute("scroll", 1); //Get Browser Window Width & Height int pageWidth = documentContainer.ScrollWidth; @@ -621,14 +622,14 @@ namespace Greenshot.Helpers { Point targetOffset = new Point(); // Loop of the pages and make a copy of the visible viewport - while ((horizontalPage * viewportWidth) < pageWidth) { + while (horizontalPage * viewportWidth < pageWidth) { // Scroll to location documentContainer.ScrollLeft = viewportWidth * horizontalPage; targetOffset.X = documentContainer.ScrollLeft; // Variable used for looping vertically int verticalPage = 0; - while ((verticalPage * viewportHeight) < pageHeight) { + while (verticalPage * viewportHeight < pageHeight) { // Scroll to location documentContainer.ScrollTop = viewportHeight * verticalPage; //Shoot visible window diff --git a/Greenshot/Helpers/IEInterop/IEContainer.cs b/Greenshot/Helpers/IEInterop/IEContainer.cs index 0b5b740bc..899ebae46 100644 --- a/Greenshot/Helpers/IEInterop/IEContainer.cs +++ b/Greenshot/Helpers/IEInterop/IEContainer.cs @@ -26,33 +26,31 @@ using System.Runtime.InteropServices; using GreenshotPlugin.Core; using Greenshot.Interop.IE; -using Greenshot.IniFile; using log4net; using IServiceProvider = Greenshot.Interop.IServiceProvider; namespace Greenshot.Helpers.IEInterop { public class DocumentContainer { - private static ILog LOG = LogManager.GetLogger(typeof(DocumentContainer)); - private static CoreConfiguration configuration = IniConfig.GetIniSection(); + private static readonly ILog LOG = LogManager.GetLogger(typeof(DocumentContainer)); private const int E_ACCESSDENIED = unchecked((int)0x80070005L); private static readonly Guid IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046"); private static readonly Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E"); - private static int counter = 0; - private int id = counter++; - private IHTMLDocument2 document2; - private IHTMLDocument3 document3; - private Point sourceLocation; - private Point destinationLocation; - private Point startLocation = Point.Empty; - private Rectangle viewportRectangle = Rectangle.Empty; - private string name = null; - private string url; - private bool isDTD; - private DocumentContainer parent; - private WindowDetails contentWindow; - private double zoomLevelX = 1; - private double zoomLevelY = 1; - private List frames = new List(); + private static int _counter; + private readonly int _id = _counter++; + private IHTMLDocument2 _document2; + private IHTMLDocument3 _document3; + private Point _sourceLocation; + private Point _destinationLocation; + private Point _startLocation = Point.Empty; + private Rectangle _viewportRectangle = Rectangle.Empty; + private string _name; + private string _url; + private bool _isDtd; + private DocumentContainer _parent; + private WindowDetails _contentWindow; + private double _zoomLevelX = 1; + private double _zoomLevelY = 1; + private readonly IList _frames = new List(); private DocumentContainer(IHTMLWindow2 frameWindow, WindowDetails contentWindow, DocumentContainer parent) { //IWebBrowser2 webBrowser2 = frame as IWebBrowser2; @@ -60,22 +58,22 @@ namespace Greenshot.Helpers.IEInterop { IHTMLDocument2 document2 = GetDocumentFromWindow(frameWindow); try { LOG.DebugFormat("frameWindow.name {0}", frameWindow.name); - name = frameWindow.name; + _name = frameWindow.name; } catch { - + // Ignore } try { LOG.DebugFormat("document2.url {0}",document2.url); } catch { - + // Ignore } try { LOG.DebugFormat("document2.title {0}", document2.title); } catch { - + // Ignore } - this.parent = parent; + _parent = parent; // Calculate startLocation for the frames IHTMLWindow2 window2 = document2.parentWindow; IHTMLWindow3 window3 = (IHTMLWindow3)window2; @@ -87,13 +85,13 @@ namespace Greenshot.Helpers.IEInterop { releaseCom(window2); releaseCom(window3); - startLocation = new Point(x, y); + _startLocation = new Point(x, y); Init(document2, contentWindow); } public DocumentContainer(IHTMLDocument2 document2, WindowDetails contentWindow) { Init(document2, contentWindow); - LOG.DebugFormat("Creating DocumentContainer for Document {0} found in window with rectangle {1}", name, SourceRectangle); + LOG.DebugFormat("Creating DocumentContainer for Document {0} found in window with rectangle {1}", _name, SourceRectangle); } /// @@ -112,17 +110,17 @@ namespace Greenshot.Helpers.IEInterop { /// IHTMLDocument2 /// WindowDetails private void Init(IHTMLDocument2 document2, WindowDetails contentWindow) { - this.document2 = document2; - this.contentWindow = contentWindow; - document3 = document2 as IHTMLDocument3; + _document2 = document2; + _contentWindow = contentWindow; + _document3 = document2 as IHTMLDocument3; // Check what access method is needed for the document IHTMLDocument5 document5 = (IHTMLDocument5)document2; //compatibility mode affects how height is computed - isDTD = false; + _isDtd = false; try { - if ((document3.documentElement != null) && (!document5.compatMode.Equals("BackCompat"))) { - isDTD = true; + if (_document3 != null && (_document3.documentElement != null) && !document5.compatMode.Equals("BackCompat")) { + _isDtd = true; } } catch (Exception ex) { LOG.Error("Error checking the compatibility mode:"); @@ -133,21 +131,21 @@ namespace Greenshot.Helpers.IEInterop { Rectangle clientRectangle = contentWindow.WindowRectangle; try { - IHTMLWindow2 window2 = (IHTMLWindow2)document2.parentWindow; + IHTMLWindow2 window2 = document2.parentWindow; //IHTMLWindow3 window3 = (IHTMLWindow3)document2.parentWindow; IHTMLScreen screen = window2.screen; IHTMLScreen2 screen2 = (IHTMLScreen2)screen; - if (parent != null) { + if (_parent != null) { // Copy parent values - zoomLevelX = parent.zoomLevelX; - zoomLevelY = parent.zoomLevelY; - viewportRectangle = parent.viewportRectangle; + _zoomLevelX = _parent._zoomLevelX; + _zoomLevelY = _parent._zoomLevelY; + _viewportRectangle = _parent._viewportRectangle; } else { //DisableScrollbars(document2); // Calculate zoom level - zoomLevelX = (double)screen2.deviceXDPI/(double)screen2.logicalXDPI; - zoomLevelY = (double)screen2.deviceYDPI/(double)screen2.logicalYDPI; + _zoomLevelX = screen2.deviceXDPI/(double)screen2.logicalXDPI; + _zoomLevelY = screen2.deviceYDPI/(double)screen2.logicalYDPI; // Calculate the viewport rectangle, needed if there is a frame around the html window @@ -162,11 +160,11 @@ namespace Greenshot.Helpers.IEInterop { if ((diffX == 4 || diffX >= 20) && (diffY == 4 || diffY >= 20)) { Point viewportOffset = new Point(2, 2); Size viewportSize = new Size(ClientWidth, ClientHeight); - viewportRectangle = new Rectangle(viewportOffset, viewportSize); - LOG.DebugFormat("viewportRect {0}", viewportRectangle); + _viewportRectangle = new Rectangle(viewportOffset, viewportSize); + LOG.DebugFormat("viewportRect {0}", _viewportRectangle); } } - LOG.DebugFormat("Zoomlevel {0}, {1}", zoomLevelX, zoomLevelY); + LOG.DebugFormat("Zoomlevel {0}, {1}", _zoomLevelX, _zoomLevelY); // Release com objects releaseCom(window2); releaseCom(screen); @@ -177,23 +175,23 @@ namespace Greenshot.Helpers.IEInterop { try { - LOG.DebugFormat("Calculated location {0} for {1}", startLocation, document2.title); - if (name == null) { - name = document2.title; + LOG.DebugFormat("Calculated location {0} for {1}", _startLocation, document2.title); + if (_name == null) { + _name = document2.title; } } catch (Exception e) { LOG.Warn("Problem while trying to get document title!", e); } try { - url = document2.url; + _url = document2.url; } catch (Exception e) { LOG.Warn("Problem while trying to get document url!", e); } - sourceLocation = new Point(ScaleX((int)startLocation.X), ScaleY((int)startLocation.Y)); - destinationLocation = new Point(ScaleX((int)startLocation.X), ScaleY((int)startLocation.Y)); + _sourceLocation = new Point(ScaleX(_startLocation.X), ScaleY(_startLocation.Y)); + _destinationLocation = new Point(ScaleX(_startLocation.X), ScaleY(_startLocation.Y)); - if (parent != null) { + if (_parent != null) { return; } try { @@ -203,9 +201,9 @@ namespace Greenshot.Helpers.IEInterop { IHTMLWindow2 frameWindow = frameCollection.item(frame); DocumentContainer frameData = new DocumentContainer(frameWindow, contentWindow, this); // check if frame is hidden - if (!frameData.isHidden) { - LOG.DebugFormat("Creating DocumentContainer for Frame {0} found in window with rectangle {1}", frameData.name, frameData.SourceRectangle); - frames.Add(frameData); + if (!frameData.IsHidden) { + LOG.DebugFormat("Creating DocumentContainer for Frame {0} found in window with rectangle {1}", frameData._name, frameData.SourceRectangle); + _frames.Add(frameData); } else { LOG.DebugFormat("Skipping frame {0}", frameData.Name); } @@ -223,7 +221,7 @@ namespace Greenshot.Helpers.IEInterop { try { // Correct iframe locations - foreach (IHTMLElement frameElement in document3.getElementsByTagName("IFRAME")) { + foreach (IHTMLElement frameElement in _document3.getElementsByTagName("IFRAME")) { try { CorrectFrameLocations(frameElement); // Clean up frameElement @@ -264,7 +262,7 @@ namespace Greenshot.Helpers.IEInterop { // Release IHTMLRect releaseCom(rec); LOG.DebugFormat("Looking for iframe to correct at {0}", elementBoundingLocation); - foreach(DocumentContainer foundFrame in frames) { + foreach(DocumentContainer foundFrame in _frames) { Point frameLocation = foundFrame.SourceLocation; if (frameLocation.Equals(elementBoundingLocation)) { // Match found, correcting location @@ -313,13 +311,13 @@ namespace Greenshot.Helpers.IEInterop { IServiceProvider sp = (IServiceProvider)htmlWindow; // Use IServiceProvider.QueryService to get IWebBrowser2 object. - Object brws = null; + object brws; Guid webBrowserApp = IID_IWebBrowserApp; Guid webBrowser2 = IID_IWebBrowser2; sp.QueryService(ref webBrowserApp, ref webBrowser2, out brws); // Get the document from IWebBrowser2. - IWebBrowser2 browser = (IWebBrowser2)(brws); + IWebBrowser2 browser = (IWebBrowser2)brws; return (IHTMLDocument2)browser.Document; } catch (Exception ex2) { @@ -331,9 +329,9 @@ namespace Greenshot.Helpers.IEInterop { public Color BackgroundColor { get { try { - string bgColor = (string)document2.bgColor; + string bgColor = (string)_document2.bgColor; if (bgColor != null) { - int rgbInt = Int32.Parse(bgColor.Substring(1), NumberStyles.HexNumber); + int rgbInt = int.Parse(bgColor.Substring(1), NumberStyles.HexNumber); return Color.FromArgb(rgbInt >> 16, (rgbInt >> 8) & 255, rgbInt & 255); } } catch (Exception ex) { @@ -345,46 +343,46 @@ namespace Greenshot.Helpers.IEInterop { public Rectangle ViewportRectangle { get { - return viewportRectangle; + return _viewportRectangle; } } public WindowDetails ContentWindow { get { - return contentWindow; + return _contentWindow; } } public DocumentContainer Parent { get { - return parent; + return _parent; } set { - parent = value; + _parent = value; } } private int ScaleX(int physicalValue) { - return (int)Math.Round(physicalValue * zoomLevelX, MidpointRounding.AwayFromZero); + return (int)Math.Round(physicalValue * _zoomLevelX, MidpointRounding.AwayFromZero); } private int ScaleY(int physicalValue) { - return (int)Math.Round(physicalValue * zoomLevelY, MidpointRounding.AwayFromZero); + return (int)Math.Round(physicalValue * _zoomLevelY, MidpointRounding.AwayFromZero); } private int UnscaleX(int physicalValue) { - return (int)Math.Round(physicalValue / zoomLevelX, MidpointRounding.AwayFromZero); + return (int)Math.Round(physicalValue / _zoomLevelX, MidpointRounding.AwayFromZero); } private int UnscaleY(int physicalValue) { - return (int)Math.Round(physicalValue / zoomLevelY, MidpointRounding.AwayFromZero); + return (int)Math.Round(physicalValue / _zoomLevelY, MidpointRounding.AwayFromZero); } /// /// Set/change an int attribute on a document /// - public void setAttribute(string attribute, int value) { - setAttribute(attribute, value.ToString()); + public void SetAttribute(string attribute, int value) { + SetAttribute(attribute, value.ToString()); } /// @@ -392,14 +390,12 @@ namespace Greenshot.Helpers.IEInterop { /// /// Attribute to set /// Value to set - /// The IHTMLDocument2 - /// The IHTMLDocument3 - public void setAttribute(string attribute, string value) { + public void SetAttribute(string attribute, string value) { IHTMLElement element = null; - if (!isDTD) { - element = document2.body; + if (!_isDtd) { + element = _document2.body; } else { - element = document3.documentElement; + element = _document3.documentElement; } element.setAttribute(attribute, value, 1); // Release IHTMLElement com object @@ -410,18 +406,15 @@ namespace Greenshot.Helpers.IEInterop { /// Get the attribute from a document /// /// Attribute to get - /// The IHTMLDocument2 - /// The IHTMLDocument3 /// object with the attribute value - public object getAttribute(string attribute) { - IHTMLElement element = null; - object retVal = 0; - if (!isDTD) { - element = document2.body; + public object GetAttribute(string attribute) { + IHTMLElement element; + if (!_isDtd) { + element = _document2.body; } else { - element = document3.documentElement; + element = _document3.documentElement; } - retVal = element.getAttribute(attribute, 1); + var retVal = element.getAttribute(attribute, 1); // Release IHTMLElement com object releaseCom(element); return retVal; @@ -430,30 +423,30 @@ namespace Greenshot.Helpers.IEInterop { /// /// Get the attribute as int from a document /// - public int getAttributeAsInt(string attribute) { - int retVal = (int)getAttribute(attribute); + public int GetAttributeAsInt(string attribute) { + int retVal = (int)GetAttribute(attribute); return retVal; } public int ID { get { - return id; + return _id; } } public string Name { get { - return name; + return _name; } } public string Url { get { - return url; + return _url; } } - public bool isHidden { + public bool IsHidden { get { return ClientWidth == 0 || ClientHeight == 0; } @@ -461,34 +454,34 @@ namespace Greenshot.Helpers.IEInterop { public int ClientWidth { get { - return ScaleX(getAttributeAsInt("clientWidth")); + return ScaleX(GetAttributeAsInt("clientWidth")); } } public int ClientHeight { get { - return ScaleY(getAttributeAsInt("clientHeight")); + return ScaleY(GetAttributeAsInt("clientHeight")); } } public int ScrollWidth { get { - return ScaleX(getAttributeAsInt("scrollWidth")); + return ScaleX(GetAttributeAsInt("scrollWidth")); } } public int ScrollHeight { get { - return ScaleY(getAttributeAsInt("scrollHeight")); + return ScaleY(GetAttributeAsInt("scrollHeight")); } } public Point SourceLocation { get { - return sourceLocation; + return _sourceLocation; } set { - sourceLocation = value; + _sourceLocation = value; } } @@ -506,34 +499,34 @@ namespace Greenshot.Helpers.IEInterop { public int SourceLeft { get { - return sourceLocation.X; + return _sourceLocation.X; } } public int SourceTop { get { - return sourceLocation.Y; + return _sourceLocation.Y; } } public int SourceRight { get { - return sourceLocation.X + ClientWidth; + return _sourceLocation.X + ClientWidth; } } public int SourceBottom { get { - return sourceLocation.Y + ClientHeight; + return _sourceLocation.Y + ClientHeight; } } public Point DestinationLocation { get { - return destinationLocation; + return _destinationLocation; } set { - destinationLocation = value; + _destinationLocation = value; } } @@ -552,55 +545,55 @@ namespace Greenshot.Helpers.IEInterop { public int DestinationLeft { get { - return destinationLocation.X; + return _destinationLocation.X; } set { - destinationLocation.X = value; + _destinationLocation.X = value; } } public int DestinationTop { get { - return destinationLocation.Y; + return _destinationLocation.Y; } set { - destinationLocation.Y = value; + _destinationLocation.Y = value; } } public int DestinationRight { get { - return destinationLocation.X + ScrollWidth; + return _destinationLocation.X + ScrollWidth; } } public int DestinationBottom { get { - return destinationLocation.Y + ScrollHeight; + return _destinationLocation.Y + ScrollHeight; } } public int ScrollLeft { get{ - return ScaleX(getAttributeAsInt("scrollLeft")); + return ScaleX(GetAttributeAsInt("scrollLeft")); } set { - setAttribute("scrollLeft", UnscaleX(value)); + SetAttribute("scrollLeft", UnscaleX(value)); } } public int ScrollTop { get{ - return ScaleY(getAttributeAsInt("scrollTop")); + return ScaleY(GetAttributeAsInt("scrollTop")); } set { - setAttribute("scrollTop", UnscaleY(value)); + SetAttribute("scrollTop", UnscaleY(value)); } } - public List Frames { + public IList Frames { get { - return frames; + return _frames; } } } diff --git a/Greenshot/Helpers/MailHelper.cs b/Greenshot/Helpers/MailHelper.cs index 4bb549603..b7024ae0d 100644 --- a/Greenshot/Helpers/MailHelper.cs +++ b/Greenshot/Helpers/MailHelper.cs @@ -97,9 +97,9 @@ namespace Greenshot.Helpers { private class MapiFileDescriptor { public int reserved = 0; public int flags = 0; - public int position = 0; - public string path = null; - public string name = null; + public int position; + public string path; + public string name; public IntPtr type = IntPtr.Zero; } @@ -110,7 +110,8 @@ namespace Greenshot.Helpers { /// /// Specifies the valid RecipientTypes for a Recipient. /// - public enum RecipientType : int { + public enum RecipientType + { /// /// Recipient will be in the TO list. /// @@ -497,25 +498,25 @@ namespace Greenshot.Helpers { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public class MapiMessage { public int Reserved = 0; - public string Subject = null; - public string NoteText = null; + public string Subject; + public string NoteText; public string MessageType = null; public string DateReceived = null; public string ConversationID = null; public int Flags = 0; public IntPtr Originator = IntPtr.Zero; - public int RecipientCount = 0; + public int RecipientCount; public IntPtr Recipients = IntPtr.Zero; - public int FileCount = 0; + public int FileCount; public IntPtr Files = IntPtr.Zero; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public class MapiRecipDesc { public int Reserved = 0; - public int RecipientClass = 0; - public string Name = null; - public string Address = null; + public int RecipientClass; + public string Name; + public string Address; public int eIDSize = 0; public IntPtr EntryID = IntPtr.Zero; } @@ -542,12 +543,12 @@ namespace Greenshot.Helpers { /// /// The email address of this recipient. /// - public string Address = null; + public string Address; /// /// The display name of this recipient. /// - public string DisplayName = null; + public string DisplayName; /// /// How the recipient will receive this message (To, CC, BCC). diff --git a/Greenshot/Helpers/PluginHelper.cs b/Greenshot/Helpers/PluginHelper.cs index 9062490e3..c757cef68 100644 --- a/Greenshot/Helpers/PluginHelper.cs +++ b/Greenshot/Helpers/PluginHelper.cs @@ -36,12 +36,12 @@ namespace Greenshot.Helpers { [Serializable] public class PluginHelper : IGreenshotHost { private static readonly ILog LOG = LogManager.GetLogger(typeof(PluginHelper)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); - private static string pluginPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),Application.ProductName); - private static string applicationPath = Path.GetDirectoryName(Application.ExecutablePath); - private static string pafPath = Path.Combine(Application.StartupPath, @"App\Greenshot"); - private static IDictionary plugins = new SortedDictionary(); + private static readonly string pluginPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),Application.ProductName); + private static readonly string applicationPath = Path.GetDirectoryName(Application.ExecutablePath); + private static readonly string pafPath = Path.Combine(Application.StartupPath, @"App\Greenshot"); + private static readonly IDictionary plugins = new SortedDictionary(); private static readonly PluginHelper instance = new PluginHelper(); public static PluginHelper Instance { get { @@ -66,7 +66,7 @@ namespace Greenshot.Helpers { } public bool HasPlugins() { - return (plugins != null && plugins.Count > 0); + return plugins != null && plugins.Count > 0; } public void Shutdown() { diff --git a/Greenshot/Helpers/PrintHelper.cs b/Greenshot/Helpers/PrintHelper.cs index ddb42b5b9..c9016569f 100644 --- a/Greenshot/Helpers/PrintHelper.cs +++ b/Greenshot/Helpers/PrintHelper.cs @@ -37,10 +37,10 @@ namespace Greenshot.Helpers { /// public class PrintHelper : IDisposable { private static readonly ILog LOG = LogManager.GetLogger(typeof(PrintHelper)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); private ISurface surface; - private ICaptureDetails captureDetails; + private readonly ICaptureDetails captureDetails; private PrintDocument printDocument = new PrintDocument(); private PrintDialog printDialog = new PrintDialog(); @@ -218,7 +218,7 @@ namespace Greenshot.Helpers { if (conf.OutputPrintFooter) { //printRect = new RectangleF(0, 0, printRect.Width, printRect.Height - (dateStringHeight * 2)); using (Font f = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular)) { - e.Graphics.DrawString(footerString, f, Brushes.Black, pageRect.Width / 2 - (footerStringWidth / 2), pageRect.Height); + e.Graphics.DrawString(footerString, f, Brushes.Black, pageRect.Width / 2 - footerStringWidth / 2, pageRect.Height); } } e.Graphics.DrawImage(image, printRect, imageRect, GraphicsUnit.Pixel); diff --git a/Greenshot/Helpers/ProcessorHelper.cs b/Greenshot/Helpers/ProcessorHelper.cs index ea5c4bef9..5da3736ac 100644 --- a/Greenshot/Helpers/ProcessorHelper.cs +++ b/Greenshot/Helpers/ProcessorHelper.cs @@ -30,8 +30,8 @@ namespace Greenshot.Helpers { /// Description of ProcessorHelper. /// public static class ProcessorHelper { - private static ILog LOG = LogManager.GetLogger(typeof(ProcessorHelper)); - private static Dictionary RegisteredProcessors = new Dictionary(); + private static readonly ILog LOG = LogManager.GetLogger(typeof(ProcessorHelper)); + private static readonly Dictionary RegisteredProcessors = new Dictionary(); /// Initialize the Processors static ProcessorHelper() { diff --git a/Greenshot/Helpers/ScaleHelper.cs b/Greenshot/Helpers/ScaleHelper.cs index 77557fc73..7f348b932 100644 --- a/Greenshot/Helpers/ScaleHelper.cs +++ b/Greenshot/Helpers/ScaleHelper.cs @@ -22,7 +22,6 @@ using System; using System.Drawing; using System.Windows.Forms; using Greenshot.Drawing; -using log4net; namespace Greenshot.Helpers { /// @@ -45,9 +44,7 @@ namespace Greenshot.Helpers { /// Rational = 0x02 } - - private static readonly ILog LOG = LogManager.GetLogger(typeof(ScaleHelper)); - + /// /// calculates the Size an element must be resized to, in order to fit another element, keeping aspect ratio /// @@ -77,7 +74,7 @@ namespace Greenshot.Helpers { 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; @@ -88,18 +85,18 @@ namespace Greenshot.Helpers { 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; @@ -323,7 +320,7 @@ namespace Greenshot.Helpers { /// the current ScaleOptions depending on modifier keys held down 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; @@ -349,7 +346,7 @@ namespace Greenshot.Helpers { } } public class FixedAngleRoundBehavior : IDoubleProcessor { - private double fixedAngle; + private readonly double fixedAngle; public FixedAngleRoundBehavior(double fixedAngle) { this.fixedAngle = fixedAngle; } diff --git a/Greenshot/Helpers/SoundHelper.cs b/Greenshot/Helpers/SoundHelper.cs index 1b84b1907..d362d8d2b 100644 --- a/Greenshot/Helpers/SoundHelper.cs +++ b/Greenshot/Helpers/SoundHelper.cs @@ -39,27 +39,27 @@ namespace Greenshot.Helpers { /// public static class SoundHelper { private static readonly ILog LOG = LogManager.GetLogger(typeof(SoundHelper)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); - private static GCHandle? gcHandle = null; - private static byte[] soundBuffer = null; + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); + private static GCHandle? _gcHandle; + private static byte[] _soundBuffer; public static void Initialize() { - if (gcHandle == null) { + if (_gcHandle == null) { try { ResourceManager resources = new ResourceManager("Greenshot.Sounds", Assembly.GetExecutingAssembly()); - soundBuffer = (byte[])resources.GetObject("camera"); + _soundBuffer = (byte[])resources.GetObject("camera"); if (conf.NotificationSound != null && conf.NotificationSound.EndsWith(".wav")) { try { if (File.Exists(conf.NotificationSound)) { - soundBuffer = File.ReadAllBytes(conf.NotificationSound); + _soundBuffer = File.ReadAllBytes(conf.NotificationSound); } } catch (Exception ex) { LOG.WarnFormat("couldn't load {0}: {1}", conf.NotificationSound, ex.Message); } } // Pin sound so it can't be moved by the Garbage Collector, this was the cause for the bad sound - gcHandle = GCHandle.Alloc(soundBuffer, GCHandleType.Pinned); + _gcHandle = GCHandle.Alloc(_soundBuffer, GCHandleType.Pinned); } catch (Exception e) { LOG.Error("Error initializing.", e); } @@ -67,11 +67,11 @@ namespace Greenshot.Helpers { } public static void Play() { - if (soundBuffer != null) { + if (_soundBuffer != null) { //Thread playSoundThread = new Thread(delegate() { SoundFlags flags = SoundFlags.SND_ASYNC | SoundFlags.SND_MEMORY | SoundFlags.SND_NOWAIT | SoundFlags.SND_NOSTOP; try { - WinMM.PlaySound(gcHandle.Value.AddrOfPinnedObject(), (UIntPtr)0, (uint)flags); + WinMM.PlaySound(_gcHandle.Value.AddrOfPinnedObject(), (UIntPtr)0, (uint)flags); } catch (Exception e) { LOG.Error("Error in play.", e); } @@ -84,10 +84,10 @@ namespace Greenshot.Helpers { public static void Deinitialize() { try { - if (gcHandle != null) { + if (_gcHandle != null) { WinMM.PlaySound((byte[])null, (UIntPtr)0, (uint)0); - gcHandle.Value.Free(); - gcHandle = null; + _gcHandle.Value.Free(); + _gcHandle = null; } } catch (Exception e) { LOG.Error("Error in deinitialize.", e); diff --git a/Greenshot/Helpers/UpdateHelper.cs b/Greenshot/Helpers/UpdateHelper.cs index 723331d25..cf7437835 100644 --- a/Greenshot/Helpers/UpdateHelper.cs +++ b/Greenshot/Helpers/UpdateHelper.cs @@ -35,7 +35,7 @@ namespace Greenshot.Experimental { /// public static class UpdateHelper { private static readonly ILog LOG = LogManager.GetLogger(typeof(UpdateHelper)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); private const string STABLE_DOWNLOAD_LINK = "http://getgreenshot.org/downloads/"; private const string VERSION_HISTORY_LINK = "http://getgreenshot.org/version-history/"; private static readonly object LockObject = new object(); diff --git a/Greenshot/Helpers/WindowWrapper.cs b/Greenshot/Helpers/WindowWrapper.cs index c23614482..4de8a60c1 100644 --- a/Greenshot/Helpers/WindowWrapper.cs +++ b/Greenshot/Helpers/WindowWrapper.cs @@ -31,6 +31,6 @@ namespace Greenshot.Helpers { get { return _hwnd; } } - private IntPtr _hwnd; + private readonly IntPtr _hwnd; } } diff --git a/Greenshot/Memento/AddElementMemento.cs b/Greenshot/Memento/AddElementMemento.cs index 91f3fcd3b..98a70214e 100644 --- a/Greenshot/Memento/AddElementMemento.cs +++ b/Greenshot/Memento/AddElementMemento.cs @@ -28,12 +28,12 @@ namespace Greenshot.Memento { /// The AddElementMemento makes it possible to undo adding an element /// 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() { @@ -43,8 +43,8 @@ namespace Greenshot.Memento { protected virtual void Dispose(bool disposing) { //if (disposing) { } - drawableContainer = null; - surface = null; + _drawableContainer = null; + _surface = null; } public LangKey ActionLanguageKey { @@ -59,16 +59,15 @@ namespace Greenshot.Memento { 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/Memento/ChangeFieldHolderMemento.cs b/Greenshot/Memento/ChangeFieldHolderMemento.cs index 0c4911ae1..03a04ab5d 100644 --- a/Greenshot/Memento/ChangeFieldHolderMemento.cs +++ b/Greenshot/Memento/ChangeFieldHolderMemento.cs @@ -29,8 +29,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) { this.drawableContainer = drawableContainer; diff --git a/Greenshot/Memento/DeleteElementMemento.cs b/Greenshot/Memento/DeleteElementMemento.cs index ba532b11c..b715e26a8 100644 --- a/Greenshot/Memento/DeleteElementMemento.cs +++ b/Greenshot/Memento/DeleteElementMemento.cs @@ -29,7 +29,7 @@ namespace Greenshot.Memento { /// public class DeleteElementMemento : IMemento { private IDrawableContainer drawableContainer; - private Surface surface; + private readonly Surface surface; public DeleteElementMemento(Surface surface, IDrawableContainer drawableContainer) { this.surface = surface; diff --git a/Greenshot/Memento/DrawableContainerBoundsChangeMemento.cs b/Greenshot/Memento/DrawableContainerBoundsChangeMemento.cs index e4aded8c6..940fbd4ee 100644 --- a/Greenshot/Memento/DrawableContainerBoundsChangeMemento.cs +++ b/Greenshot/Memento/DrawableContainerBoundsChangeMemento.cs @@ -31,8 +31,8 @@ namespace Greenshot.Memento { /// The DrawableContainerBoundsChangeMemento makes it possible to undo-redo an IDrawableContainer resize & move /// public class DrawableContainerBoundsChangeMemento : IMemento { - List points = new List(); - List sizes = new List(); + readonly List points = new List(); + readonly List sizes = new List(); List listOfdrawableContainer; private void StoreBounds() { diff --git a/Greenshot/Memento/TextChangeMemento.cs b/Greenshot/Memento/TextChangeMemento.cs index 541b4c06e..716b9e171 100644 --- a/Greenshot/Memento/TextChangeMemento.cs +++ b/Greenshot/Memento/TextChangeMemento.cs @@ -28,7 +28,7 @@ namespace Greenshot.Memento { /// public class TextChangeMemento : IMemento { private TextContainer textContainer; - private string oldText; + private readonly string oldText; public TextChangeMemento(TextContainer textContainer) { this.textContainer = textContainer; diff --git a/Greenshot/Processors/TitleFixProcessor.cs b/Greenshot/Processors/TitleFixProcessor.cs index d20798db2..a7b278d59 100644 --- a/Greenshot/Processors/TitleFixProcessor.cs +++ b/Greenshot/Processors/TitleFixProcessor.cs @@ -32,8 +32,8 @@ namespace Greenshot.Processors { /// Description of TitleFixProcessor. /// public class TitleFixProcessor : AbstractProcessor { - private static ILog LOG = LogManager.GetLogger(typeof(TitleFixProcessor)); - private static CoreConfiguration config = IniConfig.GetIniSection(); + private static readonly ILog LOG = LogManager.GetLogger(typeof(TitleFixProcessor)); + private static readonly CoreConfiguration config = IniConfig.GetIniSection(); public TitleFixProcessor() { List corruptKeys = new List(); diff --git a/GreenshotBoxPlugin/BoxCredentials.cs b/GreenshotBoxPlugin/BoxCredentials.cs index 5d70729ed..b725ff72d 100644 --- a/GreenshotBoxPlugin/BoxCredentials.cs +++ b/GreenshotBoxPlugin/BoxCredentials.cs @@ -18,7 +18,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; namespace GreenshotBoxPlugin { /// diff --git a/GreenshotBoxPlugin/BoxDestination.cs b/GreenshotBoxPlugin/BoxDestination.cs index 6e2606fbd..6f5a3976e 100644 --- a/GreenshotBoxPlugin/BoxDestination.cs +++ b/GreenshotBoxPlugin/BoxDestination.cs @@ -22,12 +22,9 @@ using System.ComponentModel; using System.Drawing; using Greenshot.Plugin; using GreenshotPlugin.Core; -using log4net; namespace GreenshotBoxPlugin { public class BoxDestination : AbstractDestination { - private static ILog LOG = LogManager.GetLogger(typeof(BoxDestination)); - private readonly BoxPlugin _plugin; public BoxDestination(BoxPlugin plugin) { _plugin = plugin; diff --git a/GreenshotBoxPlugin/Forms/SettingsForm.cs b/GreenshotBoxPlugin/Forms/SettingsForm.cs index 07b32373d..0c643692c 100644 --- a/GreenshotBoxPlugin/Forms/SettingsForm.cs +++ b/GreenshotBoxPlugin/Forms/SettingsForm.cs @@ -18,20 +18,14 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; -using System.Drawing; -using System.Windows.Forms; using GreenshotBoxPlugin.Forms; -using GreenshotPlugin.Core; namespace GreenshotBoxPlugin { /// /// Description of PasswordRequestForm. /// public partial class SettingsForm : BoxForm { - string boxTicket = string.Empty; - public SettingsForm(BoxConfiguration config) { // // The InitializeComponent() call is required for Windows Forms designer support. diff --git a/GreenshotPlugin/Controls/AnimatingForm.cs b/GreenshotPlugin/Controls/AnimatingForm.cs index 17f8baa38..3a64af991 100644 --- a/GreenshotPlugin/Controls/AnimatingForm.cs +++ b/GreenshotPlugin/Controls/AnimatingForm.cs @@ -21,9 +21,7 @@ using System; using System.Windows.Forms; -using GreenshotPlugin.Core; using GreenshotPlugin.UnmanagedHelpers; -using Greenshot.IniFile; using log4net; namespace GreenshotPlugin.Controls { @@ -33,8 +31,8 @@ namespace GreenshotPlugin.Controls { public class AnimatingForm : GreenshotForm { private static readonly ILog LOG = LogManager.GetLogger(typeof(AnimatingForm)); private const int DEFAULT_VREFRESH = 60; - private int vRefresh = 0; - private Timer timer = null; + private int _vRefresh; + private Timer _timer; /// /// This flag specifies if any animation is used @@ -49,27 +47,27 @@ namespace GreenshotPlugin.Controls { /// protected int VRefresh { get { - if (vRefresh == 0) { + if (_vRefresh == 0) { // get te hDC of the desktop to get the VREFRESH - using (SafeWindowDCHandle desktopHandle = SafeWindowDCHandle.fromDesktop()) { - vRefresh = GDI32.GetDeviceCaps(desktopHandle, DeviceCaps.VREFRESH); + using (SafeWindowDCHandle desktopHandle = SafeWindowDCHandle.FromDesktop()) { + _vRefresh = GDI32.GetDeviceCaps(desktopHandle, DeviceCaps.VREFRESH); } } // A vertical refresh rate value of 0 or 1 represents the display hardware's default refresh rate. // As there is currently no know way to get the default, we guess it. - if (vRefresh <= 1) { - vRefresh = DEFAULT_VREFRESH; + if (_vRefresh <= 1) { + _vRefresh = DEFAULT_VREFRESH; } - return vRefresh; + return _vRefresh; } } /// /// Check if we are in a Terminal Server session OR need to optimize for RDP / remote desktop connections /// - protected bool isTerminalServerSession { + protected bool IsTerminalServerSession { get { - return coreConfiguration.OptimizeForRDP || SystemInformation.TerminalServerSession; + return !coreConfiguration.DisableRDPOptimizing && (coreConfiguration.OptimizeForRDP || SystemInformation.TerminalServerSession); } } @@ -80,7 +78,7 @@ namespace GreenshotPlugin.Controls { /// Number of frames, 1 if in Terminal Server Session protected int FramesForMillis(int milliseconds) { // If we are in a Terminal Server Session we return 1 - if (isTerminalServerSession) { + if (IsTerminalServerSession) { return 1; } return milliseconds / VRefresh; @@ -92,17 +90,17 @@ namespace GreenshotPlugin.Controls { protected AnimatingForm() { Load += delegate { if (EnableAnimation) { - timer = new Timer(); - timer.Interval = 1000 / VRefresh; - timer.Tick += new EventHandler(timer_Tick); - timer.Start(); + _timer = new Timer(); + _timer.Interval = 1000 / VRefresh; + _timer.Tick += timer_Tick; + _timer.Start(); } }; // Unregister at close FormClosing += delegate { - if (timer != null) { - timer.Stop(); + if (_timer != null) { + _timer.Stop(); } }; } diff --git a/GreenshotPlugin/Controls/BackgroundForm.cs b/GreenshotPlugin/Controls/BackgroundForm.cs index e3d73ac4d..888a7a275 100644 --- a/GreenshotPlugin/Controls/BackgroundForm.cs +++ b/GreenshotPlugin/Controls/BackgroundForm.cs @@ -29,7 +29,7 @@ namespace GreenshotPlugin.Controls { /// Description of PleaseWaitForm. /// public partial class BackgroundForm : Form { - private volatile bool shouldClose = false; + private volatile bool _shouldClose; private void BackgroundShowDialog() { ShowDialog(); @@ -38,7 +38,7 @@ namespace GreenshotPlugin.Controls { 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); @@ -52,7 +52,7 @@ namespace GreenshotPlugin.Controls { // InitializeComponent(); Icon = GreenshotResources.getGreenshotIcon(); - shouldClose = false; + _shouldClose = false; Text = title; label_pleasewait.Text = text; FormClosing += PreventFormClose; @@ -76,20 +76,20 @@ namespace GreenshotPlugin.Controls { } private void PreventFormClose(object sender, FormClosingEventArgs e) { - if(!shouldClose) { + if(!_shouldClose) { e.Cancel = true; } } private void Timer_checkforcloseTick(object sender, EventArgs e) { - if (shouldClose) { + if (_shouldClose) { timer_checkforclose.Stop(); BeginInvoke(new EventHandler( delegate {Close();})); } } public void CloseDialog() { - shouldClose = true; + _shouldClose = true; Application.DoEvents(); } diff --git a/GreenshotPlugin/Controls/ExtendedWebBrowser.cs b/GreenshotPlugin/Controls/ExtendedWebBrowser.cs index 785fb37ee..98d93ba87 100644 --- a/GreenshotPlugin/Controls/ExtendedWebBrowser.cs +++ b/GreenshotPlugin/Controls/ExtendedWebBrowser.cs @@ -19,8 +19,6 @@ * along with this program. If not, see . */ using System; -using System.Collections.Generic; -using System.Text; using System.Windows.Forms; using GreenshotInterop.Interop; @@ -30,7 +28,7 @@ namespace GreenshotPlugin.Controls { const int OLECMDID_SHOWSCRIPTERROR = 40; const int OLECMDID_SHOWMESSAGE = 41; - static Guid CGID_DocHostCommandHandler = new Guid("F38BC242-B950-11D1-8918-00C04FC2C836"); + static readonly Guid CGID_DocHostCommandHandler = new Guid("F38BC242-B950-11D1-8918-00C04FC2C836"); const int S_OK = 0; const int OLECMDERR_E_NOTSUPPORTED = (-2147221248); diff --git a/GreenshotPlugin/Controls/FormWithoutActivation.cs b/GreenshotPlugin/Controls/FormWithoutActivation.cs index 2b92989a5..8ab4ada3d 100644 --- a/GreenshotPlugin/Controls/FormWithoutActivation.cs +++ b/GreenshotPlugin/Controls/FormWithoutActivation.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Windows.Forms; namespace GreenshotPlugin.Controls { diff --git a/GreenshotPlugin/Controls/GreenshotButton.cs b/GreenshotPlugin/Controls/GreenshotButton.cs index 530c34a89..e4e6d72b7 100644 --- a/GreenshotPlugin/Controls/GreenshotButton.cs +++ b/GreenshotPlugin/Controls/GreenshotButton.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.ComponentModel; using System.Windows.Forms; diff --git a/GreenshotPlugin/Controls/GreenshotCheckBox.cs b/GreenshotPlugin/Controls/GreenshotCheckBox.cs index 30aa74712..4872ba28d 100644 --- a/GreenshotPlugin/Controls/GreenshotCheckBox.cs +++ b/GreenshotPlugin/Controls/GreenshotCheckBox.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.ComponentModel; using System.Windows.Forms; @@ -33,16 +33,8 @@ namespace GreenshotPlugin.Controls { 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/GreenshotPlugin/Controls/GreenshotColumnSorter.cs b/GreenshotPlugin/Controls/GreenshotColumnSorter.cs index a64a4aabb..24c5f561d 100644 --- a/GreenshotPlugin/Controls/GreenshotColumnSorter.cs +++ b/GreenshotPlugin/Controls/GreenshotColumnSorter.cs @@ -29,28 +29,28 @@ namespace GreenshotPlugin.Controls { /// /// 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 /// 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(); } /// @@ -60,34 +60,33 @@ namespace GreenshotPlugin.Controls { /// Second object to be compared /// 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) { - return -1; - } else if (x != null && y == null) { - return 1; + } + if (x == null) { + return -1; + } + 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) { - // Descending sort is selected, return negative result of compare operation - return (-compareResult); - } else { - // Return '0' to indicate they are equal - return 0; } + if (_orderOfSort == SortOrder.Descending) { + // Descending sort is selected, return negative result of compare operation + return -compareResult; + } + // Return '0' to indicate they are equal + return 0; } /// @@ -95,10 +94,10 @@ namespace GreenshotPlugin.Controls { /// public int SortColumn { set { - ColumnToSort = value; + _columnToSort = value; } get { - return ColumnToSort; + return _columnToSort; } } @@ -107,10 +106,10 @@ namespace GreenshotPlugin.Controls { /// public SortOrder Order { set { - OrderOfSort = value; + _orderOfSort = value; } get { - return OrderOfSort; + return _orderOfSort; } } } diff --git a/GreenshotPlugin/Controls/GreenshotComboBox.cs b/GreenshotPlugin/Controls/GreenshotComboBox.cs index 0fe165061..8adf83fc6 100644 --- a/GreenshotPlugin/Controls/GreenshotComboBox.cs +++ b/GreenshotPlugin/Controls/GreenshotComboBox.cs @@ -25,18 +25,11 @@ using GreenshotPlugin.Core; namespace GreenshotPlugin.Controls { public class GreenshotComboBox : ComboBox, IGreenshotConfigBindable { - private Type enumType = null; - private Enum selectedEnum = null; - private string sectionName = "Core"; + private Type _enumType; + private Enum _selectedEnum; + [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 { @@ -52,7 +45,7 @@ namespace GreenshotPlugin.Controls { public void SetValue(Enum currentValue) { if (currentValue != null) { - selectedEnum = currentValue; + _selectedEnum = currentValue; SelectedItem = Language.Translate(currentValue); } } @@ -64,11 +57,10 @@ namespace GreenshotPlugin.Controls { /// TEnum to populate with 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(Language.Translate((Enum)enumValue)); } @@ -78,26 +70,27 @@ namespace GreenshotPlugin.Controls { /// Store the selected value internally /// 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) { + // Ignore } foreach (Enum enumValue in availableValues) { - string enumKey = enumTypeName + "." + enumValue.ToString(); + string enumKey = enumTypeName + "." + enumValue; if (Language.hasKey(enumKey)) { - string translation = Language.GetString(enumTypeName + "." + enumValue.ToString()); + string translation = Language.GetString(enumTypeName + "." + enumValue); if (translation.Equals(selectedValue)) { returnValue = enumValue; } } } - selectedEnum = (Enum)returnValue; + _selectedEnum = (Enum)returnValue; } /// @@ -105,7 +98,7 @@ namespace GreenshotPlugin.Controls { /// /// The enum value of the combobox public Enum GetSelectedEnum() { - return selectedEnum; + return _selectedEnum; } } } diff --git a/GreenshotPlugin/Controls/GreenshotForm.cs b/GreenshotPlugin/Controls/GreenshotForm.cs index ab151675a..b44003b58 100644 --- a/GreenshotPlugin/Controls/GreenshotForm.cs +++ b/GreenshotPlugin/Controls/GreenshotForm.cs @@ -34,13 +34,13 @@ namespace GreenshotPlugin.Controls { /// This form is used for automatically binding the elements of the form to the language /// public class GreenshotForm : Form, IGreenshotLanguageBindable { - private static ILog LOG = LogManager.GetLogger(typeof(GreenshotForm)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(GreenshotForm)); protected static CoreConfiguration coreConfiguration; - private static IDictionary reflectionCache = new Dictionary(); + private static readonly IDictionary reflectionCache = new Dictionary(); private IComponentChangeService m_changeService; - private bool _isDesignModeLanguageSet = false; - private bool _applyLanguageManually = false; - private bool _storeFieldsManually = false; + private bool _isDesignModeLanguageSet; + private bool _applyLanguageManually; + private bool _storeFieldsManually; private IDictionary _designTimeControls; private IDictionary _designTimeToolStripItems; @@ -210,16 +210,16 @@ namespace GreenshotPlugin.Controls { // Clear our the component change events to prepare for re-siting. if (m_changeService != null) { - m_changeService.ComponentChanged -= new ComponentChangedEventHandler(OnComponentChanged); - m_changeService.ComponentAdded -= new ComponentEventHandler(OnComponentAdded); + m_changeService.ComponentChanged -= OnComponentChanged; + m_changeService.ComponentAdded -= OnComponentAdded; } } private void RegisterChangeNotifications() { // Register the event handlers for the IComponentChangeService events if (m_changeService != null) { - m_changeService.ComponentChanged += new ComponentChangedEventHandler(OnComponentChanged); - m_changeService.ComponentAdded += new ComponentEventHandler(OnComponentAdded); + m_changeService.ComponentChanged += OnComponentChanged; + m_changeService.ComponentAdded += OnComponentAdded; } } @@ -277,7 +277,7 @@ namespace GreenshotPlugin.Controls { } protected void ApplyLanguage(ToolStripItem applyTo, string languageKey) { - string langString = null; + string langString; if (!string.IsNullOrEmpty(languageKey)) { if (!Language.TryGetString(languageKey, out langString)) { LOG.WarnFormat("Unknown language key '{0}' configured for control '{1}', this might be okay.", languageKey, applyTo.Name); @@ -473,7 +473,6 @@ namespace GreenshotPlugin.Controls { comboxBox.Populate(iniValue.ValueType); comboxBox.SetValue((Enum)iniValue.Value); comboxBox.Enabled = !iniValue.IsFixed; - continue; } } } diff --git a/GreenshotPlugin/Controls/GreenshotGroupBox.cs b/GreenshotPlugin/Controls/GreenshotGroupBox.cs index b83ce53c9..5dfcae4a5 100644 --- a/GreenshotPlugin/Controls/GreenshotGroupBox.cs +++ b/GreenshotPlugin/Controls/GreenshotGroupBox.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Windows.Forms; using System.ComponentModel; diff --git a/GreenshotPlugin/Controls/GreenshotLabel.cs b/GreenshotPlugin/Controls/GreenshotLabel.cs index 813eb7aa5..13afbb633 100644 --- a/GreenshotPlugin/Controls/GreenshotLabel.cs +++ b/GreenshotPlugin/Controls/GreenshotLabel.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Windows.Forms; using System.ComponentModel; diff --git a/GreenshotPlugin/Controls/GreenshotRadioButton.cs b/GreenshotPlugin/Controls/GreenshotRadioButton.cs index 9de1d2147..e87e95818 100644 --- a/GreenshotPlugin/Controls/GreenshotRadioButton.cs +++ b/GreenshotPlugin/Controls/GreenshotRadioButton.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.ComponentModel; using System.Windows.Forms; diff --git a/GreenshotPlugin/Controls/GreenshotTabPage.cs b/GreenshotPlugin/Controls/GreenshotTabPage.cs index 9e95517b1..c3f1e42cf 100644 --- a/GreenshotPlugin/Controls/GreenshotTabPage.cs +++ b/GreenshotPlugin/Controls/GreenshotTabPage.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Windows.Forms; using System.ComponentModel; diff --git a/GreenshotPlugin/Controls/GreenshotTextBox.cs b/GreenshotPlugin/Controls/GreenshotTextBox.cs index 772520bcd..ecaaa117f 100644 --- a/GreenshotPlugin/Controls/GreenshotTextBox.cs +++ b/GreenshotPlugin/Controls/GreenshotTextBox.cs @@ -18,22 +18,14 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.ComponentModel; using System.Windows.Forms; namespace GreenshotPlugin.Controls { public 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/GreenshotPlugin/Controls/GreenshotToolDropDownButton.cs b/GreenshotPlugin/Controls/GreenshotToolDropDownButton.cs index 48301b72d..d4ffdff47 100644 --- a/GreenshotPlugin/Controls/GreenshotToolDropDownButton.cs +++ b/GreenshotPlugin/Controls/GreenshotToolDropDownButton.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.ComponentModel; using System.Windows.Forms; diff --git a/GreenshotPlugin/Controls/GreenshotToolStripButton.cs b/GreenshotPlugin/Controls/GreenshotToolStripButton.cs index 3678081f0..5205f5434 100644 --- a/GreenshotPlugin/Controls/GreenshotToolStripButton.cs +++ b/GreenshotPlugin/Controls/GreenshotToolStripButton.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.ComponentModel; using System.Windows.Forms; diff --git a/GreenshotPlugin/Controls/GreenshotToolStripLabel.cs b/GreenshotPlugin/Controls/GreenshotToolStripLabel.cs index 615b9206e..19378027b 100644 --- a/GreenshotPlugin/Controls/GreenshotToolStripLabel.cs +++ b/GreenshotPlugin/Controls/GreenshotToolStripLabel.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Windows.Forms; using System.ComponentModel; diff --git a/GreenshotPlugin/Controls/GreenshotToolStripMenuItem.cs b/GreenshotPlugin/Controls/GreenshotToolStripMenuItem.cs index 2ef417fd9..6c3e1572c 100644 --- a/GreenshotPlugin/Controls/GreenshotToolStripMenuItem.cs +++ b/GreenshotPlugin/Controls/GreenshotToolStripMenuItem.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.ComponentModel; using System.Windows.Forms; diff --git a/GreenshotPlugin/Controls/HotkeyControl.cs b/GreenshotPlugin/Controls/HotkeyControl.cs index 706e5316f..372e67633 100644 --- a/GreenshotPlugin/Controls/HotkeyControl.cs +++ b/GreenshotPlugin/Controls/HotkeyControl.cs @@ -22,6 +22,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; @@ -37,13 +38,13 @@ namespace GreenshotPlugin.Controls { /// But is modified to fit in Greenshot, and have localized support /// public class HotkeyControl : GreenshotTextBox { - private static ILog LOG = LogManager.GetLogger(typeof(HotkeyControl)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(HotkeyControl)); - private static EventDelay eventDelay = new EventDelay(TimeSpan.FromMilliseconds(600).Ticks); - private static bool isWindows7OrOlder = Environment.OSVersion.Version.Major >= 6 && Environment.OSVersion.Version.Minor >= 1; + private static readonly EventDelay eventDelay = new EventDelay(TimeSpan.FromMilliseconds(600).Ticks); + private static readonly bool isWindows7OrOlder = Environment.OSVersion.Version.Major >= 6 && Environment.OSVersion.Version.Minor >= 1; // Holds the list of hotkeys - private static Dictionary keyHandlers = new Dictionary(); + private static readonly IDictionary keyHandlers = new Dictionary(); private static int hotKeyCounter = 1; private const uint WM_HOTKEY = 0x312; private static IntPtr hotkeyHWND; @@ -57,6 +58,7 @@ namespace GreenshotPlugin.Controls { // } // } + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum Modifiers : uint { NONE = 0, ALT = 1, @@ -66,6 +68,7 @@ namespace GreenshotPlugin.Controls { NO_REPEAT = 0x4000 } + [SuppressMessage("ReSharper", "InconsistentNaming")] private enum MapType : uint { MAPVK_VK_TO_VSC = 0, //The uCode parameter is a virtual-key code and is translated into a scan code. If it is a virtual-key code that does not distinguish between left- and right-hand keys, the left-hand scan code is returned. If there is no translation, the function returns 0. MAPVK_VSC_TO_VK = 1, //The uCode parameter is a scan code and is translated into a virtual-key code that does not distinguish between left- and right-hand keys. If there is no translation, the function returns 0. @@ -93,10 +96,10 @@ namespace GreenshotPlugin.Controls { // ArrayLists used to enforce the use of proper modifiers. // Shift+A isn't a valid hotkey, for instance, as it would screw up when the user is typing. - private ArrayList needNonShiftModifier = null; - private ArrayList needNonAltGrModifier = null; + private readonly ArrayList needNonShiftModifier; + private readonly ArrayList needNonAltGrModifier; - private ContextMenu dummy = new ContextMenu(); + private readonly ContextMenu dummy = new ContextMenu(); /// /// Used to make sure that there is no right-click menu available @@ -131,9 +134,9 @@ namespace GreenshotPlugin.Controls { Text = "None"; // Handle events that occurs when keys are pressed - KeyPress += new KeyPressEventHandler(HotkeyControl_KeyPress); - KeyUp += new KeyEventHandler(HotkeyControl_KeyUp); - KeyDown += new KeyEventHandler(HotkeyControl_KeyDown); + KeyPress += HotkeyControl_KeyPress; + KeyUp += HotkeyControl_KeyUp; + KeyDown += HotkeyControl_KeyDown; // Fill the ArrayLists that contain all invalid hotkey combinations needNonShiftModifier = new ArrayList(); diff --git a/GreenshotPlugin/Controls/IGreenshotConfigBindable.cs b/GreenshotPlugin/Controls/IGreenshotConfigBindable.cs index e17e9f112..67ab07c40 100644 --- a/GreenshotPlugin/Controls/IGreenshotConfigBindable.cs +++ b/GreenshotPlugin/Controls/IGreenshotConfigBindable.cs @@ -18,7 +18,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; namespace GreenshotPlugin.Controls { public interface IGreenshotConfigBindable { diff --git a/GreenshotPlugin/Controls/IGreenshotLanguageBindable.cs b/GreenshotPlugin/Controls/IGreenshotLanguageBindable.cs index 899f78134..8a84786b1 100644 --- a/GreenshotPlugin/Controls/IGreenshotLanguageBindable.cs +++ b/GreenshotPlugin/Controls/IGreenshotLanguageBindable.cs @@ -18,7 +18,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; namespace GreenshotPlugin.Controls { /// diff --git a/GreenshotPlugin/Controls/OAuthLoginForm.cs b/GreenshotPlugin/Controls/OAuthLoginForm.cs index e562b1185..d0a9e017d 100644 --- a/GreenshotPlugin/Controls/OAuthLoginForm.cs +++ b/GreenshotPlugin/Controls/OAuthLoginForm.cs @@ -20,12 +20,8 @@ */ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Drawing; -using System.Text; using System.Windows.Forms; -using System.Web; -using System.Collections.Specialized; using GreenshotPlugin.Core; using log4net; @@ -35,8 +31,8 @@ namespace GreenshotPlugin.Controls { /// public partial class OAuthLoginForm : Form { private static readonly ILog LOG = LogManager.GetLogger(typeof(OAuthLoginForm)); - private string _callbackUrl = null; - private IDictionary _callbackParameters = null; + private readonly string _callbackUrl; + private IDictionary _callbackParameters; public IDictionary CallbackParameters { get { diff --git a/GreenshotPlugin/Controls/PleaseWaitForm.cs b/GreenshotPlugin/Controls/PleaseWaitForm.cs index 63a0c783b..53cb527f9 100644 --- a/GreenshotPlugin/Controls/PleaseWaitForm.cs +++ b/GreenshotPlugin/Controls/PleaseWaitForm.cs @@ -19,7 +19,6 @@ * along with this program. If not, see . */ using System; -using System.Drawing; using System.Windows.Forms; using System.Threading; using GreenshotPlugin.Core; @@ -30,8 +29,8 @@ namespace GreenshotPlugin.Controls { /// Description of PleaseWaitForm. /// public partial class PleaseWaitForm : Form { - private static ILog LOG = LogManager.GetLogger(typeof(PleaseWaitForm)); - private Thread waitFor = null; + private static readonly ILog LOG = LogManager.GetLogger(typeof(PleaseWaitForm)); + private Thread waitFor; private string title; public PleaseWaitForm() { // diff --git a/GreenshotPlugin/Controls/QualityDialog.cs b/GreenshotPlugin/Controls/QualityDialog.cs index c601c8e88..000564bf1 100644 --- a/GreenshotPlugin/Controls/QualityDialog.cs +++ b/GreenshotPlugin/Controls/QualityDialog.cs @@ -19,7 +19,6 @@ * along with this program. If not, see . */ using System; -using System.Windows.Forms; using GreenshotPlugin.Core; using Greenshot.IniFile; using Greenshot.Plugin; @@ -29,7 +28,7 @@ namespace GreenshotPlugin.Controls { /// Description of JpegQualityDialog. /// public partial class QualityDialog : GreenshotForm { - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); public SurfaceOutputSettings Settings { get; set; diff --git a/GreenshotPlugin/Controls/SaveImageFileDialog.cs b/GreenshotPlugin/Controls/SaveImageFileDialog.cs index bf14f2be0..9e94d595f 100644 --- a/GreenshotPlugin/Controls/SaveImageFileDialog.cs +++ b/GreenshotPlugin/Controls/SaveImageFileDialog.cs @@ -33,12 +33,12 @@ namespace GreenshotPlugin.Controls { /// For some reason SFD is sealed :( /// public class SaveImageFileDialog : IDisposable { - private static ILog LOG = LogManager.GetLogger(typeof(SaveImageFileDialog)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); - protected SaveFileDialog saveFileDialog; - private FilterOption[] filterOptions; - private DirectoryInfo eagerlyCreatedDirectory; - private ICaptureDetails captureDetails = null; + private static readonly ILog LOG = LogManager.GetLogger(typeof(SaveImageFileDialog)); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); + protected SaveFileDialog SaveFileDialog; + private FilterOption[] _filterOptions; + private DirectoryInfo _eagerlyCreatedDirectory; + private readonly ICaptureDetails _captureDetails; public void Dispose() { Dispose(true); @@ -47,25 +47,25 @@ namespace GreenshotPlugin.Controls { protected virtual void Dispose(bool disposing) { if (disposing) { - if (saveFileDialog != null) { - saveFileDialog.Dispose(); - saveFileDialog = null; + if (SaveFileDialog != null) { + SaveFileDialog.Dispose(); + SaveFileDialog = null; } } } public SaveImageFileDialog() { - init(); + Init(); } public SaveImageFileDialog(ICaptureDetails captureDetails) { - this.captureDetails = captureDetails; - init(); + _captureDetails = captureDetails; + Init(); } - private void init() { - saveFileDialog = new SaveFileDialog(); - applyFilterOptions(); + private void Init() { + SaveFileDialog = new SaveFileDialog(); + ApplyFilterOptions(); string initialDirectory = null; try { initialDirectory = Path.GetDirectoryName(conf.OutputFileAsFullpath); @@ -74,44 +74,46 @@ namespace GreenshotPlugin.Controls { } 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() { - prepareFilterOptions(); + private void ApplyFilterOptions() { + PrepareFilterOptions(); string fdf = ""; int preselect = 0; var outputFileFormatAsString = Enum.GetName(typeof(OutputFormat), conf.OutputFileFormat); - for(int i=0; i public string FileName { - get {return saveFileDialog.FileName;} - set {saveFileDialog.FileName = value;} + get {return SaveFileDialog.FileName;} + set {SaveFileDialog.FileName = value;} } /// /// initial directory of the dialog /// public string InitialDirectory { - get {return saveFileDialog.InitialDirectory;} - set {saveFileDialog.InitialDirectory = value;} + get {return SaveFileDialog.InitialDirectory;} + set {SaveFileDialog.InitialDirectory = value;} } /// @@ -138,7 +140,7 @@ namespace GreenshotPlugin.Controls { /// 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 @@ -155,19 +157,19 @@ namespace GreenshotPlugin.Controls { /// public string Extension { get { - return filterOptions[saveFileDialog.FilterIndex-1].Extension; + return _filterOptions[SaveFileDialog.FilterIndex-1].Extension; } set { - for(int i=0; i /// 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); + FileName = FilenameHelper.GetFilenameWithoutExtensionFromPattern(conf.OutputFileFilenamePattern, _captureDetails); } - - private string GetRootDirFromConfig() { - string rootDir = conf.OutputFilePath; - rootDir = FilenameHelper.FillVariables(rootDir, false); - return rootDir; - } - + private class FilterOption { public string Label; public string Extension; @@ -195,29 +190,14 @@ namespace GreenshotPlugin.Controls { private void CleanUp() { // fix for bug #3379053 try { - if(eagerlyCreatedDirectory != null && eagerlyCreatedDirectory.GetFiles().Length == 0 && eagerlyCreatedDirectory.GetDirectories().Length == 0) { - eagerlyCreatedDirectory.Delete(); - eagerlyCreatedDirectory = null; + if(_eagerlyCreatedDirectory != null && _eagerlyCreatedDirectory.GetFiles().Length == 0 && _eagerlyCreatedDirectory.GetDirectories().Length == 0) { + _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; - } } } diff --git a/GreenshotPlugin/Controls/ThumbnailForm.cs b/GreenshotPlugin/Controls/ThumbnailForm.cs index 7f5053399..121798e00 100644 --- a/GreenshotPlugin/Controls/ThumbnailForm.cs +++ b/GreenshotPlugin/Controls/ThumbnailForm.cs @@ -31,10 +31,9 @@ namespace GreenshotPlugin.Controls { /// Didn't make it completely "generic" yet, but at least most logic is in here so we don't have it in the mainform. /// public class ThumbnailForm : FormWithoutActivation { - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); - private IntPtr thumbnailHandle = IntPtr.Zero; - private Rectangle parentMenuBounds = Rectangle.Empty; + private IntPtr _thumbnailHandle = IntPtr.Zero; public ThumbnailForm() { ShowInTaskbar = false; @@ -59,9 +58,9 @@ namespace GreenshotPlugin.Controls { } private void UnregisterThumbnail() { - if (thumbnailHandle != IntPtr.Zero) { - DWM.DwmUnregisterThumbnail(thumbnailHandle); - thumbnailHandle = IntPtr.Zero; + if (_thumbnailHandle != IntPtr.Zero) { + DWM.DwmUnregisterThumbnail(_thumbnailHandle); + _thumbnailHandle = IntPtr.Zero; } } @@ -73,10 +72,10 @@ namespace GreenshotPlugin.Controls { public void ShowThumbnail(WindowDetails window, Control parentControl) { UnregisterThumbnail(); - DWM.DwmRegisterThumbnail(Handle, window.Handle, out thumbnailHandle); - if (thumbnailHandle != IntPtr.Zero) { + DWM.DwmRegisterThumbnail(Handle, window.Handle, out _thumbnailHandle); + if (_thumbnailHandle != IntPtr.Zero) { SIZE sourceSize; - DWM.DwmQueryThumbnailSourceSize(thumbnailHandle, out sourceSize); + DWM.DwmQueryThumbnailSourceSize(_thumbnailHandle, out sourceSize); int thumbnailHeight = 200; int thumbnailWidth = (int)(thumbnailHeight * ((float)sourceSize.width / (float)sourceSize.height)); if (parentControl != null && thumbnailWidth > parentControl.Width) { @@ -86,12 +85,14 @@ namespace GreenshotPlugin.Controls { Width = thumbnailWidth; Height = thumbnailHeight; // Prepare the displaying of the Thumbnail - DWM_THUMBNAIL_PROPERTIES props = new DWM_THUMBNAIL_PROPERTIES(); - props.Opacity = (byte)255; - props.Visible = true; - props.SourceClientAreaOnly = false; - props.Destination = new RECT(0, 0, thumbnailWidth, thumbnailHeight); - DWM.DwmUpdateThumbnailProperties(thumbnailHandle, ref props); + DWM_THUMBNAIL_PROPERTIES props = new DWM_THUMBNAIL_PROPERTIES + { + Opacity = 255, + Visible = true, + SourceClientAreaOnly = false, + Destination = new RECT(0, 0, thumbnailWidth, thumbnailHeight) + }; + DWM.DwmUpdateThumbnailProperties(_thumbnailHandle, ref props); if (parentControl != null) { AlignToControl(parentControl); } diff --git a/GreenshotPlugin/Core/AbstractDestination.cs b/GreenshotPlugin/Core/AbstractDestination.cs index af74efb41..8fa0938b0 100644 --- a/GreenshotPlugin/Core/AbstractDestination.cs +++ b/GreenshotPlugin/Core/AbstractDestination.cs @@ -34,7 +34,7 @@ namespace GreenshotPlugin.Core { /// public abstract class AbstractDestination : IDestination { private static readonly ILog LOG = LogManager.GetLogger(typeof(AbstractDestination)); - private static CoreConfiguration configuration = IniConfig.GetIniSection(); + private static readonly CoreConfiguration configuration = IniConfig.GetIniSection(); public virtual int CompareTo(object obj) { IDestination other = obj as IDestination; @@ -312,7 +312,8 @@ namespace GreenshotPlugin.Core { basisMenuItem.Click += destinationClickHandler; if (isDynamic && addDynamics) { - basisMenuItem.DropDownOpening += delegate(object source, EventArgs eventArgs) { + basisMenuItem.DropDownOpening += delegate + { if (basisMenuItem.DropDownItems.Count == 0) { List subDestinations = new List(); // Fixing Bug #3536968 by catching the COMException (every exception) and not displaying the "subDestinations" diff --git a/GreenshotPlugin/Core/AccessibleHelper.cs b/GreenshotPlugin/Core/AccessibleHelper.cs index 914b27733..c54a2a51b 100644 --- a/GreenshotPlugin/Core/AccessibleHelper.cs +++ b/GreenshotPlugin/Core/AccessibleHelper.cs @@ -59,7 +59,7 @@ namespace GreenshotPlugin.Core { private const int IE_ACTIVE_TAB = 2097154; private const int CHILDID_SELF = 0; - private IAccessible accessible; + private readonly IAccessible accessible; private Accessible[] Children { get { int num = 0; diff --git a/GreenshotPlugin/Core/AnimationHelpers.cs b/GreenshotPlugin/Core/AnimationHelpers.cs index fe70fff73..3da6a5115 100644 --- a/GreenshotPlugin/Core/AnimationHelpers.cs +++ b/GreenshotPlugin/Core/AnimationHelpers.cs @@ -20,9 +20,7 @@ */ using System; using System.Drawing; -using System.Drawing.Drawing2D; using System.Collections.Generic; -using log4net; namespace GreenshotPlugin.Core { @@ -33,7 +31,7 @@ namespace GreenshotPlugin.Core { /// /// Is there a next frame? /// - bool hasNext { + bool HasNext { get; } /// @@ -81,12 +79,7 @@ namespace GreenshotPlugin.Core { /// /// Type for the animation, like Point/Rectangle/Size public abstract class AnimatorBase : IAnimator { - protected T first; - protected T last; - protected T current; - private Queue> queue = new Queue>(); - protected int frames; - protected int currentFrameNr = 0; + private readonly Queue> _queue = new Queue>(); /// /// Constructor @@ -97,10 +90,10 @@ namespace GreenshotPlugin.Core { /// /// public AnimatorBase(T first, T last, int frames, EasingType easingType, EasingMode easingMode) { - this.first = first; - this.last = last; - this.frames = frames; - current = first; + First = first; + Last = last; + Frames = frames; + Current = first; EasingType = easingType; EasingMode = easingMode; } @@ -109,39 +102,34 @@ namespace GreenshotPlugin.Core { /// The amount of frames /// public int Frames { - get { return frames; } + get; + private set; } /// /// Current frame number /// - public int CurrentFrameNr { - get { return currentFrameNr; } - } + public int CurrentFrameNr { get; private set; } /// /// First animation value /// - public T First { - get { return first; } - } + public T First { get; private set; } /// /// Last animation value, of this "leg" /// - public T Last { - get { return last; } - } + public T Last { get; private set; } /// /// Final animation value, this is including the legs /// public T Final { get { - if (queue.Count == 0) { - return last; + if (_queue.Count == 0) { + return Last; } - return queue.ToArray()[queue.Count - 1].Destination; + return _queue.ToArray()[_queue.Count - 1].Destination; } } @@ -150,7 +138,7 @@ namespace GreenshotPlugin.Core { /// /// public void ChangeDestination(T newDestination) { - ChangeDestination(newDestination, frames); + ChangeDestination(newDestination, Frames); } /// @@ -159,11 +147,11 @@ namespace GreenshotPlugin.Core { /// /// public void ChangeDestination(T newDestination, int frames) { - queue.Clear(); - first = current; - currentFrameNr = 0; - this.frames = frames; - last = newDestination; + _queue.Clear(); + First = Current; + CurrentFrameNr = 0; + Frames = frames; + Last = newDestination; } /// @@ -202,12 +190,14 @@ namespace GreenshotPlugin.Core { /// /// public void QueueDestinationLeg(T queuedDestination, int frames, EasingType easingType, EasingMode easingMode) { - AnimationLeg leg = new AnimationLeg(); - leg.Destination = queuedDestination; - leg.Frames = frames; - leg.EasingType = easingType; - leg.EasingMode = easingMode; - queue.Enqueue(leg); + AnimationLeg leg = new AnimationLeg + { + Destination = queuedDestination, + Frames = frames, + EasingType = easingType, + EasingMode = easingMode + }; + _queue.Enqueue(leg); } /// @@ -233,12 +223,12 @@ namespace GreenshotPlugin.Core { get { switch (EasingMode) { case EasingMode.EaseOut: - return Easing.EaseOut((double)currentFrameNr / (double)frames, EasingType); + return Easing.EaseOut(CurrentFrameNr / (double)Frames, EasingType); case EasingMode.EaseInOut: - return Easing.EaseInOut((double)currentFrameNr / (double)frames, EasingType); + return Easing.EaseInOut(CurrentFrameNr / (double)Frames, EasingType); case EasingMode.EaseIn: default: - return Easing.EaseIn((double)currentFrameNr / (double)frames, EasingType); + return Easing.EaseIn(CurrentFrameNr / (double)Frames, EasingType); } } } @@ -246,27 +236,23 @@ namespace GreenshotPlugin.Core { /// /// Get the current (previous) frame object /// - public virtual T Current { - get { - return current; - } - } + public virtual T Current { get; set; } /// /// Returns if there are any frame left, and if this is the case than the frame is increased. /// public virtual bool NextFrame { get { - if (currentFrameNr < frames) { - currentFrameNr++; + if (CurrentFrameNr < Frames) { + CurrentFrameNr++; return true; } - if (queue.Count > 0) { - first = current; - currentFrameNr = 0; - AnimationLeg nextLeg = queue.Dequeue(); - last = nextLeg.Destination; - frames = nextLeg.Frames; + if (_queue.Count > 0) { + First = Current; + CurrentFrameNr = 0; + AnimationLeg nextLeg = _queue.Dequeue(); + Last = nextLeg.Destination; + Frames = nextLeg.Frames; EasingType = nextLeg.EasingType; EasingMode = nextLeg.EasingMode; return true; @@ -278,12 +264,12 @@ namespace GreenshotPlugin.Core { /// /// Are there more frames to animate? /// - public virtual bool hasNext { + public virtual bool HasNext { get { - if (currentFrameNr < frames) { + if (CurrentFrameNr < Frames) { return true; } - return queue.Count > 0; + return _queue.Count > 0; } } @@ -298,8 +284,6 @@ namespace GreenshotPlugin.Core { /// Implementation of the RectangleAnimator /// public class RectangleAnimator : AnimatorBase { - private static readonly ILog LOG = LogManager.GetLogger(typeof(RectangleAnimator)); - public RectangleAnimator(Rectangle first, Rectangle last, int frames) : base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) { } @@ -318,18 +302,18 @@ namespace GreenshotPlugin.Core { public override Rectangle Next() { if (NextFrame) { double easingValue = EasingValue; - double dx = last.X - first.X; - double dy = last.Y - first.Y; + double dx = Last.X - First.X; + double dy = Last.Y - First.Y; - int x = first.X + (int)(easingValue * dx); - int y = first.Y + (int)(easingValue * dy); - double dw = last.Width - first.Width; - double dh = last.Height - first.Height; - int width = first.Width + (int)(easingValue * dw); - int height = first.Height + (int)(easingValue * dh); - current = new Rectangle(x, y, width, height); + int x = First.X + (int)(easingValue * dx); + int y = First.Y + (int)(easingValue * dy); + double dw = Last.Width - First.Width; + double dh = Last.Height - First.Height; + int width = First.Width + (int)(easingValue * dw); + int height = First.Height + (int)(easingValue * dh); + Current = new Rectangle(x, y, width, height); } - return current; + return Current; } } @@ -337,7 +321,6 @@ namespace GreenshotPlugin.Core { /// Implementation of the PointAnimator /// public class PointAnimator : AnimatorBase { - private static readonly ILog LOG = LogManager.GetLogger(typeof(PointAnimator)); public PointAnimator(Point first, Point last, int frames) : base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) { } @@ -355,14 +338,14 @@ namespace GreenshotPlugin.Core { public override Point Next() { if (NextFrame) { double easingValue = EasingValue; - double dx = last.X - first.X; - double dy = last.Y - first.Y; + double dx = Last.X - First.X; + double dy = Last.Y - First.Y; - int x = first.X + (int)(easingValue * dx); - int y = first.Y + (int)(easingValue * dy); - current = new Point(x, y); + int x = First.X + (int)(easingValue * dx); + int y = First.Y + (int)(easingValue * dy); + Current = new Point(x, y); } - return current; + return Current; } } @@ -370,7 +353,6 @@ namespace GreenshotPlugin.Core { /// Implementation of the SizeAnimator /// public class SizeAnimator : AnimatorBase { - private static readonly ILog LOG = LogManager.GetLogger(typeof(SizeAnimator)); public SizeAnimator(Size first, Size last, int frames) : base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) { } @@ -388,13 +370,13 @@ namespace GreenshotPlugin.Core { public override Size Next() { if (NextFrame) { double easingValue = EasingValue; - double dw = last.Width - first.Width; - double dh = last.Height - first.Height; - int width = first.Width + (int)(easingValue * dw); - int height = first.Height + (int)(easingValue * dh); - current = new Size(width, height); + double dw = Last.Width - First.Width; + double dh = Last.Height - First.Height; + int width = First.Width + (int)(easingValue * dw); + int height = First.Height + (int)(easingValue * dh); + Current = new Size(width, height); } - return current; + return Current; } } @@ -402,7 +384,6 @@ namespace GreenshotPlugin.Core { /// Implementation of the ColorAnimator /// public class ColorAnimator : AnimatorBase { - private static readonly ILog LOG = LogManager.GetLogger(typeof(ColorAnimator)); public ColorAnimator(Color first, Color last, int frames) : base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) { } @@ -420,17 +401,17 @@ namespace GreenshotPlugin.Core { public override Color Next() { if (NextFrame) { double easingValue = EasingValue; - double da = last.A - first.A; - double dr = last.R - first.R; - double dg = last.G - first.G; - double db = last.B - first.B; - int a = first.A + (int)(easingValue * da); - int r = first.R + (int)(easingValue * dr); - int g = first.G + (int)(easingValue * dg); - int b = first.B + (int)(easingValue * db); - current = Color.FromArgb(a,r,g,b); + double da = Last.A - First.A; + double dr = Last.R - First.R; + double dg = Last.G - First.G; + double db = Last.B - First.B; + int a = First.A + (int)(easingValue * da); + int r = First.R + (int)(easingValue * dr); + int g = First.G + (int)(easingValue * dg); + int b = First.B + (int)(easingValue * db); + Current = Color.FromArgb(a,r,g,b); } - return current; + return Current; } } @@ -438,7 +419,6 @@ namespace GreenshotPlugin.Core { /// Implementation of the IntAnimator /// public class IntAnimator : AnimatorBase { - private static readonly ILog LOG = LogManager.GetLogger(typeof(IntAnimator)); public IntAnimator(int first, int last, int frames) : base(first, last, frames, EasingType.Linear, EasingMode.EaseIn) { } @@ -456,10 +436,10 @@ namespace GreenshotPlugin.Core { public override int Next() { if (NextFrame) { double easingValue = EasingValue; - double delta = last - first; - current = first + (int)(easingValue * delta); + double delta = Last - First; + Current = First + (int)(easingValue * delta); } - return current; + return Current; } } @@ -470,7 +450,7 @@ namespace GreenshotPlugin.Core { // Adapted from http://www.robertpenner.com/easing/penner_chapter7_tweening.pdf public static double Ease(double linearStep, double acceleration, EasingType type) { - double easedStep = acceleration > 0 ? EaseIn(linearStep, type) : acceleration < 0 ? EaseOut(linearStep, type) : (double)linearStep; + double easedStep = acceleration > 0 ? EaseIn(linearStep, type) : acceleration < 0 ? EaseOut(linearStep, type) : linearStep; // Lerp: return ((easedStep - linearStep) * Math.Abs(acceleration) + linearStep); } diff --git a/GreenshotPlugin/Core/Cache.cs b/GreenshotPlugin/Core/Cache.cs index 894e389cc..06b98899f 100644 --- a/GreenshotPlugin/Core/Cache.cs +++ b/GreenshotPlugin/Core/Cache.cs @@ -31,10 +31,10 @@ namespace GreenshotPlugin.Core { /// Type of value public class Cache { private static readonly ILog LOG = LogManager.GetLogger(typeof(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; public delegate void CacheObjectExpired(TK key, TV cacheValue); /// @@ -168,7 +168,7 @@ namespace GreenshotPlugin.Core { /// 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/GreenshotPlugin/Core/ClipboardHelper.cs b/GreenshotPlugin/Core/ClipboardHelper.cs index 7bb88cd61..9e7a545ea 100644 --- a/GreenshotPlugin/Core/ClipboardHelper.cs +++ b/GreenshotPlugin/Core/ClipboardHelper.cs @@ -327,9 +327,9 @@ EndSelection:<<<<<<<4 if (formats != null && formats.Contains(FORMAT_PNG_OFFICEART) && formats.Contains(DataFormats.Dib)) { // 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) { if (formats.Contains(currentFormat)) { @@ -717,7 +717,7 @@ EndSelection:<<<<<<<4 /// string with format /// true if one the format is found public static bool ContainsFormat(string format) { - return ContainsFormat(GetDataObject(), new string[]{format}); + return ContainsFormat(GetDataObject(), new[]{format}); } /// @@ -726,7 +726,7 @@ EndSelection:<<<<<<<4 /// string with 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/GreenshotPlugin/Core/CoreConfiguration.cs b/GreenshotPlugin/Core/CoreConfiguration.cs index b5bff9abb..6aa92b757 100644 --- a/GreenshotPlugin/Core/CoreConfiguration.cs +++ b/GreenshotPlugin/Core/CoreConfiguration.cs @@ -198,6 +198,9 @@ namespace GreenshotPlugin.Core { [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/GreenshotPlugin/Core/CredentialsHelper.cs b/GreenshotPlugin/Core/CredentialsHelper.cs index 5c9474b55..45280b538 100644 --- a/GreenshotPlugin/Core/CredentialsHelper.cs +++ b/GreenshotPlugin/Core/CredentialsHelper.cs @@ -102,7 +102,7 @@ namespace GreenshotPlugin.Core { Banner = banner; } - private bool _alwaysDisplay = false; + private bool _alwaysDisplay; /// /// Gets or sets if the dialog will be shown even if the credentials /// can be returned from an existing credential in the credential manager. @@ -138,7 +138,7 @@ namespace GreenshotPlugin.Core { } } - private bool _incorrectPassword = false; + private bool _incorrectPassword; /// Gets or sets if the incorrect password balloontip needs to be shown. Introduced AFTER Windows XPGets> public bool IncorrectPassword { get { @@ -149,7 +149,7 @@ namespace GreenshotPlugin.Core { } } - private bool _keepName = false; + private bool _keepName; /// Gets or sets if the name is read-only. public bool KeepName { get { @@ -200,7 +200,7 @@ namespace GreenshotPlugin.Core { } } - private bool _saveChecked = false; + private bool _saveChecked; /// Gets or sets if the save checkbox status. public bool SaveChecked { get { @@ -285,7 +285,7 @@ namespace GreenshotPlugin.Core { } } - private Image _banner = null; + private Image _banner; /// Gets or sets the image to display on the dialog. /// A null value will cause a system default image to be used. public Image Banner { diff --git a/GreenshotPlugin/Core/Effects.cs b/GreenshotPlugin/Core/Effects.cs index 70c45bfb9..d86e591fc 100644 --- a/GreenshotPlugin/Core/Effects.cs +++ b/GreenshotPlugin/Core/Effects.cs @@ -86,7 +86,8 @@ namespace Greenshot.Core { /// [TypeConverter(typeof(EffectConverter))] public class TornEdgeEffect : DropShadowEffect { - public TornEdgeEffect() : base() { + public TornEdgeEffect() + { Reset(); } public int ToothHeight { @@ -116,7 +117,7 @@ namespace Greenshot.Core { ToothHeight = 12; HorizontalToothRange = 20; VerticalToothRange = 20; - Edges = new bool[] { true, true, true, true }; + Edges = new[] { true, true, true, true }; GenerateShadow = true; } public override Image Apply(Image sourceImage, Matrix matrix) { @@ -146,16 +147,16 @@ namespace Greenshot.Core { /// MonochromeEffect /// 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() { // TODO: Modify the threshold to have a default, which is reset here } public Image Apply(Image sourceImage, Matrix matrix) { - return ImageHelper.CreateMonochrome(sourceImage, threshold); + return ImageHelper.CreateMonochrome(sourceImage, _threshold); } } @@ -163,7 +164,8 @@ namespace Greenshot.Core { /// AdjustEffect /// public class AdjustEffect : IEffect { - public AdjustEffect() : base() { + public AdjustEffect() + { Reset(); } public float Contrast { @@ -192,8 +194,9 @@ namespace Greenshot.Core { /// ReduceColorsEffect /// public class ReduceColorsEffect : IEffect { - private static ILog LOG = LogManager.GetLogger(typeof(ReduceColorsEffect)); - public ReduceColorsEffect() : base() { + private static readonly ILog LOG = LogManager.GetLogger(typeof(ReduceColorsEffect)); + public ReduceColorsEffect() + { Reset(); } public int Colors { @@ -355,9 +358,10 @@ namespace Greenshot.Core { 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 = ","; } @@ -382,7 +386,7 @@ namespace Greenshot.Core { 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)) { StringBuilder sb = new StringBuilder(); @@ -400,7 +404,7 @@ namespace Greenshot.Core { } } // from string - if (value.GetType() == typeof(string)) { + if (value is string) { string settings = value as string; if (destinationType == typeof(DropShadowEffect)) { DropShadowEffect effect = new DropShadowEffect(); @@ -417,14 +421,13 @@ namespace Greenshot.Core { return base.ConvertTo(context, culture, value, destinationType); } - public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - if (value != null && value.GetType() == typeof(string)) { + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { + 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/GreenshotPlugin/Core/EventDelay.cs b/GreenshotPlugin/Core/EventDelay.cs index 848d19dd9..1dbd3d7c7 100644 --- a/GreenshotPlugin/Core/EventDelay.cs +++ b/GreenshotPlugin/Core/EventDelay.cs @@ -23,8 +23,8 @@ using System; 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; } diff --git a/GreenshotPlugin/Core/FastBitmap.cs b/GreenshotPlugin/Core/FastBitmap.cs index 228e1e4bf..8090a7b29 100644 --- a/GreenshotPlugin/Core/FastBitmap.cs +++ b/GreenshotPlugin/Core/FastBitmap.cs @@ -322,7 +322,7 @@ namespace GreenshotPlugin.Core { 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) { @@ -726,8 +726,8 @@ namespace GreenshotPlugin.Core { /// 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) { colorEntries = bitmap.Palette.Entries; diff --git a/GreenshotPlugin/Core/FilenameHelper.cs b/GreenshotPlugin/Core/FilenameHelper.cs index 30c7b3f59..236f4f2d9 100644 --- a/GreenshotPlugin/Core/FilenameHelper.cs +++ b/GreenshotPlugin/Core/FilenameHelper.cs @@ -41,7 +41,7 @@ namespace GreenshotPlugin.Core { 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 = "_"; /// @@ -159,7 +159,7 @@ namespace GreenshotPlugin.Core { switch (parameter.Substring(0, 1)) { // 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]); } catch { @@ -171,7 +171,7 @@ namespace GreenshotPlugin.Core { // 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]); } @@ -191,7 +191,7 @@ namespace GreenshotPlugin.Core { // 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 { startIndex = int.Parse(rangelist[0]); @@ -418,9 +418,9 @@ namespace GreenshotPlugin.Core { } return VAR_REGEXP.Replace(pattern, - new MatchEvaluator(delegate(Match m) { - return MatchVarEvaluator(m, null, processVars, userVars, machineVars, filenameSafeMode); - }) + delegate(Match m) { + return MatchVarEvaluator(m, null, processVars, userVars, machineVars, filenameSafeMode); + } ); } @@ -455,9 +455,9 @@ namespace GreenshotPlugin.Core { try { return VAR_REGEXP.Replace(pattern, - new MatchEvaluator(delegate(Match m) { - return MatchVarEvaluator(m, captureDetails, processVars, userVars, machineVars, filenameSafeMode); - }) + delegate(Match m) { + return MatchVarEvaluator(m, captureDetails, processVars, userVars, machineVars, filenameSafeMode); + } ); } catch (Exception e) { // adding additional data for bug tracking diff --git a/GreenshotPlugin/Core/GreenshotResources.cs b/GreenshotPlugin/Core/GreenshotResources.cs index 701786e80..216c82179 100644 --- a/GreenshotPlugin/Core/GreenshotResources.cs +++ b/GreenshotPlugin/Core/GreenshotResources.cs @@ -26,7 +26,7 @@ namespace GreenshotPlugin.Core { /// Centralized storage of the icons & bitmaps /// 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) { return (Image)greenshotResources.GetObject(imageName); diff --git a/GreenshotPlugin/Core/ImageHelper.cs b/GreenshotPlugin/Core/ImageHelper.cs index 86abd0dab..bad73adb5 100644 --- a/GreenshotPlugin/Core/ImageHelper.cs +++ b/GreenshotPlugin/Core/ImageHelper.cs @@ -24,10 +24,8 @@ using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; -using System.Runtime.InteropServices; using Greenshot.IniFile; using GreenshotPlugin.UnmanagedHelpers; -using Greenshot.Plugin; using Greenshot.Core; using log4net; @@ -48,8 +46,8 @@ namespace GreenshotPlugin.Core { /// Description of ImageHelper. /// public static class ImageHelper { - private static ILog LOG = LogManager.GetLogger(typeof(ImageHelper)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly ILog LOG = LogManager.GetLogger(typeof(ImageHelper)); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); private const int EXIF_ORIENTATION_ID = 0x0112; /// @@ -827,7 +825,7 @@ namespace GreenshotPlugin.Core { if ((shadowSize & 1) == 0) { shadowSize++; } - bool useGDIBlur = GDIplus.isBlurPossible(shadowSize); + bool useGDIBlur = GDIplus.IsBlurPossible(shadowSize); // Create "mask" for the shadow ColorMatrix maskMatrix = new ColorMatrix(); maskMatrix.Matrix00 = 0; @@ -1021,12 +1019,13 @@ namespace GreenshotPlugin.Core { public static ImageAttributes CreateAdjustAttributes(float brightness, float contrast, float gamma) { 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 @@ -1063,10 +1062,11 @@ namespace GreenshotPlugin.Core { /// Bitmap with grayscale 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/GreenshotPlugin/Core/ImageOutput.cs b/GreenshotPlugin/Core/ImageOutput.cs index 9b961b0f3..cc7a16af5 100644 --- a/GreenshotPlugin/Core/ImageOutput.cs +++ b/GreenshotPlugin/Core/ImageOutput.cs @@ -44,7 +44,7 @@ namespace GreenshotPlugin.Core { private static readonly ILog LOG = LogManager.GetLogger(typeof(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/GreenshotPlugin/Core/InterfaceUtils.cs b/GreenshotPlugin/Core/InterfaceUtils.cs index 0b02a9103..4b8710924 100644 --- a/GreenshotPlugin/Core/InterfaceUtils.cs +++ b/GreenshotPlugin/Core/InterfaceUtils.cs @@ -30,7 +30,7 @@ namespace GreenshotPlugin.Core { /// Description of InterfaceUtils. /// public static class InterfaceUtils { - private static ILog LOG = LogManager.GetLogger(typeof(InterfaceUtils)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(InterfaceUtils)); public static List GetSubclassesOf(Type type, bool excludeSystemTypes) { List list = new List(); diff --git a/GreenshotPlugin/Core/JSONHelper.cs b/GreenshotPlugin/Core/JSONHelper.cs index 8bb4e3625..1770e5657 100644 --- a/GreenshotPlugin/Core/JSONHelper.cs +++ b/GreenshotPlugin/Core/JSONHelper.cs @@ -8,7 +8,6 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; -using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; diff --git a/GreenshotPlugin/Core/Language.cs b/GreenshotPlugin/Core/Language.cs index e897c6a66..67899f1ed 100644 --- a/GreenshotPlugin/Core/Language.cs +++ b/GreenshotPlugin/Core/Language.cs @@ -35,21 +35,21 @@ namespace GreenshotPlugin.Core { /// The language resources are loaded from the language files found on fixed or supplied paths /// public class Language { - private static ILog LOG = LogManager.GetLogger(typeof(Language)); - private static List languagePaths = new List(); - private static IDictionary> languageFiles = new Dictionary>(); - private static IDictionary helpFiles = new Dictionary(); + private static readonly ILog LOG = LogManager.GetLogger(typeof(Language)); + private static readonly List languagePaths = new List(); + private static readonly IDictionary> languageFiles = new Dictionary>(); + private static readonly IDictionary helpFiles = new Dictionary(); private const string DEFAULT_LANGUAGE = "en-US"; private const string HELP_FILENAME_PATTERN = @"help-*.html"; private const string LANGUAGE_FILENAME_PATTERN = @"language*.xml"; - private static Regex PREFIX_REGEXP = new Regex(@"language_([a-zA-Z0-9]+).*"); - private static Regex IETF_CLEAN_REGEXP = new Regex(@"[^a-zA-Z]+"); - private static Regex IETF_REGEXP = new Regex(@"^.*([a-zA-Z]{2}-[a-zA-Z]{2})\.xml$"); + private static readonly Regex PREFIX_REGEXP = new Regex(@"language_([a-zA-Z0-9]+).*"); + private static readonly Regex IETF_CLEAN_REGEXP = new Regex(@"[^a-zA-Z]+"); + private static readonly Regex IETF_REGEXP = new Regex(@"^.*([a-zA-Z]{2}-[a-zA-Z]{2})\.xml$"); private const string LANGUAGE_GROUPS_KEY = @"SYSTEM\CurrentControlSet\Control\Nls\Language Groups"; - private static List unsupportedLanguageGroups = new List(); - private static IDictionary resources = new Dictionary(); - private static string currentLanguage = null; - private static CoreConfiguration coreConfig = null; + private static readonly List unsupportedLanguageGroups = new List(); + private static readonly IDictionary resources = new Dictionary(); + private static string currentLanguage; + private static readonly CoreConfiguration coreConfig; public static event LanguageChangedHandler LanguageChanged; diff --git a/GreenshotPlugin/Core/LogHelper.cs b/GreenshotPlugin/Core/LogHelper.cs index 253493f58..27b2b6211 100644 --- a/GreenshotPlugin/Core/LogHelper.cs +++ b/GreenshotPlugin/Core/LogHelper.cs @@ -37,7 +37,7 @@ namespace GreenshotPlugin.Core { public class LogHelper { private const string LOG4NET_FILE = "log4net.xml"; private const string LOG4NET_PORTABLE_FILE = "log4net-portable.xml"; - private static bool isLog4NetConfigured = false; + private static bool isLog4NetConfigured; private const string INIT_MESSAGE = "Greenshot initialization of log system failed"; public static bool isInitialized { get { diff --git a/GreenshotPlugin/Core/NetworkHelper.cs b/GreenshotPlugin/Core/NetworkHelper.cs index dc816eab7..5a9ec8877 100644 --- a/GreenshotPlugin/Core/NetworkHelper.cs +++ b/GreenshotPlugin/Core/NetworkHelper.cs @@ -552,10 +552,10 @@ namespace GreenshotPlugin.Core { /// A container to supply files to a Multi-part form data upload /// 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) { } public ByteContainer(byte[] file, string filename) : this(file, filename, null) { @@ -635,9 +635,9 @@ namespace GreenshotPlugin.Core { /// A container to supply images to a Multi-part form data upload /// 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; @@ -712,9 +712,9 @@ namespace GreenshotPlugin.Core { /// A container to supply surfaces to a Multi-part form data upload /// 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; diff --git a/GreenshotPlugin/Core/OAuthHelper.cs b/GreenshotPlugin/Core/OAuthHelper.cs index 110736f5e..add088da2 100644 --- a/GreenshotPlugin/Core/OAuthHelper.cs +++ b/GreenshotPlugin/Core/OAuthHelper.cs @@ -27,7 +27,6 @@ using System.Collections.Specialized; using System.Diagnostics; using System.Drawing; using System.Globalization; -using System.IO; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; @@ -968,7 +967,7 @@ Greenshot received information from CloudServiceName. You can close this browser private string _cloudServiceName; - private IDictionary _returnValues = new Dictionary(); + private readonly IDictionary _returnValues = new Dictionary(); /// @@ -991,7 +990,7 @@ Greenshot received information from CloudServiceName. You can close this browser Process.Start(authorizationUrl); // Wait to get the authorization code response. - var context = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener); + var context = listener.BeginGetContext(ListenerCallback, listener); _ready.Reset(); while (!context.AsyncWaitHandle.WaitOne(1000, true)) { diff --git a/GreenshotPlugin/Core/PluginUtils.cs b/GreenshotPlugin/Core/PluginUtils.cs index 122fbc150..a3d910e61 100644 --- a/GreenshotPlugin/Core/PluginUtils.cs +++ b/GreenshotPlugin/Core/PluginUtils.cs @@ -37,9 +37,9 @@ namespace GreenshotPlugin.Core { /// public static class PluginUtils { private static readonly ILog LOG = LogManager.GetLogger(typeof(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() { conf.PropertyChanged += OnIconSizeChanged; diff --git a/GreenshotPlugin/Core/QuantizerHelper.cs b/GreenshotPlugin/Core/QuantizerHelper.cs index d9bfa1713..d2feec81e 100644 --- a/GreenshotPlugin/Core/QuantizerHelper.cs +++ b/GreenshotPlugin/Core/QuantizerHelper.cs @@ -71,7 +71,7 @@ namespace GreenshotPlugin.Core { } public class WuQuantizer : IDisposable { - private static ILog LOG = LogManager.GetLogger(typeof(WuQuantizer)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(WuQuantizer)); private const Int32 MAXCOLOR = 512; private const Int32 RED = 2; @@ -82,23 +82,23 @@ namespace GreenshotPlugin.Core { 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/GreenshotPlugin/Core/SourceForgeHelper.cs b/GreenshotPlugin/Core/SourceForgeHelper.cs index 3a027cbbb..6ead257d0 100644 --- a/GreenshotPlugin/Core/SourceForgeHelper.cs +++ b/GreenshotPlugin/Core/SourceForgeHelper.cs @@ -21,7 +21,6 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Net; using System.Text.RegularExpressions; using System.Xml; @@ -96,7 +95,7 @@ namespace GreenshotPlugin.Core { /// Description of SourceForgeHelper. /// public class SourceForgeHelper { - private static ILog LOG = LogManager.GetLogger(typeof(SourceForgeHelper)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(SourceForgeHelper)); private const string RSSFEED = "http://getgreenshot.org/project-feed/"; /// diff --git a/GreenshotPlugin/Core/StringExtensions.cs b/GreenshotPlugin/Core/StringExtensions.cs index 9cbec97b4..6f457d212 100644 --- a/GreenshotPlugin/Core/StringExtensions.cs +++ b/GreenshotPlugin/Core/StringExtensions.cs @@ -26,7 +26,6 @@ using System.Text; using log4net; using System.Text.RegularExpressions; using System.Collections.Generic; -using System.Reflection; namespace GreenshotPlugin.Core { public static class StringExtensions { diff --git a/GreenshotPlugin/Core/WindowCapture.cs b/GreenshotPlugin/Core/WindowCapture.cs index a85792162..ebda0a660 100644 --- a/GreenshotPlugin/Core/WindowCapture.cs +++ b/GreenshotPlugin/Core/WindowCapture.cs @@ -62,7 +62,7 @@ namespace GreenshotPlugin.Core { set; } - private Dictionary metaData = new Dictionary(); + private readonly Dictionary metaData = new Dictionary(); public Dictionary MetaData { get {return metaData;} } @@ -644,7 +644,7 @@ namespace GreenshotPlugin.Core { // capture.Image = capturedBitmap; // capture.Location = captureBounds.Location; - using (SafeWindowDCHandle desktopDCHandle = SafeWindowDCHandle.fromDesktop()) { + using (SafeWindowDCHandle desktopDCHandle = SafeWindowDCHandle.FromDesktop()) { if (desktopDCHandle.IsInvalid) { // Get Exception before the error is lost Exception exceptionToThrow = CreateCaptureException("desktopDCHandle", captureBounds); diff --git a/GreenshotPlugin/Core/WindowsHelper.cs b/GreenshotPlugin/Core/WindowsHelper.cs index 4b69f88ad..412e018bc 100644 --- a/GreenshotPlugin/Core/WindowsHelper.cs +++ b/GreenshotPlugin/Core/WindowsHelper.cs @@ -47,7 +47,7 @@ namespace GreenshotPlugin.Core { /// public class WindowsEnumerator { #region Member Variables - private List items = null; + private List items; #endregion /// @@ -89,7 +89,7 @@ namespace GreenshotPlugin.Core { 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; @@ -164,11 +164,11 @@ namespace GreenshotPlugin.Core { private const string METRO_APPLAUNCHER_CLASS = "ImmersiveLauncher"; private const string METRO_GUTTER_CLASS = "ImmersiveGutter"; - private static ILog LOG = LogManager.GetLogger(typeof(WindowDetails)); - 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 ILog LOG = LogManager.GetLogger(typeof(WindowDetails)); + 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() { try { @@ -189,10 +189,10 @@ namespace GreenshotPlugin.Core { return ignoreHandles.Contains(handle); } - private List childWindows = null; + private List childWindows; private IntPtr parentHandle = IntPtr.Zero; - private WindowDetails parent = null; - private bool frozen = false; + private WindowDetails parent; + private bool frozen; public bool isApp { get { @@ -224,7 +224,7 @@ namespace GreenshotPlugin.Core { /// /// The window handle. /// - private IntPtr hWnd = IntPtr.Zero; + private readonly IntPtr hWnd = IntPtr.Zero; /// /// To allow items to be compared, the hash code @@ -588,7 +588,7 @@ namespace GreenshotPlugin.Core { } } - private string text = null; + private string text; /// /// Gets the window's title (caption) /// @@ -606,7 +606,7 @@ namespace GreenshotPlugin.Core { } } - private string className = null; + private string className; /// /// Gets the window's class name. /// @@ -755,7 +755,7 @@ namespace GreenshotPlugin.Core { } private Rectangle previousWindowRectangle = Rectangle.Empty; - private long lastWindowRectangleRetrieveTime = 0; + private long lastWindowRectangleRetrieveTime; private const long CACHE_TIME = TimeSpan.TicksPerSecond * 2; /// /// Gets the bounding rectangle of the window @@ -1515,7 +1515,7 @@ namespace GreenshotPlugin.Core { 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; } @@ -1585,7 +1585,7 @@ namespace GreenshotPlugin.Core { 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; } diff --git a/GreenshotPlugin/IEInterop/IHTMLBodyElement.cs b/GreenshotPlugin/IEInterop/IHTMLBodyElement.cs index eb5b399e2..dd9e8a2b8 100644 --- a/GreenshotPlugin/IEInterop/IHTMLBodyElement.cs +++ b/GreenshotPlugin/IEInterop/IHTMLBodyElement.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLCurrentStyle.cs b/GreenshotPlugin/IEInterop/IHTMLCurrentStyle.cs index 0bab7edf0..40d511c56 100644 --- a/GreenshotPlugin/IEInterop/IHTMLCurrentStyle.cs +++ b/GreenshotPlugin/IEInterop/IHTMLCurrentStyle.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLDocument.cs b/GreenshotPlugin/IEInterop/IHTMLDocument.cs index 176b66fea..d89a81159 100644 --- a/GreenshotPlugin/IEInterop/IHTMLDocument.cs +++ b/GreenshotPlugin/IEInterop/IHTMLDocument.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLDocument2.cs b/GreenshotPlugin/IEInterop/IHTMLDocument2.cs index a7a2e26e4..79de005d0 100644 --- a/GreenshotPlugin/IEInterop/IHTMLDocument2.cs +++ b/GreenshotPlugin/IEInterop/IHTMLDocument2.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLDocument3.cs b/GreenshotPlugin/IEInterop/IHTMLDocument3.cs index 8d4825044..6d9f2c8ba 100644 --- a/GreenshotPlugin/IEInterop/IHTMLDocument3.cs +++ b/GreenshotPlugin/IEInterop/IHTMLDocument3.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLDocument4.cs b/GreenshotPlugin/IEInterop/IHTMLDocument4.cs index 2ee041264..b78943ced 100644 --- a/GreenshotPlugin/IEInterop/IHTMLDocument4.cs +++ b/GreenshotPlugin/IEInterop/IHTMLDocument4.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLDocument5.cs b/GreenshotPlugin/IEInterop/IHTMLDocument5.cs index 10c603d7d..124f595b5 100644 --- a/GreenshotPlugin/IEInterop/IHTMLDocument5.cs +++ b/GreenshotPlugin/IEInterop/IHTMLDocument5.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLElement.cs b/GreenshotPlugin/IEInterop/IHTMLElement.cs index 5bdf3bf6f..e87c73efb 100644 --- a/GreenshotPlugin/IEInterop/IHTMLElement.cs +++ b/GreenshotPlugin/IEInterop/IHTMLElement.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLElement2.cs b/GreenshotPlugin/IEInterop/IHTMLElement2.cs index 44a278179..0aa0092b6 100644 --- a/GreenshotPlugin/IEInterop/IHTMLElement2.cs +++ b/GreenshotPlugin/IEInterop/IHTMLElement2.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLElementCollection.cs b/GreenshotPlugin/IEInterop/IHTMLElementCollection.cs index 3a393c69c..4a82b7e99 100644 --- a/GreenshotPlugin/IEInterop/IHTMLElementCollection.cs +++ b/GreenshotPlugin/IEInterop/IHTMLElementCollection.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Collections; using System.Runtime.InteropServices; diff --git a/GreenshotPlugin/IEInterop/IHTMLFrameBase.cs b/GreenshotPlugin/IEInterop/IHTMLFrameBase.cs index a41922c14..015ce20af 100644 --- a/GreenshotPlugin/IEInterop/IHTMLFrameBase.cs +++ b/GreenshotPlugin/IEInterop/IHTMLFrameBase.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLFramesCollection2.cs b/GreenshotPlugin/IEInterop/IHTMLFramesCollection2.cs index 07c2fab8a..65a541060 100644 --- a/GreenshotPlugin/IEInterop/IHTMLFramesCollection2.cs +++ b/GreenshotPlugin/IEInterop/IHTMLFramesCollection2.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLRect.cs b/GreenshotPlugin/IEInterop/IHTMLRect.cs index 943081b03..0045087a5 100644 --- a/GreenshotPlugin/IEInterop/IHTMLRect.cs +++ b/GreenshotPlugin/IEInterop/IHTMLRect.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLScreen.cs b/GreenshotPlugin/IEInterop/IHTMLScreen.cs index f51807b0d..f2f50b8b8 100644 --- a/GreenshotPlugin/IEInterop/IHTMLScreen.cs +++ b/GreenshotPlugin/IEInterop/IHTMLScreen.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLScreen2.cs b/GreenshotPlugin/IEInterop/IHTMLScreen2.cs index 459aeb741..d354175e4 100644 --- a/GreenshotPlugin/IEInterop/IHTMLScreen2.cs +++ b/GreenshotPlugin/IEInterop/IHTMLScreen2.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLSelectionObject.cs b/GreenshotPlugin/IEInterop/IHTMLSelectionObject.cs index 43fb5434c..17bcd982c 100644 --- a/GreenshotPlugin/IEInterop/IHTMLSelectionObject.cs +++ b/GreenshotPlugin/IEInterop/IHTMLSelectionObject.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLStyle.cs b/GreenshotPlugin/IEInterop/IHTMLStyle.cs index 31433a84c..5c3928bb4 100644 --- a/GreenshotPlugin/IEInterop/IHTMLStyle.cs +++ b/GreenshotPlugin/IEInterop/IHTMLStyle.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLTxtRange.cs b/GreenshotPlugin/IEInterop/IHTMLTxtRange.cs index 21e2997b8..78206f573 100644 --- a/GreenshotPlugin/IEInterop/IHTMLTxtRange.cs +++ b/GreenshotPlugin/IEInterop/IHTMLTxtRange.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLWindow2.cs b/GreenshotPlugin/IEInterop/IHTMLWindow2.cs index 16e1fd9cc..7eb6dfc53 100644 --- a/GreenshotPlugin/IEInterop/IHTMLWindow2.cs +++ b/GreenshotPlugin/IEInterop/IHTMLWindow2.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLWindow3.cs b/GreenshotPlugin/IEInterop/IHTMLWindow3.cs index 0fb76e227..0ddf5bbc4 100644 --- a/GreenshotPlugin/IEInterop/IHTMLWindow3.cs +++ b/GreenshotPlugin/IEInterop/IHTMLWindow3.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IHTMLWindow4.cs b/GreenshotPlugin/IEInterop/IHTMLWindow4.cs index 276f2bc73..bde9d27d5 100644 --- a/GreenshotPlugin/IEInterop/IHTMLWindow4.cs +++ b/GreenshotPlugin/IEInterop/IHTMLWindow4.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IEInterop/IWebBrowser2.cs b/GreenshotPlugin/IEInterop/IWebBrowser2.cs index 00abda678..d53d8df5b 100644 --- a/GreenshotPlugin/IEInterop/IWebBrowser2.cs +++ b/GreenshotPlugin/IEInterop/IWebBrowser2.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Runtime.InteropServices; namespace Greenshot.Interop.IE { diff --git a/GreenshotPlugin/IniFile/IniConfig.cs b/GreenshotPlugin/IniFile/IniConfig.cs index a6bbfca12..0f9d7401d 100644 --- a/GreenshotPlugin/IniFile/IniConfig.cs +++ b/GreenshotPlugin/IniFile/IniConfig.cs @@ -28,7 +28,7 @@ using log4net; namespace Greenshot.IniFile { public class IniConfig { - private static ILog LOG = LogManager.GetLogger(typeof(IniConfig)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(IniConfig)); private const string INI_EXTENSION = ".ini"; private const string DEFAULTS_POSTFIX = "-defaults"; private const string FIXED_POSTFIX = "-fixed"; @@ -36,22 +36,22 @@ namespace Greenshot.IniFile { /// /// 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; /// /// 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 @@ -61,17 +61,17 @@ namespace Greenshot.IniFile { /// /// A Dictionary with the fixed-properties for a section stored by section name /// - private static Dictionary> fixedProperties = null; + private static Dictionary> fixedProperties; /// /// Stores if we checked for portable /// - private static bool portableCheckMade = false; + private static bool portableCheckMade; /// /// Is the configuration portable (meaning we don't store it in the AppData directory) /// - private static bool portable = false; + private static bool portable; public static bool IsPortable { get { return portable; diff --git a/GreenshotPlugin/IniFile/IniReader.cs b/GreenshotPlugin/IniFile/IniReader.cs index 3447bf9db..205efc616 100644 --- a/GreenshotPlugin/IniFile/IniReader.cs +++ b/GreenshotPlugin/IniFile/IniReader.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Collections.Generic; using System.IO; using System.Text; @@ -28,7 +28,7 @@ namespace Greenshot.IniFile { 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/GreenshotPlugin/IniFile/IniSection.cs b/GreenshotPlugin/IniFile/IniSection.cs index 40aba49f9..4587ae8fb 100644 --- a/GreenshotPlugin/IniFile/IniSection.cs +++ b/GreenshotPlugin/IniFile/IniSection.cs @@ -34,9 +34,9 @@ namespace Greenshot.IniFile { protected static ILog LOG = LogManager.GetLogger(typeof(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 { if (iniSectionAttribute == null) { diff --git a/GreenshotPlugin/IniFile/IniValue.cs b/GreenshotPlugin/IniFile/IniValue.cs index c7fe99d01..9c2cee792 100644 --- a/GreenshotPlugin/IniFile/IniValue.cs +++ b/GreenshotPlugin/IniFile/IniValue.cs @@ -31,11 +31,11 @@ namespace Greenshot.IniFile { /// A container to be able to pass the value from a IniSection around. /// public class IniValue { - private static ILog LOG = LogManager.GetLogger(typeof(IniValue)); - private PropertyInfo propertyInfo; - private FieldInfo fieldInfo; - private IniSection containingIniSection; - private IniPropertyAttribute attributes; + private static readonly ILog LOG = LogManager.GetLogger(typeof(IniValue)); + private readonly PropertyInfo propertyInfo; + private readonly FieldInfo fieldInfo; + private readonly IniSection containingIniSection; + private readonly IniPropertyAttribute attributes; public IniValue(IniSection containingIniSection, PropertyInfo propertyInfo, IniPropertyAttribute iniPropertyAttribute) { this.containingIniSection = containingIniSection; @@ -216,7 +216,7 @@ namespace Greenshot.IniFile { // Get all the values. 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)); } @@ -293,7 +293,7 @@ namespace Greenshot.IniFile { 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; } } @@ -370,7 +370,7 @@ namespace Greenshot.IniFile { 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; } @@ -385,7 +385,7 @@ namespace Greenshot.IniFile { LOG.Warn("Problem converting " + arrayValue + " to type " + valueType.FullName, ex); } if (newValue != null) { - addMethodInfo.Invoke(list, new object[] { newValue }); + addMethodInfo.Invoke(list, new[] { newValue }); } } } @@ -394,7 +394,7 @@ namespace Greenshot.IniFile { //LOG.Debug("No convertor for " + fieldType.ToString()); 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/GreenshotPlugin/Interfaces/Forms/ImageEditor.cs b/GreenshotPlugin/Interfaces/Forms/ImageEditor.cs index 8c49e4e2d..0cebfc6b7 100644 --- a/GreenshotPlugin/Interfaces/Forms/ImageEditor.cs +++ b/GreenshotPlugin/Interfaces/Forms/ImageEditor.cs @@ -18,12 +18,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; -using System.Drawing; -using System.IO; -using System.Windows.Forms; -using GreenshotPlugin.Core; +using System.Drawing; +using System.Windows.Forms; namespace Greenshot.Plugin { /// diff --git a/GreenshotPlugin/Interfaces/Generic.cs b/GreenshotPlugin/Interfaces/Generic.cs index 73e6c2cf6..96283027a 100644 --- a/GreenshotPlugin/Interfaces/Generic.cs +++ b/GreenshotPlugin/Interfaces/Generic.cs @@ -20,7 +20,6 @@ */ using System; using System.Drawing; -using System.Drawing.Imaging; using System.Windows.Forms; using Greenshot.Plugin.Drawing; diff --git a/GreenshotPlugin/Interfaces/IDestination.cs b/GreenshotPlugin/Interfaces/IDestination.cs index e7da7eb9a..0377f5783 100644 --- a/GreenshotPlugin/Interfaces/IDestination.cs +++ b/GreenshotPlugin/Interfaces/IDestination.cs @@ -25,14 +25,14 @@ using System.Windows.Forms; 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) { this.destinationDesignation = destinationDesignation; diff --git a/GreenshotPlugin/Interfaces/IProcessor.cs b/GreenshotPlugin/Interfaces/IProcessor.cs index 40737888f..d69d4d378 100644 --- a/GreenshotPlugin/Interfaces/IProcessor.cs +++ b/GreenshotPlugin/Interfaces/IProcessor.cs @@ -19,9 +19,6 @@ * along with this program. If not, see . */ using System; -using System.Collections.Generic; -using System.Drawing; -using System.Windows.Forms; namespace Greenshot.Plugin { /// diff --git a/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs b/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs index b21963bf2..f075adc73 100644 --- a/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs +++ b/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs @@ -21,7 +21,6 @@ using System; using System.Collections.Generic; using System.Drawing; -using System.IO; using System.Windows.Forms; using GreenshotPlugin.Core; @@ -76,10 +75,10 @@ namespace Greenshot.Plugin { public delegate void HotKeyHandler(); 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() { disableReduceColors = false; diff --git a/GreenshotPlugin/Interop/Base.cs b/GreenshotPlugin/Interop/Base.cs index af344c6c2..16c4799fe 100644 --- a/GreenshotPlugin/Interop/Base.cs +++ b/GreenshotPlugin/Interop/Base.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; namespace Greenshot.Interop { /// diff --git a/GreenshotPlugin/Interop/COMWrapper.cs b/GreenshotPlugin/Interop/COMWrapper.cs index 49c3e1d8d..e06aea399 100644 --- a/GreenshotPlugin/Interop/COMWrapper.cs +++ b/GreenshotPlugin/Interop/COMWrapper.cs @@ -55,12 +55,12 @@ namespace Greenshot.Interop { /// /// The type of which method calls are intercepted and executed on the COM object. /// - private readonly Type _InterceptType; + private readonly Type _interceptType; /// /// The humanly readable target name /// - private readonly string _TargetName; + private readonly string _targetName; #endregion [DllImport("ole32.dll")] @@ -341,8 +341,8 @@ namespace Greenshot.Interop { private COMWrapper(object comObject, Type type, string targetName) : base(type) { _COMObject = comObject; _COMType = comObject.GetType(); - _InterceptType = type; - _TargetName = targetName; + _interceptType = type; + _targetName = targetName; } #endregion @@ -354,7 +354,7 @@ namespace Greenshot.Interop { /// sure that the COM object is still cleaned up. /// ~COMWrapper() { - LOG.DebugFormat("Finalize {0}", _InterceptType.ToString()); + LOG.DebugFormat("Finalize {0}", _interceptType); Dispose(false); } @@ -375,13 +375,13 @@ namespace Greenshot.Interop { /// private void Dispose(bool disposing) { if (null != _COMObject) { - LOG.DebugFormat("Disposing {0}", _InterceptType.ToString()); + LOG.DebugFormat("Disposing {0}", _interceptType); if (Marshal.IsComObject(_COMObject)) { try { int count; 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) { LOG.WarnFormat("Problem releasing COM object {0}", _COMType); @@ -406,7 +406,7 @@ namespace Greenshot.Interop { /// The full name of the intercepted type. /// public override string ToString() { - return _InterceptType.FullName; + return _interceptType.FullName; } /// @@ -485,11 +485,11 @@ namespace Greenshot.Interop { if (oldWrapper == null) { throw new ArgumentException("wrapper proxy was no COMWrapper"); } - if (oldWrapper._InterceptType.IsAssignableFrom(newType)) { - COMWrapper newWrapper = new COMWrapper(oldWrapper._COMObject, newType, oldWrapper._TargetName); + if (oldWrapper._interceptType.IsAssignableFrom(newType)) { + 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)); } /// @@ -536,21 +536,21 @@ namespace Greenshot.Interop { LOG.InfoFormat("Type information for Type with name: {0}", type.Name); try { foreach (MemberInfo memberInfo in type.GetMembers()) { - LOG.InfoFormat("Member: {0};", memberInfo.ToString()); + LOG.InfoFormat("Member: {0};", memberInfo); } } catch (Exception memberException) { LOG.Error(memberException); } try { foreach (PropertyInfo propertyInfo in type.GetProperties()) { - LOG.InfoFormat("Property: {0};", propertyInfo.ToString()); + LOG.InfoFormat("Property: {0};", propertyInfo); } } catch (Exception propertyException) { LOG.Error(propertyException); } try { foreach (FieldInfo fieldInfo in type.GetFields()) { - LOG.InfoFormat("Field: {0};", fieldInfo.ToString()); + LOG.InfoFormat("Field: {0};", fieldInfo); } } catch (Exception fieldException) { LOG.Error(fieldException); @@ -570,13 +570,13 @@ namespace Greenshot.Interop { 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; } @@ -589,25 +589,15 @@ namespace Greenshot.Interop { 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) { Dispose(); } else if ("ToString" == methodName && 0 == argCount && typeof(string) == returnType) { returnValue = ToString(); } else if ("GetType" == methodName && 0 == argCount && typeof(Type) == returnType) { - returnValue = _InterceptType; + returnValue = _interceptType; } else if ("GetHashCode" == methodName && 0 == argCount && typeof(int) == returnType) { returnValue = GetHashCode(); } else if ("Equals" == methodName && 1 == argCount && typeof(bool) == returnType) { @@ -621,9 +611,11 @@ namespace Greenshot.Interop { return new ReturnMessage(new ArgumentNullException("handler"), callMessage); } } else { - invokeObject = _COMObject; - invokeType = _COMType; + var invokeObject = _COMObject; + var invokeType = _COMType; + object[] args; + ParameterInfo parameter; if (methodName.StartsWith("get_")) { // Property Get methodName = methodName.Substring(4); @@ -657,6 +649,9 @@ namespace Greenshot.Interop { } // Un-wrap wrapped COM objects before passing to the method + Type byValType; + COMWrapper wrapper; + COMWrapper[] originalArgs; if (null == args || 0 == args.Length) { originalArgs = null; } else { @@ -677,7 +672,7 @@ namespace Greenshot.Interop { if (null == args[i]) { 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 // type mismatch exception. @@ -694,7 +689,7 @@ namespace Greenshot.Interop { break; } 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) { // Test for rejected @@ -703,13 +698,13 @@ namespace Greenshot.Interop { comEx = ex.InnerException as COMException; } 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(".")) { - destinationName = destinationName.Substring(0, destinationName.IndexOf(".")); + destinationName = destinationName.Substring(0, destinationName.IndexOf(".", StringComparison.Ordinal)); } if (destinationName == null) { - destinationName = _InterceptType.FullName; + destinationName = _interceptType.FullName; } DialogResult result = MessageBox.Show(PluginUtils.Host.GreenshotForm, Language.GetFormattedString("com_rejected", destinationName), Language.GetString("com_rejected_title"), MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation); if (result == DialogResult.OK) { @@ -726,7 +721,7 @@ namespace Greenshot.Interop { if (returnType.IsInterface) { // 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) { // Convert to proper Enum type @@ -742,7 +737,7 @@ namespace Greenshot.Interop { continue; } - arg = args[i]; + var arg = args[i]; if (null == arg) { continue; } @@ -751,7 +746,7 @@ namespace Greenshot.Interop { wrapper = null; byValType = GetByValType(parameter.ParameterType); - if (typeof(Decimal) == byValType) { + if (typeof(decimal) == byValType) { if (arg is CurrencyWrapper) { arg = ((CurrencyWrapper)arg).WrappedObject; } @@ -766,7 +761,7 @@ namespace Greenshot.Interop { } if (null == wrapper) { - wrapper = new COMWrapper(arg, byValType, _TargetName); + wrapper = new COMWrapper(arg, byValType, _targetName); } arg = wrapper.GetTransparentProxy(); } @@ -787,7 +782,7 @@ namespace Greenshot.Interop { /// object to cast /// public bool CanCastTo(Type toType, object o) { - bool returnValue = _InterceptType.IsAssignableFrom(toType); + bool returnValue = _interceptType.IsAssignableFrom(toType); return returnValue; } diff --git a/GreenshotPlugin/Interop/ComProgIdAttribute.cs b/GreenshotPlugin/Interop/ComProgIdAttribute.cs index c2d9e1434..7a64b4814 100644 --- a/GreenshotPlugin/Interop/ComProgIdAttribute.cs +++ b/GreenshotPlugin/Interop/ComProgIdAttribute.cs @@ -26,7 +26,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/GreenshotPlugin/Interop/IAppVisibility.cs b/GreenshotPlugin/Interop/IAppVisibility.cs index edcfcf915..8eb267376 100644 --- a/GreenshotPlugin/Interop/IAppVisibility.cs +++ b/GreenshotPlugin/Interop/IAppVisibility.cs @@ -20,7 +20,6 @@ */ using System; using System.Runtime.InteropServices; -using Greenshot.Interop; namespace Greenshot.Interop { // This is used for Windows 8 to see if the App Launcher is active diff --git a/GreenshotPlugin/Properties/AssemblyInfo.cs b/GreenshotPlugin/Properties/AssemblyInfo.cs index f4e66e2f6..b28bc45ab 100644 --- a/GreenshotPlugin/Properties/AssemblyInfo.cs +++ b/GreenshotPlugin/Properties/AssemblyInfo.cs @@ -21,7 +21,6 @@ using System.Reflection; using System.Runtime.InteropServices; -using System.Security; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information diff --git a/GreenshotPlugin/UnmanagedHelpers/Enumerations.cs b/GreenshotPlugin/UnmanagedHelpers/Enumerations.cs index 9a3fbbaf4..481c979e7 100644 --- a/GreenshotPlugin/UnmanagedHelpers/Enumerations.cs +++ b/GreenshotPlugin/UnmanagedHelpers/Enumerations.cs @@ -19,13 +19,15 @@ * along with this program. If not, see . */ using System; +using System.Diagnostics.CodeAnalysis; namespace GreenshotPlugin.UnmanagedHelpers { /// /// Window Style Flags /// [Flags] - public enum WindowStyleFlags : long { + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum WindowStyleFlags : long { //WS_OVERLAPPED = 0x00000000, WS_POPUP = 0x80000000, WS_CHILD = 0x40000000, @@ -76,7 +78,8 @@ namespace GreenshotPlugin.UnmanagedHelpers { } [Flags] - public enum ExtendedWindowStyleFlags : uint { + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum ExtendedWindowStyleFlags : uint { WS_EX_DLGMODALFRAME = 0x00000001, WS_EX_NOPARENTNOTIFY = 0x00000004, WS_EX_TOPMOST = 0x00000008, @@ -112,6 +115,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { } [Flags] + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum WindowPlacementFlags : uint { // The coordinates of the minimized window may be specified. // This flag must be specified if the coordinates are set in the ptMinPosition member. @@ -123,6 +127,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { WPF_RESTORETOMAXIMIZED = 0x0002 } + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum ShowWindowCommand : uint { /// /// Hides the window and activates another window. @@ -149,7 +154,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { 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, @@ -164,13 +169,13 @@ namespace GreenshotPlugin.UnmanagedHelpers { 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, @@ -194,7 +199,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { ForceMinimize = 11 } - public enum SYSCOLOR : int { + [SuppressMessage("ReSharper", "InconsistentNaming")] + public enum SYSCOLOR + { SCROLLBAR = 0, BACKGROUND = 1, DESKTOP = 1, @@ -234,7 +241,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// 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). /// @@ -612,7 +621,8 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// SM_REMOTECONTROL=0x2001 } - + + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum RegionResult { REGION_ERROR = 0, REGION_NULLREGION = 1, @@ -621,6 +631,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { } // See http://msdn.microsoft.com/en-us/library/aa969530(v=vs.85).aspx + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum DWMWINDOWATTRIBUTE { DWMWA_NCRENDERING_ENABLED = 1, DWMWA_NCRENDERING_POLICY, @@ -639,7 +650,8 @@ namespace GreenshotPlugin.UnmanagedHelpers { DWMWA_FREEZE_REPRESENTATION, // Since Windows 8 DWMWA_LAST } - + + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum GetWindowCommand : uint { GW_HWNDFIRST = 0, GW_HWNDLAST = 1, @@ -651,13 +663,16 @@ namespace GreenshotPlugin.UnmanagedHelpers { } [Flags] + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum DWM_BB { Enable = 1, BlurRegion = 2, 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. GCL_HBRBACKGROUND = -10, // a handle to the background brush associated with the class. @@ -670,7 +685,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { 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, WM_DESTROY = 0x0002, @@ -877,7 +894,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { } // 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. GWL_ID = -12, // Sets a new identifier of the child window. The window cannot be a top-level window. @@ -888,7 +907,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { // 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. SWP_DRAWFRAME = 0x0020, // Draws a frame (defined in the window's class description) around the window. @@ -906,13 +927,18 @@ namespace GreenshotPlugin.UnmanagedHelpers { 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. SB_PAGEUP = 2, // Scrolls one page up. @@ -924,6 +950,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { SB_ENDSCROLL = 8 // Ends scroll. } + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum ScrollInfoMask { SIF_RANGE = 0x1, SIF_PAGE = 0x2, @@ -937,6 +964,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// See: http://www.pinvoke.net/default.aspx/Enums/SendMessageTimeoutFlags.html /// [Flags] + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum SendMessageTimeoutFlags : uint { SMTO_NORMAL = 0x0, SMTO_BLOCK = 0x1, @@ -945,6 +973,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { } [Flags] + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum ProcessAccessFlags : uint { All = 0x001F0FFF, Terminate = 0x00000001, @@ -962,7 +991,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// 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 SND_NODEFAULT = 0x0002, // silence (!default) if sound not found @@ -979,6 +1010,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// 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 { /// /// Device driver version @@ -1147,7 +1179,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// 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, WINEVENT_OUTOFCONTEXT = 0, @@ -1158,6 +1192,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// 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, EVENT_OBJECT_CREATE = 32768, @@ -1207,7 +1242,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// 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, OBJID_CLIENT = -4, @@ -1223,6 +1260,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { } [Flags] + [SuppressMessage("ReSharper", "InconsistentNaming")] public enum DesktopAccessRight : uint { DESKTOP_READOBJECTS = 0x00000001, DESKTOP_CREATEWINDOW = 0x00000002, diff --git a/GreenshotPlugin/UnmanagedHelpers/GDI32.cs b/GreenshotPlugin/UnmanagedHelpers/GDI32.cs index f3e2aff3e..dd4c9d604 100644 --- a/GreenshotPlugin/UnmanagedHelpers/GDI32.cs +++ b/GreenshotPlugin/UnmanagedHelpers/GDI32.cs @@ -53,7 +53,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// /// SafeDeviceContextHandle public static SafeDeviceContextHandle GetSafeDeviceContext(this Graphics graphics) { - return SafeDeviceContextHandle.fromGraphics(graphics); + return SafeDeviceContextHandle.FromGraphics(graphics); } } @@ -77,10 +77,6 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// A hbitmap SafeHandle implementation /// public class SafeHBitmapHandle : SafeObjectHandle { - [SecurityCritical] - private SafeHBitmapHandle() : base(true) { - } - [SecurityCritical] public SafeHBitmapHandle(IntPtr preexistingHandle) : base(true) { SetHandle(preexistingHandle); @@ -105,10 +101,6 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// A dibsection SafeHandle implementation /// public class SafeDibSectionHandle : SafeObjectHandle { - [SecurityCritical] - private SafeDibSectionHandle() : base(true) { - } - [SecurityCritical] public SafeDibSectionHandle(IntPtr preexistingHandle) : base(true) { SetHandle(preexistingHandle); @@ -123,20 +115,16 @@ namespace GreenshotPlugin.UnmanagedHelpers { [DllImport("gdi32", SetLastError = true)] private static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject); - private SafeHandle hdc; - - [SecurityCritical] - private SafeSelectObjectHandle() : base(true) { - } + private readonly SafeHandle _hdc; [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; } } @@ -153,10 +141,6 @@ namespace GreenshotPlugin.UnmanagedHelpers { [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DeleteDC(IntPtr hDC); - [SecurityCritical] - private SafeCompatibleDCHandle() : base(true) { - } - [SecurityCritical] public SafeCompatibleDCHandle(IntPtr preexistingHandle) : base(true) { SetHandle(preexistingHandle); @@ -175,20 +159,16 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// A DeviceContext SafeHandle implementation /// public class SafeDeviceContextHandle : SafeDCHandle { - private Graphics graphics = null; - - [SecurityCritical] - private SafeDeviceContextHandle() : base(true) { - } + private readonly Graphics _graphics; [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; } @@ -196,7 +176,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { return new SafeSelectObjectHandle(this, newHandle); } - public static SafeDeviceContextHandle fromGraphics(Graphics graphics) { + public static SafeDeviceContextHandle FromGraphics(Graphics graphics) { return new SafeDeviceContextHandle(graphics, graphics.GetHdc()); } } @@ -221,41 +201,6 @@ namespace GreenshotPlugin.UnmanagedHelpers { public static extern uint GetPixel(SafeHandle hdc, int nXPos, int nYPos); [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)] @@ -380,10 +325,12 @@ namespace GreenshotPlugin.UnmanagedHelpers { 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/GreenshotPlugin/UnmanagedHelpers/GDIplus.cs b/GreenshotPlugin/UnmanagedHelpers/GDIplus.cs index dd446b425..ba0c86156 100644 --- a/GreenshotPlugin/UnmanagedHelpers/GDIplus.cs +++ b/GreenshotPlugin/UnmanagedHelpers/GDIplus.cs @@ -21,9 +21,7 @@ using System; using System.Drawing; using System.Runtime.InteropServices; -using System.Security; using log4net; -using Microsoft.Win32.SafeHandles; using System.Reflection; using System.Drawing.Drawing2D; using System.Drawing.Imaging; @@ -94,7 +92,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// GDIplus Helpers /// public static class GDIplus { - private static ILog LOG = LogManager.GetLogger(typeof(GDIplus)); + private static readonly ILog LOG = LogManager.GetLogger(typeof(GDIplus)); [DllImport("gdiplus.dll", SetLastError = true, ExactSpelling = true)] private static extern int GdipBitmapApplyEffect(IntPtr bitmap, IntPtr effect, ref RECT rectOfInterest, bool useAuxData, IntPtr auxData, int auxDataSize); @@ -107,7 +105,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { private static extern int GdipCreateEffect(Guid guid, out IntPtr effect); [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); @@ -118,7 +116,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { // 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 /// @@ -173,10 +171,11 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// /// /// - public static bool isBlurPossible(int radius) { - if (!isBlurEnabled) { + public static bool IsBlurPossible(int radius) { + if (!_isBlurEnabled) { return false; - } else if (Environment.OSVersion.Version.Minor >= 2 && radius < 20) { + } + if (Environment.OSVersion.Version.Minor >= 2 && radius < 20) { return false; } return true; @@ -191,7 +190,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// bool true if the edges are expanded with the 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; } IntPtr hBlurParams = IntPtr.Zero; @@ -226,7 +225,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { // Everything worked, return true return true; } catch (Exception ex) { - isBlurEnabled = false; + _isBlurEnabled = false; LOG.Error("Problem using GdipBitmapApplyEffect: ", ex); return false; } finally { @@ -240,7 +239,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { Marshal.FreeHGlobal(hBlurParams); } } catch (Exception ex) { - isBlurEnabled = false; + _isBlurEnabled = false; LOG.Error("Problem cleaning up ApplyBlur: ", ex); } } @@ -251,7 +250,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// /// 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; } @@ -291,7 +290,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { // Everything worked, return true return true; } catch (Exception ex) { - isBlurEnabled = false; + _isBlurEnabled = false; LOG.Error("Problem using GdipDrawImageFX: ", ex); return false; } finally { @@ -305,7 +304,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { Marshal.FreeHGlobal(hBlurParams); } } catch (Exception ex) { - isBlurEnabled = false; + _isBlurEnabled = false; LOG.Error("Problem cleaning up DrawWithBlur: ", ex); } } diff --git a/GreenshotPlugin/UnmanagedHelpers/Shell32.cs b/GreenshotPlugin/UnmanagedHelpers/Shell32.cs index e74d38310..4da73b482 100644 --- a/GreenshotPlugin/UnmanagedHelpers/Shell32.cs +++ b/GreenshotPlugin/UnmanagedHelpers/Shell32.cs @@ -37,39 +37,16 @@ namespace GreenshotPlugin.UnmanagedHelpers { private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags); #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, CharSet=CharSet.Unicode)] - private struct BROWSEINFO { - public IntPtr hwndOwner; - public IntPtr pidlRoot; - public IntPtr pszDisplayName; - [MarshalAs(UnmanagedType.LPWStr)] - 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 @@ -146,27 +123,27 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// 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 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) { - flags += Shell32.SHGFI_LINKOVERLAY; + if (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/GreenshotPlugin/UnmanagedHelpers/User32.cs b/GreenshotPlugin/UnmanagedHelpers/User32.cs index b3335a204..ef85d5994 100644 --- a/GreenshotPlugin/UnmanagedHelpers/User32.cs +++ b/GreenshotPlugin/UnmanagedHelpers/User32.cs @@ -63,7 +63,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { #region DllImports [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); [DllImport("user32", SetLastError = true)] @@ -75,9 +75,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { [DllImport("user32", SetLastError = true)] 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); [DllImport("user32", SetLastError = true)] @@ -98,13 +98,13 @@ namespace GreenshotPlugin.UnmanagedHelpers { public static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WindowPlacement lpwndpl); [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); - [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - public extern static int GetClassName (IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); + public static extern bool IsZoomed(IntPtr hwnd); [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern int GetClassName (IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); + [DllImport("user32", SetLastError = true)] public static extern uint GetClassLong(IntPtr hWnd, int nIndex); [DllImport("user32", SetLastError = true, EntryPoint = "GetClassLongPtr")] public static extern IntPtr GetClassLongPtr(IntPtr hWnd, int nIndex); @@ -112,13 +112,13 @@ namespace GreenshotPlugin.UnmanagedHelpers { [return: MarshalAs(UnmanagedType.Bool)] public static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags); [DllImport("user32", CharSet=CharSet.Unicode, SetLastError=true)] - public extern static IntPtr SendMessage(IntPtr hWnd, uint wMsg, IntPtr wParam, IntPtr lParam); + 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", CharSet = CharSet.Unicode, SetLastError = true)] public static extern int SetWindowLong(IntPtr hWnd, int index, int styleFlags); [DllImport("user32", SetLastError = true, EntryPoint = "SetWindowLongPtr")] @@ -131,9 +131,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { [return: MarshalAs(UnmanagedType.Bool)] 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)] public static extern bool GetScrollInfo(IntPtr hwnd, int fnBar, ref SCROLLINFO lpsi); @@ -187,7 +187,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { [DllImport("user32", SetLastError = true, CharSet = CharSet.Unicode)] 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); [DllImport("user32", SetLastError=true)] @@ -359,9 +359,6 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// A SafeHandle class implementation for the hIcon /// public class SafeIconHandle : SafeHandleZeroOrMinusOneIsInvalid { - private SafeIconHandle() : base(true) { - } - public SafeIconHandle(IntPtr hIcon) : base(true) { SetHandle(hIcon); } @@ -381,24 +378,21 @@ namespace GreenshotPlugin.UnmanagedHelpers { [DllImport("user32", SetLastError = true)] private static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC); - private IntPtr hWnd; - [SecurityCritical] - private SafeWindowDCHandle() : base(true) { - } + private readonly IntPtr _hWnd; [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); return new SafeWindowDCHandle(hWndDesktop, hDCDesktop); From 0fa6224ea6325e05280d866c156deb2227abb21e Mon Sep 17 00:00:00 2001 From: Robin Date: Tue, 26 Apr 2016 20:44:47 +0200 Subject: [PATCH 03/19] BUG-1941: Fixed a NullReferenceException, which is the issue itself. Don't know if it was caused by a different problem. --- Greenshot/Drawing/TextContainer.cs | 38 ++++++++++++++++++------------ 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/Greenshot/Drawing/TextContainer.cs b/Greenshot/Drawing/TextContainer.cs index f02ecbf39..6c58e2683 100644 --- a/Greenshot/Drawing/TextContainer.cs +++ b/Greenshot/Drawing/TextContainer.cs @@ -22,7 +22,6 @@ using Greenshot.Drawing.Fields; using Greenshot.Helpers; using Greenshot.Memento; -using Greenshot.Plugin; using Greenshot.Plugin.Drawing; using System; using System.ComponentModel; @@ -72,7 +71,7 @@ namespace Greenshot.Drawing { } internal void ChangeText(string newText, bool allowUndoable) { - if ((text == null && newText != null) || !text.Equals(newText)) { + if ((text == null && newText != null) || !string.Equals(text, newText)) { if (makeUndoable && allowUndoable) { makeUndoable = false; _parent.MakeUndoable(new TextChangeMemento(this), false); @@ -123,8 +122,10 @@ namespace Greenshot.Drawing { } private void Init() { - _stringFormat = new StringFormat(); - _stringFormat.Trimming = StringTrimming.EllipsisWord; + _stringFormat = new StringFormat + { + Trimming = StringTrimming.EllipsisWord + }; CreateTextBox(); @@ -178,15 +179,18 @@ namespace Greenshot.Drawing { } // 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 { UpdateAlignment(); } UpdateTextBoxFormat(); - if (_textBox.Visible) { + if (_textBox != null && _textBox.Visible) { _textBox.Invalidate(); } } @@ -196,17 +200,19 @@ namespace Greenshot.Drawing { } 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() { @@ -294,6 +300,7 @@ namespace Greenshot.Drawing { } } } + _font?.Dispose(); _font = new Font(fam, fontSize, fs, GraphicsUnit.Pixel); _textBox.Font = _font; } @@ -390,7 +397,7 @@ namespace Greenshot.Drawing { DrawSelectionBorder(graphics, rect); } - if (text == null || text.Length == 0 ) { + if (string.IsNullOrEmpty(text) ) { return; } @@ -411,6 +418,7 @@ namespace Greenshot.Drawing { /// /// /// + /// /// /// /// From 066ea19568e25696298e34d1d60cc251e95f1c53 Mon Sep 17 00:00:00 2001 From: Robin Date: Tue, 26 Apr 2016 21:21:00 +0200 Subject: [PATCH 04/19] BUG-1945: Fixed a problem during startup, where Greenshot can't specify the ServerCertificateValidationCallback which is needed to ignore SSL errors. --- GreenshotPlugin/Core/NetworkHelper.cs | 133 +++++++++++++------------- 1 file changed, 69 insertions(+), 64 deletions(-) diff --git a/GreenshotPlugin/Core/NetworkHelper.cs b/GreenshotPlugin/Core/NetworkHelper.cs index 5a9ec8877..de8ff9204 100644 --- a/GreenshotPlugin/Core/NetworkHelper.cs +++ b/GreenshotPlugin/Core/NetworkHelper.cs @@ -52,11 +52,17 @@ namespace GreenshotPlugin.Core { private static readonly CoreConfiguration Config = IniConfig.GetIniSection(); static NetworkHelper() { - // Disable certificate checking - ServicePointManager.ServerCertificateValidationCallback += - delegate { - return true; - }; + try + { + // Disable certificate checking + ServicePointManager.ServerCertificateValidationCallback += delegate { + return true; + }; + } + catch (Exception ex) + { + LOG.Warn("An error has occured while allowing self-signed certificates:", ex); + } } /// @@ -137,12 +143,18 @@ namespace GreenshotPlugin.Core { using (StreamReader streamReader = new StreamReader(memoryStream, Encoding.UTF8, true)) { content = streamReader.ReadLine(); } - Regex imageUrlRegex = new Regex(@"(http|https)://.*(\.png|\.gif|\.jpg|\.tiff|\.jpeg|\.bmp)"); - Match match = imageUrlRegex.Match(content); - if (match.Success) { - using (MemoryStream memoryStream2 = GetAsMemoryStream(match.Value)) { - using (Image image = Image.FromStream(memoryStream2)) { - return ImageHelper.Clone(image, PixelFormat.Format32bppArgb); + if (!string.IsNullOrEmpty(content)) + { + Regex imageUrlRegex = new Regex(@"(http|https)://.*(\.png|\.gif|\.jpg|\.tiff|\.jpeg|\.bmp)"); + Match match = imageUrlRegex.Match(content); + if (match.Success) + { + using (MemoryStream memoryStream2 = GetAsMemoryStream(match.Value)) + { + using (Image image = Image.FromStream(memoryStream2)) + { + return ImageHelper.Clone(image, PixelFormat.Format32bppArgb); + } } } } @@ -193,12 +205,7 @@ namespace GreenshotPlugin.Core { /// WebRequest 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; @@ -396,9 +403,10 @@ namespace GreenshotPlugin.Core { /// 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()) { @@ -460,6 +468,7 @@ namespace GreenshotPlugin.Core { /// /// /// + /// /// public static string GetResponseAsString(HttpWebRequest webRequest, bool alsoReturnContentOnError) { string responseData = null; @@ -552,10 +561,10 @@ namespace GreenshotPlugin.Core { /// A container to supply files to a Multi-part form data upload /// public class ByteContainer : IBinaryContainer { - private readonly byte[] file; - private readonly string fileName; - private readonly string contentType; - private readonly 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) { } public ByteContainer(byte[] file, string filename) : this(file, filename, null) { @@ -563,14 +572,10 @@ namespace GreenshotPlugin.Core { public ByteContainer(byte[] file, string filename, string contenttype) : this(file, filename, contenttype, 0) { } 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; } /// @@ -578,7 +583,7 @@ namespace GreenshotPlugin.Core { /// /// string public string ToBase64String(Base64FormattingOptions formattingOptions) { - return Convert.ToBase64String(file, 0, fileSize, formattingOptions); + return Convert.ToBase64String(_file, 0, _fileSize, formattingOptions); } /// @@ -586,7 +591,7 @@ namespace GreenshotPlugin.Core { /// /// byte[] public byte[] ToByteArray() { - return file; + return _file; } /// @@ -600,13 +605,13 @@ namespace GreenshotPlugin.Core { 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); } /// @@ -615,7 +620,7 @@ namespace GreenshotPlugin.Core { /// Stream to write to 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); } /// @@ -623,8 +628,8 @@ namespace GreenshotPlugin.Core { /// /// public void Upload(HttpWebRequest webRequest) { - webRequest.ContentType = contentType; - webRequest.ContentLength = fileSize; + webRequest.ContentType = _contentType; + webRequest.ContentLength = _fileSize; using (var requestStream = webRequest.GetRequestStream()) { WriteToStream(requestStream); } @@ -635,14 +640,14 @@ namespace GreenshotPlugin.Core { /// A container to supply images to a Multi-part form data upload /// public class BitmapContainer : IBinaryContainer { - private readonly Bitmap bitmap; - private readonly SurfaceOutputSettings outputSettings; - private readonly 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; } /// @@ -652,7 +657,7 @@ namespace GreenshotPlugin.Core { /// string 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); } } @@ -664,7 +669,7 @@ namespace GreenshotPlugin.Core { /// byte[] public byte[] ToByteArray() { using (MemoryStream stream = new MemoryStream()) { - ImageOutput.SaveToStream(bitmap, null, stream, outputSettings); + ImageOutput.SaveToStream(_bitmap, null, stream, _outputSettings); return stream.ToArray(); } } @@ -680,11 +685,11 @@ namespace GreenshotPlugin.Core { 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); } /// @@ -693,7 +698,7 @@ namespace GreenshotPlugin.Core { /// 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); } /// @@ -701,7 +706,7 @@ namespace GreenshotPlugin.Core { /// /// public void Upload(HttpWebRequest webRequest) { - webRequest.ContentType = "image/" + outputSettings.Format.ToString(); + webRequest.ContentType = "image/" + _outputSettings.Format; using (var requestStream = webRequest.GetRequestStream()) { WriteToStream(requestStream); } @@ -712,14 +717,14 @@ namespace GreenshotPlugin.Core { /// A container to supply surfaces to a Multi-part form data upload /// public class SurfaceContainer : IBinaryContainer { - private readonly ISurface surface; - private readonly SurfaceOutputSettings outputSettings; - private readonly 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; } /// @@ -729,7 +734,7 @@ namespace GreenshotPlugin.Core { /// string 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); } } @@ -741,7 +746,7 @@ namespace GreenshotPlugin.Core { /// byte[] public byte[] ToByteArray() { using (MemoryStream stream = new MemoryStream()) { - ImageOutput.SaveToStream(surface, stream, outputSettings); + ImageOutput.SaveToStream(_surface, stream, _outputSettings); return stream.ToArray(); } } @@ -757,11 +762,11 @@ namespace GreenshotPlugin.Core { 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); } /// @@ -770,7 +775,7 @@ namespace GreenshotPlugin.Core { /// 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); } /// @@ -778,7 +783,7 @@ namespace GreenshotPlugin.Core { /// /// public void Upload(HttpWebRequest webRequest) { - webRequest.ContentType = "image/" + outputSettings.Format.ToString(); + webRequest.ContentType = "image/" + _outputSettings.Format.ToString(); using (var requestStream = webRequest.GetRequestStream()) { WriteToStream(requestStream); } From e781bdcd5c90946087ba0b3d580419ba0674a6d0 Mon Sep 17 00:00:00 2001 From: Robin Date: Tue, 26 Apr 2016 23:12:45 +0200 Subject: [PATCH 05/19] BUG-1949: Fixed imgur issues, especially the delete. --- GreenshotImgurPlugin/ImgurConfiguration.cs | 2 - GreenshotImgurPlugin/ImgurInfo.cs | 70 ++++++++++++++-------- GreenshotImgurPlugin/ImgurUtils.cs | 55 ++++++++++------- 3 files changed, 79 insertions(+), 48 deletions(-) diff --git a/GreenshotImgurPlugin/ImgurConfiguration.cs b/GreenshotImgurPlugin/ImgurConfiguration.cs index 104839352..5392ec265 100644 --- a/GreenshotImgurPlugin/ImgurConfiguration.cs +++ b/GreenshotImgurPlugin/ImgurConfiguration.cs @@ -32,8 +32,6 @@ namespace GreenshotImgurPlugin { /// [IniSection("Imgur", Description="Greenshot Imgur Plugin configuration")] public class ImgurConfiguration : IniSection { - [IniProperty("ImgurApiUrl", Description="Url to Imgur system.", DefaultValue= "http://api.imgur.com/2")] - public string ImgurApiUrl; [IniProperty("ImgurApi3Url", Description = "Url to Imgur system.", DefaultValue = "https://api.imgur.com/3")] public string ImgurApi3Url; diff --git a/GreenshotImgurPlugin/ImgurInfo.cs b/GreenshotImgurPlugin/ImgurInfo.cs index 37e5a3ce8..c43903c04 100644 --- a/GreenshotImgurPlugin/ImgurInfo.cs +++ b/GreenshotImgurPlugin/ImgurInfo.cs @@ -27,7 +27,8 @@ namespace GreenshotImgurPlugin /// /// Description of ImgurInfo. /// - public class ImgurInfo : IDisposable { + public class ImgurInfo : IDisposable + { private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImgurInfo)); public string Hash @@ -37,9 +38,11 @@ namespace GreenshotImgurPlugin } private string deleteHash; - public string DeleteHash { - get {return deleteHash;} - set { + public string DeleteHash + { + get { return deleteHash; } + set + { deleteHash = value; DeletePage = "https://imgur.com/delete/" + value; } @@ -94,24 +97,29 @@ namespace GreenshotImgurPlugin } private Image image; - public Image Image { - get {return image;} - set { - if (image != null) { + public Image Image + { + get { return image; } + set + { + if (image != null) + { image.Dispose(); } image = value; } } - public ImgurInfo() { + public ImgurInfo() + { } /// /// The public accessible Dispose /// Will call the GarbageCollector to SuppressFinalize, preventing being cleaned twice /// - public void Dispose() { + public void Dispose() + { Dispose(true); GC.SuppressFinalize(this); } @@ -121,15 +129,19 @@ namespace GreenshotImgurPlugin /// When disposing==true all non-managed resources should be freed too! /// /// - protected virtual void Dispose(bool disposing) { - if (disposing) { - if (image != null) { + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + if (image != null) + { image.Dispose(); } } image = null; } - public static ImgurInfo ParseResponse(string response) { + public static ImgurInfo ParseResponse(string response) + { LOG.Debug(response); // This is actually a hack for BUG-1695 // The problem is the (C) sign, we send it HTML encoded "®" to Imgur and get it HTML encoded in the XML back @@ -142,11 +154,13 @@ namespace GreenshotImgurPlugin response = response.Replace("®", "®"); ImgurInfo imgurInfo = new ImgurInfo(); - try { + try + { XmlDocument doc = new XmlDocument(); doc.LoadXml(response); XmlNodeList nodes = doc.GetElementsByTagName("id"); - if(nodes.Count > 0) { + if (nodes.Count > 0) + { imgurInfo.Hash = nodes.Item(0).InnerText; } nodes = doc.GetElementsByTagName("hash"); @@ -155,19 +169,23 @@ namespace GreenshotImgurPlugin imgurInfo.Hash = nodes.Item(0).InnerText; } nodes = doc.GetElementsByTagName("deletehash"); - if(nodes.Count > 0) { + if (nodes.Count > 0) + { imgurInfo.DeleteHash = nodes.Item(0).InnerText; } nodes = doc.GetElementsByTagName("type"); - if(nodes.Count > 0) { + if (nodes.Count > 0) + { imgurInfo.ImageType = nodes.Item(0).InnerText; } nodes = doc.GetElementsByTagName("title"); - if(nodes.Count > 0) { + if (nodes.Count > 0) + { imgurInfo.Title = nodes.Item(0).InnerText; } nodes = doc.GetElementsByTagName("datetime"); - if(nodes.Count > 0) { + if (nodes.Count > 0) + { // Version 3 has seconds since Epoch double secondsSince; if (double.TryParse(nodes.Item(0).InnerText, out secondsSince)) @@ -198,15 +216,17 @@ namespace GreenshotImgurPlugin imgurInfo.Page = string.Format("https://imgur.com/{0}", imgurInfo.Hash); } nodes = doc.GetElementsByTagName("small_square"); - if(nodes.Count > 0) { + if (nodes.Count > 0) + { imgurInfo.SmallSquare = nodes.Item(0).InnerText; } - nodes = doc.GetElementsByTagName("large_thumbnail"); - if(nodes.Count > 0) + else { - imgurInfo.LargeThumbnail = nodes.Item(0).InnerText.Replace("http:", "https:"); + imgurInfo.SmallSquare = string.Format("http://i.imgur.com/{0}s.png",imgurInfo.Hash); } - } catch(Exception e) { + } + catch (Exception e) + { LOG.ErrorFormat("Could not parse Imgur response due to error {0}, response was: {1}", e.Message, response); } return imgurInfo; diff --git a/GreenshotImgurPlugin/ImgurUtils.cs b/GreenshotImgurPlugin/ImgurUtils.cs index 3bb80e0f8..0e426157d 100644 --- a/GreenshotImgurPlugin/ImgurUtils.cs +++ b/GreenshotImgurPlugin/ImgurUtils.cs @@ -119,7 +119,7 @@ namespace GreenshotImgurPlugin { if (filename != null && Config.AddFilename) { otherParameters.Add("name", filename); } - string responseString; + string responseString = null; if (Config.AnonymousAccess) { // add key, we only use the other parameters for the AnonymousAccess //otherParameters.Add("key", IMGUR_ANONYMOUS_API_KEY); @@ -133,11 +133,17 @@ namespace GreenshotImgurPlugin { ImageOutput.SaveToStream(surfaceToUpload, requestStream, outputSettings); } - using (WebResponse response = webRequest.GetResponse()) { - using (StreamReader reader = new StreamReader(response.GetResponseStream(), true)) { - responseString = reader.ReadToEnd(); - } + using (WebResponse response = webRequest.GetResponse()) + { LogRateLimitInfo(response); + var responseStream = response.GetResponseStream(); + if (responseStream != null) + { + using (StreamReader reader = new StreamReader(responseStream, true)) + { + responseString = reader.ReadToEnd(); + } + } } } catch (Exception ex) { LOG.Error("Upload to imgur gave an exeption: ", ex); @@ -145,20 +151,22 @@ namespace GreenshotImgurPlugin { } } else { - var oauth2Settings = new OAuth2Settings(); - oauth2Settings.AuthUrlPattern = AuthUrlPattern; - oauth2Settings.TokenUrl = TokenUrl; - oauth2Settings.RedirectUrl = "https://imgur.com"; - oauth2Settings.CloudServiceName = "Imgur"; - oauth2Settings.ClientId = ImgurCredentials.CONSUMER_KEY; - oauth2Settings.ClientSecret = ImgurCredentials.CONSUMER_SECRET; - oauth2Settings.AuthorizeMode = OAuth2AuthorizeMode.EmbeddedBrowser; - oauth2Settings.BrowserSize = new Size(680, 880); + var oauth2Settings = new OAuth2Settings + { + AuthUrlPattern = AuthUrlPattern, + TokenUrl = TokenUrl, + RedirectUrl = "https://imgur.com", + CloudServiceName = "Imgur", + ClientId = ImgurCredentials.CONSUMER_KEY, + ClientSecret = ImgurCredentials.CONSUMER_SECRET, + AuthorizeMode = OAuth2AuthorizeMode.EmbeddedBrowser, + BrowserSize = new Size(680, 880), + RefreshToken = Config.RefreshToken, + AccessToken = Config.AccessToken, + AccessTokenExpires = Config.AccessTokenExpires + }; // Copy the settings from the config, which is kept in memory and on the disk - oauth2Settings.RefreshToken = Config.RefreshToken; - oauth2Settings.AccessToken = Config.AccessToken; - oauth2Settings.AccessTokenExpires = Config.AccessTokenExpires; try { @@ -179,6 +187,10 @@ namespace GreenshotImgurPlugin { IniConfig.Save(); } } + if (string.IsNullOrEmpty(responseString)) + { + return null; + } return ImgurInfo.ParseResponse(responseString); } @@ -194,7 +206,8 @@ namespace GreenshotImgurPlugin { LOG.InfoFormat("Retrieving Imgur image for {0} with url {1}", imgurInfo.Hash, imgurInfo.SmallSquare); HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(string.Format(SmallUrlPattern, imgurInfo.Hash), HTTPMethod.GET); webRequest.ServicePoint.Expect100Continue = false; - SetClientId(webRequest); + // Not for getting the thumbnail, in anonymous modus + //SetClientId(webRequest); using (WebResponse response = webRequest.GetResponse()) { LogRateLimitInfo(response); Stream responseStream = response.GetResponseStream(); @@ -212,7 +225,7 @@ namespace GreenshotImgurPlugin { /// /// ImgurInfo public static ImgurInfo RetrieveImgurInfo(string hash, string deleteHash) { - string url = Config.ImgurApiUrl + "/image/" + hash; + string url = Config.ImgurApi3Url + "/image/" + hash + ".xml"; LOG.InfoFormat("Retrieving Imgur info for {0} with url {1}", hash, url); HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(url, HTTPMethod.GET); webRequest.ServicePoint.Expect100Continue = false; @@ -247,8 +260,8 @@ namespace GreenshotImgurPlugin { LOG.InfoFormat("Deleting Imgur image for {0}", imgurInfo.DeleteHash); try { - string url = Config.ImgurApiUrl + "/delete/" + imgurInfo.DeleteHash; - HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(url, HTTPMethod.GET); + string url = Config.ImgurApi3Url + "/image/" + imgurInfo.DeleteHash + ".xml"; + HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(url, HTTPMethod.DELETE); webRequest.ServicePoint.Expect100Continue = false; SetClientId(webRequest); string responseString; From 5c04af1684acc1957be3d7604d89e76daca84c9a Mon Sep 17 00:00:00 2001 From: Robin Date: Tue, 26 Apr 2016 23:13:37 +0200 Subject: [PATCH 06/19] Undo of some cleanup which causes issues, --- GreenshotPlugin/UnmanagedHelpers/GDI32.cs | 47 +++++++++++++++++++++- GreenshotPlugin/UnmanagedHelpers/User32.cs | 17 ++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/GreenshotPlugin/UnmanagedHelpers/GDI32.cs b/GreenshotPlugin/UnmanagedHelpers/GDI32.cs index dd4c9d604..95462a63b 100644 --- a/GreenshotPlugin/UnmanagedHelpers/GDI32.cs +++ b/GreenshotPlugin/UnmanagedHelpers/GDI32.cs @@ -77,6 +77,16 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// A hbitmap SafeHandle implementation /// public class SafeHBitmapHandle : SafeObjectHandle { + + /// + /// Needed for marshalling return values + /// + [SecurityCritical] + public SafeHBitmapHandle() : base(true) + { + + } + [SecurityCritical] public SafeHBitmapHandle(IntPtr preexistingHandle) : base(true) { SetHandle(preexistingHandle); @@ -87,8 +97,12 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// A hRegion SafeHandle implementation /// public class SafeRegionHandle : SafeObjectHandle { + /// + /// Needed for marshalling return values + /// [SecurityCritical] - private SafeRegionHandle() : base(true) { + public SafeRegionHandle() : base(true) + { } [SecurityCritical] @@ -101,6 +115,14 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// A dibsection SafeHandle implementation /// public class SafeDibSectionHandle : SafeObjectHandle { + /// + /// Needed for marshalling return values + /// + [SecurityCritical] + public SafeDibSectionHandle() : base(true) + { + } + [SecurityCritical] public SafeDibSectionHandle(IntPtr preexistingHandle) : base(true) { SetHandle(preexistingHandle); @@ -116,6 +138,13 @@ namespace GreenshotPlugin.UnmanagedHelpers { private static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject); private readonly SafeHandle _hdc; + /// + /// Needed for marshalling return values + /// + [SecurityCritical] + public SafeSelectObjectHandle() : base(true) + { + } [SecurityCritical] public SafeSelectObjectHandle(SafeDCHandle hdc, SafeHandle newHandle) : base(true) { @@ -141,6 +170,14 @@ namespace GreenshotPlugin.UnmanagedHelpers { [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DeleteDC(IntPtr hDC); + /// + /// Needed for marshalling return values + /// + [SecurityCritical] + public SafeCompatibleDCHandle() : base(true) + { + } + [SecurityCritical] public SafeCompatibleDCHandle(IntPtr preexistingHandle) : base(true) { SetHandle(preexistingHandle); @@ -161,6 +198,14 @@ namespace GreenshotPlugin.UnmanagedHelpers { public class SafeDeviceContextHandle : SafeDCHandle { private readonly Graphics _graphics; + /// + /// Needed for marshalling return values + /// + [SecurityCritical] + public SafeDeviceContextHandle() : base(true) + { + } + [SecurityCritical] public SafeDeviceContextHandle(Graphics graphics, IntPtr preexistingHandle) : base(true) { _graphics = graphics; diff --git a/GreenshotPlugin/UnmanagedHelpers/User32.cs b/GreenshotPlugin/UnmanagedHelpers/User32.cs index ef85d5994..76b7c5056 100644 --- a/GreenshotPlugin/UnmanagedHelpers/User32.cs +++ b/GreenshotPlugin/UnmanagedHelpers/User32.cs @@ -359,6 +359,16 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// A SafeHandle class implementation for the hIcon /// public class SafeIconHandle : SafeHandleZeroOrMinusOneIsInvalid { + + /// + /// Needed for marshalling return values + /// + [SecurityCritical] + public SafeIconHandle() : base(true) + { + } + + public SafeIconHandle(IntPtr hIcon) : base(true) { SetHandle(hIcon); } @@ -380,6 +390,13 @@ namespace GreenshotPlugin.UnmanagedHelpers { private readonly IntPtr _hWnd; + /// + /// Needed for marshalling return values + /// + public SafeWindowDCHandle() : base(true) + { + } + [SecurityCritical] public SafeWindowDCHandle(IntPtr hWnd, IntPtr preexistingHandle) : base(true) { _hWnd = hWnd; From 728f49944fd3473aab300ba5d7934e3a13de0e82 Mon Sep 17 00:00:00 2001 From: Robin Date: Tue, 26 Apr 2016 23:33:17 +0200 Subject: [PATCH 07/19] BUG-1890: Fixed wrong cropping when window is maximized on Windows 10 --- .../Core/OperatingSystemExtensions.cs | 92 +++++++++++++++++++ GreenshotPlugin/Core/WindowsHelper.cs | 24 +++-- GreenshotPlugin/GreenshotPlugin.csproj | 1 + 3 files changed, 109 insertions(+), 8 deletions(-) create mode 100644 GreenshotPlugin/Core/OperatingSystemExtensions.cs diff --git a/GreenshotPlugin/Core/OperatingSystemExtensions.cs b/GreenshotPlugin/Core/OperatingSystemExtensions.cs new file mode 100644 index 000000000..769547e03 --- /dev/null +++ b/GreenshotPlugin/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); + } + } +} diff --git a/GreenshotPlugin/Core/WindowsHelper.cs b/GreenshotPlugin/Core/WindowsHelper.cs index 412e018bc..0fa642128 100644 --- a/GreenshotPlugin/Core/WindowsHelper.cs +++ b/GreenshotPlugin/Core/WindowsHelper.cs @@ -768,7 +768,13 @@ namespace GreenshotPlugin.Core { if (previousWindowRectangle.IsEmpty || now - lastWindowRectangleRetrieveTime > CACHE_TIME) { Rectangle windowRect = Rectangle.Empty; if (DWM.isDWMEnabled()) { - GetExtendedFrameBounds(out windowRect); + if (GetExtendedFrameBounds(out windowRect) && Environment.OSVersion.IsWindows10()) + { + lastWindowRectangleRetrieveTime = now; + previousWindowRectangle = windowRect; + // DWM does it corectly, just return the window rectangle we just gotten. + return windowRect; + } } if (windowRect.IsEmpty) { @@ -915,10 +921,12 @@ namespace GreenshotPlugin.Core { 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); @@ -932,8 +940,8 @@ namespace GreenshotPlugin.Core { } // Calculate the location of the temp form - Point formLocation; Rectangle windowRectangle = WindowRectangle; + Point formLocation = formLocation = windowRectangle.Location; Size borderSize = new Size(); bool doesCaptureFit = false; if (!Maximised) { @@ -962,7 +970,7 @@ namespace GreenshotPlugin.Core { doesCaptureFit = true; } } - } else { + } else if (!Environment.OSVersion.IsWindows8OrLater()) { //GetClientRect(out windowRectangle); GetBorderSize(out borderSize); formLocation = new Point(windowRectangle.X - borderSize.Width, windowRectangle.Y - borderSize.Height); @@ -1067,7 +1075,7 @@ namespace GreenshotPlugin.Core { } 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) { // Remove corners diff --git a/GreenshotPlugin/GreenshotPlugin.csproj b/GreenshotPlugin/GreenshotPlugin.csproj index 917a12654..f29b3b79b 100644 --- a/GreenshotPlugin/GreenshotPlugin.csproj +++ b/GreenshotPlugin/GreenshotPlugin.csproj @@ -42,6 +42,7 @@ + From db5a92dea4d62dc2ec7b35d083a0b13b91aaa651 Mon Sep 17 00:00:00 2001 From: Robin Date: Tue, 26 Apr 2016 23:42:25 +0200 Subject: [PATCH 08/19] Fixed build, and updated readme. --- .../additional_files/readme.txt.template | 20 +++++++++++++++++++ appveyor12.yml | 4 ++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/Greenshot/releases/additional_files/readme.txt.template b/Greenshot/releases/additional_files/readme.txt.template index 0881700f2..4fd81e5dc 100644 --- a/Greenshot/releases/additional_files/readme.txt.template +++ b/Greenshot/releases/additional_files/readme.txt.template @@ -21,6 +21,26 @@ In this version we fix the bug in the update check, and we are also working on a Here is the list of chances: +This is a pre-release for the comming bug-fix release of Greenshot. + +This version has changes, compared to 1.2.8.12, for the following reported tickets: + +* BUG-1884: OCR has trailing blank spaces| +* BUG-1890: Slight cropping around window on Windows 10| +* BUG-1892: Greenshot saves blank JPG file with reduce colors| +* BUG-1898: Specify GPLv3 in the license text| +* BUG-1918: Speechbubble issue: Artifacts appeared when shadow is on and transparency is used| +* BUG-1933: Greenshot Installer sets bad registry key permission| +* BUG-1935: Delay when pasting and ShapeShifter from FlameFusion is running| +* BUG-1941: Error when creating speech bubble| +* BUG-1945: Failure starting Greenshot at system startup| +* BUG-1949: Can't delete Imgur upload| + +Testing is not finished, use at your own risk... + + +1.2.8.12 Release + Bugs Resolved: BUG-1527 / BUG-1848 / BUG-1850 / BUG-1851 / BUG-1859 : Greenshot stops responding, hangs or crashes diff --git a/appveyor12.yml b/appveyor12.yml index 19f38fd44..05ac9b5b6 100644 --- a/appveyor12.yml +++ b/appveyor12.yml @@ -42,12 +42,12 @@ environment: rsakey: secure: GNomwdlwZOCyd8d7xEWTnMVs1lpOeHvF+tlnvcbXGovLRtwAp2Ufu0r7paGY7BHGGkIs2WE7xUfyQ9UauVB+58JZ6fwVega8ucUgVJhl4x0QQNN2d6sULUhHfhuEHmxw+FDO/FxKFE6Lmf+ZRY+OGiw0wKIl4qD7mGRHcDQTipNEsTbau8HzqRVCdu3dx7pODC61DlsbO71xLF7UlqnmuZE+91Zz3V6AgaqE246n1499d6bXBYw1AH+8opNnKDFLnTHf7hUVcZn9mj6tKZXeTCuVUOr/SVQcgHKxlBlqzhfaEkxCR5GPtzQRqwDMxEycmFvj2wNP/sie6UEGhQxE4YMCc2OgqNOkpc5BbP/fxLr/SLFOEf1XXzTWCFMhsgpHx7TZbgQH26sa0rK/xaBRacZlwAaNk7V2nFZT7TebYEFy6zWNr9Y+IyeXIofj42XQTNXv8d8hyh+UYLByVEFYRf2DnActQkZQyNdWjZ+CxDV50QSZZs8FT3IIqraHYKsj2ITAN5LrUtWCi7bpNJL0UGo0EJiB2i0bp++tEAAwyrCljxI8d4bbGl/flHk/xd+ysQPnomndijeObjguEzqT8pyXZluSZhF+lI50mIDhMdtdAfMi5yn5RW7P6NWOSlC8xgQQgMZylsuSvRflKbEd/gsoDyEOnakNcdH2jekt9OD6GnuYM7iHkbMC89LBZ0VaHNGvCC+BQXdGUG7O9R3NthZcDXE7q7xbtGRB5ncVQDRfKoT5HVfiV6bSDrcfRODiuR59mZgiSYtZG+3kQWYUKn2wagvZKckGukA0SlOuTRCKZhgLcVHhWeRWeGE3iJ8K6BeHf2EgB8Qr6ayTyTUjBcn+u4qqWKgkvG4qRavlvrBSdMrAXWIKE8vSq1od0A2ZzP6+HCsrkuUR+HFfpE2dpjeckoa5vATQgyn8j5x11iIOB9HnT3YKbZ0aTU4rQgYMJXA/fPcgKDGkAPdgtGbQLssy/mwSdsXBYtMgEcs7vI9laR8Ik+NK2dbFHGFPnxS43WToGyKBxojt8SZbgPJXm22WRrN1+9AZvvhI7/mpZiEE7HWgNRClZYuqbfCMpelLGvVq832OLjelrWMJ0XBVNHnOw0p8qZKI1UpqQJXX1nL8j3JttEVHsfryIanM03kNDL0dX1VAKECKUMCVQ6i6tG4VWsR0C2JccPJ3PSoPgo5KMJhuZNaBoiPjZ2eaMREV6vUYbBYzrvdDQzUcE2stacREl4eJzGJ4GP5h08GQmIirGF/SCyZV1CadAbKZVjqb70XpIbE6NT/+84O82LZR4ui5KgTAv87lTZgvNJ7LxM7rRg1awj/iBxQeARNJxuPMPlk1CVx8Z3091UdL1K1avPKa85lCRwCkDKLcJPO9tlqi4dVjCrwpoCJkQMm3fbTl/BgHn00/RsnFZ2qfl5m2DyF+XuaOPauzsRdLUFAC4h44qoUuzRb4Pv6RFhN5CI4fddRKafNBHU9f69UCkO080/hIjTdj0+bpr4oNY4UEi80huyJY/c0iUPE8o48qBB8F3cW30SwhPmuphn4/18lB8GEwEPqoatmli4QRaDFUCUf9Hj0DEUqEAya/OHOW7/PvWcw/l/ZaIMUpOZ6q0xvPDAXokFRJAWzZhG7hNbWNEzQ3f/BjlYlYsBtMY0JUU8mH6YxwIzIGbHiLTBC0OglH0rDd5W+3NaUG9FZ//o9MAP5j2QqwSuFWXppbigh4zk+h17eJn5zhld7dtvOr+YmgYULj6NFIDKBZHUJdqLYScVzdc1p812FCCBcLmmw4RnwuF+RldHixTdy4UZ17T/hD4OLpWCINl9lUAficC0OFeLJLHxFW6Em8SCbZ3aUtFDIQD8oTqzUHZhGWYF2ukrOc8Dzm4FQ8xy3BhqfntTod1gwoilIirsP/z+GGMnTltkqiqK+gCmkVOfICwNFmHltZeJrmDQ4YU5abR09Yr1TaAk3CzWjV1XGBaf/oek0+tFkMOtZNdFRdlzLLE90PsZZFFnZhFBoNoOhYnMB9K2VqgEpJs0nXvF6qBOllptcpBYUYMzMdb0Ggu6m1d/phxuBuOsm+Xtr0Zw8Xd0vxIOQNDGsskCDIEUYWYajw2i66MmRPRyFEennXfLA0WIPpztXvfsrKjf42rjE3RukBsRff1Sci68cel4fGfmvj2y7gW0Tt before_build: -- ps: iex (new-object Net.WebClient).DownloadString("https://bitbucket.org/greenshot/greenshot/raw/1.2/prebuild.ps1") +- ps: .\prebuild.ps1 build: project: greenshot\greenshot.sln verbosity: normal after_build: -- ps: iex (new-object Net.WebClient).DownloadString("https://bitbucket.org/greenshot/greenshot/raw/1.2/build.ps1") +- ps: .\build.ps1 test: off artifacts: - path: Greenshot\releases\Greenshot*INSTALLER*.exe From 4f326c9c0ed9bfc79d3eccbe74b129a701145021 Mon Sep 17 00:00:00 2001 From: Robin Date: Fri, 29 Apr 2016 16:44:16 +0200 Subject: [PATCH 09/19] [skip ci] Added horizontal scrolling with the mousewheel when keeping shift pressed. --- Greenshot/Controls/NonJumpingPanel.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Greenshot/Controls/NonJumpingPanel.cs b/Greenshot/Controls/NonJumpingPanel.cs index 93f2f713c..6677c0da1 100644 --- a/Greenshot/Controls/NonJumpingPanel.cs +++ b/Greenshot/Controls/NonJumpingPanel.cs @@ -32,5 +32,23 @@ namespace GreenshotPlugin.Controls { // 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); + } + } } } From d25021631e75d732fa75c358baa903108a9f15d6 Mon Sep 17 00:00:00 2001 From: Robin Date: Fri, 20 May 2016 23:43:31 +0200 Subject: [PATCH 10/19] FEATURE-945: Added environment variables to the external command (also removed unused imports and made some variables readonly) --- Greenshot/AssemblyInfo.cs | 1 - ...ontextMenuToolStripProfessionalRenderer.cs | 1 - Greenshot/Destinations/EmailDestination.cs | 4 - Greenshot/Drawing/HighlightContainer.cs | 1 - Greenshot/Drawing/SpeechbubbleContainer.cs | 3 - Greenshot/Forms/DropShadowSettingsForm.cs | 1 - Greenshot/Forms/PrintOptionsDialog.cs | 1 - Greenshot/Forms/TornEdgeSettingsForm.cs | 1 - .../additional_files/readme.txt.template | 3 +- GreenshotBoxPlugin/Properties/AssemblyInfo.cs | 1 - GreenshotConfluencePlugin/Confluence.cs | 16 ++-- .../ConfluenceDestination.cs | 14 ++-- GreenshotConfluencePlugin/ConfluenceUtils.cs | 1 - GreenshotConfluencePlugin/EnumDisplayer.cs | 8 +- .../Forms/ConfluenceConfigurationForm.xaml.cs | 6 +- .../Forms/ConfluencePagePicker.xaml.cs | 6 +- .../Forms/ConfluenceSearch.xaml.cs | 19 ++--- .../Forms/ConfluenceTreePicker.xaml.cs | 7 +- .../Forms/ConfluenceUpload.xaml.cs | 4 +- .../Support/ITranslationProvider.cs | 6 +- .../Support/LanguageXMLTranslationProvider.cs | 7 +- .../Support/TranslationData.cs | 2 +- .../Support/TranslationManager.cs | 4 - GreenshotDropboxPlugin/DropboxDestination.cs | 6 +- GreenshotDropboxPlugin/DropboxPlugin.cs | 4 +- GreenshotDropboxPlugin/DropboxUtils.cs | 2 +- GreenshotDropboxPlugin/Forms/DropboxForm.cs | 2 +- GreenshotDropboxPlugin/Forms/SettingsForm.cs | 3 - .../Properties/AssemblyInfo.cs | 1 - .../ExternalCommandConfiguration.cs | 8 +- .../ExternalCommandDestination.cs | 74 +++++++++-------- .../ExternalCommandPlugin.cs | 44 +++++----- GreenshotExternalCommandPlugin/IconCache.cs | 28 ++++++- .../Properties/AssemblyInfo.cs | 1 - .../SettingsForm.cs | 2 +- .../SettingsFormDetail.cs | 81 ++++++++++++------- GreenshotFlickrPlugin/FlickrDestination.cs | 2 +- GreenshotFlickrPlugin/FlickrUtils.cs | 2 +- GreenshotFlickrPlugin/Forms/FlickrForm.cs | 1 - GreenshotFlickrPlugin/Forms/SettingsForm.cs | 4 - .../Properties/AssemblyInfo.cs | 1 - GreenshotImgurPlugin/Forms/ImgurForm.cs | 1 - GreenshotImgurPlugin/Forms/ImgurHistory.cs | 14 ++-- GreenshotImgurPlugin/Forms/SettingsForm.cs | 3 - GreenshotImgurPlugin/ImgurDestination.cs | 4 +- GreenshotImgurPlugin/ImgurPlugin.cs | 2 +- .../Properties/AssemblyInfo.cs | 1 - GreenshotJiraPlugin/Forms/JiraForm.cs | 20 ++--- GreenshotJiraPlugin/Forms/JiraFormBase.cs | 2 +- GreenshotJiraPlugin/Forms/SettingsForm.cs | 3 - GreenshotJiraPlugin/Jira.cs | 48 +++++------ GreenshotJiraPlugin/JiraDestination.cs | 10 +-- GreenshotJiraPlugin/JiraPlugin.cs | 2 +- GreenshotJiraPlugin/JiraUtils.cs | 2 +- .../Properties/AssemblyInfo.cs | 1 - GreenshotOCRCommand/COMWrapper.cs | 46 +++++------ GreenshotOCRCommand/ComProgIdAttribute.cs | 2 +- .../Properties/AssemblyInfo.cs | 1 - GreenshotOCRPlugin/OCRDestination.cs | 4 +- GreenshotOCRPlugin/OCRPlugin.cs | 3 +- GreenshotOCRPlugin/Properties/AssemblyInfo.cs | 1 - GreenshotOCRPlugin/SettingsForm.cs | 4 +- .../Destinations/ExcelDestination.cs | 11 +-- .../Destinations/OneNoteDestination.cs | 8 +- .../Destinations/OutlookDestination.cs | 18 ++--- .../Destinations/PowerpointDestination.cs | 11 +-- .../Destinations/WordDestination.cs | 10 +-- .../OfficeExport/ExcelExporter.cs | 3 - .../OfficeExport/OneNoteExporter.cs | 1 - .../OfficeExport/OutlookEmailExporter.cs | 6 -- .../OfficeExport/WordExporter.cs | 5 +- .../OfficeInterop/OutlookUtils.cs | 6 +- .../Properties/AssemblyInfo.cs | 1 - .../Forms/SettingsForm.cs | 4 - .../PhotobucketDestination.cs | 6 +- .../PhotobucketPlugin.cs | 2 +- .../Properties/AssemblyInfo.cs | 1 - GreenshotPicasaPlugin/Forms/SettingsForm.cs | 7 -- GreenshotPicasaPlugin/PicasaDestination.cs | 4 +- GreenshotPicasaPlugin/PicasaPlugin.cs | 6 +- GreenshotPicasaPlugin/PicasaUtils.cs | 1 - .../Properties/AssemblyInfo.cs | 1 - GreenshotPlugin/Controls/HotkeyControl.cs | 2 +- GreenshotPlugin/Core/Cache.cs | 15 +++- GreenshotPlugin/Core/EventDelay.cs | 2 +- GreenshotPlugin/Core/FilenameHelper.cs | 50 +++++++++++- GreenshotPlugin/Core/LogHelper.cs | 2 +- GreenshotPlugin/Core/OAuthHelper.cs | 2 +- GreenshotPlugin/Core/PluginUtils.cs | 15 ++-- GreenshotPlugin/Core/SourceForgeHelper.cs | 6 +- 90 files changed, 390 insertions(+), 373 deletions(-) diff --git a/Greenshot/AssemblyInfo.cs b/Greenshot/AssemblyInfo.cs index 71277cb02..6694dedb4 100644 --- a/Greenshot/AssemblyInfo.cs +++ b/Greenshot/AssemblyInfo.cs @@ -21,7 +21,6 @@ using System.Reflection; using System.Runtime.InteropServices; -using System.Security; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information diff --git a/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs b/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs index d8c8ef68c..161f566bd 100644 --- a/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs +++ b/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs @@ -22,7 +22,6 @@ using Greenshot.IniFile; using GreenshotPlugin.Core; using System.Drawing; -using System.Drawing.Drawing2D; using System.Windows.Forms; namespace Greenshot.Controls { diff --git a/Greenshot/Destinations/EmailDestination.cs b/Greenshot/Destinations/EmailDestination.cs index 16dcf0866..c8ff8ad24 100644 --- a/Greenshot/Destinations/EmailDestination.cs +++ b/Greenshot/Destinations/EmailDestination.cs @@ -26,16 +26,12 @@ using Greenshot.Configuration; using Greenshot.Helpers; using Greenshot.Plugin; using GreenshotPlugin.Core; -using Greenshot.IniFile; -using log4net; namespace Greenshot.Destinations { /// /// Description of EmailDestination. /// public class EmailDestination : AbstractDestination { - private static ILog LOG = LogManager.GetLogger(typeof(EmailDestination)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); private static readonly Image mailIcon = GreenshotResources.getImage("Email.Image"); private static bool isActiveFlag; private static string mapiClient; diff --git a/Greenshot/Drawing/HighlightContainer.cs b/Greenshot/Drawing/HighlightContainer.cs index aec48208f..701592539 100644 --- a/Greenshot/Drawing/HighlightContainer.cs +++ b/Greenshot/Drawing/HighlightContainer.cs @@ -19,7 +19,6 @@ * along with this program. If not, see . */ using System; -using System.Drawing; using System.Runtime.Serialization; using Greenshot.Drawing.Fields; diff --git a/Greenshot/Drawing/SpeechbubbleContainer.cs b/Greenshot/Drawing/SpeechbubbleContainer.cs index eef5e8ef6..4bbc91c29 100644 --- a/Greenshot/Drawing/SpeechbubbleContainer.cs +++ b/Greenshot/Drawing/SpeechbubbleContainer.cs @@ -21,15 +21,12 @@ using Greenshot.Drawing.Fields; using Greenshot.Helpers; -using Greenshot.Plugin; using Greenshot.Plugin.Drawing; using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Text; using System.Runtime.Serialization; -using System.Windows.Forms; -using log4net; namespace Greenshot.Drawing { /// diff --git a/Greenshot/Forms/DropShadowSettingsForm.cs b/Greenshot/Forms/DropShadowSettingsForm.cs index 358b98970..06e170117 100644 --- a/Greenshot/Forms/DropShadowSettingsForm.cs +++ b/Greenshot/Forms/DropShadowSettingsForm.cs @@ -22,7 +22,6 @@ using System; using System.Drawing; using System.Windows.Forms; using Greenshot.Core; -using GreenshotPlugin.Core; namespace Greenshot.Forms { public partial class DropShadowSettingsForm : BaseForm { diff --git a/Greenshot/Forms/PrintOptionsDialog.cs b/Greenshot/Forms/PrintOptionsDialog.cs index 1175bf1dc..fb728a590 100644 --- a/Greenshot/Forms/PrintOptionsDialog.cs +++ b/Greenshot/Forms/PrintOptionsDialog.cs @@ -21,7 +21,6 @@ using System; using System.Windows.Forms; using Greenshot.IniFile; -using GreenshotPlugin.Core; namespace Greenshot.Forms { /// diff --git a/Greenshot/Forms/TornEdgeSettingsForm.cs b/Greenshot/Forms/TornEdgeSettingsForm.cs index 707ea5c32..1bf429ea6 100644 --- a/Greenshot/Forms/TornEdgeSettingsForm.cs +++ b/Greenshot/Forms/TornEdgeSettingsForm.cs @@ -22,7 +22,6 @@ using System; using System.Drawing; using System.Windows.Forms; using Greenshot.Core; -using GreenshotPlugin.Core; namespace Greenshot.Forms { public partial class TornEdgeSettingsForm : BaseForm { diff --git a/Greenshot/releases/additional_files/readme.txt.template b/Greenshot/releases/additional_files/readme.txt.template index 4fd81e5dc..3668769d5 100644 --- a/Greenshot/releases/additional_files/readme.txt.template +++ b/Greenshot/releases/additional_files/readme.txt.template @@ -34,7 +34,8 @@ This version has changes, compared to 1.2.8.12, for the following reported ticke * BUG-1935: Delay when pasting and ShapeShifter from FlameFusion is running| * BUG-1941: Error when creating speech bubble| * BUG-1945: Failure starting Greenshot at system startup| -* BUG-1949: Can't delete Imgur upload| +* BUG-1949: Can't delete Imgur upload +* FEATURE-945: Added environment variables to the external command Testing is not finished, use at your own risk... diff --git a/GreenshotBoxPlugin/Properties/AssemblyInfo.cs b/GreenshotBoxPlugin/Properties/AssemblyInfo.cs index 4dbee7804..d8104cf29 100644 --- a/GreenshotBoxPlugin/Properties/AssemblyInfo.cs +++ b/GreenshotBoxPlugin/Properties/AssemblyInfo.cs @@ -22,7 +22,6 @@ using Greenshot.Plugin; using System.Reflection; using System.Runtime.InteropServices; -using System.Security; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information diff --git a/GreenshotConfluencePlugin/Confluence.cs b/GreenshotConfluencePlugin/Confluence.cs index 05651949d..b875052ba 100644 --- a/GreenshotConfluencePlugin/Confluence.cs +++ b/GreenshotConfluencePlugin/Confluence.cs @@ -95,14 +95,14 @@ namespace Confluence { private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ConfluenceConnector)); private const string AUTH_FAILED_EXCEPTION_NAME = "com.atlassian.confluence.rpc.AuthenticationFailedException"; private const string V2_FAILED = "AXIS"; - private static ConfluenceConfiguration config = IniConfig.GetIniSection(); + private static readonly ConfluenceConfiguration config = IniConfig.GetIniSection(); private string credentials = null; private DateTime loggedInTime = DateTime.Now; private bool loggedIn = false; private ConfluenceSoapServiceService confluence; - private int timeout; + private readonly int timeout; private string url; - private Cache pageCache = new Cache(60 * config.Timeout); + private readonly Cache pageCache = new Cache(60 * config.Timeout); public void Dispose() { Dispose(true); @@ -143,9 +143,9 @@ namespace Confluence { /// true if login was done sucessfully private bool doLogin(string user, string password) { try { - this.credentials = confluence.login(user, password); - this.loggedInTime = DateTime.Now; - this.loggedIn = true; + credentials = confluence.login(user, password); + loggedInTime = DateTime.Now; + loggedIn = true; } catch (Exception e) { // Check if confluence-v2 caused an error, use v1 instead if (e.Message.Contains(V2_FAILED) && url.Contains("v2")) { @@ -157,8 +157,8 @@ namespace Confluence { return false; } // Not an authentication issue - this.loggedIn = false; - this.credentials = null; + loggedIn = false; + credentials = null; e.Data.Add("user", user); e.Data.Add("url", url); throw; diff --git a/GreenshotConfluencePlugin/ConfluenceDestination.cs b/GreenshotConfluencePlugin/ConfluenceDestination.cs index 10e212d5e..8161908ac 100644 --- a/GreenshotConfluencePlugin/ConfluenceDestination.cs +++ b/GreenshotConfluencePlugin/ConfluenceDestination.cs @@ -36,11 +36,11 @@ namespace GreenshotConfluencePlugin { /// Description of ConfluenceDestination. /// public class ConfluenceDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ConfluenceDestination)); + private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ConfluenceDestination)); private static readonly ConfluenceConfiguration config = IniConfig.GetIniSection(); private static readonly CoreConfiguration coreConfig = IniConfig.GetIniSection(); - private static Image confluenceIcon = null; - private Confluence.Page page; + private static readonly Image confluenceIcon = null; + private readonly Page page; public static bool IsInitialized { get; private set; @@ -63,7 +63,7 @@ namespace GreenshotConfluencePlugin { public ConfluenceDestination() { } - public ConfluenceDestination(Confluence.Page page) { + public ConfluenceDestination(Page page) { this.page = page; } @@ -105,17 +105,17 @@ namespace GreenshotConfluencePlugin { if (ConfluencePlugin.ConfluenceConnectorNoLogin == null || !ConfluencePlugin.ConfluenceConnectorNoLogin.isLoggedIn) { yield break; } - List currentPages = ConfluenceUtils.GetCurrentPages(); + List currentPages = ConfluenceUtils.GetCurrentPages(); if (currentPages == null || currentPages.Count == 0) { yield break; } - foreach(Confluence.Page currentPage in currentPages) { + foreach(Page currentPage in currentPages) { yield return new ConfluenceDestination(currentPage); } } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); + ExportInformation exportInformation = new ExportInformation(Designation, Description); // force password check to take place before the pages load if (!ConfluencePlugin.ConfluenceConnector.isLoggedIn) { return exportInformation; diff --git a/GreenshotConfluencePlugin/ConfluenceUtils.cs b/GreenshotConfluencePlugin/ConfluenceUtils.cs index 3ffafbfd6..72f62c3e4 100644 --- a/GreenshotConfluencePlugin/ConfluenceUtils.cs +++ b/GreenshotConfluencePlugin/ConfluenceUtils.cs @@ -20,7 +20,6 @@ */ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Text.RegularExpressions; using System.Windows.Automation; diff --git a/GreenshotConfluencePlugin/EnumDisplayer.cs b/GreenshotConfluencePlugin/EnumDisplayer.cs index 102bf6732..e601c2a30 100644 --- a/GreenshotConfluencePlugin/EnumDisplayer.cs +++ b/GreenshotConfluencePlugin/EnumDisplayer.cs @@ -40,7 +40,7 @@ namespace GreenshotConfluencePlugin { } public EnumDisplayer(Type type) { - this.Type = type; + Type = type; } public Type Type { @@ -49,15 +49,15 @@ namespace GreenshotConfluencePlugin { if (!value.IsEnum) { throw new ArgumentException("parameter is not an Enumerated type", "value"); } - this.type = value; + type = value; } } public ReadOnlyCollection DisplayNames { get { - this.reverseValues = (IDictionary) Activator.CreateInstance(typeof(Dictionary<,>).GetGenericTypeDefinition().MakeGenericType(typeof(string),type)); + reverseValues = (IDictionary) Activator.CreateInstance(typeof(Dictionary<,>).GetGenericTypeDefinition().MakeGenericType(typeof(string),type)); - this.displayValues = (IDictionary)Activator.CreateInstance(typeof(Dictionary<,>).GetGenericTypeDefinition().MakeGenericType(type, typeof(string))); + displayValues = (IDictionary)Activator.CreateInstance(typeof(Dictionary<,>).GetGenericTypeDefinition().MakeGenericType(type, typeof(string))); var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static); foreach (var field in fields) { diff --git a/GreenshotConfluencePlugin/Forms/ConfluenceConfigurationForm.xaml.cs b/GreenshotConfluencePlugin/Forms/ConfluenceConfigurationForm.xaml.cs index 63b72292d..507f1ee8f 100644 --- a/GreenshotConfluencePlugin/Forms/ConfluenceConfigurationForm.xaml.cs +++ b/GreenshotConfluencePlugin/Forms/ConfluenceConfigurationForm.xaml.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Windows; namespace GreenshotConfluencePlugin { @@ -26,7 +26,7 @@ namespace GreenshotConfluencePlugin { /// Interaction logic for ConfluenceConfigurationForm.xaml /// public partial class ConfluenceConfigurationForm : Window { - private ConfluenceConfiguration config; + private readonly ConfluenceConfiguration config; public ConfluenceConfiguration Config { get { return config; @@ -34,7 +34,7 @@ namespace GreenshotConfluencePlugin { } public ConfluenceConfigurationForm(ConfluenceConfiguration config) { - this.DataContext = config; + DataContext = config; this.config = config; InitializeComponent(); } diff --git a/GreenshotConfluencePlugin/Forms/ConfluencePagePicker.xaml.cs b/GreenshotConfluencePlugin/Forms/ConfluencePagePicker.xaml.cs index a8ddec0dd..381eb4139 100644 --- a/GreenshotConfluencePlugin/Forms/ConfluencePagePicker.xaml.cs +++ b/GreenshotConfluencePlugin/Forms/ConfluencePagePicker.xaml.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using Confluence; using System.Collections.Generic; @@ -28,11 +28,11 @@ namespace GreenshotConfluencePlugin { /// public partial class ConfluencePagePicker : System.Windows.Controls.Page { private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ConfluencePagePicker)); - private ConfluenceUpload confluenceUpload = null; + private readonly ConfluenceUpload confluenceUpload = null; public ConfluencePagePicker(ConfluenceUpload confluenceUpload, List pagesToPick) { this.confluenceUpload = confluenceUpload; - this.DataContext = pagesToPick; + DataContext = pagesToPick; InitializeComponent(); } diff --git a/GreenshotConfluencePlugin/Forms/ConfluenceSearch.xaml.cs b/GreenshotConfluencePlugin/Forms/ConfluenceSearch.xaml.cs index 3c816a2f9..042a68427 100644 --- a/GreenshotConfluencePlugin/Forms/ConfluenceSearch.xaml.cs +++ b/GreenshotConfluencePlugin/Forms/ConfluenceSearch.xaml.cs @@ -18,20 +18,17 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows; - -using Confluence; -using GreenshotPlugin.Core; using Greenshot.IniFile; namespace GreenshotConfluencePlugin { public partial class ConfluenceSearch : System.Windows.Controls.Page { private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ConfluenceSearch)); - private static ConfluenceConfiguration config = IniConfig.GetIniSection(); - private ConfluenceUpload confluenceUpload; + private static readonly ConfluenceConfiguration config = IniConfig.GetIniSection(); + private readonly ConfluenceUpload confluenceUpload; public List Spaces { get { @@ -39,7 +36,7 @@ namespace GreenshotConfluencePlugin { } } - private ObservableCollection pages = new ObservableCollection(); + private readonly ObservableCollection pages = new ObservableCollection(); public ObservableCollection Pages { get { return pages; @@ -48,14 +45,14 @@ namespace GreenshotConfluencePlugin { public ConfluenceSearch(ConfluenceUpload confluenceUpload) { this.confluenceUpload = confluenceUpload; - this.DataContext = this; + DataContext = this; InitializeComponent(); if (config.SearchSpaceKey == null) { - this.SpaceComboBox.SelectedItem = Spaces[0]; + SpaceComboBox.SelectedItem = Spaces[0]; } else { foreach(Confluence.Space space in Spaces) { if (space.Key.Equals(config.SearchSpaceKey)) { - this.SpaceComboBox.SelectedItem = space; + SpaceComboBox.SelectedItem = space; } } } @@ -94,7 +91,7 @@ namespace GreenshotConfluencePlugin { } } - void Page_Loaded(object sender, System.Windows.RoutedEventArgs e) { + void Page_Loaded(object sender, RoutedEventArgs e) { SelectionChanged(); } diff --git a/GreenshotConfluencePlugin/Forms/ConfluenceTreePicker.xaml.cs b/GreenshotConfluencePlugin/Forms/ConfluenceTreePicker.xaml.cs index b639a5f98..716262030 100644 --- a/GreenshotConfluencePlugin/Forms/ConfluenceTreePicker.xaml.cs +++ b/GreenshotConfluencePlugin/Forms/ConfluenceTreePicker.xaml.cs @@ -27,7 +27,6 @@ using System.Windows.Input; using System.Windows.Threading; using Confluence; -using GreenshotPlugin.Core; namespace GreenshotConfluencePlugin { /// @@ -35,12 +34,12 @@ namespace GreenshotConfluencePlugin { /// public partial class ConfluenceTreePicker : System.Windows.Controls.Page { private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ConfluenceTreePicker)); - private ConfluenceConnector confluenceConnector; - private ConfluenceUpload confluenceUpload; + private readonly ConfluenceConnector confluenceConnector; + private readonly ConfluenceUpload confluenceUpload; private bool isInitDone = false; public ConfluenceTreePicker(ConfluenceUpload confluenceUpload) { - this.confluenceConnector = ConfluencePlugin.ConfluenceConnector; + confluenceConnector = ConfluencePlugin.ConfluenceConnector; this.confluenceUpload = confluenceUpload; InitializeComponent(); } diff --git a/GreenshotConfluencePlugin/Forms/ConfluenceUpload.xaml.cs b/GreenshotConfluencePlugin/Forms/ConfluenceUpload.xaml.cs index 3c3d9442e..fe1b81a8a 100644 --- a/GreenshotConfluencePlugin/Forms/ConfluenceUpload.xaml.cs +++ b/GreenshotConfluencePlugin/Forms/ConfluenceUpload.xaml.cs @@ -100,12 +100,12 @@ namespace GreenshotConfluencePlugin { } public ConfluenceUpload(string filename) { - this.Filename = filename; + Filename = filename; InitializeComponent(); this.DataContext = this; updateSpaces(); if (PickerPage == null) { - PickerTab.Visibility = System.Windows.Visibility.Collapsed; + PickerTab.Visibility = Visibility.Collapsed; SearchTab.IsSelected = true; } } diff --git a/GreenshotConfluencePlugin/Support/ITranslationProvider.cs b/GreenshotConfluencePlugin/Support/ITranslationProvider.cs index 6bd4bf402..a19c27fd8 100644 --- a/GreenshotConfluencePlugin/Support/ITranslationProvider.cs +++ b/GreenshotConfluencePlugin/Support/ITranslationProvider.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Globalization; - -namespace TranslationByMarkupExtension { +namespace TranslationByMarkupExtension { public interface ITranslationProvider { /// /// Translates the specified key. diff --git a/GreenshotConfluencePlugin/Support/LanguageXMLTranslationProvider.cs b/GreenshotConfluencePlugin/Support/LanguageXMLTranslationProvider.cs index 75d952e76..f3ebcaca0 100644 --- a/GreenshotConfluencePlugin/Support/LanguageXMLTranslationProvider.cs +++ b/GreenshotConfluencePlugin/Support/LanguageXMLTranslationProvider.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Globalization; - -using GreenshotConfluencePlugin; -using GreenshotPlugin.Core; +using GreenshotPlugin.Core; namespace TranslationByMarkupExtension { /// diff --git a/GreenshotConfluencePlugin/Support/TranslationData.cs b/GreenshotConfluencePlugin/Support/TranslationData.cs index b47fe4a65..e9be13aff 100644 --- a/GreenshotConfluencePlugin/Support/TranslationData.cs +++ b/GreenshotConfluencePlugin/Support/TranslationData.cs @@ -6,7 +6,7 @@ namespace TranslationByMarkupExtension { public class TranslationData : IWeakEventListener, INotifyPropertyChanged { #region Private Members - private string _key; + private readonly string _key; #endregion diff --git a/GreenshotConfluencePlugin/Support/TranslationManager.cs b/GreenshotConfluencePlugin/Support/TranslationManager.cs index fa801d3d2..7e9516271 100644 --- a/GreenshotConfluencePlugin/Support/TranslationManager.cs +++ b/GreenshotConfluencePlugin/Support/TranslationManager.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Threading; namespace TranslationByMarkupExtension { public class TranslationManager { diff --git a/GreenshotDropboxPlugin/DropboxDestination.cs b/GreenshotDropboxPlugin/DropboxDestination.cs index c4f79732f..d9ef2cd33 100644 --- a/GreenshotDropboxPlugin/DropboxDestination.cs +++ b/GreenshotDropboxPlugin/DropboxDestination.cs @@ -26,9 +26,9 @@ using GreenshotPlugin.Core; namespace GreenshotDropboxPlugin { class DropboxDestination : AbstractDestination { private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(DropboxDestination)); - private static DropboxPluginConfiguration config = IniConfig.GetIniSection(); + private static readonly DropboxPluginConfiguration config = IniConfig.GetIniSection(); - private DropboxPlugin plugin = null; + private readonly DropboxPlugin plugin = null; public DropboxDestination(DropboxPlugin plugin) { this.plugin = plugin; } @@ -53,7 +53,7 @@ namespace GreenshotDropboxPlugin { } public override ExportInformation ExportCapture(bool manually, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); + ExportInformation exportInformation = new ExportInformation(Designation, Description); string uploadURL = null; bool uploaded = plugin.Upload(captureDetails, surface, out uploadURL); if (uploaded) { diff --git a/GreenshotDropboxPlugin/DropboxPlugin.cs b/GreenshotDropboxPlugin/DropboxPlugin.cs index 772545395..7fd82cd60 100644 --- a/GreenshotDropboxPlugin/DropboxPlugin.cs +++ b/GreenshotDropboxPlugin/DropboxPlugin.cs @@ -73,7 +73,7 @@ namespace GreenshotDropboxPlugin { /// Use the IGreenshotPluginHost interface to register events /// My own attributes public virtual bool Initialize(IGreenshotHost pluginHost, PluginAttribute myAttributes) { - this.host = (IGreenshotHost)pluginHost; + host = (IGreenshotHost)pluginHost; Attributes = myAttributes; // Register configuration (don't need the configuration itself) @@ -83,7 +83,7 @@ namespace GreenshotDropboxPlugin { itemPlugInConfig = new ToolStripMenuItem(); itemPlugInConfig.Text = Language.GetString("dropbox", LangKey.Configure); itemPlugInConfig.Tag = host; - itemPlugInConfig.Click += new System.EventHandler(ConfigMenuClick); + itemPlugInConfig.Click += new EventHandler(ConfigMenuClick); itemPlugInConfig.Image = (Image)resources.GetObject("Dropbox"); PluginUtils.AddToContextMenu(host, itemPlugInConfig); diff --git a/GreenshotDropboxPlugin/DropboxUtils.cs b/GreenshotDropboxPlugin/DropboxUtils.cs index 126a41cd3..f7775d106 100644 --- a/GreenshotDropboxPlugin/DropboxUtils.cs +++ b/GreenshotDropboxPlugin/DropboxUtils.cs @@ -31,7 +31,7 @@ namespace GreenshotDropboxPlugin { /// public class DropboxUtils { private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(DropboxUtils)); - private static DropboxPluginConfiguration config = IniConfig.GetIniSection(); + private static readonly DropboxPluginConfiguration config = IniConfig.GetIniSection(); private DropboxUtils() { } diff --git a/GreenshotDropboxPlugin/Forms/DropboxForm.cs b/GreenshotDropboxPlugin/Forms/DropboxForm.cs index b2c87ec61..8cadb1fc3 100644 --- a/GreenshotDropboxPlugin/Forms/DropboxForm.cs +++ b/GreenshotDropboxPlugin/Forms/DropboxForm.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using GreenshotPlugin.Controls; namespace GreenshotDropboxPlugin.Forms { diff --git a/GreenshotDropboxPlugin/Forms/SettingsForm.cs b/GreenshotDropboxPlugin/Forms/SettingsForm.cs index 280ded7f1..9529986cf 100644 --- a/GreenshotDropboxPlugin/Forms/SettingsForm.cs +++ b/GreenshotDropboxPlugin/Forms/SettingsForm.cs @@ -19,10 +19,7 @@ * along with this program. If not, see . */ -using System; -using System.Windows.Forms; using GreenshotDropboxPlugin.Forms; -using GreenshotPlugin.Core; using Greenshot.IniFile; namespace GreenshotDropboxPlugin { diff --git a/GreenshotDropboxPlugin/Properties/AssemblyInfo.cs b/GreenshotDropboxPlugin/Properties/AssemblyInfo.cs index 67d20ede5..4d498f26f 100644 --- a/GreenshotDropboxPlugin/Properties/AssemblyInfo.cs +++ b/GreenshotDropboxPlugin/Properties/AssemblyInfo.cs @@ -22,7 +22,6 @@ using Greenshot.Plugin; using System.Reflection; using System.Runtime.InteropServices; -using System.Security; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information diff --git a/GreenshotExternalCommandPlugin/ExternalCommandConfiguration.cs b/GreenshotExternalCommandPlugin/ExternalCommandConfiguration.cs index f83bc9370..daea99116 100644 --- a/GreenshotExternalCommandPlugin/ExternalCommandConfiguration.cs +++ b/GreenshotExternalCommandPlugin/ExternalCommandConfiguration.cs @@ -61,12 +61,12 @@ namespace ExternalCommand { public Dictionary runInbackground; private const string MSPAINT = "MS Paint"; - private static string paintPath; - private static bool hasPaint = false; + private static readonly string paintPath; + private static readonly bool hasPaint = false; private const string PAINTDOTNET = "Paint.NET"; - private static string paintDotNetPath; - private static bool hasPaintDotNet = false; + private static readonly string paintDotNetPath; + private static readonly bool hasPaintDotNet = false; static ExternalCommandConfiguration() { try { paintPath = PluginUtils.GetExePath("pbrush.exe"); diff --git a/GreenshotExternalCommandPlugin/ExternalCommandDestination.cs b/GreenshotExternalCommandPlugin/ExternalCommandDestination.cs index ee13f6eee..bec3be704 100644 --- a/GreenshotExternalCommandPlugin/ExternalCommandDestination.cs +++ b/GreenshotExternalCommandPlugin/ExternalCommandDestination.cs @@ -34,24 +34,24 @@ namespace ExternalCommand { /// Description of OCRDestination. /// public class ExternalCommandDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ExternalCommandDestination)); - private static Regex URI_REGEXP = new Regex(@"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)"); - private static ExternalCommandConfiguration config = IniConfig.GetIniSection(); - private string presetCommand; + private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ExternalCommandDestination)); + private static readonly Regex URI_REGEXP = new Regex(@"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)"); + private static readonly ExternalCommandConfiguration config = IniConfig.GetIniSection(); + private readonly string _presetCommand; public ExternalCommandDestination(string commando) { - this.presetCommand = commando; + _presetCommand = commando; } public override string Designation { get { - return "External " + presetCommand.Replace(',','_'); + return "External " + _presetCommand.Replace(',','_'); } } public override string Description { get { - return presetCommand; + return _presetCommand; } } @@ -61,20 +61,20 @@ namespace ExternalCommand { public override Image DisplayIcon { get { - return IconCache.IconForCommand(presetCommand); + return IconCache.IconForCommand(_presetCommand); } } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); + ExportInformation exportInformation = new ExportInformation(Designation, Description); SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(); - if (presetCommand != null) { - if (!config.runInbackground.ContainsKey(presetCommand)) { - config.runInbackground.Add(presetCommand, true); + if (_presetCommand != null) { + if (!config.runInbackground.ContainsKey(_presetCommand)) { + config.runInbackground.Add(_presetCommand, true); } - bool runInBackground = config.runInbackground[presetCommand]; + bool runInBackground = config.runInbackground[_presetCommand]; string fullPath = captureDetails.Filename; if (fullPath == null) { fullPath = ImageOutput.SaveNamedTmpFile(surface, captureDetails, outputSettings); @@ -83,17 +83,20 @@ namespace ExternalCommand { string output; string error; if (runInBackground) { - Thread commandThread = new Thread(delegate() { - CallExternalCommand(exportInformation, presetCommand, fullPath, out output, out error); + Thread commandThread = new Thread(delegate() + { + CallExternalCommand(exportInformation, fullPath, out output, out error); ProcessExport(exportInformation, surface); - }); - commandThread.Name = "Running " + presetCommand; - commandThread.IsBackground = true; + }) + { + Name = "Running " + _presetCommand, + IsBackground = true + }; commandThread.SetApartmentState(ApartmentState.STA); commandThread.Start(); exportInformation.ExportMade = true; } else { - CallExternalCommand(exportInformation, presetCommand, fullPath, out output, out error); + CallExternalCommand(exportInformation, fullPath, out output, out error); ProcessExport(exportInformation, surface); } } @@ -105,15 +108,14 @@ namespace ExternalCommand { /// Call the external command, parse for URI, place to clipboard and set the export information /// /// - /// /// /// /// - private void CallExternalCommand(ExportInformation exportInformation, string commando, string fullPath, out string output, out string error) { + private void CallExternalCommand(ExportInformation exportInformation, string fullPath, out string output, out string error) { output = null; error = null; try { - if (CallExternalCommand(presetCommand, fullPath, out output, out error) == 0) { + if (CallExternalCommand(_presetCommand, fullPath, out output, out error) == 0) { exportInformation.ExportMade = true; if (!string.IsNullOrEmpty(output)) { MatchCollection uriMatches = URI_REGEXP.Matches(output); @@ -121,7 +123,7 @@ namespace ExternalCommand { if (config.OutputToClipboard) { ClipboardHelper.SetClipboardData(output); } - if (uriMatches != null && uriMatches.Count > 0) { + if (uriMatches.Count > 0) { exportInformation.Uri = uriMatches[0].Groups[1].Value; LOG.InfoFormat("Got URI : {0} ", exportInformation.Uri); if (config.UriToClipboard) { @@ -156,13 +158,13 @@ namespace ExternalCommand { try { return CallExternalCommand(commando, fullPath, "runas", out output, out error); } catch { - w32ex.Data.Add("commandline", config.commandlines[presetCommand]); - w32ex.Data.Add("arguments", config.arguments[presetCommand]); + w32ex.Data.Add("commandline", config.commandlines[_presetCommand]); + w32ex.Data.Add("arguments", config.arguments[_presetCommand]); throw; } } catch (Exception ex) { - ex.Data.Add("commandline", config.commandlines[presetCommand]); - ex.Data.Add("arguments", config.arguments[presetCommand]); + ex.Data.Add("commandline", config.commandlines[_presetCommand]); + ex.Data.Add("arguments", config.arguments[_presetCommand]); throw; } } @@ -182,8 +184,16 @@ namespace ExternalCommand { output = null; error = null; if (!string.IsNullOrEmpty(commandline)) { - using (Process process = new Process()) { - process.StartInfo.FileName = commandline; + using (Process process = new Process()) + { + // Fix variables + commandline = FilenameHelper.FillVariables(commandline, true); + commandline = FilenameHelper.FillCmdVariables(commandline, true); + + arguments = FilenameHelper.FillVariables(arguments, false); + arguments = FilenameHelper.FillCmdVariables(arguments, false); + + process.StartInfo.FileName = FilenameHelper.FillCmdVariables(commandline, true); process.StartInfo.Arguments = FormatArguments(arguments, fullPath); process.StartInfo.UseShellExecute = false; if (config.RedirectStandardOutput) { @@ -200,13 +210,13 @@ namespace ExternalCommand { process.WaitForExit(); if (config.RedirectStandardOutput) { output = process.StandardOutput.ReadToEnd(); - if (config.ShowStandardOutputInLog && output != null && output.Trim().Length > 0) { + if (config.ShowStandardOutputInLog && output.Trim().Length > 0) { LOG.InfoFormat("Output:\n{0}", output); } } if (config.RedirectStandardError) { error = process.StandardError.ReadToEnd(); - if (error != null && error.Trim().Length > 0) { + if (error.Trim().Length > 0) { LOG.WarnFormat("Error:\n{0}", error); } } @@ -219,7 +229,7 @@ namespace ExternalCommand { public static string FormatArguments(string arguments, string fullpath) { - return String.Format(arguments, fullpath); + return string.Format(arguments, fullpath); } } } diff --git a/GreenshotExternalCommandPlugin/ExternalCommandPlugin.cs b/GreenshotExternalCommandPlugin/ExternalCommandPlugin.cs index 9531b0066..7848128a7 100644 --- a/GreenshotExternalCommandPlugin/ExternalCommandPlugin.cs +++ b/GreenshotExternalCommandPlugin/ExternalCommandPlugin.cs @@ -34,11 +34,11 @@ namespace ExternalCommand { /// public class ExternalCommandPlugin : IGreenshotPlugin { private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ExternalCommandPlugin)); - private static CoreConfiguration coreConfig = IniConfig.GetIniSection(); - private static ExternalCommandConfiguration config = IniConfig.GetIniSection(); - private IGreenshotHost host; - private PluginAttribute myAttributes; - private ToolStripMenuItem itemPlugInRoot; + private static readonly CoreConfiguration coreConfig = IniConfig.GetIniSection(); + private static readonly ExternalCommandConfiguration config = IniConfig.GetIniSection(); + private IGreenshotHost _host; + private PluginAttribute _myAttributes; + private ToolStripMenuItem _itemPlugInRoot; public void Dispose() { Dispose(true); @@ -47,16 +47,13 @@ namespace ExternalCommand { protected virtual void Dispose(bool disposing) { if (disposing) { - if (itemPlugInRoot != null) { - itemPlugInRoot.Dispose(); - itemPlugInRoot = null; + if (_itemPlugInRoot != null) { + _itemPlugInRoot.Dispose(); + _itemPlugInRoot = null; } } } - public ExternalCommandPlugin() { - } - public IEnumerable Destinations() { foreach(string command in config.commands) { yield return new ExternalCommandDestination(command); @@ -87,7 +84,10 @@ namespace ExternalCommand { LOG.WarnFormat("Found missing commandline for {0}", command); return false; } - if (!File.Exists(config.commandlines[command])) { + string commandline = FilenameHelper.FillVariables(config.commandlines[command], true); + commandline = FilenameHelper.FillCmdVariables(commandline, true); + + if (!File.Exists(commandline)) { LOG.WarnFormat("Found 'invalid' commandline {0} for command {1}", config.commandlines[command], command); return false; } @@ -118,17 +118,17 @@ namespace ExternalCommand { config.commands.Remove(command); } - this.host = pluginHost; - this.myAttributes = myAttributes; + _host = pluginHost; + _myAttributes = myAttributes; - itemPlugInRoot = new ToolStripMenuItem(); - itemPlugInRoot.Tag = host; + _itemPlugInRoot = new ToolStripMenuItem(); + _itemPlugInRoot.Tag = _host; OnIconSizeChanged(this, new PropertyChangedEventArgs("IconSize")); OnLanguageChanged(this, null); - itemPlugInRoot.Click += new System.EventHandler(ConfigMenuClick); + _itemPlugInRoot.Click += new EventHandler(ConfigMenuClick); - PluginUtils.AddToContextMenu(host, itemPlugInRoot); + PluginUtils.AddToContextMenu(_host, _itemPlugInRoot); Language.LanguageChanged += OnLanguageChanged; coreConfig.PropertyChanged += OnIconSizeChanged; return true; @@ -144,7 +144,7 @@ namespace ExternalCommand { try { string exePath = PluginUtils.GetExePath("cmd.exe"); if (exePath != null && File.Exists(exePath)) { - itemPlugInRoot.Image = PluginUtils.GetCachedExeIcon(exePath, 0); + _itemPlugInRoot.Image = PluginUtils.GetCachedExeIcon(exePath, 0); } } catch (Exception ex) { LOG.Warn("Couldn't get the cmd.exe image", ex); @@ -153,13 +153,13 @@ namespace ExternalCommand { } private void OnLanguageChanged(object sender, EventArgs e) { - if (itemPlugInRoot != null) { - itemPlugInRoot.Text = Language.GetString("externalcommand", "contextmenu_configure"); + if (_itemPlugInRoot != null) { + _itemPlugInRoot.Text = Language.GetString("externalcommand", "contextmenu_configure"); } } public virtual void Shutdown() { - LOG.Debug("Shutdown of " + myAttributes.Name); + LOG.Debug("Shutdown of " + _myAttributes.Name); } private void ConfigMenuClick(object sender, EventArgs eventArgs) { diff --git a/GreenshotExternalCommandPlugin/IconCache.cs b/GreenshotExternalCommandPlugin/IconCache.cs index c3e3f16bd..d7eac4410 100644 --- a/GreenshotExternalCommandPlugin/IconCache.cs +++ b/GreenshotExternalCommandPlugin/IconCache.cs @@ -1,5 +1,25 @@ -using System; -using System.Collections.Generic; +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/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; using System.Drawing; using System.IO; using Greenshot.IniFile; @@ -7,8 +27,8 @@ using GreenshotPlugin.Core; namespace ExternalCommand { public static class IconCache { - private static ExternalCommandConfiguration config = IniConfig.GetIniSection(); - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(IconCache)); + private static readonly ExternalCommandConfiguration config = IniConfig.GetIniSection(); + private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(IconCache)); public static Image IconForCommand(string commandName) { Image icon = null; diff --git a/GreenshotExternalCommandPlugin/Properties/AssemblyInfo.cs b/GreenshotExternalCommandPlugin/Properties/AssemblyInfo.cs index 812fd723c..26af92de2 100644 --- a/GreenshotExternalCommandPlugin/Properties/AssemblyInfo.cs +++ b/GreenshotExternalCommandPlugin/Properties/AssemblyInfo.cs @@ -22,7 +22,6 @@ using Greenshot.Plugin; using System.Reflection; using System.Runtime.InteropServices; -using System.Security; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information diff --git a/GreenshotExternalCommandPlugin/SettingsForm.cs b/GreenshotExternalCommandPlugin/SettingsForm.cs index 247e38b59..a872b6882 100644 --- a/GreenshotExternalCommandPlugin/SettingsForm.cs +++ b/GreenshotExternalCommandPlugin/SettingsForm.cs @@ -30,7 +30,7 @@ namespace ExternalCommand { /// public partial class SettingsForm : ExternalCommandForm { private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(SettingsForm)); - private static ExternalCommandConfiguration config = IniConfig.GetIniSection(); + private static readonly ExternalCommandConfiguration config = IniConfig.GetIniSection(); public SettingsForm() { // diff --git a/GreenshotExternalCommandPlugin/SettingsFormDetail.cs b/GreenshotExternalCommandPlugin/SettingsFormDetail.cs index ae9d4b030..4890ee2a1 100644 --- a/GreenshotExternalCommandPlugin/SettingsFormDetail.cs +++ b/GreenshotExternalCommandPlugin/SettingsFormDetail.cs @@ -24,44 +24,45 @@ using System; using System.Drawing; using System.IO; using System.Windows.Forms; +using GreenshotPlugin.Core; namespace ExternalCommand { /// /// Description of SettingsFormDetail. /// public partial class SettingsFormDetail : ExternalCommandForm { - private string commando; - private int commandIndex; - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(SettingsFormDetail)); - private static ExternalCommandConfiguration config = IniConfig.GetIniSection(); + private static readonly ExternalCommandConfiguration config = IniConfig.GetIniSection(); + + private readonly string _commando; + private readonly int _commandIndex; public SettingsFormDetail(string commando) { InitializeComponent(); AcceptButton = buttonOk; CancelButton = buttonCancel; - this.commando = commando; + _commando = commando; if(commando != null) { textBox_name.Text = commando; textBox_commandline.Text = config.commandlines[commando]; textBox_arguments.Text = config.arguments[commando]; - commandIndex = config.commands.FindIndex(delegate(string s) { return s == commando; }); + _commandIndex = config.commands.FindIndex(delegate(string s) { return s == commando; }); } else { textBox_arguments.Text = "\"{0}\""; } - OKButtonState(); + OkButtonState(); } void ButtonOkClick(object sender, EventArgs e) { string commandName = textBox_name.Text; string commandLine = textBox_commandline.Text; string arguments = textBox_arguments.Text; - if(commando != null) { - config.commands[commandIndex] = commandName; - config.commandlines.Remove(commando); + if(_commando != null) { + config.commands[_commandIndex] = commandName; + config.commandlines.Remove(_commando); config.commandlines.Add(commandName, commandLine); - config.arguments.Remove(commando); + config.arguments.Remove(_commando); config.arguments.Add(commandName, arguments); } else { config.commands.Add(commandName); @@ -71,15 +72,23 @@ namespace ExternalCommand { } void Button3Click(object sender, EventArgs e) { - OpenFileDialog openFileDialog = new OpenFileDialog(); - openFileDialog.Filter = "Executables (*.exe, *.bat, *.com)|*.exe; *.bat; *.com|All files (*)|*"; - openFileDialog.FilterIndex = 1; - openFileDialog.CheckFileExists = true; - openFileDialog.Multiselect = false; + OpenFileDialog openFileDialog = new OpenFileDialog + { + Filter = "Executables (*.exe, *.bat, *.com)|*.exe; *.bat; *.com|All files (*)|*", + FilterIndex = 1, + CheckFileExists = true, + Multiselect = false + }; string initialPath = null; - try { + try + { initialPath = Path.GetDirectoryName(textBox_commandline.Text); - } catch { } + } + catch (Exception ex) + { + LOG.WarnFormat("Can't get the initial path via {0}", textBox_commandline.Text); + LOG.Warn("Exception: ", ex); + } if(initialPath != null && Directory.Exists(initialPath)) { openFileDialog.InitialDirectory = initialPath; } else { @@ -92,7 +101,7 @@ namespace ExternalCommand { } } - private void OKButtonState() { + private void OkButtonState() { // Assume OK buttonOk.Enabled = true; textBox_name.BackColor = Color.White; @@ -103,7 +112,7 @@ namespace ExternalCommand { buttonOk.Enabled = false; } // Check if commandname is unique - if(commando == null && !string.IsNullOrEmpty(textBox_name.Text) && config.commands.Contains(textBox_name.Text)) { + if(_commando == null && !string.IsNullOrEmpty(textBox_name.Text) && config.commands.Contains(textBox_name.Text)) { buttonOk.Enabled = false; textBox_name.BackColor = Color.Red; } @@ -111,15 +120,27 @@ namespace ExternalCommand { if(string.IsNullOrEmpty(textBox_commandline.Text)) { buttonOk.Enabled = false; } - // Is the command available? - if(!string.IsNullOrEmpty(textBox_commandline.Text) && !File.Exists(textBox_commandline.Text)) { - buttonOk.Enabled = false; - textBox_commandline.BackColor = Color.Red; + + if (!string.IsNullOrEmpty(textBox_commandline.Text)) + { + // Added this to be more flexible, using the Greenshot var format + string cmdPath = FilenameHelper.FillVariables(textBox_commandline.Text, true); + // And also replace the "DOS" Variables + cmdPath = FilenameHelper.FillCmdVariables(cmdPath, true); + // Is the command available? + if (!File.Exists(cmdPath)) + { + buttonOk.Enabled = false; + textBox_commandline.BackColor = Color.Red; + } } - // Are the arguments in a valid format? - try + // Are the arguments in a valid format? + try { - ExternalCommandDestination.FormatArguments(textBox_arguments.Text, string.Empty); + string arguments = FilenameHelper.FillVariables(textBox_arguments.Text, false); + arguments = FilenameHelper.FillCmdVariables(arguments, false); + + ExternalCommandDestination.FormatArguments(arguments, string.Empty); } catch { @@ -129,16 +150,16 @@ namespace ExternalCommand { } private void textBox_name_TextChanged(object sender, EventArgs e) { - OKButtonState(); + OkButtonState(); } private void textBox_commandline_TextChanged(object sender, EventArgs e) { - OKButtonState(); + OkButtonState(); } private void textBox_arguments_TextChanged(object sender, EventArgs e) { - OKButtonState(); + OkButtonState(); } } diff --git a/GreenshotFlickrPlugin/FlickrDestination.cs b/GreenshotFlickrPlugin/FlickrDestination.cs index 7155937aa..0630ae933 100644 --- a/GreenshotFlickrPlugin/FlickrDestination.cs +++ b/GreenshotFlickrPlugin/FlickrDestination.cs @@ -27,7 +27,7 @@ using log4net; namespace GreenshotFlickrPlugin { public class FlickrDestination : AbstractDestination { private static ILog LOG = LogManager.GetLogger(typeof(FlickrDestination)); - private FlickrPlugin plugin; + private readonly FlickrPlugin plugin; public FlickrDestination(FlickrPlugin plugin) { this.plugin = plugin; } diff --git a/GreenshotFlickrPlugin/FlickrUtils.cs b/GreenshotFlickrPlugin/FlickrUtils.cs index 8737f85e0..08cc9e139 100644 --- a/GreenshotFlickrPlugin/FlickrUtils.cs +++ b/GreenshotFlickrPlugin/FlickrUtils.cs @@ -34,7 +34,7 @@ namespace GreenshotFlickrPlugin { /// public class FlickrUtils { private static readonly ILog LOG = LogManager.GetLogger(typeof(FlickrUtils)); - private static FlickrConfiguration config = IniConfig.GetIniSection(); + private static readonly FlickrConfiguration config = IniConfig.GetIniSection(); private const string FLICKR_API_BASE_URL = "https://api.flickr.com/services/"; private const string FLICKR_UPLOAD_URL = FLICKR_API_BASE_URL + "upload/"; // OAUTH diff --git a/GreenshotFlickrPlugin/Forms/FlickrForm.cs b/GreenshotFlickrPlugin/Forms/FlickrForm.cs index 59358436e..f302308b2 100644 --- a/GreenshotFlickrPlugin/Forms/FlickrForm.cs +++ b/GreenshotFlickrPlugin/Forms/FlickrForm.cs @@ -19,7 +19,6 @@ * along with this program. If not, see . */ -using System; using GreenshotPlugin.Controls; namespace GreenshotFlickrPlugin.Forms { diff --git a/GreenshotFlickrPlugin/Forms/SettingsForm.cs b/GreenshotFlickrPlugin/Forms/SettingsForm.cs index 0835e2ea5..5622670b8 100644 --- a/GreenshotFlickrPlugin/Forms/SettingsForm.cs +++ b/GreenshotFlickrPlugin/Forms/SettingsForm.cs @@ -18,12 +18,8 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; -using System.Drawing; -using System.Windows.Forms; using GreenshotFlickrPlugin.Forms; -using GreenshotPlugin.Core; namespace GreenshotFlickrPlugin { /// diff --git a/GreenshotFlickrPlugin/Properties/AssemblyInfo.cs b/GreenshotFlickrPlugin/Properties/AssemblyInfo.cs index 810171a92..445f5e3e7 100644 --- a/GreenshotFlickrPlugin/Properties/AssemblyInfo.cs +++ b/GreenshotFlickrPlugin/Properties/AssemblyInfo.cs @@ -22,7 +22,6 @@ using Greenshot.Plugin; using System.Reflection; using System.Runtime.InteropServices; -using System.Security; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information diff --git a/GreenshotImgurPlugin/Forms/ImgurForm.cs b/GreenshotImgurPlugin/Forms/ImgurForm.cs index d476f9313..35cd2949c 100644 --- a/GreenshotImgurPlugin/Forms/ImgurForm.cs +++ b/GreenshotImgurPlugin/Forms/ImgurForm.cs @@ -19,7 +19,6 @@ * along with this program. If not, see . */ -using System; using GreenshotPlugin.Controls; namespace GreenshotImgurPlugin { diff --git a/GreenshotImgurPlugin/Forms/ImgurHistory.cs b/GreenshotImgurPlugin/Forms/ImgurHistory.cs index 064fcc21f..b7efa5cb1 100644 --- a/GreenshotImgurPlugin/Forms/ImgurHistory.cs +++ b/GreenshotImgurPlugin/Forms/ImgurHistory.cs @@ -33,8 +33,8 @@ namespace GreenshotImgurPlugin { /// public partial class ImgurHistory : ImgurForm { private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImgurHistory)); - private GreenshotColumnSorter columnSorter; - private static ImgurConfiguration config = IniConfig.GetIniSection(); + private readonly GreenshotColumnSorter columnSorter; + private static readonly ImgurConfiguration config = IniConfig.GetIniSection(); private static ImgurHistory instance; public static void ShowHistory() { @@ -48,7 +48,7 @@ namespace GreenshotImgurPlugin { } private ImgurHistory() { - this.ManualLanguageApply = true; + ManualLanguageApply = true; // // The InitializeComponent() call is required for Windows Forms designer support. // @@ -57,7 +57,7 @@ namespace GreenshotImgurPlugin { CancelButton = finishedButton; // Init sorting columnSorter = new GreenshotColumnSorter(); - this.listview_imgur_uploads.ListViewItemSorter = columnSorter; + listview_imgur_uploads.ListViewItemSorter = columnSorter; columnSorter.SortColumn = 3; columnSorter.Order = SortOrder.Descending; redraw(); @@ -66,7 +66,7 @@ namespace GreenshotImgurPlugin { } ApplyLanguage(); if (config.Credits > 0) { - this.Text = this.Text + " (" + config.Credits + " credits)"; + Text = Text + " (" + config.Credits + " credits)"; } } @@ -169,7 +169,7 @@ namespace GreenshotImgurPlugin { private void FinishedButtonClick(object sender, EventArgs e) { - this.Hide(); + Hide(); } private void OpenButtonClick(object sender, EventArgs e) { @@ -197,7 +197,7 @@ namespace GreenshotImgurPlugin { } // Perform the sort with these new sort options. - this.listview_imgur_uploads.Sort(); + listview_imgur_uploads.Sort(); } diff --git a/GreenshotImgurPlugin/Forms/SettingsForm.cs b/GreenshotImgurPlugin/Forms/SettingsForm.cs index 8a35fc06e..40b9d65d3 100644 --- a/GreenshotImgurPlugin/Forms/SettingsForm.cs +++ b/GreenshotImgurPlugin/Forms/SettingsForm.cs @@ -19,9 +19,6 @@ * along with this program. If not, see . */ using System; -using System.Windows.Forms; -using GreenshotPlugin.Core; -using GreenshotPlugin.Controls; namespace GreenshotImgurPlugin { /// diff --git a/GreenshotImgurPlugin/ImgurDestination.cs b/GreenshotImgurPlugin/ImgurDestination.cs index 9002463f3..6f931376f 100644 --- a/GreenshotImgurPlugin/ImgurDestination.cs +++ b/GreenshotImgurPlugin/ImgurDestination.cs @@ -31,7 +31,7 @@ namespace GreenshotImgurPlugin { public class ImgurDestination : AbstractDestination { private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImgurDestination)); private static ImgurConfiguration config = IniConfig.GetIniSection(); - private ImgurPlugin plugin = null; + private readonly ImgurPlugin plugin = null; public ImgurDestination(ImgurPlugin plugin) { this.plugin = plugin; @@ -57,7 +57,7 @@ namespace GreenshotImgurPlugin { } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); + ExportInformation exportInformation = new ExportInformation(Designation, Description); string uploadURL = null; exportInformation.ExportMade = plugin.Upload(captureDetails, surface, out uploadURL); exportInformation.Uri = uploadURL; diff --git a/GreenshotImgurPlugin/ImgurPlugin.cs b/GreenshotImgurPlugin/ImgurPlugin.cs index c5c354eec..1a69aee2e 100644 --- a/GreenshotImgurPlugin/ImgurPlugin.cs +++ b/GreenshotImgurPlugin/ImgurPlugin.cs @@ -80,7 +80,7 @@ namespace GreenshotImgurPlugin { /// My own attributes /// true if plugin is initialized, false if not (doesn't show) public virtual bool Initialize(IGreenshotHost pluginHost, PluginAttribute myAttributes) { - this.host = (IGreenshotHost)pluginHost; + host = (IGreenshotHost)pluginHost; Attributes = myAttributes; // Get configuration diff --git a/GreenshotImgurPlugin/Properties/AssemblyInfo.cs b/GreenshotImgurPlugin/Properties/AssemblyInfo.cs index 06afabdf8..ba9c51983 100644 --- a/GreenshotImgurPlugin/Properties/AssemblyInfo.cs +++ b/GreenshotImgurPlugin/Properties/AssemblyInfo.cs @@ -22,7 +22,6 @@ using Greenshot.Plugin; using System.Reflection; using System.Runtime.InteropServices; -using System.Security; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information diff --git a/GreenshotJiraPlugin/Forms/JiraForm.cs b/GreenshotJiraPlugin/Forms/JiraForm.cs index 535a039bf..e0c81c827 100644 --- a/GreenshotJiraPlugin/Forms/JiraForm.cs +++ b/GreenshotJiraPlugin/Forms/JiraForm.cs @@ -29,21 +29,21 @@ using Jira; namespace GreenshotJiraPlugin { public partial class JiraForm : Form { - private JiraConnector jiraConnector; + private readonly JiraConnector jiraConnector; private JiraIssue selectedIssue; - private GreenshotColumnSorter columnSorter; - private JiraConfiguration config = IniConfig.GetIniSection(); + private readonly GreenshotColumnSorter columnSorter; + private readonly JiraConfiguration config = IniConfig.GetIniSection(); public JiraForm(JiraConnector jiraConnector) { InitializeComponent(); - this.Icon = GreenshotPlugin.Core.GreenshotResources.getGreenshotIcon(); + Icon = GreenshotResources.getGreenshotIcon(); AcceptButton = uploadButton; CancelButton = cancelButton; initializeComponentText(); - this.columnSorter = new GreenshotColumnSorter(); - this.jiraListView.ListViewItemSorter = columnSorter; + columnSorter = new GreenshotColumnSorter(); + jiraListView.ListViewItemSorter = columnSorter; this.jiraConnector = jiraConnector; @@ -60,9 +60,9 @@ namespace GreenshotJiraPlugin { } private void initializeComponentText() { - this.label_jirafilter.Text = Language.GetString("jira", LangKey.label_jirafilter); - this.label_comment.Text = Language.GetString("jira", LangKey.label_comment); - this.label_filename.Text = Language.GetString("jira", LangKey.label_filename); + label_jirafilter.Text = Language.GetString("jira", LangKey.label_jirafilter); + label_comment.Text = Language.GetString("jira", LangKey.label_comment); + label_filename.Text = Language.GetString("jira", LangKey.label_filename); } private void updateForm() { @@ -188,7 +188,7 @@ namespace GreenshotJiraPlugin { } // Perform the sort with these new sort options. - this.jiraListView.Sort(); + jiraListView.Sort(); } void JiraKeyTextChanged(object sender, EventArgs e) { diff --git a/GreenshotJiraPlugin/Forms/JiraFormBase.cs b/GreenshotJiraPlugin/Forms/JiraFormBase.cs index 6cba807a3..b67d2e947 100644 --- a/GreenshotJiraPlugin/Forms/JiraFormBase.cs +++ b/GreenshotJiraPlugin/Forms/JiraFormBase.cs @@ -18,7 +18,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using GreenshotPlugin.Controls; namespace GreenshotJiraPlugin { diff --git a/GreenshotJiraPlugin/Forms/SettingsForm.cs b/GreenshotJiraPlugin/Forms/SettingsForm.cs index 1ecaecfbf..49954efea 100644 --- a/GreenshotJiraPlugin/Forms/SettingsForm.cs +++ b/GreenshotJiraPlugin/Forms/SettingsForm.cs @@ -18,9 +18,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; -using System.Windows.Forms; -using GreenshotPlugin.Core; namespace GreenshotJiraPlugin { /// diff --git a/GreenshotJiraPlugin/Jira.cs b/GreenshotJiraPlugin/Jira.cs index cdaaae97a..53fdfa37f 100644 --- a/GreenshotJiraPlugin/Jira.cs +++ b/GreenshotJiraPlugin/Jira.cs @@ -33,8 +33,8 @@ namespace Jira { #region transport classes public class JiraFilter { public JiraFilter(string name, string id) { - this.Name = name; - this.Id = id; + Name = name; + Id = id; } public string Name { get; @@ -48,15 +48,15 @@ namespace Jira { public class JiraIssue { public JiraIssue(string key, DateTime? created, string reporter, string assignee, string project, string summary, string description, string environment, string [] attachmentNames) { - this.Key = key; - this.Created = created; - this.Reporter = reporter; - this.Assignee = assignee; - this.Project = project; - this.Summary = summary; - this.Description = description; - this.Environment = environment; - this.AttachmentNames = attachmentNames; + Key = key; + Created = created; + Reporter = reporter; + Assignee = assignee; + Project = project; + Summary = summary; + Description = description; + Environment = environment; + AttachmentNames = attachmentNames; } public string Key { get; @@ -100,17 +100,17 @@ namespace Jira { public class JiraConnector : IDisposable { private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(JiraConnector)); private const string AUTH_FAILED_EXCEPTION_NAME = "com.atlassian.jira.rpc.exception.RemoteAuthenticationException"; - private static JiraConfiguration config = IniConfig.GetIniSection(); + private static readonly JiraConfiguration config = IniConfig.GetIniSection(); public const string DEFAULT_POSTFIX = "/rpc/soap/jirasoapservice-v2?wsdl"; private string credentials; private DateTime loggedInTime = DateTime.Now; private bool loggedIn; private JiraSoapServiceService jira; - private int timeout; + private readonly int timeout; private string url; - private Cache jiraCache = new Cache(60 * config.Timeout); - private Cache userCache = new Cache(60 * config.Timeout); - private bool suppressBackgroundForm = false; + private readonly Cache jiraCache = new Cache(60 * config.Timeout); + private readonly Cache userCache = new Cache(60 * config.Timeout); + private readonly bool suppressBackgroundForm = false; public void Dispose() { Dispose(true); @@ -134,8 +134,8 @@ namespace Jira { } public JiraConnector(bool suppressBackgroundForm) { - this.url = config.Url; - this.timeout = config.Timeout; + url = config.Url; + timeout = config.Timeout; this.suppressBackgroundForm = suppressBackgroundForm; createService(); } @@ -171,13 +171,13 @@ namespace Jira { ThreadStart jiraLogin = delegate { LOG.DebugFormat("Loggin in"); try { - this.credentials = jira.login(user, password); + credentials = jira.login(user, password); } catch (Exception) { if (!url.EndsWith("wsdl")) { url = url + "/rpc/soap/jirasoapservice-v2?wsdl"; // recreate the service with the new url createService(); - this.credentials = jira.login(user, password); + credentials = jira.login(user, password); // Worked, store the url in the configuration config.Url = url; IniConfig.Save(); @@ -187,8 +187,8 @@ namespace Jira { } LOG.DebugFormat("Logged in"); - this.loggedInTime = DateTime.Now; - this.loggedIn = true; + loggedInTime = DateTime.Now; + loggedIn = true; }; // Here we do it @@ -204,8 +204,8 @@ namespace Jira { return false; } // Not an authentication issue - this.loggedIn = false; - this.credentials = null; + loggedIn = false; + credentials = null; e.Data.Add("user", user); e.Data.Add("url", url); throw; diff --git a/GreenshotJiraPlugin/JiraDestination.cs b/GreenshotJiraPlugin/JiraDestination.cs index bd443b37e..71bdd9d9e 100644 --- a/GreenshotJiraPlugin/JiraDestination.cs +++ b/GreenshotJiraPlugin/JiraDestination.cs @@ -35,10 +35,10 @@ namespace GreenshotJiraPlugin { /// Description of JiraDestination. /// public class JiraDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(JiraDestination)); - private static JiraConfiguration config = IniConfig.GetIniSection(); - private JiraPlugin jiraPlugin = null; - private JiraIssue jira = null; + private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(JiraDestination)); + private static readonly JiraConfiguration config = IniConfig.GetIniSection(); + private readonly JiraPlugin jiraPlugin = null; + private readonly JiraIssue jira = null; public JiraDestination(JiraPlugin jiraPlugin) { this.jiraPlugin = jiraPlugin; @@ -100,7 +100,7 @@ namespace GreenshotJiraPlugin { } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surfaceToUpload, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); + ExportInformation exportInformation = new ExportInformation(Designation, Description); string filename = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails)); SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(config.UploadFormat, config.UploadJpegQuality, config.UploadReduceColors); if (jira != null) { diff --git a/GreenshotJiraPlugin/JiraPlugin.cs b/GreenshotJiraPlugin/JiraPlugin.cs index 18e6576b9..b57a7a795 100644 --- a/GreenshotJiraPlugin/JiraPlugin.cs +++ b/GreenshotJiraPlugin/JiraPlugin.cs @@ -101,7 +101,7 @@ namespace GreenshotJiraPlugin { /// My own attributes /// true if plugin is initialized, false if not (doesn't show) public virtual bool Initialize(IGreenshotHost pluginHost, PluginAttribute myAttributes) { - this.host = (IGreenshotHost)pluginHost; + host = (IGreenshotHost)pluginHost; jiraPluginAttributes = myAttributes; // Register configuration (don't need the configuration itself) diff --git a/GreenshotJiraPlugin/JiraUtils.cs b/GreenshotJiraPlugin/JiraUtils.cs index cd78c4bde..51e518dfd 100644 --- a/GreenshotJiraPlugin/JiraUtils.cs +++ b/GreenshotJiraPlugin/JiraUtils.cs @@ -30,7 +30,7 @@ namespace GreenshotJiraPlugin { /// public class JiraUtils { private static readonly Regex JIRA_KEY_REGEX = new Regex(@"/browse/([A-Z0-9]+\-[0-9]+)"); - private static JiraConfiguration config = IniConfig.GetIniSection(); + private static readonly JiraConfiguration config = IniConfig.GetIniSection(); public static List GetCurrentJiras() { // Make sure we suppress the login diff --git a/GreenshotJiraPlugin/Properties/AssemblyInfo.cs b/GreenshotJiraPlugin/Properties/AssemblyInfo.cs index 080ba5f3d..c3e1b2a63 100644 --- a/GreenshotJiraPlugin/Properties/AssemblyInfo.cs +++ b/GreenshotJiraPlugin/Properties/AssemblyInfo.cs @@ -22,7 +22,6 @@ using Greenshot.Plugin; using System.Reflection; using System.Runtime.InteropServices; -using System.Security; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information diff --git a/GreenshotOCRCommand/COMWrapper.cs b/GreenshotOCRCommand/COMWrapper.cs index af7ef4bb0..9c8f0da03 100644 --- a/GreenshotOCRCommand/COMWrapper.cs +++ b/GreenshotOCRCommand/COMWrapper.cs @@ -43,12 +43,12 @@ namespace Greenshot.Interop { /// /// Type of the COM object, set on constructor after getting the COM reference /// - private Type _COMType; + private readonly Type _COMType; /// /// The type of which method calls are intercepted and executed on the COM object. /// - private Type _InterceptType; + private readonly Type _InterceptType; #endregion [DllImport("ole32.dll")] @@ -214,9 +214,9 @@ namespace Greenshot.Interop { /// private COMWrapper(object comObject, Type type) : base(type) { - this._COMObject = comObject; - this._COMType = comObject.GetType(); - this._InterceptType = type; + _COMObject = comObject; + _COMType = comObject.GetType(); + _InterceptType = type; } #endregion @@ -228,14 +228,14 @@ namespace Greenshot.Interop { /// sure that the COM object is still cleaned up. /// ~COMWrapper() { - this.Dispose(false); + Dispose(false); } /// /// Cleans up the COM object. /// public void Dispose() { - this.Dispose(true); + Dispose(true); GC.SuppressFinalize(this); } @@ -247,17 +247,17 @@ namespace Greenshot.Interop { /// interface. /// private void Dispose(bool disposing) { - if (disposing && null != this._COMObject) { - if (Marshal.IsComObject(this._COMObject)) { + if (disposing && null != _COMObject) { + if (Marshal.IsComObject(_COMObject)) { try { - while (Marshal.ReleaseComObject(this._COMObject) > 0); + while (Marshal.ReleaseComObject(_COMObject) > 0); } catch (Exception) { //LOG.WarnFormat("Problem releasing {0}", _COMType); //LOG.Warn("Error: ", ex); } } - this._COMObject = null; + _COMObject = null; } } @@ -272,7 +272,7 @@ namespace Greenshot.Interop { /// The full name of the intercepted type. /// public override string ToString() { - return this._InterceptType.FullName; + return _InterceptType.FullName; } /// @@ -282,7 +282,7 @@ namespace Greenshot.Interop { /// The hash code of the wrapped object. /// public override int GetHashCode() { - return this._COMObject.GetHashCode(); + return _COMObject.GetHashCode(); } /// @@ -298,7 +298,7 @@ namespace Greenshot.Interop { if (null != value && RemotingServices.IsTransparentProxy(value)) { COMWrapper wrapper = RemotingServices.GetRealProxy(value) as COMWrapper; if (null != wrapper) { - return this._COMObject == wrapper._COMObject; + return _COMObject == wrapper._COMObject; } } @@ -469,15 +469,15 @@ namespace Greenshot.Interop { ParameterInfo parameter; if ("Dispose" == methodName && 0 == argCount && typeof(void) == returnType) { - this.Dispose(); + Dispose(); } else if ("ToString" == methodName && 0 == argCount && typeof(string) == returnType) { - returnValue = this.ToString(); - } else if ("GetType" == methodName && 0 == argCount && typeof(System.Type) == returnType) { - returnValue = this._InterceptType; + returnValue = ToString(); + } else if ("GetType" == methodName && 0 == argCount && typeof(Type) == returnType) { + returnValue = _InterceptType; } else if ("GetHashCode" == methodName && 0 == argCount && typeof(int) == returnType) { - returnValue = this.GetHashCode(); + returnValue = GetHashCode(); } else if ("Equals" == methodName && 1 == argCount && typeof(bool) == returnType) { - returnValue = this.Equals(callMessage.Args[0]); + returnValue = Equals(callMessage.Args[0]); } else if (1 == argCount && typeof(void) == returnType && (methodName.StartsWith("add_") || methodName.StartsWith("remove_"))) { bool removeHandler = methodName.StartsWith("remove_"); methodName = methodName.Substring(removeHandler ? 7 : 4); @@ -487,8 +487,8 @@ namespace Greenshot.Interop { return new ReturnMessage(new ArgumentNullException("handler"), callMessage); } } else { - invokeObject = this._COMObject; - invokeType = this._COMType; + invokeObject = _COMObject; + invokeType = _COMType; if (methodName.StartsWith("get_")) { // Property Get @@ -565,7 +565,7 @@ namespace Greenshot.Interop { if (returnType.IsInterface) { // Wrap the returned value in an intercepting COM wrapper if (Marshal.IsComObject(returnValue)) { - returnValue = COMWrapper.Wrap(returnValue, returnType); + returnValue = Wrap(returnValue, returnType); } } else if (returnType.IsEnum) { // Convert to proper Enum type diff --git a/GreenshotOCRCommand/ComProgIdAttribute.cs b/GreenshotOCRCommand/ComProgIdAttribute.cs index 231786e12..b8ef6a98e 100644 --- a/GreenshotOCRCommand/ComProgIdAttribute.cs +++ b/GreenshotOCRCommand/ComProgIdAttribute.cs @@ -26,7 +26,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/GreenshotOCRCommand/Properties/AssemblyInfo.cs b/GreenshotOCRCommand/Properties/AssemblyInfo.cs index 419eb53b6..2daec6629 100644 --- a/GreenshotOCRCommand/Properties/AssemblyInfo.cs +++ b/GreenshotOCRCommand/Properties/AssemblyInfo.cs @@ -21,7 +21,6 @@ using System.Reflection; using System.Runtime.InteropServices; -using System.Security; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, diff --git a/GreenshotOCRPlugin/OCRDestination.cs b/GreenshotOCRPlugin/OCRDestination.cs index ac50ad74a..cd745baab 100644 --- a/GreenshotOCRPlugin/OCRDestination.cs +++ b/GreenshotOCRPlugin/OCRDestination.cs @@ -33,7 +33,7 @@ namespace GreenshotOCR { private static OCRConfiguration config = IniConfig.GetIniSection(); private const int MIN_WIDTH = 130; private const int MIN_HEIGHT = 130; - private OcrPlugin plugin; + private readonly OcrPlugin plugin; public override string Designation { get { @@ -62,7 +62,7 @@ namespace GreenshotOCR { } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); + ExportInformation exportInformation = new ExportInformation(Designation, Description); exportInformation.ExportMade = plugin.DoOCR(surface) != null; return exportInformation; } diff --git a/GreenshotOCRPlugin/OCRPlugin.cs b/GreenshotOCRPlugin/OCRPlugin.cs index 8b4440136..c0e3137c9 100644 --- a/GreenshotOCRPlugin/OCRPlugin.cs +++ b/GreenshotOCRPlugin/OCRPlugin.cs @@ -21,7 +21,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Drawing; using System.IO; using System.Windows.Forms; using Greenshot.IniFile; @@ -61,7 +60,7 @@ namespace GreenshotOCR { /// OCR Plugin Greenshot /// public class OcrPlugin : IGreenshotPlugin { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(OcrPlugin)); + private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(OcrPlugin)); private const string CONFIG_FILENAME = "ocr-config.properties"; private string OCR_COMMAND; private static IGreenshotHost host; diff --git a/GreenshotOCRPlugin/Properties/AssemblyInfo.cs b/GreenshotOCRPlugin/Properties/AssemblyInfo.cs index c524510e1..303fbc1ea 100644 --- a/GreenshotOCRPlugin/Properties/AssemblyInfo.cs +++ b/GreenshotOCRPlugin/Properties/AssemblyInfo.cs @@ -22,7 +22,6 @@ using Greenshot.Plugin; using System.Reflection; using System.Runtime.InteropServices; -using System.Security; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information diff --git a/GreenshotOCRPlugin/SettingsForm.cs b/GreenshotOCRPlugin/SettingsForm.cs index 88b1d029a..8fcb4ea90 100644 --- a/GreenshotOCRPlugin/SettingsForm.cs +++ b/GreenshotOCRPlugin/SettingsForm.cs @@ -19,15 +19,13 @@ * along with this program. If not, see . */ using System; -using System.Windows.Forms; -using GreenshotPlugin.Core; namespace GreenshotOCR { /// /// Description of SettingsForm. /// public partial class SettingsForm : OCRForm { - private OCRConfiguration config; + private readonly OCRConfiguration config; public SettingsForm(string [] languages, OCRConfiguration config) { // diff --git a/GreenshotOfficePlugin/Destinations/ExcelDestination.cs b/GreenshotOfficePlugin/Destinations/ExcelDestination.cs index 1b9e6febb..31771ca62 100644 --- a/GreenshotOfficePlugin/Destinations/ExcelDestination.cs +++ b/GreenshotOfficePlugin/Destinations/ExcelDestination.cs @@ -18,16 +18,13 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Collections.Generic; using System.Drawing; using System.IO; -using System.Windows.Forms; - using GreenshotPlugin.Core; using Greenshot.Plugin; using Greenshot.Interop.Office; -using Greenshot.IniFile; using System.Text.RegularExpressions; namespace GreenshotOfficePlugin { @@ -38,8 +35,8 @@ namespace GreenshotOfficePlugin { private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ExcelDestination)); private const int ICON_APPLICATION = 0; private const int ICON_WORKBOOK = 1; - private static string exePath = null; - private string workbookName = null; + private static readonly string exePath = null; + private readonly string workbookName = null; static ExcelDestination() { exePath = PluginUtils.GetExePath("EXCEL.EXE"); @@ -107,7 +104,7 @@ namespace GreenshotOfficePlugin { } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); + ExportInformation exportInformation = new ExportInformation(Designation, Description); bool createdFile = false; string imageFile = captureDetails.Filename; if (imageFile == null || surface.Modified || !Regex.IsMatch(imageFile, @".*(\.png|\.gif|\.jpg|\.jpeg|\.tiff|\.bmp)$")) { diff --git a/GreenshotOfficePlugin/Destinations/OneNoteDestination.cs b/GreenshotOfficePlugin/Destinations/OneNoteDestination.cs index 9a72feee5..048b039ef 100644 --- a/GreenshotOfficePlugin/Destinations/OneNoteDestination.cs +++ b/GreenshotOfficePlugin/Destinations/OneNoteDestination.cs @@ -29,11 +29,11 @@ using System.IO; namespace GreenshotOfficePlugin { public class OneNoteDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(WordDestination)); + private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(WordDestination)); private const int ICON_APPLICATION = 0; public const string DESIGNATION = "OneNote"; - private static string exePath = null; - private OneNotePage page = null; + private static readonly string exePath = null; + private readonly OneNotePage page = null; static OneNoteDestination() { exePath = PluginUtils.GetExePath("ONENOTE.EXE"); @@ -99,7 +99,7 @@ namespace GreenshotOfficePlugin { } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); + ExportInformation exportInformation = new ExportInformation(Designation, Description); if (page == null) { try { diff --git a/GreenshotOfficePlugin/Destinations/OutlookDestination.cs b/GreenshotOfficePlugin/Destinations/OutlookDestination.cs index 66db19b40..6410e82d5 100644 --- a/GreenshotOfficePlugin/Destinations/OutlookDestination.cs +++ b/GreenshotOfficePlugin/Destinations/OutlookDestination.cs @@ -34,18 +34,18 @@ namespace GreenshotOfficePlugin { /// Description of OutlookDestination. /// public class OutlookDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(OutlookDestination)); + private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(OutlookDestination)); private const int ICON_APPLICATION = 0; private const int ICON_MEETING = 2; - private static Image mailIcon = GreenshotPlugin.Core.GreenshotResources.getImage("Email.Image"); - private static OfficeConfiguration conf = IniConfig.GetIniSection(); - private static string exePath = null; - private static bool isActiveFlag = false; - private static string mapiClient = "Microsoft Outlook"; + private static readonly Image mailIcon = GreenshotResources.getImage("Email.Image"); + private static readonly OfficeConfiguration conf = IniConfig.GetIniSection(); + private static readonly string exePath = null; + private static readonly bool isActiveFlag = false; + private static readonly string mapiClient = "Microsoft Outlook"; public const string DESIGNATION = "Outlook"; - private string outlookInspectorCaption; - private OlObjectClass outlookInspectorType; + private readonly string outlookInspectorCaption; + private readonly OlObjectClass outlookInspectorType; static OutlookDestination() { if (EmailConfigHelper.HasOutlook()) { @@ -142,7 +142,7 @@ namespace GreenshotOfficePlugin { /// /// public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); + ExportInformation exportInformation = new ExportInformation(Designation, Description); // Outlook logic string tmpFile = captureDetails.Filename; if (tmpFile == null || surface.Modified || !Regex.IsMatch(tmpFile, @".*(\.png|\.gif|\.jpg|\.jpeg|\.tiff|\.bmp)$")) { diff --git a/GreenshotOfficePlugin/Destinations/PowerpointDestination.cs b/GreenshotOfficePlugin/Destinations/PowerpointDestination.cs index 30a5d3df5..b3b317cba 100644 --- a/GreenshotOfficePlugin/Destinations/PowerpointDestination.cs +++ b/GreenshotOfficePlugin/Destinations/PowerpointDestination.cs @@ -18,16 +18,13 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; + using System.Collections.Generic; using System.Drawing; using System.IO; -using System.Windows.Forms; - using GreenshotPlugin.Core; using Greenshot.Plugin; using Greenshot.Interop.Office; -using Greenshot.IniFile; using System.Text.RegularExpressions; namespace GreenshotOfficePlugin { @@ -39,8 +36,8 @@ namespace GreenshotOfficePlugin { private const int ICON_APPLICATION = 0; private const int ICON_PRESENTATION = 1; - private static string exePath = null; - private string presentationName = null; + private static readonly string exePath = null; + private readonly string presentationName = null; static PowerpointDestination() { exePath = PluginUtils.GetExePath("POWERPNT.EXE"); @@ -109,7 +106,7 @@ namespace GreenshotOfficePlugin { } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); + ExportInformation exportInformation = new ExportInformation(Designation, Description); string tmpFile = captureDetails.Filename; Size imageSize = Size.Empty; if (tmpFile == null || surface.Modified || !Regex.IsMatch(tmpFile, @".*(\.png|\.gif|\.jpg|\.jpeg|\.tiff|\.bmp)$")) { diff --git a/GreenshotOfficePlugin/Destinations/WordDestination.cs b/GreenshotOfficePlugin/Destinations/WordDestination.cs index 202b2ee72..b92001cea 100644 --- a/GreenshotOfficePlugin/Destinations/WordDestination.cs +++ b/GreenshotOfficePlugin/Destinations/WordDestination.cs @@ -33,11 +33,11 @@ namespace GreenshotOfficePlugin { /// Description of EmailDestination. /// public class WordDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(WordDestination)); + private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(WordDestination)); private const int ICON_APPLICATION = 0; private const int ICON_DOCUMENT = 1; - private static string exePath = null; - private string documentCaption = null; + private static readonly string exePath = null; + private readonly string documentCaption = null; static WordDestination() { exePath = PluginUtils.GetExePath("WINWORD.EXE"); @@ -51,7 +51,7 @@ namespace GreenshotOfficePlugin { } public WordDestination(string wordCaption) { - this.documentCaption = wordCaption; + documentCaption = wordCaption; } public override string Designation { @@ -104,7 +104,7 @@ namespace GreenshotOfficePlugin { } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); + ExportInformation exportInformation = new ExportInformation(Designation, Description); string tmpFile = captureDetails.Filename; if (tmpFile == null || surface.Modified || !Regex.IsMatch(tmpFile, @".*(\.png|\.gif|\.jpg|\.jpeg|\.tiff|\.bmp)$")) { tmpFile = ImageOutput.SaveNamedTmpFile(surface, captureDetails, new SurfaceOutputSettings().PreventGreenshotFormat()); diff --git a/GreenshotOfficePlugin/OfficeExport/ExcelExporter.cs b/GreenshotOfficePlugin/OfficeExport/ExcelExporter.cs index 0a5bfd161..5da5de6da 100644 --- a/GreenshotOfficePlugin/OfficeExport/ExcelExporter.cs +++ b/GreenshotOfficePlugin/OfficeExport/ExcelExporter.cs @@ -20,10 +20,7 @@ */ using System; using System.Collections.Generic; -using System.Text; using System.Reflection; - -using Greenshot.Interop; using System.Drawing; using GreenshotOfficePlugin; using Greenshot.IniFile; diff --git a/GreenshotOfficePlugin/OfficeExport/OneNoteExporter.cs b/GreenshotOfficePlugin/OfficeExport/OneNoteExporter.cs index f2e419411..d152c8ec5 100644 --- a/GreenshotOfficePlugin/OfficeExport/OneNoteExporter.cs +++ b/GreenshotOfficePlugin/OfficeExport/OneNoteExporter.cs @@ -20,7 +20,6 @@ */ using System.Runtime.InteropServices; -using System.Windows.Forms; using Greenshot.Plugin; using GreenshotPlugin.Core; using System; diff --git a/GreenshotOfficePlugin/OfficeExport/OutlookEmailExporter.cs b/GreenshotOfficePlugin/OfficeExport/OutlookEmailExporter.cs index 39e0ea13c..6ecab8c4c 100644 --- a/GreenshotOfficePlugin/OfficeExport/OutlookEmailExporter.cs +++ b/GreenshotOfficePlugin/OfficeExport/OutlookEmailExporter.cs @@ -24,13 +24,7 @@ using System.Text; using System.IO; using Microsoft.Win32; - -using Greenshot.Interop; using Greenshot.Interop.IE; -using System.Threading; -using System.Runtime.InteropServices; -using System.Windows.Forms; -using GreenshotPlugin.Core; using GreenshotOfficePlugin; using Greenshot.IniFile; diff --git a/GreenshotOfficePlugin/OfficeExport/WordExporter.cs b/GreenshotOfficePlugin/OfficeExport/WordExporter.cs index bd45749e2..22e26eb00 100644 --- a/GreenshotOfficePlugin/OfficeExport/WordExporter.cs +++ b/GreenshotOfficePlugin/OfficeExport/WordExporter.cs @@ -20,9 +20,6 @@ */ using System; using System.Collections.Generic; -using System.Text; - -using Greenshot.Interop; using GreenshotOfficePlugin; using Greenshot.IniFile; @@ -30,7 +27,7 @@ namespace Greenshot.Interop.Office { public class WordExporter { private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(WordExporter)); private static Version wordVersion = null; - private static OfficeConfiguration config = IniConfig.GetIniSection(); + private static readonly OfficeConfiguration config = IniConfig.GetIniSection(); /// /// Check if the used version is higher than Office 2003 diff --git a/GreenshotOfficePlugin/OfficeInterop/OutlookUtils.cs b/GreenshotOfficePlugin/OfficeInterop/OutlookUtils.cs index 3f1532cef..ad6c9f840 100644 --- a/GreenshotOfficePlugin/OfficeInterop/OutlookUtils.cs +++ b/GreenshotOfficePlugin/OfficeInterop/OutlookUtils.cs @@ -601,11 +601,11 @@ namespace Greenshot.Interop.Office { [FieldOffset(0)] public uint propTag; [FieldOffset(4)] - public uint alignPad; + public readonly uint alignPad; [FieldOffset(8)] public IntPtr Value; [FieldOffset(8)] - public long filler; + public readonly long filler; } /// @@ -770,7 +770,7 @@ namespace Greenshot.Interop.Office { Marshal.FreeHGlobal(propValue.Value); IMAPIProp mapiProp = (IMAPIProp)Marshal.GetTypedObjectForIUnknown(IUnknown, typeof(IMAPIProp)); return mapiProp.SaveChanges(4) == 0; - } catch (System.Exception ex) { + } catch (Exception ex) { LOG.Error(ex); return false; } finally { diff --git a/GreenshotOfficePlugin/Properties/AssemblyInfo.cs b/GreenshotOfficePlugin/Properties/AssemblyInfo.cs index 79ad89124..a2c7f647e 100644 --- a/GreenshotOfficePlugin/Properties/AssemblyInfo.cs +++ b/GreenshotOfficePlugin/Properties/AssemblyInfo.cs @@ -22,7 +22,6 @@ using Greenshot.Plugin; using System.Reflection; using System.Runtime.InteropServices; -using System.Security; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information diff --git a/GreenshotPhotobucketPlugin/Forms/SettingsForm.cs b/GreenshotPhotobucketPlugin/Forms/SettingsForm.cs index 560a29b39..dcb077820 100644 --- a/GreenshotPhotobucketPlugin/Forms/SettingsForm.cs +++ b/GreenshotPhotobucketPlugin/Forms/SettingsForm.cs @@ -18,10 +18,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; -using System.Windows.Forms; -using GreenshotPlugin.Core; -using GreenshotPlugin.Controls; namespace GreenshotPhotobucketPlugin { /// diff --git a/GreenshotPhotobucketPlugin/PhotobucketDestination.cs b/GreenshotPhotobucketPlugin/PhotobucketDestination.cs index 68f467c53..11642c24e 100644 --- a/GreenshotPhotobucketPlugin/PhotobucketDestination.cs +++ b/GreenshotPhotobucketPlugin/PhotobucketDestination.cs @@ -33,8 +33,8 @@ namespace GreenshotPhotobucketPlugin { public class PhotobucketDestination : AbstractDestination { private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(PhotobucketDestination)); private static PhotobucketConfiguration config = IniConfig.GetIniSection(); - private PhotobucketPlugin plugin = null; - private string albumPath = null; + private readonly PhotobucketPlugin plugin = null; + private readonly string albumPath = null; /// /// Create a Photobucket destination, which also has the path to the album in it @@ -97,7 +97,7 @@ namespace GreenshotPhotobucketPlugin { /// /// public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); + ExportInformation exportInformation = new ExportInformation(Designation, Description); string uploadURL = null; bool uploaded = plugin.Upload(captureDetails, surface, albumPath, out uploadURL); if (uploaded) { diff --git a/GreenshotPhotobucketPlugin/PhotobucketPlugin.cs b/GreenshotPhotobucketPlugin/PhotobucketPlugin.cs index 63fd3f035..3f2a70da7 100644 --- a/GreenshotPhotobucketPlugin/PhotobucketPlugin.cs +++ b/GreenshotPhotobucketPlugin/PhotobucketPlugin.cs @@ -74,7 +74,7 @@ namespace GreenshotPhotobucketPlugin { /// My own attributes /// true if plugin is initialized, false if not (doesn't show) public virtual bool Initialize(IGreenshotHost pluginHost, PluginAttribute myAttributes) { - this.host = (IGreenshotHost)pluginHost; + host = (IGreenshotHost)pluginHost; Attributes = myAttributes; // Get configuration diff --git a/GreenshotPhotobucketPlugin/Properties/AssemblyInfo.cs b/GreenshotPhotobucketPlugin/Properties/AssemblyInfo.cs index d732925da..acdab0857 100644 --- a/GreenshotPhotobucketPlugin/Properties/AssemblyInfo.cs +++ b/GreenshotPhotobucketPlugin/Properties/AssemblyInfo.cs @@ -22,7 +22,6 @@ using Greenshot.Plugin; using System.Reflection; using System.Runtime.InteropServices; -using System.Security; // General Information about an assembly is controlled through the following diff --git a/GreenshotPicasaPlugin/Forms/SettingsForm.cs b/GreenshotPicasaPlugin/Forms/SettingsForm.cs index edb7597f0..1ee8f5594 100644 --- a/GreenshotPicasaPlugin/Forms/SettingsForm.cs +++ b/GreenshotPicasaPlugin/Forms/SettingsForm.cs @@ -17,13 +17,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; -using System.Drawing; -using System.Windows.Forms; - -using Greenshot.Plugin; -using GreenshotPlugin.Controls; -using GreenshotPlugin.Core; namespace GreenshotPicasaPlugin { /// diff --git a/GreenshotPicasaPlugin/PicasaDestination.cs b/GreenshotPicasaPlugin/PicasaDestination.cs index 8e489ef09..2a245716a 100644 --- a/GreenshotPicasaPlugin/PicasaDestination.cs +++ b/GreenshotPicasaPlugin/PicasaDestination.cs @@ -28,7 +28,7 @@ namespace GreenshotPicasaPlugin { private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(PicasaDestination)); private static PicasaConfiguration config = IniConfig.GetIniSection(); - private PicasaPlugin plugin = null; + private readonly PicasaPlugin plugin = null; public PicasaDestination(PicasaPlugin plugin) { this.plugin = plugin; } @@ -53,7 +53,7 @@ namespace GreenshotPicasaPlugin { } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description); + ExportInformation exportInformation = new ExportInformation(Designation, Description); string uploadURL = null; bool uploaded = plugin.Upload(captureDetails, surface, out uploadURL); if (uploaded) { diff --git a/GreenshotPicasaPlugin/PicasaPlugin.cs b/GreenshotPicasaPlugin/PicasaPlugin.cs index 7de3b12c9..334cead8c 100644 --- a/GreenshotPicasaPlugin/PicasaPlugin.cs +++ b/GreenshotPicasaPlugin/PicasaPlugin.cs @@ -73,7 +73,7 @@ namespace GreenshotPicasaPlugin { /// Use the ICaptureHost interface to register in the MainContextMenu /// My own attributes public virtual bool Initialize(IGreenshotHost pluginHost, PluginAttribute myAttributes) { - this.host = (IGreenshotHost)pluginHost; + host = (IGreenshotHost)pluginHost; Attributes = myAttributes; // Get configuration @@ -84,7 +84,7 @@ namespace GreenshotPicasaPlugin { itemPlugInRoot.Text = Language.GetString("picasa", LangKey.Configure); itemPlugInRoot.Tag = host; itemPlugInRoot.Image = (Image)resources.GetObject("Picasa"); - itemPlugInRoot.Click += new System.EventHandler(ConfigMenuClick); + itemPlugInRoot.Click += new EventHandler(ConfigMenuClick); PluginUtils.AddToContextMenu(host, itemPlugInRoot); Language.LanguageChanged += new LanguageChangedHandler(OnLanguageChanged); return true; @@ -127,7 +127,7 @@ namespace GreenshotPicasaPlugin { SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(config.UploadFormat, config.UploadJpegQuality); try { string url = null; - new PleaseWaitForm().ShowAndWait(PicasaPlugin.Attributes.Name, Language.GetString("picasa", LangKey.communication_wait), + new PleaseWaitForm().ShowAndWait(Attributes.Name, Language.GetString("picasa", LangKey.communication_wait), delegate() { string filename = Path.GetFileName(FilenameHelper.GetFilename(config.UploadFormat, captureDetails)); string contentType = "image/" + config.UploadFormat.ToString(); diff --git a/GreenshotPicasaPlugin/PicasaUtils.cs b/GreenshotPicasaPlugin/PicasaUtils.cs index 14c8307d1..4aef53b5c 100644 --- a/GreenshotPicasaPlugin/PicasaUtils.cs +++ b/GreenshotPicasaPlugin/PicasaUtils.cs @@ -22,7 +22,6 @@ using Greenshot.IniFile; using Greenshot.Plugin; using GreenshotPlugin.Core; using System; -using System.Net; using System.Xml; namespace GreenshotPicasaPlugin { diff --git a/GreenshotPicasaPlugin/Properties/AssemblyInfo.cs b/GreenshotPicasaPlugin/Properties/AssemblyInfo.cs index 4e50cceda..479b13c8e 100644 --- a/GreenshotPicasaPlugin/Properties/AssemblyInfo.cs +++ b/GreenshotPicasaPlugin/Properties/AssemblyInfo.cs @@ -22,7 +22,6 @@ using Greenshot.Plugin; using System.Reflection; using System.Runtime.InteropServices; -using System.Security; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information diff --git a/GreenshotPlugin/Controls/HotkeyControl.cs b/GreenshotPlugin/Controls/HotkeyControl.cs index 372e67633..1d5b9d5d0 100644 --- a/GreenshotPlugin/Controls/HotkeyControl.cs +++ b/GreenshotPlugin/Controls/HotkeyControl.cs @@ -441,7 +441,7 @@ namespace GreenshotPlugin.Controls { if (hotkey.LastIndexOf('+') > 0) { hotkey = hotkey.Remove(0,hotkey.LastIndexOf('+')+1).Trim(); } - key = (Keys)Keys.Parse(typeof(Keys), hotkey); + key = (Keys)Enum.Parse(typeof(Keys), hotkey); } return key; } diff --git a/GreenshotPlugin/Core/Cache.cs b/GreenshotPlugin/Core/Cache.cs index 06b98899f..faf2a75a7 100644 --- a/GreenshotPlugin/Core/Cache.cs +++ b/GreenshotPlugin/Core/Cache.cs @@ -74,8 +74,11 @@ namespace GreenshotPlugin.Core { get { List elements = new List(); - foreach (TV element in internalCache.Values) { - elements.Add(element); + lock (lockObject) + { + foreach (TV element in internalCache.Values) { + elements.Add(element); + } } foreach (TV element in elements) { yield return element; @@ -105,8 +108,12 @@ namespace GreenshotPlugin.Core { /// /// /// true if the cache contains the key - public bool Contains(TK key) { - return internalCache.ContainsKey(key); + public bool Contains(TK key) + { + lock (lockObject) + { + return internalCache.ContainsKey(key); + } } /// diff --git a/GreenshotPlugin/Core/EventDelay.cs b/GreenshotPlugin/Core/EventDelay.cs index 1dbd3d7c7..c1c686107 100644 --- a/GreenshotPlugin/Core/EventDelay.cs +++ b/GreenshotPlugin/Core/EventDelay.cs @@ -26,7 +26,7 @@ namespace GreenshotPlugin.Core { private long lastCheck; private readonly long waitTime; public EventDelay(long ticks) { - this.waitTime = ticks; + waitTime = ticks; } public bool Check() { diff --git a/GreenshotPlugin/Core/FilenameHelper.cs b/GreenshotPlugin/Core/FilenameHelper.cs index 236f4f2d9..33a41a3a2 100644 --- a/GreenshotPlugin/Core/FilenameHelper.cs +++ b/GreenshotPlugin/Core/FilenameHelper.cs @@ -38,6 +38,7 @@ namespace GreenshotPlugin.Core { // 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; @@ -74,7 +75,7 @@ namespace GreenshotPlugin.Core { /// /// 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) { // Make the path save! @@ -389,6 +390,51 @@ namespace GreenshotPlugin.Core { 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 /// @@ -419,7 +465,7 @@ namespace GreenshotPlugin.Core { return VAR_REGEXP.Replace(pattern, delegate(Match m) { - return MatchVarEvaluator(m, null, processVars, userVars, machineVars, filenameSafeMode); + return MatchVarEvaluator(m, null, processVars, userVars, machineVars, filenameSafeMode); } ); } diff --git a/GreenshotPlugin/Core/LogHelper.cs b/GreenshotPlugin/Core/LogHelper.cs index 27b2b6211..bd6aae4c9 100644 --- a/GreenshotPlugin/Core/LogHelper.cs +++ b/GreenshotPlugin/Core/LogHelper.cs @@ -101,7 +101,7 @@ namespace GreenshotPlugin.Core { /// public class SpecialFolderPatternConverter : PatternConverter { override protected void Convert(TextWriter writer, object state) { - Environment.SpecialFolder specialFolder = (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), base.Option, true); + Environment.SpecialFolder specialFolder = (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), Option, true); writer.Write(Environment.GetFolderPath(specialFolder)); } } diff --git a/GreenshotPlugin/Core/OAuthHelper.cs b/GreenshotPlugin/Core/OAuthHelper.cs index add088da2..23651a7ef 100644 --- a/GreenshotPlugin/Core/OAuthHelper.cs +++ b/GreenshotPlugin/Core/OAuthHelper.cs @@ -1032,7 +1032,7 @@ Greenshot received information from CloudServiceName. You can close this browser // Get response object. using (HttpListenerResponse response = context.Response) { // Write a "close" response. - byte[] buffer = System.Text.Encoding.UTF8.GetBytes(ClosePageResponse.Replace("CloudServiceName", _cloudServiceName)); + byte[] buffer = Encoding.UTF8.GetBytes(ClosePageResponse.Replace("CloudServiceName", _cloudServiceName)); // Write to response stream. response.ContentLength64 = buffer.Length; using (var stream = response.OutputStream) { diff --git a/GreenshotPlugin/Core/PluginUtils.cs b/GreenshotPlugin/Core/PluginUtils.cs index a3d910e61..e50210a5c 100644 --- a/GreenshotPlugin/Core/PluginUtils.cs +++ b/GreenshotPlugin/Core/PluginUtils.cs @@ -110,12 +110,15 @@ namespace GreenshotPlugin.Core { 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) { - if (!exeIconCache.TryGetValue(cacheKey, out returnValue)) { - returnValue = GetExeIcon(path, index); - if (returnValue != null) { - exeIconCache.Add(cacheKey, returnValue); + lock (exeIconCache) + { + if (!exeIconCache.TryGetValue(cacheKey, out returnValue)) { + lock (exeIconCache) { + if (!exeIconCache.TryGetValue(cacheKey, out returnValue)) { + returnValue = GetExeIcon(path, index); + if (returnValue != null) { + exeIconCache.Add(cacheKey, returnValue); + } } } } diff --git a/GreenshotPlugin/Core/SourceForgeHelper.cs b/GreenshotPlugin/Core/SourceForgeHelper.cs index 6ead257d0..c58b6fbb0 100644 --- a/GreenshotPlugin/Core/SourceForgeHelper.cs +++ b/GreenshotPlugin/Core/SourceForgeHelper.cs @@ -85,10 +85,10 @@ namespace GreenshotPlugin.Core { } public SourceforgeFile(string file, string pubdate, string link, string directLink) { - this._file = file; + _file = file; DateTime.TryParse(pubdate, out _pubdate); - this._link = link; - this._directLink = directLink; + _link = link; + _directLink = directLink; } } /// From 1469f1fa41e56986e20dd09bec2023ad9dcdb5e4 Mon Sep 17 00:00:00 2001 From: Robin Date: Sun, 22 May 2016 00:16:06 +0200 Subject: [PATCH 11/19] BUG-1965: Fixed a bug where a 1 pixel wide border around an active window is visible. Probably due to the "shadow" being captured too. --- Greenshot/Forms/MainForm.cs | 2 +- Greenshot/Forms/SettingsForm.cs | 2 +- Greenshot/Helpers/CaptureHelper.cs | 36 +- .../additional_files/readme.txt.template | 1 + GreenshotPlugin/Controls/ThumbnailForm.cs | 4 +- GreenshotPlugin/Core/WindowsHelper.cs | 319 +++++++++--------- GreenshotPlugin/UnmanagedHelpers/DWM.cs | 2 +- GreenshotPlugin/UnmanagedHelpers/Structs.cs | 10 +- appveyor12.yml | 3 + 9 files changed, 200 insertions(+), 179 deletions(-) diff --git a/Greenshot/Forms/MainForm.cs b/Greenshot/Forms/MainForm.cs index 686f507d4..19643627a 100644 --- a/Greenshot/Forms/MainForm.cs +++ b/Greenshot/Forms/MainForm.cs @@ -908,7 +908,7 @@ namespace Greenshot { public void AddCaptureWindowMenuItems(ToolStripMenuItem menuItem, EventHandler eventHandler) { menuItem.DropDownItems.Clear(); // check if thumbnailPreview is enabled and DWM is enabled - bool thumbnailPreview = _conf.ThumnailPreview && DWM.isDWMEnabled(); + bool thumbnailPreview = _conf.ThumnailPreview && DWM.IsDwmEnabled(); List windows = WindowDetails.GetTopLevelWindows(); foreach(WindowDetails window in windows) { diff --git a/Greenshot/Forms/SettingsForm.cs b/Greenshot/Forms/SettingsForm.cs index 10b8cec7a..59f8c85be 100644 --- a/Greenshot/Forms/SettingsForm.cs +++ b/Greenshot/Forms/SettingsForm.cs @@ -146,7 +146,7 @@ namespace Greenshot { private void SetWindowCaptureMode(WindowCaptureMode selectedWindowCaptureMode) { WindowCaptureMode[] availableModes; - if (!DWM.isDWMEnabled()) { + if (!DWM.IsDwmEnabled()) { // Remove DWM from configuration, as DWM is disabled! if (coreConfiguration.WindowCaptureMode == WindowCaptureMode.Aero || coreConfiguration.WindowCaptureMode == WindowCaptureMode.AeroTransparent) { coreConfiguration.WindowCaptureMode = WindowCaptureMode.GDI; diff --git a/Greenshot/Helpers/CaptureHelper.cs b/Greenshot/Helpers/CaptureHelper.cs index 5d3868194..fa12e5e30 100644 --- a/Greenshot/Helpers/CaptureHelper.cs +++ b/Greenshot/Helpers/CaptureHelper.cs @@ -693,7 +693,10 @@ namespace Greenshot.Helpers { } else { _selectedCaptureWindow = WindowDetails.GetActiveWindow(); if (_selectedCaptureWindow != null) { - LOG.DebugFormat("Capturing window: {0} with {1}", _selectedCaptureWindow.Text, _selectedCaptureWindow.WindowRectangle); + if (LOG.IsDebugEnabled) + { + LOG.DebugFormat("Capturing window: {0} with {1}", _selectedCaptureWindow.Text, _selectedCaptureWindow.WindowRectangle); + } } } if (_selectedCaptureWindow == null || (!presupplied && _selectedCaptureWindow.Iconic)) { @@ -731,7 +734,6 @@ namespace Greenshot.Helpers { // Trying workaround, the size 0 arrises with e.g. Toad.exe, has a different Window when minimized WindowDetails linkedWindow = WindowDetails.GetLinkedWindow(windowToCapture); if (linkedWindow != null) { - windowRectangle = linkedWindow.WindowRectangle; windowToCapture = linkedWindow; } else { return null; @@ -777,7 +779,7 @@ namespace Greenshot.Helpers { Rectangle windowRectangle = windowToCapture.WindowRectangle; // When Vista & DWM (Aero) enabled - bool dwmEnabled = DWM.isDWMEnabled(); + bool dwmEnabled = DWM.IsDwmEnabled(); // get process name to be able to exclude certain processes from certain capture modes using (Process process = windowToCapture.Process) { bool isAutoMode = windowCaptureMode == WindowCaptureMode.Auto; @@ -801,7 +803,7 @@ namespace Greenshot.Helpers { windowCaptureMode = WindowCaptureMode.Screen; // Change to GDI, if allowed - if (!windowToCapture.isMetroApp && WindowCapture.IsGdiAllowed(process)) { + if (!windowToCapture.IsMetroApp && WindowCapture.IsGdiAllowed(process)) { if (!dwmEnabled && isWPF(process)) { // do not use GDI, as DWM is not enabled and the application uses PresentationFramework.dll -> isWPF LOG.InfoFormat("Not using GDI for windows of process {0}, as the process uses WPF", process.ProcessName); @@ -812,12 +814,12 @@ namespace Greenshot.Helpers { // Change to DWM, if enabled and allowed if (dwmEnabled) { - if (windowToCapture.isMetroApp || WindowCapture.IsDwmAllowed(process)) { + if (windowToCapture.IsMetroApp || WindowCapture.IsDwmAllowed(process)) { windowCaptureMode = WindowCaptureMode.Aero; } } } else if (windowCaptureMode == WindowCaptureMode.Aero || windowCaptureMode == WindowCaptureMode.AeroTransparent) { - if (!dwmEnabled || (!windowToCapture.isMetroApp && !WindowCapture.IsDwmAllowed(process))) { + if (!dwmEnabled || (!windowToCapture.IsMetroApp && !WindowCapture.IsDwmAllowed(process))) { // Take default screen windowCaptureMode = WindowCaptureMode.Screen; // Change to GDI, if allowed @@ -845,32 +847,32 @@ namespace Greenshot.Helpers { } else { windowToCapture.ToForeground(); } - tmpCapture = windowToCapture.CaptureGDIWindow(captureForWindow); + tmpCapture = windowToCapture.CaptureGdiWindow(captureForWindow); if (tmpCapture != null) { // check if GDI capture any good, by comparing it with the screen content - int blackCountGDI = ImageHelper.CountColor(tmpCapture.Image, Color.Black, false); - int GDIPixels = tmpCapture.Image.Width * tmpCapture.Image.Height; - int blackPercentageGDI = blackCountGDI * 100 / GDIPixels; - if (blackPercentageGDI >= 1) { + int blackCountGdi = ImageHelper.CountColor(tmpCapture.Image, Color.Black, false); + int gdiPixels = tmpCapture.Image.Width * tmpCapture.Image.Height; + int blackPercentageGdi = blackCountGdi * 100 / gdiPixels; + if (blackPercentageGdi >= 1) { int screenPixels = windowRectangle.Width * windowRectangle.Height; using (ICapture screenCapture = new Capture()) { screenCapture.CaptureDetails = captureForWindow.CaptureDetails; if (WindowCapture.CaptureRectangleFromDesktopScreen(screenCapture, windowRectangle) != null) { int blackCountScreen = ImageHelper.CountColor(screenCapture.Image, Color.Black, false); int blackPercentageScreen = blackCountScreen * 100 / screenPixels; - if (screenPixels == GDIPixels) { + if (screenPixels == gdiPixels) { // "easy compare", both have the same size // If GDI has more black, use the screen capture. - if (blackPercentageGDI > blackPercentageScreen) { + if (blackPercentageGdi > blackPercentageScreen) { LOG.Debug("Using screen capture, as GDI had additional black."); // changeing the image will automatically dispose the previous tmpCapture.Image = screenCapture.Image; // Make sure it's not disposed, else the picture is gone! screenCapture.NullImage(); } - } else if (screenPixels < GDIPixels) { + } else if (screenPixels < gdiPixels) { // Screen capture is cropped, window is outside of screen - if (blackPercentageGDI > 50 && blackPercentageGDI > blackPercentageScreen) { + if (blackPercentageGdi > 50 && blackPercentageGdi > blackPercentageScreen) { LOG.Debug("Using screen capture, as GDI had additional black."); // changeing the image will automatically dispose the previous tmpCapture.Image = screenCapture.Image; @@ -896,8 +898,8 @@ namespace Greenshot.Helpers { break; case WindowCaptureMode.Aero: case WindowCaptureMode.AeroTransparent: - if (windowToCapture.isMetroApp || WindowCapture.IsDwmAllowed(process)) { - tmpCapture = windowToCapture.CaptureDWMWindow(captureForWindow, windowCaptureMode, isAutoMode); + if (windowToCapture.IsMetroApp || WindowCapture.IsDwmAllowed(process)) { + tmpCapture = windowToCapture.CaptureDwmWindow(captureForWindow, windowCaptureMode, isAutoMode); } if (tmpCapture != null) { captureForWindow = tmpCapture; diff --git a/Greenshot/releases/additional_files/readme.txt.template b/Greenshot/releases/additional_files/readme.txt.template index 3668769d5..f836f567f 100644 --- a/Greenshot/releases/additional_files/readme.txt.template +++ b/Greenshot/releases/additional_files/readme.txt.template @@ -35,6 +35,7 @@ This version has changes, compared to 1.2.8.12, for the following reported ticke * BUG-1941: Error when creating speech bubble| * BUG-1945: Failure starting Greenshot at system startup| * BUG-1949: Can't delete Imgur upload +* BUG-1965: Activation border around window is visible in the capture * FEATURE-945: Added environment variables to the external command Testing is not finished, use at your own risk... diff --git a/GreenshotPlugin/Controls/ThumbnailForm.cs b/GreenshotPlugin/Controls/ThumbnailForm.cs index 121798e00..4155eef9f 100644 --- a/GreenshotPlugin/Controls/ThumbnailForm.cs +++ b/GreenshotPlugin/Controls/ThumbnailForm.cs @@ -77,10 +77,10 @@ namespace GreenshotPlugin.Controls { SIZE sourceSize; DWM.DwmQueryThumbnailSourceSize(_thumbnailHandle, out sourceSize); int thumbnailHeight = 200; - int thumbnailWidth = (int)(thumbnailHeight * ((float)sourceSize.width / (float)sourceSize.height)); + int thumbnailWidth = (int)(thumbnailHeight * ((float)sourceSize.Width / (float)sourceSize.Height)); if (parentControl != null && thumbnailWidth > parentControl.Width) { thumbnailWidth = parentControl.Width; - thumbnailHeight = (int)(thumbnailWidth * ((float)sourceSize.height / (float)sourceSize.width)); + thumbnailHeight = (int)(thumbnailWidth * ((float)sourceSize.Height / (float)sourceSize.Width)); } Width = thumbnailWidth; Height = thumbnailHeight; diff --git a/GreenshotPlugin/Core/WindowsHelper.cs b/GreenshotPlugin/Core/WindowsHelper.cs index 0fa642128..08259c1bd 100644 --- a/GreenshotPlugin/Core/WindowsHelper.cs +++ b/GreenshotPlugin/Core/WindowsHelper.cs @@ -26,6 +26,7 @@ using GreenshotPlugin.UnmanagedHelpers; using log4net; using System; using System.Collections.Generic; +using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; @@ -34,12 +35,6 @@ using System.Text; 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 /// @@ -139,7 +134,7 @@ namespace GreenshotPlugin.Core { /// Window handle to add /// 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)); } return true; @@ -150,12 +145,16 @@ namespace GreenshotPlugin.Core { // nothing to do } #endregion - } + } #endregion EnumWindows - /// #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 /// @@ -165,9 +164,9 @@ namespace GreenshotPlugin.Core { private const string METRO_GUTTER_CLASS = "ImmersiveGutter"; private static readonly ILog LOG = LogManager.GetLogger(typeof(WindowDetails)); - private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); - private static readonly List ignoreHandles = new List(); - private static readonly List excludeProcessesFromFreeze = new List(); + 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() { @@ -180,33 +179,33 @@ namespace GreenshotPlugin.Core { } public static void AddProcessToExcludeFromFreeze(string processname) { - if (!excludeProcessesFromFreeze.Contains(processname)) { - excludeProcessesFromFreeze.Add(processname); + if (!ExcludeProcessesFromFreeze.Contains(processname)) { + ExcludeProcessesFromFreeze.Add(processname); } } - internal static bool isIgnoreHandle(IntPtr handle) { - return ignoreHandles.Contains(handle); + internal static bool IsIgnoreHandle(IntPtr handle) { + return IgnoreHandles.Contains(handle); } - private List childWindows; - private IntPtr parentHandle = IntPtr.Zero; - private WindowDetails parent; - private bool frozen; + private List _childWindows; + private IntPtr _parentHandle = IntPtr.Zero; + private WindowDetails _parent; + private bool _frozen; - public bool isApp { + public bool IsApp { get { return METRO_WINDOWS_CLASS.Equals(ClassName); } } - public bool isGutter { + public bool IsGutter { get { return METRO_GUTTER_CLASS.Equals(ClassName); } } - public bool isAppLauncher { + public bool IsAppLauncher { get { return METRO_APPLAUNCHER_CLASS.Equals(ClassName); } @@ -215,16 +214,16 @@ namespace GreenshotPlugin.Core { /// /// 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 readonly IntPtr hWnd = IntPtr.Zero; + private readonly IntPtr _hWnd = IntPtr.Zero; /// /// To allow items to be compared, the hash code @@ -257,15 +256,15 @@ namespace GreenshotPlugin.Core { 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 { @@ -297,7 +296,7 @@ namespace GreenshotPlugin.Core { 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; } @@ -321,8 +320,8 @@ namespace GreenshotPlugin.Core { 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) { iconHandle = User32.GetClassLongWrapper(hwnd, (int)ClassLongIndex.GCL_HICON); @@ -357,7 +356,7 @@ namespace GreenshotPlugin.Core { /// /// public static void RegisterIgnoreHandle(IntPtr ignoreHandle) { - ignoreHandles.Add(ignoreHandle); + IgnoreHandles.Add(ignoreHandle); } /// @@ -365,24 +364,25 @@ namespace GreenshotPlugin.Core { /// /// 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 + /// List WindowDetails with all the found windows private static List FindWindow(List windows, string titlePattern, string classnamePattern) { List foundWindows = new List(); Regex titleRegexp = null; @@ -430,16 +430,16 @@ namespace GreenshotPlugin.Core { public IntPtr ParentHandle { get { - if (parentHandle == IntPtr.Zero) { - parentHandle = User32.GetParent(Handle); - parent = null; + if (_parentHandle == IntPtr.Zero) { + _parentHandle = User32.GetParent(Handle); + _parent = null; } - return parentHandle; + return _parentHandle; } set { - if (parentHandle != value) { - parentHandle = value; - parent = null; + if (_parentHandle != value) { + _parentHandle = value; + _parent = null; } } } @@ -448,15 +448,15 @@ namespace GreenshotPlugin.Core { /// /// WindowDetails of the parent, or null if none public WindowDetails GetParent() { - if (parent == null) { - if (parentHandle == IntPtr.Zero) { - parentHandle = User32.GetParent(Handle); + if (_parent == null) { + if (_parentHandle == IntPtr.Zero) { + _parentHandle = User32.GetParent(Handle); } - if (parentHandle != IntPtr.Zero) { - parent = new WindowDetails(parentHandle); + if (_parentHandle != IntPtr.Zero) { + _parent = new WindowDetails(_parentHandle); } } - return parent; + return _parent; } /// @@ -464,10 +464,10 @@ namespace GreenshotPlugin.Core { /// One should normally use the getter "Children" /// public List GetChildren() { - if (childWindows == null) { + if (_childWindows == null) { return GetChildren(0); } - return childWindows; + return _childWindows; } /// @@ -475,16 +475,16 @@ namespace GreenshotPlugin.Core { /// /// Specify how many levels we go in public List GetChildren(int levelsToGo) { - if (childWindows == null) { - childWindows = new List(); - foreach(WindowDetails childWindow in new WindowsEnumerator().GetWindows(hWnd, null).Items) { - childWindows.Add(childWindow); + if (_childWindows == null) { + _childWindows = new List(); + foreach(WindowDetails childWindow in new WindowsEnumerator().GetWindows(_hWnd, null).Items) { + _childWindows.Add(childWindow); if (levelsToGo > 0) { childWindow.GetChildren(levelsToGo-1); } } } - return childWindows; + return _childWindows; } /// @@ -492,7 +492,7 @@ namespace GreenshotPlugin.Core { /// /// 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); } @@ -500,7 +500,7 @@ namespace GreenshotPlugin.Core { /// /// Recursing helper method for the FindPath /// - /// List with classnames + /// List string with classnames /// The index in the list to look for /// WindowDetails if a match was found private WindowDetails FindPath(List classnames, int index) { @@ -542,6 +542,7 @@ namespace GreenshotPlugin.Core { /// /// Deep scan for a certain classname pattern /// + /// Window to scan into /// Classname regexp pattern /// The first WindowDetails found public static WindowDetails DeepScan(WindowDetails windowDetails, Regex classnamePattern) { @@ -575,7 +576,7 @@ namespace GreenshotPlugin.Core { return null; } WindowDetails windowDetails = new WindowDetails(tmphWnd); - windowDetails.parent = this; + windowDetails._parent = this; return windowDetails; } @@ -584,38 +585,38 @@ namespace GreenshotPlugin.Core { /// public IntPtr Handle { get { - return hWnd; + return _hWnd; } } - private string text; + private string _text; /// /// Gets the window's title (caption) /// 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; + private string _className; /// /// Gets the window's class name. /// public string ClassName { get { - if (className == null) { - className = GetClassName(hWnd); + if (_className == null) { + _className = GetClassName(_hWnd); } - return className; + return _className; } } @@ -624,16 +625,16 @@ namespace GreenshotPlugin.Core { /// 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); } } } @@ -643,7 +644,7 @@ namespace GreenshotPlugin.Core { /// public bool Maximised { get { - if (isApp) { + if (IsApp) { if (Visible) { Rectangle windowRectangle = WindowRectangle; foreach (Screen screen in Screen.AllScreens) { @@ -656,13 +657,13 @@ namespace GreenshotPlugin.Core { } 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); } } } @@ -679,7 +680,7 @@ namespace GreenshotPlugin.Core { /// public bool Visible { get { - if (isApp) { + if (IsApp) { Rectangle windowRectangle = WindowRectangle; foreach (Screen screen in Screen.AllScreens) { if (screen.Bounds.Contains(windowRectangle)) { @@ -705,21 +706,21 @@ namespace GreenshotPlugin.Core { } 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); } } public bool HasParent { get { GetParent(); - return parentHandle != IntPtr.Zero; + return _parentHandle != IntPtr.Zero; } } @@ -751,12 +752,12 @@ namespace GreenshotPlugin.Core { /// Make sure the next call of a cached value is guaranteed the real value /// public void Reset() { - previousWindowRectangle = Rectangle.Empty; + _previousWindowRectangle = Rectangle.Empty; } - private Rectangle previousWindowRectangle = Rectangle.Empty; - private long lastWindowRectangleRetrieveTime; - 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 /// @@ -764,39 +765,48 @@ namespace GreenshotPlugin.Core { get { // Try to return a cached value long now = DateTime.Now.Ticks; - if (previousWindowRectangle.IsEmpty || !frozen) { - if (previousWindowRectangle.IsEmpty || now - lastWindowRectangleRetrieveTime > CACHE_TIME) { + if (_previousWindowRectangle.IsEmpty || !_frozen) { + if (_previousWindowRectangle.IsEmpty || now - _lastWindowRectangleRetrieveTime > CacheTime) { Rectangle windowRect = Rectangle.Empty; - if (DWM.isDWMEnabled()) { + if (DWM.IsDwmEnabled() && !Maximised) { if (GetExtendedFrameBounds(out windowRect) && Environment.OSVersion.IsWindows10()) { - lastWindowRectangleRetrieveTime = now; - previousWindowRectangle = windowRect; - // DWM does it corectly, just return the window rectangle we just gotten. + _lastWindowRectangleRetrieveTime = now; + // 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; 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) { - 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)); + if (!HasParent && !IsApp && Maximised) { + 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; } } @@ -825,8 +835,12 @@ namespace GreenshotPlugin.Core { /// 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; } } @@ -846,10 +860,10 @@ namespace GreenshotPlugin.Core { /// 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) { Application.DoEvents(); @@ -861,10 +875,10 @@ namespace GreenshotPlugin.Core { /// 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)); } } @@ -887,10 +901,10 @@ namespace GreenshotPlugin.Core { /// 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)); } } @@ -899,7 +913,7 @@ namespace GreenshotPlugin.Core { /// /// The capture to fill /// ICapture - public ICapture CaptureGDIWindow(ICapture capture) { + public ICapture CaptureGdiWindow(ICapture capture) { Image capturedImage = PrintWindow(); if (capturedImage != null) { capture.Image = capturedImage; @@ -916,7 +930,7 @@ namespace GreenshotPlugin.Core { /// 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; @@ -935,13 +949,13 @@ namespace GreenshotPlugin.Core { 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 Rectangle windowRectangle = WindowRectangle; - Point formLocation = formLocation = windowRectangle.Location; + Point formLocation = windowRectangle.Location; Size borderSize = new Size(); bool doesCaptureFit = false; if (!Maximised) { @@ -950,7 +964,7 @@ namespace GreenshotPlugin.Core { using (Region workingArea = new Region(Screen.PrimaryScreen.Bounds)) { // 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); } } @@ -980,32 +994,34 @@ namespace GreenshotPlugin.Core { 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; - } else if (autoMode) { - // check if the capture fits - if (!doesCaptureFit) { - // if GDI is allowed.. (a screenshot won't be better than we comes if we continue) - using (Process thisWindowProcess = Process) { - if (!isMetroApp && WindowCapture.IsGdiAllowed(thisWindowProcess)) { - // we return null which causes the capturing code to try another method. - return null; + captureRectangle.Inflate(borderSize.Width, borderSize.Height); + } else { + captureRectangle.Inflate(-1, -1); + + if (autoMode) { + // check if the capture fits + if (!doesCaptureFit) { + // if GDI is allowed.. (a screenshot won't be better than we comes if we continue) + using (Process thisWindowProcess = Process) { + 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; @@ -1032,7 +1048,7 @@ namespace GreenshotPlugin.Core { 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(); } @@ -1055,7 +1071,7 @@ namespace GreenshotPlugin.Core { if (capturedBitmap == null) { // 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 { Color colorizationColor = DWM.ColorizationColor; // Modify by losing the transparency and increasing the intensity (as if the background color is white) @@ -1064,7 +1080,7 @@ namespace GreenshotPlugin.Core { } // 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(); } @@ -1077,7 +1093,7 @@ namespace GreenshotPlugin.Core { // Not needed for Windows 8 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)) { LOG.Debug("Changing pixelformat to Alpha for the RemoveCorners"); @@ -1122,8 +1138,8 @@ namespace GreenshotPlugin.Core { /// The bitmap to remove the corners from. private void RemoveCorners(Bitmap image) { using (IFastBitmap fastBitmap = FastBitmap.Create(image)) { - for (int y = 0; y < conf.WindowCornerCutShape.Count; y++) { - for (int x = 0; x < conf.WindowCornerCutShape[y]; x++) { + for (int y = 0; y < Conf.WindowCornerCutShape.Count; y++) { + for (int x = 0; x < Conf.WindowCornerCutShape[y]; x++) { fastBitmap.SetColorAt(x, y, Color.Transparent); fastBitmap.SetColorAt(image.Width-1-x, y, Color.Transparent); fastBitmap.SetColorAt(image.Width-1-x, image.Height-1-y, Color.Transparent); @@ -1230,7 +1246,7 @@ namespace GreenshotPlugin.Core { /// /// 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) { WindowInfo windowInfo = new WindowInfo(); @@ -1281,7 +1297,7 @@ namespace GreenshotPlugin.Core { return false; } - foreach (string excludeProcess in excludeProcessesFromFreeze) { + foreach (string excludeProcess in ExcludeProcessesFromFreeze) { if (titleOrProcessname.ToLower().Contains(excludeProcess)) { return false; } @@ -1409,7 +1425,7 @@ namespace GreenshotPlugin.Core { /// /// The Window Handle public WindowDetails(IntPtr hWnd) { - this.hWnd = hWnd; + this._hWnd = hWnd; } /// @@ -1419,7 +1435,7 @@ namespace GreenshotPlugin.Core { public static WindowDetails GetActiveWindow() { IntPtr hWnd = User32.GetForegroundWindow(); if (hWnd != null && hWnd != IntPtr.Zero) { - if (ignoreHandles.Contains(hWnd)) { + if (IgnoreHandles.Contains(hWnd)) { return GetDesktopWindow(); } @@ -1439,7 +1455,7 @@ namespace GreenshotPlugin.Core { public bool IsGreenshot { get { try { - if (!isMetroApp) { + if (!IsMetroApp) { using (Process thisWindowProcess = Process) { return "Greenshot".Equals(thisWindowProcess.MainModule.FileVersionInfo.ProductName); } @@ -1470,7 +1486,7 @@ namespace GreenshotPlugin.Core { /// /// 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; } @@ -1478,7 +1494,6 @@ namespace GreenshotPlugin.Core { /// /// Recursive "find children which" /// - /// Window to look into /// point to check for /// public WindowDetails FindChildUnderPoint(Point point) { @@ -1507,7 +1522,7 @@ namespace GreenshotPlugin.Core { /// /// 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(); Rectangle screenBounds = WindowCapture.GetScreenBounds(); @@ -1542,7 +1557,7 @@ namespace GreenshotPlugin.Core { /// 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(); // if the appVisibility != null we have Windows 8. @@ -1582,7 +1597,7 @@ namespace GreenshotPlugin.Core { /// /// Get all the top level windows /// - /// List with all the top level windows + /// List WindowDetails with all the top level windows public static List GetTopLevelWindows() { List windows = new List(); var possibleTopLevelWindows = GetMetroApps(); @@ -1660,7 +1675,7 @@ namespace GreenshotPlugin.Core { /// 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(); foreach(WindowDetails window in windowsAfter) { diff --git a/GreenshotPlugin/UnmanagedHelpers/DWM.cs b/GreenshotPlugin/UnmanagedHelpers/DWM.cs index 7a5c77b72..36950eca4 100644 --- a/GreenshotPlugin/UnmanagedHelpers/DWM.cs +++ b/GreenshotPlugin/UnmanagedHelpers/DWM.cs @@ -130,7 +130,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// 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 // DMW is always enabled on Windows 8! So return true and save a check! ;-) diff --git a/GreenshotPlugin/UnmanagedHelpers/Structs.cs b/GreenshotPlugin/UnmanagedHelpers/Structs.cs index e0e3cadcb..b3a8919a5 100644 --- a/GreenshotPlugin/UnmanagedHelpers/Structs.cs +++ b/GreenshotPlugin/UnmanagedHelpers/Structs.cs @@ -25,17 +25,17 @@ using System.Runtime.InteropServices; 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) { } 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); } } [StructLayout(LayoutKind.Sequential), Serializable()] diff --git a/appveyor12.yml b/appveyor12.yml index 05ac9b5b6..5c63431bf 100644 --- a/appveyor12.yml +++ b/appveyor12.yml @@ -67,12 +67,15 @@ deploy: auth_token: secure: 4sYcNGg7byBFtR7EkJHS8d3H3qP0u0LodlJWCV7g/4jEyv3vvVxqzh19zZ6Zgrf1 prerelease: true + draft: true on: build_type: UNSTABLE - provider: GitHub tag: Greenshot-$(build_type)-$(APPVEYOR_BUILD_VERSION) auth_token: secure: 4sYcNGg7byBFtR7EkJHS8d3H3qP0u0LodlJWCV7g/4jEyv3vvVxqzh19zZ6Zgrf1 + prerelease: false + draft: true on: build_type: RELEASE notifications: From bd71f47e95a46642fe6a83bdd76cc4d2a7eed7c2 Mon Sep 17 00:00:00 2001 From: Robin Date: Sun, 22 May 2016 13:13:07 +0200 Subject: [PATCH 12/19] Fixed a stacktrace overflow due recursive loop when processing Metro-Apps (Windows 8, which also run on 10) --- GreenshotPlugin/Core/WindowsHelper.cs | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/GreenshotPlugin/Core/WindowsHelper.cs b/GreenshotPlugin/Core/WindowsHelper.cs index 08259c1bd..1cd77fb91 100644 --- a/GreenshotPlugin/Core/WindowsHelper.cs +++ b/GreenshotPlugin/Core/WindowsHelper.cs @@ -159,7 +159,7 @@ namespace GreenshotPlugin.Core { /// 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"; @@ -193,6 +193,10 @@ namespace GreenshotPlugin.Core { private WindowDetails _parent; private bool _frozen; + /// + /// 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 { return METRO_WINDOWS_CLASS.Equals(ClassName); @@ -644,7 +648,8 @@ namespace GreenshotPlugin.Core { /// public bool Maximised { get { - if (IsApp) { + if (IsApp) + { if (Visible) { Rectangle windowRectangle = WindowRectangle; foreach (Screen screen in Screen.AllScreens) { @@ -758,6 +763,7 @@ namespace GreenshotPlugin.Core { private Rectangle _previousWindowRectangle = Rectangle.Empty; private long _lastWindowRectangleRetrieveTime; private const long CacheTime = TimeSpan.TicksPerSecond * 2; + /// /// Gets the bounding rectangle of the window /// @@ -768,14 +774,25 @@ namespace GreenshotPlugin.Core { if (_previousWindowRectangle.IsEmpty || !_frozen) { if (_previousWindowRectangle.IsEmpty || now - _lastWindowRectangleRetrieveTime > CacheTime) { Rectangle windowRect = Rectangle.Empty; - if (DWM.IsDwmEnabled() && !Maximised) { - if (GetExtendedFrameBounds(out windowRect) && Environment.OSVersion.IsWindows10()) + if (DWM.IsDwmEnabled()) + { + 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) { - _lastWindowRectangleRetrieveTime = now; // 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; } } From c02bd6ce6253644f1ab32eb922f2173c08a989bd Mon Sep 17 00:00:00 2001 From: Robin Date: Sun, 22 May 2016 13:16:28 +0200 Subject: [PATCH 13/19] Enhanced log statement [skip ci] --- GreenshotPlugin/Core/WindowsHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GreenshotPlugin/Core/WindowsHelper.cs b/GreenshotPlugin/Core/WindowsHelper.cs index 1cd77fb91..855dd79be 100644 --- a/GreenshotPlugin/Core/WindowsHelper.cs +++ b/GreenshotPlugin/Core/WindowsHelper.cs @@ -856,7 +856,7 @@ namespace GreenshotPlugin.Core { if (GetClientRect(out clientRect)) { Win32Error error = Win32.GetLastErrorCode(); - LOG.WarnFormat("Couldn't retrieve the client rectangle: {0}", Win32.GetMessage(error)); + LOG.WarnFormat("Couldn't retrieve the client rectangle for {0}, error: {1}", Text, Win32.GetMessage(error)); } return clientRect; } From 31db071394ab275e2a03eeafe2e7af84beac8094 Mon Sep 17 00:00:00 2001 From: Robin Date: Mon, 23 May 2016 13:32:52 +0200 Subject: [PATCH 14/19] Trying to replace the Gripper (which is a Label/Control) with adorners (custom code). This should prevent the slow cleanup, reduce resources and speedup the editor. Also we should have better "UI" feedback. This is still very experimental. --- Greenshot/Drawing/Adorners/GripperAdorner.cs | 232 ++++++++++++++++ Greenshot/Drawing/Adorners/TargetAdorner.cs | 177 ++++++++++++ Greenshot/Drawing/DrawableContainer.cs | 257 ++---------------- Greenshot/Drawing/DrawableContainerList.cs | 20 -- Greenshot/Drawing/FreehandContainer.cs | 18 +- Greenshot/Drawing/LineContainer.cs | 6 +- .../Drawing/{Gripper.cs => Positions.cs} | 44 +-- Greenshot/Drawing/SpeechbubbleContainer.cs | 6 +- Greenshot/Drawing/Surface.cs | 81 +++++- Greenshot/Greenshot.csproj | 6 +- Greenshot/Helpers/ScaleHelper.cs | 46 ++-- GreenshotPlugin/GreenshotPlugin.csproj | 1 + .../Interfaces/Drawing/Adorners/IAdorner.cs | 81 ++++++ .../Interfaces/Drawing/Container.cs | 15 +- GreenshotPlugin/Interfaces/Generic.cs | 2 + 15 files changed, 643 insertions(+), 349 deletions(-) create mode 100644 Greenshot/Drawing/Adorners/GripperAdorner.cs create mode 100644 Greenshot/Drawing/Adorners/TargetAdorner.cs rename Greenshot/Drawing/{Gripper.cs => Positions.cs} (54%) create mode 100644 GreenshotPlugin/Interfaces/Drawing/Adorners/IAdorner.cs diff --git a/Greenshot/Drawing/Adorners/GripperAdorner.cs b/Greenshot/Drawing/Adorners/GripperAdorner.cs new file mode 100644 index 000000000..532fdcedb --- /dev/null +++ b/Greenshot/Drawing/Adorners/GripperAdorner.cs @@ -0,0 +1,232 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/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 Greenshot.Helpers; +using Greenshot.Plugin; +using Greenshot.Plugin.Drawing; +using Greenshot.Plugin.Drawing.Adorners; +using System; +using System.Drawing; +using System.Windows.Forms; +using System.Drawing.Drawing2D; + +namespace Greenshot.Drawing.Adorners +{ + /// + /// This is the default "legacy" gripper adorner, not the one used for the tail in the speech-bubble + /// + public class GripperAdorner : IAdorner + { + private Rectangle _boundsBeforeResize = Rectangle.Empty; + private RectangleF _boundsAfterResize = RectangleF.Empty; + private EditStatus _editStatus; + + public Positions Position { get; private set; } + + public GripperAdorner(IDrawableContainer owner, Positions position) + { + Owner = owner; + Position = position; + } + + /// + /// Returns the cursor for when the mouse is over the adorner + /// + public Cursor Cursor + { + get + { + bool horizontalSwitched = Owner.Width < 0; + switch (Position) + { + case Positions.TopLeft: + case Positions.BottomRight: + return horizontalSwitched ? Cursors.SizeNWSE : Cursors.SizeNESW; + case Positions.TopRight: + case Positions.BottomLeft: + return horizontalSwitched ? Cursors.SizeNESW : Cursors.SizeNWSE; + case Positions.MiddleLeft: + case Positions.MiddleRight: + return Cursors.SizeWE; + case Positions.TopCenter: + case Positions.BottomCenter: + return Cursors.SizeNS; + default: + return Cursors.SizeAll; + } + } + } + + public IDrawableContainer Owner + { + get; + set; + } + + /// + /// Test if the point is inside the adorner + /// + /// + /// + public bool HitTest(Point point) + { + return Bounds.Contains(point); + } + + /// + /// Handle the mouse down + /// + /// + /// + public void MouseDown(object sender, MouseEventArgs mouseEventArgs) + { + _editStatus = EditStatus.RESIZING; + _boundsBeforeResize = new Rectangle(Owner.Left, Owner.Top, Owner.Width, Owner.Height); + _boundsAfterResize = _boundsBeforeResize; + } + + /// + /// Handle the mouse move + /// + /// + /// + public void MouseMove(object sender, MouseEventArgs mouseEventArgs) + { + Owner.Invalidate(); + int absX = Owner.Left + mouseEventArgs.X; + int absY = Owner.Top + mouseEventArgs.Y; + + if (_editStatus.Equals(EditStatus.RESIZING)) + { + Owner.MakeBoundsChangeUndoable(false); + + //SuspendLayout(); + + // reset "workbench" rectangle to current bounds + _boundsAfterResize.X = _boundsBeforeResize.X; + _boundsAfterResize.Y = _boundsBeforeResize.Y; + _boundsAfterResize.Width = _boundsBeforeResize.Width; + _boundsAfterResize.Height = _boundsBeforeResize.Height; + + // calculate scaled rectangle + ScaleHelper.Scale(ref _boundsAfterResize, Position, new PointF(absX, absY), ScaleHelper.GetScaleOptions()); + + // apply scaled bounds to this DrawableContainer + Owner.ApplyBounds(_boundsAfterResize); + + //ResumeLayout(); + Owner.DoLayout(); + } + Owner.Invalidate(); + } + + /// + /// Handle the mouse up + /// + /// + /// + public void MouseUp(object sender, MouseEventArgs mouseEventArgs) + { + _editStatus = EditStatus.IDLE; + Owner.Invalidate(); + } + + /// + /// Return the location of the adorner + /// + public Point Location { + get + { + int x = 0,y = 0; + switch (Position) + { + case Positions.TopLeft: + x = Owner.Left; + y = Owner.Top; + break; + case Positions.BottomLeft: + x = Owner.Left; + y = Owner.Top + Owner.Height; + break; + case Positions.MiddleLeft: + x = Owner.Left; + y = Owner.Top + (Owner.Height / 2); + break; + case Positions.TopCenter: + x = Owner.Left + (Owner.Width / 2); + y = Owner.Top; + break; + case Positions.BottomCenter: + x = Owner.Left + (Owner.Width / 2); + y = Owner.Top + Owner.Height; + break; + case Positions.TopRight: + x = Owner.Left + Owner.Width; + y = Owner.Top; + break; + case Positions.BottomRight: + x = Owner.Left + Owner.Width; + y = Owner.Top + Owner.Height; + break; + case Positions.MiddleRight: + x = Owner.Left + Owner.Width; + y = Owner.Top + (Owner.Height / 2); + break; + } + return new Point(x, y); + } + } + + /// + /// Return the bounds of the Adorner + /// + public Rectangle Bounds + { + get + { + Point location = Location; + Size size = new Size(10, 10); + return new Rectangle(location.X - (size.Width / 2), location.Y - (size.Height / 2), size.Width, size.Height); + } + } + + /// + /// Draw the adorner + /// + /// PaintEventArgs + public void Paint(PaintEventArgs paintEventArgs) + { + Graphics targetGraphics = paintEventArgs.Graphics; + Rectangle clipRectangle = paintEventArgs.ClipRectangle; + + var bounds = Bounds; + targetGraphics.DrawRectangle(Pens.Black, bounds.X, bounds.Y, bounds.Width , bounds.Height); + } + + /// + /// We ignore the Transform, as the coordinates are directly bound to those of the owner + /// + /// + public void Transform(Matrix matrix) + { + } + } +} diff --git a/Greenshot/Drawing/Adorners/TargetAdorner.cs b/Greenshot/Drawing/Adorners/TargetAdorner.cs new file mode 100644 index 000000000..965bed5a6 --- /dev/null +++ b/Greenshot/Drawing/Adorners/TargetAdorner.cs @@ -0,0 +1,177 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/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 Greenshot.Plugin.Drawing; +using Greenshot.Plugin.Drawing.Adorners; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; + +namespace Greenshot.Drawing.Adorners +{ + /// + /// This implements the special "gripper" for the Speech-Bubble tail + /// + public class TargetAdorner : IAdorner + { + private EditStatus _editStatus; + + public TargetAdorner(IDrawableContainer owner, Point location) + { + Owner = owner; + Location = location; + } + + /// + /// Returns the cursor for when the mouse is over the adorner + /// + public Cursor Cursor + { + get + { + return Cursors.SizeAll; + } + } + + public IDrawableContainer Owner + { + get; + set; + } + + /// + /// Test if the point is inside the adorner + /// + /// + /// + public bool HitTest(Point point) + { + return Bounds.Contains(point); + } + + /// + /// Handle the mouse down + /// + /// + /// + public void MouseDown(object sender, MouseEventArgs mouseEventArgs) + { + _editStatus = EditStatus.MOVING; + } + + /// + /// Handle the mouse move + /// + /// + /// + public void MouseMove(object sender, MouseEventArgs mouseEventArgs) + { + Owner.Invalidate(); + Point newGripperLocation = new Point(mouseEventArgs.X, mouseEventArgs.Y); + Rectangle surfaceBounds = new Rectangle(0, 0, Owner.Parent.Width, Owner.Parent.Height); + // Check if gripper inside the parent (surface), if not we need to move it inside + // This was made for BUG-1682 + if (!surfaceBounds.Contains(newGripperLocation)) + { + if (newGripperLocation.X > surfaceBounds.Right) + { + newGripperLocation.X = surfaceBounds.Right - 5; + } + if (newGripperLocation.X < surfaceBounds.Left) + { + newGripperLocation.X = surfaceBounds.Left; + } + if (newGripperLocation.Y > surfaceBounds.Bottom) + { + newGripperLocation.Y = surfaceBounds.Bottom - 5; + } + if (newGripperLocation.Y < surfaceBounds.Top) + { + newGripperLocation.Y = surfaceBounds.Top; + } + } + + Location = newGripperLocation; + Owner.Invalidate(); + } + + /// + /// Handle the mouse up + /// + /// + /// + public void MouseUp(object sender, MouseEventArgs mouseEventArgs) + { + _editStatus = EditStatus.IDLE; + Owner.Invalidate(); + } + + /// + /// Return the location of the adorner + /// + public Point Location + { + get; + set; + } + + /// + /// Return the bounds of the Adorner + /// + public Rectangle Bounds + { + get + { + Point location = Location; + Size size = new Size(10, 10); + return new Rectangle(location.X - (size.Width / 2), location.Y - (size.Height / 2), size.Width, size.Height); + } + } + + /// + /// Draw the adorner + /// + /// PaintEventArgs + public void Paint(PaintEventArgs paintEventArgs) + { + Graphics targetGraphics = paintEventArgs.Graphics; + Rectangle clipRectangle = paintEventArgs.ClipRectangle; + + var bounds = Bounds; + targetGraphics.DrawRectangle(Pens.Green, bounds.X, bounds.Y, bounds.Width, bounds.Height); + } + + /// + /// Made sure this adorner is transformed + /// + /// Matrix + public void Transform(Matrix matrix) + { + if (matrix == null) + { + return; + } + Point[] points = new[] { Location }; + matrix.TransformPoints(points); + Location = points[0]; + } + } +} diff --git a/Greenshot/Drawing/DrawableContainer.cs b/Greenshot/Drawing/DrawableContainer.cs index aa4ffce43..cdd7125d6 100644 --- a/Greenshot/Drawing/DrawableContainer.cs +++ b/Greenshot/Drawing/DrawableContainer.cs @@ -20,6 +20,7 @@ */ using Greenshot.Configuration; +using Greenshot.Drawing.Adorners; using Greenshot.Drawing.Fields; using Greenshot.Drawing.Filters; using Greenshot.Helpers; @@ -27,6 +28,7 @@ using Greenshot.IniFile; using Greenshot.Memento; using Greenshot.Plugin; using Greenshot.Plugin.Drawing; +using Greenshot.Plugin.Drawing.Adorners; using log4net; using System; using System.Collections.Generic; @@ -35,7 +37,8 @@ using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; -namespace Greenshot.Drawing { +namespace Greenshot.Drawing +{ /// /// represents a rectangle, ellipse, label or whatever. Can contain filters, too. /// serializable for clipboard support @@ -73,16 +76,6 @@ namespace Greenshot.Drawing { if (!disposing) { return; } - if (_grippers != null) { - for (int i = 0; i < _grippers.Length; i++) { - if (_grippers[i] == null) { - continue; - } - _grippers[i].Dispose(); - _grippers[i] = null; - } - _grippers = null; - } FieldAggregator aggProps = _parent.FieldAggregator; aggProps.UnbindElement(this); @@ -117,14 +110,13 @@ namespace Greenshot.Drawing { get { return _parent; } set { SwitchParent((Surface)value); } } - [NonSerialized] - protected Gripper[] _grippers; + private bool layoutSuspended; [NonSerialized] - private Gripper _targetGripper; + private TargetAdorner _targetGripper; - public Gripper TargetGripper { + public TargetAdorner TargetGripper { get { return _targetGripper; } @@ -220,6 +212,11 @@ namespace Greenshot.Drawing { } } + /// + /// List of available Adorners + /// + public IList Adorners { get; } = new List(); + [NonSerialized] // will store current bounds of this DrawableContainer before starting a resize protected Rectangle _boundsBeforeResize = Rectangle.Empty; @@ -329,73 +326,23 @@ namespace Greenshot.Drawing { DoLayout(); } - /// - /// Move the TargetGripper around, confined to the surface to solve BUG-1682 - /// - /// - /// - protected virtual void TargetGripperMove(int newX, int newY) { - Point newGripperLocation = new Point(newX, newY); - Rectangle surfaceBounds = new Rectangle(0, 0, _parent.Width, _parent.Height); - // Check if gripper inside the parent (surface), if not we need to move it inside - // This was made for BUG-1682 - if (!surfaceBounds.Contains(newGripperLocation)) { - if (newGripperLocation.X > surfaceBounds.Right) { - newGripperLocation.X = surfaceBounds.Right - 5; - } - if (newGripperLocation.X < surfaceBounds.Left) { - newGripperLocation.X = surfaceBounds.Left; - } - if (newGripperLocation.Y > surfaceBounds.Bottom) { - newGripperLocation.Y = surfaceBounds.Bottom - 5; - } - if (newGripperLocation.Y < surfaceBounds.Top) { - newGripperLocation.Y = surfaceBounds.Top; - } - } - - _targetGripper.Left = newGripperLocation.X; - _targetGripper.Top = newGripperLocation.Y; - } - /// /// Initialize a target gripper /// protected void InitTargetGripper(Color gripperColor, Point location) { - _targetGripper = new Gripper { - Cursor = Cursors.SizeAll, - BackColor = gripperColor, - Visible = false, - Parent = _parent, - Location = location - }; - _targetGripper.MouseDown += GripperMouseDown; - _targetGripper.MouseUp += GripperMouseUp; - _targetGripper.MouseMove += GripperMouseMove; - if (_parent != null) { - _parent.Controls.Add(_targetGripper); // otherwise we'll attach them in switchParent - } + _targetGripper = new TargetAdorner(this, location); } protected void InitGrippers() { - - _grippers = new Gripper[8]; - for(int i=0; i<_grippers.Length; i++) { - _grippers[i] = new Gripper(); - _grippers[i].Position = i; - _grippers[i].MouseDown += GripperMouseDown; - _grippers[i].MouseUp += GripperMouseUp; - _grippers[i].MouseMove += GripperMouseMove; - _grippers[i].Visible = false; - _grippers[i].Parent = _parent; - } - _grippers[Gripper.POSITION_TOP_CENTER].Cursor = Cursors.SizeNS; - _grippers[Gripper.POSITION_MIDDLE_RIGHT].Cursor = Cursors.SizeWE; - _grippers[Gripper.POSITION_BOTTOM_CENTER].Cursor = Cursors.SizeNS; - _grippers[Gripper.POSITION_MIDDLE_LEFT].Cursor = Cursors.SizeWE; - if (_parent != null) { - _parent.Controls.AddRange(_grippers); // otherwise we'll attach them in switchParent - } + // Create the GripperAdorners + Adorners.Add(new GripperAdorner(this, Positions.TopLeft)); + Adorners.Add(new GripperAdorner(this, Positions.TopCenter)); + Adorners.Add(new GripperAdorner(this, Positions.TopRight)); + Adorners.Add(new GripperAdorner(this, Positions.BottomLeft)); + Adorners.Add(new GripperAdorner(this, Positions.BottomCenter)); + Adorners.Add(new GripperAdorner(this, Positions.BottomRight)); + Adorners.Add(new GripperAdorner(this, Positions.MiddleLeft)); + Adorners.Add(new GripperAdorner(this, Positions.MiddleRight)); } public void SuspendLayout() { @@ -407,101 +354,8 @@ namespace Greenshot.Drawing { DoLayout(); } - protected virtual void DoLayout() { - if (_grippers == null) { - return; - } - if (!layoutSuspended) { - int[] xChoords = {Left-2,Left+Width/2-2,Left+Width-2}; - int[] yChoords = {Top-2,Top+Height/2-2,Top+Height-2}; + public virtual void DoLayout() { - _grippers[Gripper.POSITION_TOP_LEFT].Left = xChoords[0]; _grippers[Gripper.POSITION_TOP_LEFT].Top = yChoords[0]; - _grippers[Gripper.POSITION_TOP_CENTER].Left = xChoords[1]; _grippers[Gripper.POSITION_TOP_CENTER].Top = yChoords[0]; - _grippers[Gripper.POSITION_TOP_RIGHT].Left = xChoords[2]; _grippers[Gripper.POSITION_TOP_RIGHT].Top = yChoords[0]; - _grippers[Gripper.POSITION_MIDDLE_RIGHT].Left = xChoords[2]; _grippers[Gripper.POSITION_MIDDLE_RIGHT].Top = yChoords[1]; - _grippers[Gripper.POSITION_BOTTOM_RIGHT].Left = xChoords[2]; _grippers[Gripper.POSITION_BOTTOM_RIGHT].Top = yChoords[2]; - _grippers[Gripper.POSITION_BOTTOM_CENTER].Left = xChoords[1]; _grippers[Gripper.POSITION_BOTTOM_CENTER].Top = yChoords[2]; - _grippers[Gripper.POSITION_BOTTOM_LEFT].Left = xChoords[0]; _grippers[Gripper.POSITION_BOTTOM_LEFT].Top = yChoords[2]; - _grippers[Gripper.POSITION_MIDDLE_LEFT].Left = xChoords[0]; _grippers[Gripper.POSITION_MIDDLE_LEFT].Top = yChoords[1]; - - if((_grippers[Gripper.POSITION_TOP_LEFT].Left < _grippers[Gripper.POSITION_BOTTOM_RIGHT].Left && _grippers[Gripper.POSITION_TOP_LEFT].Top < _grippers[Gripper.POSITION_BOTTOM_RIGHT].Top) || - _grippers[Gripper.POSITION_TOP_LEFT].Left > _grippers[Gripper.POSITION_BOTTOM_RIGHT].Left && _grippers[Gripper.POSITION_TOP_LEFT].Top > _grippers[Gripper.POSITION_BOTTOM_RIGHT].Top) { - _grippers[Gripper.POSITION_TOP_LEFT].Cursor = Cursors.SizeNWSE; - _grippers[Gripper.POSITION_TOP_RIGHT].Cursor = Cursors.SizeNESW; - _grippers[Gripper.POSITION_BOTTOM_RIGHT].Cursor = Cursors.SizeNWSE; - _grippers[Gripper.POSITION_BOTTOM_LEFT].Cursor = Cursors.SizeNESW; - } else if((_grippers[Gripper.POSITION_TOP_LEFT].Left > _grippers[Gripper.POSITION_BOTTOM_RIGHT].Left && _grippers[Gripper.POSITION_TOP_LEFT].Top < _grippers[Gripper.POSITION_BOTTOM_RIGHT].Top) || - _grippers[Gripper.POSITION_TOP_LEFT].Left < _grippers[Gripper.POSITION_BOTTOM_RIGHT].Left && _grippers[Gripper.POSITION_TOP_LEFT].Top > _grippers[Gripper.POSITION_BOTTOM_RIGHT].Top) { - _grippers[Gripper.POSITION_TOP_LEFT].Cursor = Cursors.SizeNESW; - _grippers[Gripper.POSITION_TOP_RIGHT].Cursor = Cursors.SizeNWSE; - _grippers[Gripper.POSITION_BOTTOM_RIGHT].Cursor = Cursors.SizeNESW; - _grippers[Gripper.POSITION_BOTTOM_LEFT].Cursor = Cursors.SizeNWSE; - } else if (_grippers[Gripper.POSITION_TOP_LEFT].Left == _grippers[Gripper.POSITION_BOTTOM_RIGHT].Left) { - _grippers[Gripper.POSITION_TOP_LEFT].Cursor = Cursors.SizeNS; - _grippers[Gripper.POSITION_BOTTOM_RIGHT].Cursor = Cursors.SizeNS; - } else if (_grippers[Gripper.POSITION_TOP_LEFT].Top == _grippers[Gripper.POSITION_BOTTOM_RIGHT].Top) { - _grippers[Gripper.POSITION_TOP_LEFT].Cursor = Cursors.SizeWE; - _grippers[Gripper.POSITION_BOTTOM_RIGHT].Cursor = Cursors.SizeWE; - } - } - } - - private void GripperMouseDown(object sender, MouseEventArgs e) { - Gripper originatingGripper = (Gripper)sender; - if (originatingGripper != _targetGripper) { - Status = EditStatus.RESIZING; - _boundsBeforeResize = new Rectangle(left, top, width, height); - _boundsAfterResize = new RectangleF(_boundsBeforeResize.Left, _boundsBeforeResize.Top, _boundsBeforeResize.Width, _boundsBeforeResize.Height); - } else { - Status = EditStatus.MOVING; - } - isMadeUndoable = false; - } - - private void GripperMouseUp(object sender, MouseEventArgs e) { - Gripper originatingGripper = (Gripper)sender; - if (originatingGripper != _targetGripper) { - _boundsBeforeResize = Rectangle.Empty; - _boundsAfterResize = RectangleF.Empty; - isMadeUndoable = false; - } - Status = EditStatus.IDLE; - Invalidate(); - } - - private void GripperMouseMove(object sender, MouseEventArgs e) { - Invalidate(); - Gripper originatingGripper = (Gripper)sender; - int absX = originatingGripper.Left + e.X; - int absY = originatingGripper.Top + e.Y; - if (originatingGripper == _targetGripper && Status.Equals(EditStatus.MOVING)) { - TargetGripperMove(absX, absY); - } else if (Status.Equals(EditStatus.RESIZING)) { - // check if we already made this undoable - if (!isMadeUndoable) { - // don't allow another undo until we are finished with this move - isMadeUndoable = true; - // Make undo-able - MakeBoundsChangeUndoable(false); - } - - SuspendLayout(); - - // reset "workbench" rectangle to current bounds - _boundsAfterResize.X = _boundsBeforeResize.X; - _boundsAfterResize.Y = _boundsBeforeResize.Y; - _boundsAfterResize.Width = _boundsBeforeResize.Width; - _boundsAfterResize.Height = _boundsBeforeResize.Height; - - // calculate scaled rectangle - ScaleHelper.Scale(ref _boundsAfterResize, originatingGripper.Position, new PointF(absX, absY), ScaleHelper.GetScaleOptions()); - - // apply scaled bounds to this DrawableContainer - ApplyBounds(_boundsAfterResize); - - ResumeLayout(); - } - Invalidate(); } public bool hasFilters { @@ -558,38 +412,6 @@ namespace Greenshot.Drawing { } } - public virtual void ShowGrippers() { - if (_grippers != null) { - for (int i = 0; i < _grippers.Length; i++) { - if (_grippers[i].Enabled) { - _grippers[i].Show(); - } else { - _grippers[i].Hide(); - } - } - } - if (_targetGripper != null) { - if (_targetGripper.Enabled) { - _targetGripper.Show(); - } else { - _targetGripper.Hide(); - } - } - ResumeLayout(); - } - - public virtual void HideGrippers() { - SuspendLayout(); - if (_grippers != null) { - for (int i = 0; i < _grippers.Length; i++) { - _grippers[i].Hide(); - } - } - if (_targetGripper != null) { - _targetGripper.Hide(); - } - } - public void ResizeTo(int width, int height, int anchorPosition) { SuspendLayout(); Width = width; @@ -659,28 +481,6 @@ namespace Greenshot.Drawing { } protected virtual void SwitchParent(Surface newParent) { - // Target gripper - if (_parent != null && _targetGripper != null) { - _parent.Controls.Remove(_targetGripper); - } - // Normal grippers - if (_parent != null && _grippers != null) { - for (int i=0; i<_grippers.Length; i++) { - _parent.Controls.Remove(_grippers[i]); - } - } else if (_grippers == null) { - InitControls(); - } - _parent = newParent; - // Target gripper - if (_parent != null && _targetGripper != null) { - _parent.Controls.Add(_targetGripper); - } - // Normal grippers - if (_grippers != null) { - _parent.Controls.AddRange(_grippers); - } - foreach(IFilter filter in Filters) { filter.Parent = this; } @@ -778,22 +578,13 @@ namespace Greenshot.Drawing { SuspendLayout(); Point topLeft = new Point(Left, Top); Point bottomRight = new Point(Left + Width, Top + Height); - Point[] points; - if (TargetGripper != null) { - points = new[] {topLeft, bottomRight, TargetGripper.Location}; - - } else { - points = new[] { topLeft, bottomRight }; - } + Point[] points = new[] { topLeft, bottomRight }; matrix.TransformPoints(points); Left = points[0].X; Top = points[0].Y; Width = points[1].X - points[0].X; Height = points[1].Y - points[0].Y; - if (TargetGripper != null) { - TargetGripper.Location = points[points.Length-1]; - } ResumeLayout(); } diff --git a/Greenshot/Drawing/DrawableContainerList.cs b/Greenshot/Drawing/DrawableContainerList.cs index 570949a40..5dd4bb79d 100644 --- a/Greenshot/Drawing/DrawableContainerList.cs +++ b/Greenshot/Drawing/DrawableContainerList.cs @@ -171,26 +171,6 @@ namespace Greenshot.Drawing { } } - /// - /// Hides the grippers of all elements in the list. - /// - public void HideGrippers() { - foreach(var dc in this) { - dc.HideGrippers(); - dc.Invalidate(); - } - } - - /// - /// Shows the grippers of all elements in the list. - /// - public void ShowGrippers() { - foreach(var dc in this) { - dc.ShowGrippers(); - dc.Invalidate(); - } - } - /// /// Indicates whether on of the elements is clickable at the given location /// diff --git a/Greenshot/Drawing/FreehandContainer.cs b/Greenshot/Drawing/FreehandContainer.cs index b30937c2b..553d28294 100644 --- a/Greenshot/Drawing/FreehandContainer.cs +++ b/Greenshot/Drawing/FreehandContainer.cs @@ -63,12 +63,7 @@ namespace Greenshot.Drawing { protected void Init() { - if (_grippers != null) { - for (int i = 0; i < _grippers.Length; i++) { - _grippers[i].Enabled = false; - _grippers[i].Visible = false; - } - } + // TODO: Remove grippers } public override void Transform(Matrix matrix) { @@ -258,17 +253,6 @@ namespace Greenshot.Drawing { return freehandPath.GetHashCode(); } - /// - /// This is overriden to prevent the grippers to be modified. - /// Might not be the best way... - /// - protected override void DoLayout() { - } - - public override void ShowGrippers() { - ResumeLayout(); - } - public override bool ClickableAt(int x, int y) { bool returnValue = base.ClickableAt(x, y); if (returnValue) { diff --git a/Greenshot/Drawing/LineContainer.cs b/Greenshot/Drawing/LineContainer.cs index 4189134ac..37357b4fa 100644 --- a/Greenshot/Drawing/LineContainer.cs +++ b/Greenshot/Drawing/LineContainer.cs @@ -53,11 +53,7 @@ namespace Greenshot.Drawing { } protected void Init() { - if (_grippers != null) { - foreach (int index in new[] { 1, 2, 3, 5, 6, 7 }) { - _grippers[index].Enabled = false; - } - } + // TODO: Remove the unneeded grippers (1, 2, 3, 5, 6, 7) } public override void Draw(Graphics graphics, RenderMode rm) { diff --git a/Greenshot/Drawing/Gripper.cs b/Greenshot/Drawing/Positions.cs similarity index 54% rename from Greenshot/Drawing/Gripper.cs rename to Greenshot/Drawing/Positions.cs index 7a65fc57a..63d7cb759 100644 --- a/Greenshot/Drawing/Gripper.cs +++ b/Greenshot/Drawing/Positions.cs @@ -19,38 +19,20 @@ * along with this program. If not, see . */ -using System.Drawing; -using System.Windows.Forms; - -namespace Greenshot.Drawing { +namespace Greenshot.Drawing +{ /// - /// Grippers are the dragable edges of our containers + /// Position /// - public class Gripper : Label { - /// - /// Constants for anchor/gripper position: - /// 0 1 2 - /// 7 3 - /// 6 5 4 - /// - public const int POSITION_TOP_LEFT = 0; - public const int POSITION_TOP_CENTER = 1; - public const int POSITION_TOP_RIGHT = 2; - public const int POSITION_MIDDLE_RIGHT = 3; - public const int POSITION_BOTTOM_RIGHT = 4; - public const int POSITION_BOTTOM_CENTER = 5; - public const int POSITION_BOTTOM_LEFT = 6; - public const int POSITION_MIDDLE_LEFT = 7; - - public int Position { - get; - set; - } - - public Gripper() { - Width = 5; - Height = 5; - BackColor = Color.Black; - } + public enum Positions : int + { + TopLeft = 0, + TopCenter = 1, + TopRight = 2, + MiddleRight = 3, + BottomRight = 4, + BottomCenter = 5, + BottomLeft = 6, + MiddleLeft = 7 } } diff --git a/Greenshot/Drawing/SpeechbubbleContainer.cs b/Greenshot/Drawing/SpeechbubbleContainer.cs index 64ede51e8..6b2f6e7ba 100644 --- a/Greenshot/Drawing/SpeechbubbleContainer.cs +++ b/Greenshot/Drawing/SpeechbubbleContainer.cs @@ -118,7 +118,7 @@ namespace Greenshot.Drawing { if (TargetGripper.Location != newGripperLocation) { Invalidate(); - TargetGripperMove(newGripperLocation.X, newGripperLocation.Y); + TargetGripper.Location = newGripperLocation; Invalidate(); } return returnValue; @@ -180,7 +180,7 @@ namespace Greenshot.Drawing { 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.Location.X, TargetGripper.Location.Y); int tailWidth = (Math.Abs(rect.Width) + Math.Abs(rect.Height)) / 20; // This should fix a problem with the tail being to wide @@ -192,7 +192,7 @@ namespace Greenshot.Drawing { 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.Location.X, TargetGripper.Location.Y); using (Matrix tailMatrix = new Matrix()) { tailMatrix.Translate(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2)); diff --git a/Greenshot/Drawing/Surface.cs b/Greenshot/Drawing/Surface.cs index b28e2a86f..2dd451493 100644 --- a/Greenshot/Drawing/Surface.cs +++ b/Greenshot/Drawing/Surface.cs @@ -21,12 +21,14 @@ using Greenshot.Configuration; using Greenshot.Core; +using Greenshot.Drawing.Adorners; using Greenshot.Drawing.Fields; using Greenshot.Helpers; using Greenshot.IniFile; using Greenshot.Memento; using Greenshot.Plugin; using Greenshot.Plugin.Drawing; +using Greenshot.Plugin.Drawing.Adorners; using GreenshotPlugin.Controls; using GreenshotPlugin.Core; using log4net; @@ -991,12 +993,45 @@ namespace Greenshot.Drawing { Invalidate(); } + /// + /// Check if an adorner was "hit", and change the cursor if so + /// + /// MouseEventArgs + /// IAdorner + private IAdorner AdornersHitTest(MouseEventArgs mouseEventArgs) + { + foreach(IDrawableContainer drawableContainer in selectedElements) + { + foreach(IAdorner adorner in drawableContainer.Adorners) + { + if (adorner.HitTest(mouseEventArgs.Location)) + { + if (adorner.Cursor != null) + { + Cursor = adorner.Cursor; + } + return adorner; + } + } + } + return null; + } + /// /// This event handler is called when someone presses the mouse on a surface. /// /// /// void SurfaceMouseDown(object sender, MouseEventArgs e) { + + // Handle Adorners + var adorner = AdornersHitTest(e); + if (adorner != null) + { + adorner.MouseDown(sender, e); + return; + } + _mouseStart = e.Location; // check contextmenu @@ -1065,6 +1100,15 @@ namespace Greenshot.Drawing { /// /// void SurfaceMouseUp(object sender, MouseEventArgs e) { + + // Handle Adorners + var adorner = AdornersHitTest(e); + if (adorner != null) + { + adorner.MouseUp(sender, e); + return; + } + Point currentMouse = new Point(e.X, e.Y); _elements.Status = EditStatus.IDLE; @@ -1098,7 +1142,7 @@ namespace Greenshot.Drawing { } if (selectedElements.Count > 0) { - selectedElements.ShowGrippers(); + selectedElements.Invalidate(); selectedElements.Selected = true; } @@ -1126,6 +1170,14 @@ namespace Greenshot.Drawing { /// /// void SurfaceMouseMove(object sender, MouseEventArgs e) { + // Handle Adorners + var adorner = AdornersHitTest(e); + if (adorner != null) + { + adorner.MouseMove(sender, e); + return; + } + Point currentMouse = e.Location; if (DrawingMode != DrawingModes.None) { @@ -1137,7 +1189,7 @@ namespace Greenshot.Drawing { if (_mouseDown) { if (_mouseDownElement != null) { // an element is currently dragged _mouseDownElement.Invalidate(); - selectedElements.HideGrippers(); + selectedElements.Invalidate(); // Move the element if (_mouseDownElement.Selected) { if (!_isSurfaceMoveMadeUndoable) { @@ -1203,15 +1255,15 @@ namespace Greenshot.Drawing { public Image GetImageForExport() { return GetImage(RenderMode.EXPORT); } - + /// /// This is the event handler for the Paint Event, try to draw as little as possible! /// /// - /// - void SurfacePaint(object sender, PaintEventArgs e) { - Graphics targetGraphics = e.Graphics; - Rectangle clipRectangle = e.ClipRectangle; + /// PaintEventArgs + void SurfacePaint(object sender, PaintEventArgs paintEventArgs) { + Graphics targetGraphics = paintEventArgs.Graphics; + Rectangle clipRectangle = paintEventArgs.ClipRectangle; if (Rectangle.Empty.Equals(clipRectangle)) { LOG.Debug("Empty cliprectangle??"); return; @@ -1246,6 +1298,15 @@ namespace Greenshot.Drawing { targetGraphics.DrawImage(Image, clipRectangle, clipRectangle, GraphicsUnit.Pixel); _elements.Draw(targetGraphics, null, RenderMode.EDIT, clipRectangle); } + + // Draw adorners last + foreach(var drawableContainer in selectedElements) + { + foreach(var adorner in drawableContainer.Adorners) + { + adorner.Paint(paintEventArgs); + } + } } private void DrawBackground(Graphics targetGraphics, Rectangle clipRectangle) { @@ -1531,9 +1592,9 @@ namespace Greenshot.Drawing { /// /// public void DeselectElement(IDrawableContainer container) { - container.HideGrippers(); container.Selected = false; selectedElements.Remove(container); + container.Invalidate(); FieldAggregator.UnbindElement(container); if (_movingElementChanged != null) { SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs(); @@ -1549,10 +1610,9 @@ namespace Greenshot.Drawing { if (HasSelectedElements) { while(selectedElements.Count > 0) { IDrawableContainer element = selectedElements[0]; - element.Invalidate(); - element.HideGrippers(); element.Selected = false; selectedElements.Remove(element); + element.Invalidate(); FieldAggregator.UnbindElement(element); } if (_movingElementChanged != null) { @@ -1570,7 +1630,6 @@ namespace Greenshot.Drawing { public void SelectElement(IDrawableContainer container) { if (!selectedElements.Contains(container)) { selectedElements.Add(container); - container.ShowGrippers(); container.Selected = true; FieldAggregator.BindElement(container); if (_movingElementChanged != null) { diff --git a/Greenshot/Greenshot.csproj b/Greenshot/Greenshot.csproj index ee50aa76a..8a1c1de40 100644 --- a/Greenshot/Greenshot.csproj +++ b/Greenshot/Greenshot.csproj @@ -75,7 +75,10 @@ + + + @@ -101,9 +104,6 @@ - - Component - diff --git a/Greenshot/Helpers/ScaleHelper.cs b/Greenshot/Helpers/ScaleHelper.cs index 77557fc73..ffab1be15 100644 --- a/Greenshot/Helpers/ScaleHelper.cs +++ b/Greenshot/Helpers/ScaleHelper.cs @@ -119,15 +119,15 @@ namespace Greenshot.Helpers { return GetAlignedRectangle(newRect, targetRect, alignment); } - public static void RationalScale(ref RectangleF originalRectangle, int resizeHandlePosition, PointF resizeHandleCoords) { + public static void RationalScale(ref RectangleF originalRectangle, Positions resizeHandlePosition, PointF resizeHandleCoords) { Scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords, ScaleOptions.Rational); } - public static void CenteredScale(ref RectangleF originalRectangle, int resizeHandlePosition, PointF resizeHandleCoords) { + public static void CenteredScale(ref RectangleF originalRectangle, Positions resizeHandlePosition, PointF resizeHandleCoords) { Scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords, ScaleOptions.Centered); } - public static void Scale(ref RectangleF originalRectangle, int resizeHandlePosition, PointF resizeHandleCoords) { + public static void Scale(ref RectangleF originalRectangle, Positions resizeHandlePosition, PointF resizeHandleCoords) { Scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords, null); } @@ -138,7 +138,7 @@ namespace Greenshot.Helpers { /// position of the handle/gripper being used for resized, see constants in Gripper.cs, e.g. Gripper.POSITION_TOP_LEFT /// coordinates of the used handle/gripper /// ScaleOptions to use when scaling - public static void Scale(ref RectangleF originalRectangle, int resizeHandlePosition, PointF resizeHandleCoords, ScaleOptions? options) { + public static void Scale(ref RectangleF originalRectangle, Positions resizeHandlePosition, PointF resizeHandleCoords, ScaleOptions? options) { if(options == null) { options = GetScaleOptions(); } @@ -157,7 +157,7 @@ namespace Greenshot.Helpers { resizeHandleCoords.X -= 2 * (resizeHandleCoords.X - rectCenterX); resizeHandleCoords.Y -= 2 * (resizeHandleCoords.Y - rectCenterY); // scale again with opposing handle and mirrored coordinates - resizeHandlePosition = (resizeHandlePosition + 4) % 8; + resizeHandlePosition = (Positions)((((int)resizeHandlePosition) + 4) % 8); scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords); } else { scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords); @@ -171,47 +171,47 @@ namespace Greenshot.Helpers { /// bounds of the current rectangle, scaled values will be written to this reference /// position of the handle/gripper being used for resized, see constants in Gripper.cs, e.g. Gripper.POSITION_TOP_LEFT /// coordinates of the used handle/gripper - private static void scale(ref RectangleF originalRectangle, int resizeHandlePosition, PointF resizeHandleCoords) { + private static void scale(ref RectangleF originalRectangle, Positions resizeHandlePosition, PointF resizeHandleCoords) { switch(resizeHandlePosition) { - case Gripper.POSITION_TOP_LEFT: + case Positions.TopLeft: originalRectangle.Width = originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X; originalRectangle.Height = originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y; originalRectangle.X = resizeHandleCoords.X; originalRectangle.Y = resizeHandleCoords.Y; break; - case Gripper.POSITION_TOP_CENTER: + case Positions.TopCenter: originalRectangle.Height = originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y; originalRectangle.Y = resizeHandleCoords.Y; break; - case Gripper.POSITION_TOP_RIGHT: + case Positions.TopRight: originalRectangle.Width = resizeHandleCoords.X - originalRectangle.Left; originalRectangle.Height = originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y; originalRectangle.Y = resizeHandleCoords.Y; break; - case Gripper.POSITION_MIDDLE_LEFT: + case Positions.MiddleLeft: originalRectangle.Width = originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X; originalRectangle.X = resizeHandleCoords.X; break; - case Gripper.POSITION_MIDDLE_RIGHT: + case Positions.MiddleRight: originalRectangle.Width = resizeHandleCoords.X - originalRectangle.Left; break; - case Gripper.POSITION_BOTTOM_LEFT: + case Positions.BottomLeft: originalRectangle.Width = originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X; originalRectangle.Height = resizeHandleCoords.Y - originalRectangle.Top; originalRectangle.X = resizeHandleCoords.X; break; - case Gripper.POSITION_BOTTOM_CENTER: + case Positions.BottomCenter: originalRectangle.Height = resizeHandleCoords.Y - originalRectangle.Top; break; - case Gripper.POSITION_BOTTOM_RIGHT: + case Positions.BottomRight: originalRectangle.Width = resizeHandleCoords.X - originalRectangle.Left; originalRectangle.Height = resizeHandleCoords.Y - originalRectangle.Top; break; @@ -221,19 +221,19 @@ namespace Greenshot.Helpers { } } - + /// /// Adjusts resizeHandleCoords so that aspect ratio is kept after resizing a given rectangle with provided arguments /// /// bounds of the current rectangle - /// position of the handle/gripper being used for resized, see constants in Gripper.cs, e.g. Gripper.POSITION_TOP_LEFT + /// position of the handle/gripper being used for resized, see Position /// coordinates of the used handle/gripper, adjusted coordinates will be written to this reference - private static void adjustCoordsForRationalScale(RectangleF originalRectangle, int resizeHandlePosition, ref PointF resizeHandleCoords) { + private static void adjustCoordsForRationalScale(RectangleF originalRectangle, Positions resizeHandlePosition, ref PointF resizeHandleCoords) { float originalRatio = originalRectangle.Width / originalRectangle.Height; float newWidth, newHeight, newRatio; switch(resizeHandlePosition) { - case Gripper.POSITION_TOP_LEFT: + case Positions.TopLeft: newWidth = originalRectangle.Right - resizeHandleCoords.X; newHeight = originalRectangle.Bottom - resizeHandleCoords.Y; newRatio = newWidth / newHeight; @@ -244,7 +244,7 @@ namespace Greenshot.Helpers { } break; - case Gripper.POSITION_TOP_RIGHT: + case Positions.TopRight: newWidth = resizeHandleCoords.X - originalRectangle.Left; newHeight = originalRectangle.Bottom - resizeHandleCoords.Y; newRatio = newWidth / newHeight; @@ -255,7 +255,7 @@ namespace Greenshot.Helpers { } break; - case Gripper.POSITION_BOTTOM_LEFT: + case Positions.BottomLeft: newWidth = originalRectangle.Right - resizeHandleCoords.X; newHeight = resizeHandleCoords.Y - originalRectangle.Top; newRatio = newWidth / newHeight; @@ -266,7 +266,7 @@ namespace Greenshot.Helpers { } break; - case Gripper.POSITION_BOTTOM_RIGHT: + case Positions.BottomRight: newWidth = resizeHandleCoords.X - originalRectangle.Left; newHeight = resizeHandleCoords.Y - originalRectangle.Top; newRatio = newWidth / newHeight; @@ -285,10 +285,10 @@ namespace Greenshot.Helpers { public static void Scale(Rectangle boundsBeforeResize, int cursorX, int cursorY, ref RectangleF boundsAfterResize, IDoubleProcessor angleRoundBehavior) { - Scale(boundsBeforeResize, Gripper.POSITION_TOP_LEFT, cursorX, cursorY, ref boundsAfterResize, angleRoundBehavior); + Scale(boundsBeforeResize, Positions.TopLeft, cursorX, cursorY, ref boundsAfterResize, angleRoundBehavior); } - public static void Scale(Rectangle boundsBeforeResize, int gripperPosition, int cursorX, int cursorY, ref RectangleF boundsAfterResize, IDoubleProcessor angleRoundBehavior) { + public static void Scale(Rectangle boundsBeforeResize, Positions gripperPosition, int cursorX, int cursorY, ref RectangleF boundsAfterResize, IDoubleProcessor angleRoundBehavior) { ScaleOptions opts = GetScaleOptions(); diff --git a/GreenshotPlugin/GreenshotPlugin.csproj b/GreenshotPlugin/GreenshotPlugin.csproj index 917a12654..bef018b9f 100644 --- a/GreenshotPlugin/GreenshotPlugin.csproj +++ b/GreenshotPlugin/GreenshotPlugin.csproj @@ -66,6 +66,7 @@ + diff --git a/GreenshotPlugin/Interfaces/Drawing/Adorners/IAdorner.cs b/GreenshotPlugin/Interfaces/Drawing/Adorners/IAdorner.cs new file mode 100644 index 000000000..cf3c3fa70 --- /dev/null +++ b/GreenshotPlugin/Interfaces/Drawing/Adorners/IAdorner.cs @@ -0,0 +1,81 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/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.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; + +namespace Greenshot.Plugin.Drawing.Adorners +{ + public interface IAdorner + { + /// + /// The owner of this adorner + /// + IDrawableContainer Owner { get; } + + /// + /// Is the current point "over" the Adorner? + /// If this is the case, the + /// + /// Point to test + /// true if so + bool HitTest(Point point); + + /// + /// Handle the MouseDown event + /// + /// + /// MouseEventArgs + void MouseDown(object sender, MouseEventArgs mouseEventArgs); + + /// + /// Handle the MouseUp event + /// + /// + /// MouseEventArgs + void MouseUp(object sender, MouseEventArgs mouseEventArgs); + + /// + /// Handle the MouseMove event + /// + /// + /// MouseEventArgs + void MouseMove(object sender, MouseEventArgs mouseEventArgs); + + /// + /// Gets the cursor that should be displayed for this behavior. + /// + Cursor Cursor { get; } + + /// + /// Draw the adorner + /// + /// PaintEventArgs + void Paint(PaintEventArgs paintEventArgs); + + /// + /// Called if the owner is transformed + /// + /// Matrix + void Transform(Matrix matrix); + } +} diff --git a/GreenshotPlugin/Interfaces/Drawing/Container.cs b/GreenshotPlugin/Interfaces/Drawing/Container.cs index 7be49e852..cd96f774b 100644 --- a/GreenshotPlugin/Interfaces/Drawing/Container.cs +++ b/GreenshotPlugin/Interfaces/Drawing/Container.cs @@ -24,6 +24,8 @@ using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Windows.Forms; using System.ComponentModel; +using System.Collections.Generic; +using Greenshot.Plugin.Drawing.Adorners; namespace Greenshot.Plugin.Drawing { public enum RenderMode {EDIT, EXPORT}; @@ -73,7 +75,11 @@ namespace Greenshot.Plugin.Drawing { Rectangle DrawingBounds { get; } - + + void ApplyBounds(RectangleF newBounds); + + void DoLayout(); + bool hasFilters { get; } @@ -85,8 +91,6 @@ namespace Greenshot.Plugin.Drawing { void AlignToParent(HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment); void Invalidate(); bool ClickableAt(int x, int y); - void HideGrippers(); - void ShowGrippers(); void MoveBy(int x, int y); void Transform(Matrix matrix); bool HandleMouseDown(int x, int y); @@ -97,6 +101,11 @@ namespace Greenshot.Plugin.Drawing { EditStatus DefaultEditMode { get; } + + /// + /// Available adorners for the DrawableContainer + /// + IList Adorners { get; } } public interface ITextContainer: IDrawableContainer { diff --git a/GreenshotPlugin/Interfaces/Generic.cs b/GreenshotPlugin/Interfaces/Generic.cs index 73e6c2cf6..ed49327dd 100644 --- a/GreenshotPlugin/Interfaces/Generic.cs +++ b/GreenshotPlugin/Interfaces/Generic.cs @@ -198,5 +198,7 @@ namespace Greenshot.Plugin { get; set; } + int Width { get; } + int Height { get; } } } \ No newline at end of file From 5b2d5b1397957020ff08e03a30e82dc287addc79 Mon Sep 17 00:00:00 2001 From: Robin Date: Mon, 23 May 2016 15:39:21 +0200 Subject: [PATCH 15/19] Fixed most adorner related drawing issues, need to test a few more (freehand) --- Greenshot/Drawing/Adorners/AbstractAdorner.cs | 147 ++++++++++++++++++ Greenshot/Drawing/Adorners/GripperAdorner.cs | 130 ++++++---------- Greenshot/Drawing/Adorners/TargetAdorner.cs | 83 ++-------- Greenshot/Drawing/DrawableContainer.cs | 1 + Greenshot/Drawing/Surface.cs | 11 +- Greenshot/Greenshot.csproj | 1 + .../Interfaces/Drawing/Adorners/IAdorner.cs | 10 ++ 7 files changed, 223 insertions(+), 160 deletions(-) create mode 100644 Greenshot/Drawing/Adorners/AbstractAdorner.cs diff --git a/Greenshot/Drawing/Adorners/AbstractAdorner.cs b/Greenshot/Drawing/Adorners/AbstractAdorner.cs new file mode 100644 index 000000000..685ec779f --- /dev/null +++ b/Greenshot/Drawing/Adorners/AbstractAdorner.cs @@ -0,0 +1,147 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/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 Greenshot.Plugin.Drawing; +using Greenshot.Plugin.Drawing.Adorners; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; +using System; + +namespace Greenshot.Drawing.Adorners +{ + public class AbstractAdorner : IAdorner + { + public virtual EditStatus EditStatus { get; protected set; } = EditStatus.IDLE; + + protected Size _size = new Size(4, 4); + + public AbstractAdorner(IDrawableContainer owner) + { + Owner = owner; + } + + /// + /// Returns the cursor for when the mouse is over the adorner + /// + public virtual Cursor Cursor + { + get + { + return Cursors.SizeAll; + } + } + + public virtual IDrawableContainer Owner + { + get; + set; + } + + /// + /// Test if the point is inside the adorner + /// + /// + /// + public virtual bool HitTest(Point point) + { + Rectangle hitBounds = Bounds; + hitBounds.Inflate(3, 3); + return hitBounds.Contains(point); + } + + /// + /// Handle the mouse down + /// + /// + /// + public virtual void MouseDown(object sender, MouseEventArgs mouseEventArgs) + { + } + + /// + /// Handle the mouse move + /// + /// + /// + public virtual void MouseMove(object sender, MouseEventArgs mouseEventArgs) + { + } + + /// + /// Handle the mouse up + /// + /// + /// + public virtual void MouseUp(object sender, MouseEventArgs mouseEventArgs) + { + EditStatus = EditStatus.IDLE; + } + + /// + /// Return the location of the adorner + /// + public virtual Point Location + { + get; + set; + } + + /// + /// Return the bounds of the Adorner + /// + public virtual Rectangle Bounds + { + get + { + Point location = Location; + return new Rectangle(location.X - (_size.Width / 2), location.Y - (_size.Height / 2), _size.Width, _size.Height); + } + } + + /// + /// The adorner is active if the edit status is not idle or undrawn + /// + public virtual bool IsActive + { + get + { + return EditStatus != EditStatus.IDLE && EditStatus != EditStatus.UNDRAWN; + } + } + + /// + /// Draw the adorner + /// + /// PaintEventArgs + public virtual void Paint(PaintEventArgs paintEventArgs) + { + } + + /// + /// We ignore the Transform, as the coordinates are directly bound to those of the owner + /// + /// + public virtual void Transform(Matrix matrix) + { + } + } +} diff --git a/Greenshot/Drawing/Adorners/GripperAdorner.cs b/Greenshot/Drawing/Adorners/GripperAdorner.cs index 532fdcedb..a550f5195 100644 --- a/Greenshot/Drawing/Adorners/GripperAdorner.cs +++ b/Greenshot/Drawing/Adorners/GripperAdorner.cs @@ -20,49 +20,49 @@ */ using Greenshot.Helpers; -using Greenshot.Plugin; using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing.Adorners; -using System; using System.Drawing; -using System.Windows.Forms; using System.Drawing.Drawing2D; +using System.Windows.Forms; namespace Greenshot.Drawing.Adorners { /// /// This is the default "legacy" gripper adorner, not the one used for the tail in the speech-bubble /// - public class GripperAdorner : IAdorner + public class GripperAdorner : AbstractAdorner { private Rectangle _boundsBeforeResize = Rectangle.Empty; private RectangleF _boundsAfterResize = RectangleF.Empty; - private EditStatus _editStatus; public Positions Position { get; private set; } - public GripperAdorner(IDrawableContainer owner, Positions position) + public GripperAdorner(IDrawableContainer owner, Positions position) : base(owner) { - Owner = owner; Position = position; } /// /// Returns the cursor for when the mouse is over the adorner /// - public Cursor Cursor + public override Cursor Cursor { get { - bool horizontalSwitched = Owner.Width < 0; + bool isNotSwitched = Owner.Width >= 0; + if (Owner.Height < 0) + { + isNotSwitched = !isNotSwitched; + } switch (Position) { case Positions.TopLeft: case Positions.BottomRight: - return horizontalSwitched ? Cursors.SizeNWSE : Cursors.SizeNESW; + return isNotSwitched ? Cursors.SizeNWSE : Cursors.SizeNESW; case Positions.TopRight: case Positions.BottomLeft: - return horizontalSwitched ? Cursors.SizeNESW : Cursors.SizeNWSE; + return isNotSwitched ? Cursors.SizeNESW : Cursors.SizeNWSE; case Positions.MiddleLeft: case Positions.MiddleRight: return Cursors.SizeWE; @@ -75,30 +75,14 @@ namespace Greenshot.Drawing.Adorners } } - public IDrawableContainer Owner - { - get; - set; - } - - /// - /// Test if the point is inside the adorner - /// - /// - /// - public bool HitTest(Point point) - { - return Bounds.Contains(point); - } - /// /// Handle the mouse down /// /// /// - public void MouseDown(object sender, MouseEventArgs mouseEventArgs) + public override void MouseDown(object sender, MouseEventArgs mouseEventArgs) { - _editStatus = EditStatus.RESIZING; + EditStatus = EditStatus.RESIZING; _boundsBeforeResize = new Rectangle(Owner.Left, Owner.Top, Owner.Width, Owner.Height); _boundsAfterResize = _boundsBeforeResize; } @@ -108,51 +92,39 @@ namespace Greenshot.Drawing.Adorners /// /// /// - public void MouseMove(object sender, MouseEventArgs mouseEventArgs) + public override void MouseMove(object sender, MouseEventArgs mouseEventArgs) { - Owner.Invalidate(); - int absX = Owner.Left + mouseEventArgs.X; - int absY = Owner.Top + mouseEventArgs.Y; - - if (_editStatus.Equals(EditStatus.RESIZING)) + if (EditStatus != EditStatus.RESIZING) { - Owner.MakeBoundsChangeUndoable(false); - - //SuspendLayout(); - - // reset "workbench" rectangle to current bounds - _boundsAfterResize.X = _boundsBeforeResize.X; - _boundsAfterResize.Y = _boundsBeforeResize.Y; - _boundsAfterResize.Width = _boundsBeforeResize.Width; - _boundsAfterResize.Height = _boundsBeforeResize.Height; - - // calculate scaled rectangle - ScaleHelper.Scale(ref _boundsAfterResize, Position, new PointF(absX, absY), ScaleHelper.GetScaleOptions()); - - // apply scaled bounds to this DrawableContainer - Owner.ApplyBounds(_boundsAfterResize); - - //ResumeLayout(); - Owner.DoLayout(); + return; } Owner.Invalidate(); - } + Owner.MakeBoundsChangeUndoable(false); + + //SuspendLayout(); + + // reset "workbench" rectangle to current bounds + _boundsAfterResize.X = _boundsBeforeResize.X; + _boundsAfterResize.Y = _boundsBeforeResize.Y; + _boundsAfterResize.Width = _boundsBeforeResize.Width; + _boundsAfterResize.Height = _boundsBeforeResize.Height; + + // calculate scaled rectangle + ScaleHelper.Scale(ref _boundsAfterResize, Position, new PointF(mouseEventArgs.X, mouseEventArgs.Y), ScaleHelper.GetScaleOptions()); + + // apply scaled bounds to this DrawableContainer + Owner.ApplyBounds(_boundsAfterResize); + + //ResumeLayout(); + Owner.DoLayout(); - /// - /// Handle the mouse up - /// - /// - /// - public void MouseUp(object sender, MouseEventArgs mouseEventArgs) - { - _editStatus = EditStatus.IDLE; Owner.Invalidate(); } /// /// Return the location of the adorner /// - public Point Location { + public override Point Location { get { int x = 0,y = 0; @@ -195,38 +167,26 @@ namespace Greenshot.Drawing.Adorners } } - /// - /// Return the bounds of the Adorner - /// - public Rectangle Bounds - { - get - { - Point location = Location; - Size size = new Size(10, 10); - return new Rectangle(location.X - (size.Width / 2), location.Y - (size.Height / 2), size.Width, size.Height); - } - } - /// /// Draw the adorner /// /// PaintEventArgs - public void Paint(PaintEventArgs paintEventArgs) + public override void Paint(PaintEventArgs paintEventArgs) { Graphics targetGraphics = paintEventArgs.Graphics; Rectangle clipRectangle = paintEventArgs.ClipRectangle; var bounds = Bounds; - targetGraphics.DrawRectangle(Pens.Black, bounds.X, bounds.Y, bounds.Width , bounds.Height); - } + GraphicsState state = targetGraphics.Save(); + + targetGraphics.SmoothingMode = SmoothingMode.None; + targetGraphics.CompositingMode = CompositingMode.SourceCopy; + targetGraphics.PixelOffsetMode = PixelOffsetMode.Half; + targetGraphics.InterpolationMode = InterpolationMode.NearestNeighbor; + + targetGraphics.FillRectangle(Brushes.Black, bounds.X, bounds.Y, bounds.Width , bounds.Height); + targetGraphics.Restore(state); - /// - /// We ignore the Transform, as the coordinates are directly bound to those of the owner - /// - /// - public void Transform(Matrix matrix) - { } } } diff --git a/Greenshot/Drawing/Adorners/TargetAdorner.cs b/Greenshot/Drawing/Adorners/TargetAdorner.cs index 965bed5a6..a2817421e 100644 --- a/Greenshot/Drawing/Adorners/TargetAdorner.cs +++ b/Greenshot/Drawing/Adorners/TargetAdorner.cs @@ -30,51 +30,22 @@ namespace Greenshot.Drawing.Adorners /// /// This implements the special "gripper" for the Speech-Bubble tail /// - public class TargetAdorner : IAdorner + public class TargetAdorner : AbstractAdorner { - private EditStatus _editStatus; - public TargetAdorner(IDrawableContainer owner, Point location) + public TargetAdorner(IDrawableContainer owner, Point location) : base(owner) { - Owner = owner; Location = location; } - /// - /// Returns the cursor for when the mouse is over the adorner - /// - public Cursor Cursor - { - get - { - return Cursors.SizeAll; - } - } - - public IDrawableContainer Owner - { - get; - set; - } - - /// - /// Test if the point is inside the adorner - /// - /// - /// - public bool HitTest(Point point) - { - return Bounds.Contains(point); - } - /// /// Handle the mouse down /// /// /// - public void MouseDown(object sender, MouseEventArgs mouseEventArgs) + public override void MouseDown(object sender, MouseEventArgs mouseEventArgs) { - _editStatus = EditStatus.MOVING; + EditStatus = EditStatus.MOVING; } /// @@ -82,8 +53,13 @@ namespace Greenshot.Drawing.Adorners /// /// /// - public void MouseMove(object sender, MouseEventArgs mouseEventArgs) + public override void MouseMove(object sender, MouseEventArgs mouseEventArgs) { + if (EditStatus != EditStatus.MOVING) + { + return; + } + Owner.Invalidate(); Point newGripperLocation = new Point(mouseEventArgs.X, mouseEventArgs.Y); Rectangle surfaceBounds = new Rectangle(0, 0, Owner.Parent.Width, Owner.Parent.Height); @@ -113,57 +89,24 @@ namespace Greenshot.Drawing.Adorners Owner.Invalidate(); } - /// - /// Handle the mouse up - /// - /// - /// - public void MouseUp(object sender, MouseEventArgs mouseEventArgs) - { - _editStatus = EditStatus.IDLE; - Owner.Invalidate(); - } - - /// - /// Return the location of the adorner - /// - public Point Location - { - get; - set; - } - - /// - /// Return the bounds of the Adorner - /// - public Rectangle Bounds - { - get - { - Point location = Location; - Size size = new Size(10, 10); - return new Rectangle(location.X - (size.Width / 2), location.Y - (size.Height / 2), size.Width, size.Height); - } - } - /// /// Draw the adorner /// /// PaintEventArgs - public void Paint(PaintEventArgs paintEventArgs) + public override void Paint(PaintEventArgs paintEventArgs) { Graphics targetGraphics = paintEventArgs.Graphics; Rectangle clipRectangle = paintEventArgs.ClipRectangle; var bounds = Bounds; - targetGraphics.DrawRectangle(Pens.Green, bounds.X, bounds.Y, bounds.Width, bounds.Height); + targetGraphics.FillRectangle(Brushes.Green, bounds.X, bounds.Y, bounds.Width, bounds.Height); } /// /// Made sure this adorner is transformed /// /// Matrix - public void Transform(Matrix matrix) + public override void Transform(Matrix matrix) { if (matrix == null) { diff --git a/Greenshot/Drawing/DrawableContainer.cs b/Greenshot/Drawing/DrawableContainer.cs index cdd7125d6..56f84c25d 100644 --- a/Greenshot/Drawing/DrawableContainer.cs +++ b/Greenshot/Drawing/DrawableContainer.cs @@ -331,6 +331,7 @@ namespace Greenshot.Drawing /// protected void InitTargetGripper(Color gripperColor, Point location) { _targetGripper = new TargetAdorner(this, location); + Adorners.Add(_targetGripper); } protected void InitGrippers() { diff --git a/Greenshot/Drawing/Surface.cs b/Greenshot/Drawing/Surface.cs index 2dd451493..71ebc154a 100644 --- a/Greenshot/Drawing/Surface.cs +++ b/Greenshot/Drawing/Surface.cs @@ -998,13 +998,14 @@ namespace Greenshot.Drawing { /// /// MouseEventArgs /// IAdorner - private IAdorner AdornersHitTest(MouseEventArgs mouseEventArgs) + private IAdorner FindActiveAdorner(MouseEventArgs mouseEventArgs) { foreach(IDrawableContainer drawableContainer in selectedElements) { foreach(IAdorner adorner in drawableContainer.Adorners) { - if (adorner.HitTest(mouseEventArgs.Location)) + + if (adorner.IsActive || adorner.HitTest(mouseEventArgs.Location)) { if (adorner.Cursor != null) { @@ -1025,7 +1026,7 @@ namespace Greenshot.Drawing { void SurfaceMouseDown(object sender, MouseEventArgs e) { // Handle Adorners - var adorner = AdornersHitTest(e); + var adorner = FindActiveAdorner(e); if (adorner != null) { adorner.MouseDown(sender, e); @@ -1102,7 +1103,7 @@ namespace Greenshot.Drawing { void SurfaceMouseUp(object sender, MouseEventArgs e) { // Handle Adorners - var adorner = AdornersHitTest(e); + var adorner = FindActiveAdorner(e); if (adorner != null) { adorner.MouseUp(sender, e); @@ -1171,7 +1172,7 @@ namespace Greenshot.Drawing { /// void SurfaceMouseMove(object sender, MouseEventArgs e) { // Handle Adorners - var adorner = AdornersHitTest(e); + var adorner = FindActiveAdorner(e); if (adorner != null) { adorner.MouseMove(sender, e); diff --git a/Greenshot/Greenshot.csproj b/Greenshot/Greenshot.csproj index 8a1c1de40..d92465c41 100644 --- a/Greenshot/Greenshot.csproj +++ b/Greenshot/Greenshot.csproj @@ -75,6 +75,7 @@ + diff --git a/GreenshotPlugin/Interfaces/Drawing/Adorners/IAdorner.cs b/GreenshotPlugin/Interfaces/Drawing/Adorners/IAdorner.cs index cf3c3fa70..27f825de4 100644 --- a/GreenshotPlugin/Interfaces/Drawing/Adorners/IAdorner.cs +++ b/GreenshotPlugin/Interfaces/Drawing/Adorners/IAdorner.cs @@ -27,6 +27,16 @@ namespace Greenshot.Plugin.Drawing.Adorners { public interface IAdorner { + /// + /// Returns if this adorner is active + /// + bool IsActive { get; } + + /// + /// The current edit status, this is needed to locate the adorner to send events to + /// + EditStatus EditStatus { get; } + /// /// The owner of this adorner /// From 9ab6bff116b7cd376161d0eff1c2b19bfeb61dd1 Mon Sep 17 00:00:00 2001 From: Robin Date: Mon, 23 May 2016 16:43:10 +0200 Subject: [PATCH 16/19] Fixed serialization issues, and made sure the arrow / line have the right adorners. --- Greenshot/Drawing/Adorners/MoveAdorner.cs | 165 ++++++++++++++++++ .../{GripperAdorner.cs => ResizeAdorner.cs} | 10 +- Greenshot/Drawing/Adorners/TargetAdorner.cs | 1 - Greenshot/Drawing/CropContainer.cs | 12 ++ Greenshot/Drawing/CursorContainer.cs | 15 +- Greenshot/Drawing/DrawableContainer.cs | 86 +++++---- Greenshot/Drawing/EllipseContainer.cs | 1 + .../Drawing/Fields/AbstractFieldHolder.cs | 2 +- .../Fields/AbstractFieldHolderWithChildren.cs | 4 +- Greenshot/Drawing/FilterContainer.cs | 13 ++ Greenshot/Drawing/FreehandContainer.cs | 12 +- Greenshot/Drawing/HighlightContainer.cs | 4 +- Greenshot/Drawing/IconContainer.cs | 13 ++ Greenshot/Drawing/ImageContainer.cs | 13 ++ Greenshot/Drawing/LineContainer.cs | 14 +- Greenshot/Drawing/ObfuscateContainer.cs | 7 +- Greenshot/Drawing/RectangleContainer.cs | 17 ++ Greenshot/Drawing/SpeechbubbleContainer.cs | 10 +- Greenshot/Drawing/StepLabelContainer.cs | 11 +- Greenshot/Drawing/Surface.cs | 8 +- Greenshot/Drawing/TextContainer.cs | 10 +- Greenshot/Greenshot.csproj | 3 +- .../Interfaces/Drawing/Container.cs | 3 +- 23 files changed, 335 insertions(+), 99 deletions(-) create mode 100644 Greenshot/Drawing/Adorners/MoveAdorner.cs rename Greenshot/Drawing/Adorners/{GripperAdorner.cs => ResizeAdorner.cs} (93%) diff --git a/Greenshot/Drawing/Adorners/MoveAdorner.cs b/Greenshot/Drawing/Adorners/MoveAdorner.cs new file mode 100644 index 000000000..78e00e2dd --- /dev/null +++ b/Greenshot/Drawing/Adorners/MoveAdorner.cs @@ -0,0 +1,165 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/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 Greenshot.Helpers; +using Greenshot.Plugin.Drawing; +using Greenshot.Plugin.Drawing.Adorners; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; + +namespace Greenshot.Drawing.Adorners +{ + /// + /// This is the adorner for the line based containers + /// + public class MoveAdorner : AbstractAdorner + { + private Rectangle _boundsBeforeResize = Rectangle.Empty; + private RectangleF _boundsAfterResize = RectangleF.Empty; + + public Positions Position { get; private set; } + + public MoveAdorner(IDrawableContainer owner, Positions position) : base(owner) + { + Position = position; + } + + /// + /// Returns the cursor for when the mouse is over the adorner + /// + public override Cursor Cursor + { + get + { + return Cursors.SizeAll; + } + } + + /// + /// Handle the mouse down + /// + /// + /// + public override void MouseDown(object sender, MouseEventArgs mouseEventArgs) + { + EditStatus = EditStatus.RESIZING; + _boundsBeforeResize = new Rectangle(Owner.Left, Owner.Top, Owner.Width, Owner.Height); + _boundsAfterResize = _boundsBeforeResize; + } + + /// + /// Handle the mouse move + /// + /// + /// + public override void MouseMove(object sender, MouseEventArgs mouseEventArgs) + { + if (EditStatus != EditStatus.RESIZING) + { + return; + } + Owner.Invalidate(); + Owner.MakeBoundsChangeUndoable(false); + + // reset "workbench" rectangle to current bounds + _boundsAfterResize.X = _boundsBeforeResize.X; + _boundsAfterResize.Y = _boundsBeforeResize.Y; + _boundsAfterResize.Width = _boundsBeforeResize.Width; + _boundsAfterResize.Height = _boundsBeforeResize.Height; + + // calculate scaled rectangle + ScaleHelper.Scale(ref _boundsAfterResize, Position, new PointF(mouseEventArgs.X, mouseEventArgs.Y), ScaleHelper.GetScaleOptions()); + + // apply scaled bounds to this DrawableContainer + Owner.ApplyBounds(_boundsAfterResize); + + Owner.Invalidate(); + } + + /// + /// Return the location of the adorner + /// + public override Point Location { + get + { + int x = 0,y = 0; + switch (Position) + { + case Positions.TopLeft: + x = Owner.Left; + y = Owner.Top; + break; + case Positions.BottomLeft: + x = Owner.Left; + y = Owner.Top + Owner.Height; + break; + case Positions.MiddleLeft: + x = Owner.Left; + y = Owner.Top + (Owner.Height / 2); + break; + case Positions.TopCenter: + x = Owner.Left + (Owner.Width / 2); + y = Owner.Top; + break; + case Positions.BottomCenter: + x = Owner.Left + (Owner.Width / 2); + y = Owner.Top + Owner.Height; + break; + case Positions.TopRight: + x = Owner.Left + Owner.Width; + y = Owner.Top; + break; + case Positions.BottomRight: + x = Owner.Left + Owner.Width; + y = Owner.Top + Owner.Height; + break; + case Positions.MiddleRight: + x = Owner.Left + Owner.Width; + y = Owner.Top + (Owner.Height / 2); + break; + } + return new Point(x, y); + } + } + + /// + /// Draw the adorner + /// + /// PaintEventArgs + public override void Paint(PaintEventArgs paintEventArgs) + { + Graphics targetGraphics = paintEventArgs.Graphics; + Rectangle clipRectangle = paintEventArgs.ClipRectangle; + + var bounds = Bounds; + GraphicsState state = targetGraphics.Save(); + + targetGraphics.SmoothingMode = SmoothingMode.None; + targetGraphics.CompositingMode = CompositingMode.SourceCopy; + targetGraphics.PixelOffsetMode = PixelOffsetMode.Half; + targetGraphics.InterpolationMode = InterpolationMode.NearestNeighbor; + + targetGraphics.FillRectangle(Brushes.Black, bounds.X, bounds.Y, bounds.Width , bounds.Height); + targetGraphics.Restore(state); + } + } +} diff --git a/Greenshot/Drawing/Adorners/GripperAdorner.cs b/Greenshot/Drawing/Adorners/ResizeAdorner.cs similarity index 93% rename from Greenshot/Drawing/Adorners/GripperAdorner.cs rename to Greenshot/Drawing/Adorners/ResizeAdorner.cs index a550f5195..da536b1f5 100644 --- a/Greenshot/Drawing/Adorners/GripperAdorner.cs +++ b/Greenshot/Drawing/Adorners/ResizeAdorner.cs @@ -31,14 +31,14 @@ namespace Greenshot.Drawing.Adorners /// /// This is the default "legacy" gripper adorner, not the one used for the tail in the speech-bubble /// - public class GripperAdorner : AbstractAdorner + public class ResizeAdorner : AbstractAdorner { private Rectangle _boundsBeforeResize = Rectangle.Empty; private RectangleF _boundsAfterResize = RectangleF.Empty; public Positions Position { get; private set; } - public GripperAdorner(IDrawableContainer owner, Positions position) : base(owner) + public ResizeAdorner(IDrawableContainer owner, Positions position) : base(owner) { Position = position; } @@ -101,8 +101,6 @@ namespace Greenshot.Drawing.Adorners Owner.Invalidate(); Owner.MakeBoundsChangeUndoable(false); - //SuspendLayout(); - // reset "workbench" rectangle to current bounds _boundsAfterResize.X = _boundsBeforeResize.X; _boundsAfterResize.Y = _boundsBeforeResize.Y; @@ -115,9 +113,6 @@ namespace Greenshot.Drawing.Adorners // apply scaled bounds to this DrawableContainer Owner.ApplyBounds(_boundsAfterResize); - //ResumeLayout(); - Owner.DoLayout(); - Owner.Invalidate(); } @@ -186,7 +181,6 @@ namespace Greenshot.Drawing.Adorners targetGraphics.FillRectangle(Brushes.Black, bounds.X, bounds.Y, bounds.Width , bounds.Height); targetGraphics.Restore(state); - } } } diff --git a/Greenshot/Drawing/Adorners/TargetAdorner.cs b/Greenshot/Drawing/Adorners/TargetAdorner.cs index a2817421e..27e499bac 100644 --- a/Greenshot/Drawing/Adorners/TargetAdorner.cs +++ b/Greenshot/Drawing/Adorners/TargetAdorner.cs @@ -20,7 +20,6 @@ */ using Greenshot.Plugin.Drawing; -using Greenshot.Plugin.Drawing.Adorners; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; diff --git a/Greenshot/Drawing/CropContainer.cs b/Greenshot/Drawing/CropContainer.cs index 676836f93..e1bf7a78a 100644 --- a/Greenshot/Drawing/CropContainer.cs +++ b/Greenshot/Drawing/CropContainer.cs @@ -20,6 +20,7 @@ */ using System.Drawing; +using System.Runtime.Serialization; using Greenshot.Drawing.Fields; using Greenshot.Helpers; using Greenshot.Plugin.Drawing; @@ -30,8 +31,19 @@ namespace Greenshot.Drawing { /// public class CropContainer : DrawableContainer { public CropContainer(Surface parent) : base(parent) { + Init(); } + protected override void OnDeserialized(StreamingContext streamingContext) + { + base.OnDeserialized(streamingContext); + Init(); + } + + private void Init() + { + CreateDefaultAdorners(); + } protected override void InitializeFields() { AddField(GetType(), FieldType.FLAGS, FieldType.Flag.CONFIRMABLE); } diff --git a/Greenshot/Drawing/CursorContainer.cs b/Greenshot/Drawing/CursorContainer.cs index 3911d5940..5d9d41b74 100644 --- a/Greenshot/Drawing/CursorContainer.cs +++ b/Greenshot/Drawing/CursorContainer.cs @@ -26,6 +26,7 @@ using System.Windows.Forms; using Greenshot.Plugin.Drawing; using System.Drawing.Drawing2D; using log4net; +using System.Runtime.Serialization; namespace Greenshot.Drawing { /// @@ -38,9 +39,21 @@ namespace Greenshot.Drawing { protected Cursor cursor; public CursorContainer(Surface parent) : base(parent) { + Init(); } - public CursorContainer(Surface parent, string filename) : base(parent) { + protected override void OnDeserialized(StreamingContext streamingContext) + { + base.OnDeserialized(streamingContext); + Init(); + } + + private void Init() + { + CreateDefaultAdorners(); + } + + public CursorContainer(Surface parent, string filename) : this(parent) { Load(filename); } diff --git a/Greenshot/Drawing/DrawableContainer.cs b/Greenshot/Drawing/DrawableContainer.cs index 56f84c25d..21971e5f7 100644 --- a/Greenshot/Drawing/DrawableContainer.cs +++ b/Greenshot/Drawing/DrawableContainer.cs @@ -35,6 +35,7 @@ using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; +using System.Runtime.Serialization; using System.Windows.Forms; namespace Greenshot.Drawing @@ -55,6 +56,20 @@ namespace Greenshot.Drawing private const int M21 = 2; private const int M22 = 3; + [OnDeserialized] + private void OnDeserializedInit(StreamingContext context) + { + _adorners = new List(); + OnDeserialized(context); + } + + /// + /// Override to implement your own deserialization logic, like initializing properties which are not serialized + /// + /// + protected virtual void OnDeserialized(StreamingContext streamingContext) + { + } protected EditStatus _defaultEditMode = EditStatus.DRAWING; public EditStatus DefaultEditMode { @@ -111,11 +126,8 @@ namespace Greenshot.Drawing set { SwitchParent((Surface)value); } } - private bool layoutSuspended; - [NonSerialized] private TargetAdorner _targetGripper; - public TargetAdorner TargetGripper { get { return _targetGripper; @@ -152,7 +164,6 @@ namespace Greenshot.Drawing return; } left = value; - DoLayout(); } } @@ -164,7 +175,6 @@ namespace Greenshot.Drawing return; } top = value; - DoLayout(); } } @@ -176,7 +186,6 @@ namespace Greenshot.Drawing return; } width = value; - DoLayout(); } } @@ -188,7 +197,6 @@ namespace Greenshot.Drawing return; } height = value; - DoLayout(); } } @@ -215,7 +223,15 @@ namespace Greenshot.Drawing /// /// List of available Adorners /// - public IList Adorners { get; } = new List(); + [NonSerialized] + private IList _adorners = new List(); + public IList Adorners + { + get + { + return _adorners; + } + } [NonSerialized] // will store current bounds of this DrawableContainer before starting a resize @@ -245,7 +261,6 @@ namespace Greenshot.Drawing public DrawableContainer(Surface parent) { InitializeFields(); _parent = parent; - InitControls(); } public void Add(IFilter filter) { @@ -319,12 +334,6 @@ namespace Greenshot.Drawing public virtual bool InitContent() { return true; } public virtual void OnDoubleClick() {} - - private void InitControls() { - InitGrippers(); - - DoLayout(); - } /// /// Initialize a target gripper @@ -334,29 +343,23 @@ namespace Greenshot.Drawing Adorners.Add(_targetGripper); } - protected void InitGrippers() { + /// + /// Create the default adorners for a rectangle based container + /// + protected void CreateDefaultAdorners() { + if (Adorners.Count > 0) + { + LOG.Warn("Adorners are already defined!"); + } // Create the GripperAdorners - Adorners.Add(new GripperAdorner(this, Positions.TopLeft)); - Adorners.Add(new GripperAdorner(this, Positions.TopCenter)); - Adorners.Add(new GripperAdorner(this, Positions.TopRight)); - Adorners.Add(new GripperAdorner(this, Positions.BottomLeft)); - Adorners.Add(new GripperAdorner(this, Positions.BottomCenter)); - Adorners.Add(new GripperAdorner(this, Positions.BottomRight)); - Adorners.Add(new GripperAdorner(this, Positions.MiddleLeft)); - Adorners.Add(new GripperAdorner(this, Positions.MiddleRight)); - } - - public void SuspendLayout() { - layoutSuspended = true; - } - - public void ResumeLayout() { - layoutSuspended = false; - DoLayout(); - } - - public virtual void DoLayout() { - + Adorners.Add(new ResizeAdorner(this, Positions.TopLeft)); + Adorners.Add(new ResizeAdorner(this, Positions.TopCenter)); + Adorners.Add(new ResizeAdorner(this, Positions.TopRight)); + Adorners.Add(new ResizeAdorner(this, Positions.BottomLeft)); + Adorners.Add(new ResizeAdorner(this, Positions.BottomCenter)); + Adorners.Add(new ResizeAdorner(this, Positions.BottomRight)); + Adorners.Add(new ResizeAdorner(this, Positions.MiddleLeft)); + Adorners.Add(new ResizeAdorner(this, Positions.MiddleRight)); } public bool hasFilters { @@ -414,10 +417,8 @@ namespace Greenshot.Drawing } public void ResizeTo(int width, int height, int anchorPosition) { - SuspendLayout(); Width = width; Height = height; - ResumeLayout(); } /// @@ -429,10 +430,8 @@ namespace Greenshot.Drawing } public void MoveBy(int dx, int dy) { - SuspendLayout(); Left += dx; Top += dy; - ResumeLayout(); } /// @@ -455,7 +454,6 @@ namespace Greenshot.Drawing /// true if the event is handled, false if the surface needs to handle it public virtual bool HandleMouseMove(int x, int y) { Invalidate(); - SuspendLayout(); // reset "workrbench" rectangle to current bounds _boundsAfterResize.X = _boundsBeforeResize.Left; @@ -468,7 +466,6 @@ namespace Greenshot.Drawing // apply scaled bounds to this DrawableContainer ApplyBounds(_boundsAfterResize); - ResumeLayout(); Invalidate(); return true; } @@ -482,6 +479,7 @@ namespace Greenshot.Drawing } protected virtual void SwitchParent(Surface newParent) { + _parent = newParent; foreach(IFilter filter in Filters) { filter.Parent = this; } @@ -576,7 +574,6 @@ namespace Greenshot.Drawing if (matrix == null) { return; } - SuspendLayout(); Point topLeft = new Point(Left, Top); Point bottomRight = new Point(Left + Width, Top + Height); Point[] points = new[] { topLeft, bottomRight }; @@ -586,7 +583,6 @@ namespace Greenshot.Drawing Top = points[0].Y; Width = points[1].X - points[0].X; Height = points[1].Y - points[0].Y; - ResumeLayout(); } protected virtual ScaleHelper.IDoubleProcessor GetAngleRoundProcessor() { diff --git a/Greenshot/Drawing/EllipseContainer.cs b/Greenshot/Drawing/EllipseContainer.cs index caf41824b..6873baf8a 100644 --- a/Greenshot/Drawing/EllipseContainer.cs +++ b/Greenshot/Drawing/EllipseContainer.cs @@ -33,6 +33,7 @@ namespace Greenshot.Drawing { [Serializable()] public class EllipseContainer : DrawableContainer { public EllipseContainer(Surface parent) : base(parent) { + CreateDefaultAdorners(); } protected override void InitializeFields() { diff --git a/Greenshot/Drawing/Fields/AbstractFieldHolder.cs b/Greenshot/Drawing/Fields/AbstractFieldHolder.cs index 0f8df4937..e1f91c6d4 100644 --- a/Greenshot/Drawing/Fields/AbstractFieldHolder.cs +++ b/Greenshot/Drawing/Fields/AbstractFieldHolder.cs @@ -55,7 +55,7 @@ namespace Greenshot.Drawing.Fields { public AbstractFieldHolder() {} [OnDeserialized] - private void OnDeserialized(StreamingContext context) { + private void OnFieldHolderDeserialized(StreamingContext context) { fieldsByType = new Dictionary(); // listen to changing properties foreach(Field field in fields) { diff --git a/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs b/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs index b919edd9b..1680e7c22 100644 --- a/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs +++ b/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs @@ -46,8 +46,8 @@ namespace Greenshot.Drawing.Fields { fieldChangedEventHandler = OnFieldChanged; } - [OnDeserialized()] - private void OnDeserialized(StreamingContext context) { + [OnDeserialized] + private void OnFieldHolderWithChildrenDeserialized(StreamingContext context) { // listen to changing properties foreach(IFieldHolder fieldHolder in Children) { fieldHolder.FieldChanged += fieldChangedEventHandler; diff --git a/Greenshot/Drawing/FilterContainer.cs b/Greenshot/Drawing/FilterContainer.cs index 630c5c35d..40bb93e95 100644 --- a/Greenshot/Drawing/FilterContainer.cs +++ b/Greenshot/Drawing/FilterContainer.cs @@ -24,6 +24,7 @@ using Greenshot.Drawing.Fields; using Greenshot.Helpers; using Greenshot.Plugin.Drawing; using System.Drawing.Drawing2D; +using System.Runtime.Serialization; namespace Greenshot.Drawing { /// @@ -40,6 +41,18 @@ namespace Greenshot.Drawing { } public FilterContainer(Surface parent) : base(parent) { + Init(); + } + + protected override void OnDeserialized(StreamingContext streamingContext) + { + base.OnDeserialized(streamingContext); + Init(); + } + + private void Init() + { + CreateDefaultAdorners(); } protected override void InitializeFields() { diff --git a/Greenshot/Drawing/FreehandContainer.cs b/Greenshot/Drawing/FreehandContainer.cs index 553d28294..b51299037 100644 --- a/Greenshot/Drawing/FreehandContainer.cs +++ b/Greenshot/Drawing/FreehandContainer.cs @@ -49,7 +49,6 @@ namespace Greenshot.Drawing { /// Constructor /// public FreehandContainer(Surface parent) : base(parent) { - Init(); Width = parent.Width; Height = parent.Height; Top = 0; @@ -61,11 +60,6 @@ namespace Greenshot.Drawing { AddField(GetType(), FieldType.LINE_COLOR, Color.Red); } - - protected void Init() { - // TODO: Remove grippers - } - public override void Transform(Matrix matrix) { Point[] points = capturePoints.ToArray(); @@ -75,11 +69,7 @@ namespace Greenshot.Drawing { RecalculatePath(); } - [OnDeserialized] - private void OnDeserialized(StreamingContext context) { - InitGrippers(); - DoLayout(); - Init(); + protected override void OnDeserialized(StreamingContext context) { RecalculatePath(); } diff --git a/Greenshot/Drawing/HighlightContainer.cs b/Greenshot/Drawing/HighlightContainer.cs index aec48208f..0cb2791a5 100644 --- a/Greenshot/Drawing/HighlightContainer.cs +++ b/Greenshot/Drawing/HighlightContainer.cs @@ -43,8 +43,8 @@ namespace Greenshot.Drawing { AddField(GetType(), FieldType.PREPARED_FILTER_HIGHLIGHT, PreparedFilter.TEXT_HIGHTLIGHT); } - [OnDeserialized] - private void OnDeserialized(StreamingContext context) { + protected override void OnDeserialized(StreamingContext context) + { Init(); } diff --git a/Greenshot/Drawing/IconContainer.cs b/Greenshot/Drawing/IconContainer.cs index 86b82a46f..623e10bfc 100644 --- a/Greenshot/Drawing/IconContainer.cs +++ b/Greenshot/Drawing/IconContainer.cs @@ -24,6 +24,7 @@ using System.IO; using Greenshot.Plugin.Drawing; using System.Drawing.Drawing2D; using log4net; +using System.Runtime.Serialization; namespace Greenshot.Drawing { /// @@ -36,6 +37,18 @@ namespace Greenshot.Drawing { protected Icon icon; public IconContainer(Surface parent) : base(parent) { + Init(); + } + + protected override void OnDeserialized(StreamingContext streamingContext) + { + base.OnDeserialized(streamingContext); + Init(); + } + + private void Init() + { + CreateDefaultAdorners(); } public IconContainer(Surface parent, string filename) : base(parent) { diff --git a/Greenshot/Drawing/ImageContainer.cs b/Greenshot/Drawing/ImageContainer.cs index b9f9c6dc3..7c023bf2f 100644 --- a/Greenshot/Drawing/ImageContainer.cs +++ b/Greenshot/Drawing/ImageContainer.cs @@ -27,6 +27,7 @@ using GreenshotPlugin.Core; using System.Drawing.Drawing2D; using Greenshot.Core; using log4net; +using System.Runtime.Serialization; namespace Greenshot.Drawing { /// @@ -58,6 +59,18 @@ namespace Greenshot.Drawing { public ImageContainer(Surface parent) : base(parent) { FieldChanged += BitmapContainer_OnFieldChanged; + Init(); + } + + protected override void OnDeserialized(StreamingContext streamingContext) + { + base.OnDeserialized(streamingContext); + Init(); + } + + private void Init() + { + CreateDefaultAdorners(); } protected override void InitializeFields() { diff --git a/Greenshot/Drawing/LineContainer.cs b/Greenshot/Drawing/LineContainer.cs index 37357b4fa..d42d2d5b9 100644 --- a/Greenshot/Drawing/LineContainer.cs +++ b/Greenshot/Drawing/LineContainer.cs @@ -26,6 +26,7 @@ using System.Runtime.Serialization; using Greenshot.Drawing.Fields; using Greenshot.Helpers; using Greenshot.Plugin.Drawing; +using Greenshot.Drawing.Adorners; namespace Greenshot.Drawing { /// @@ -45,15 +46,14 @@ namespace Greenshot.Drawing { AddField(GetType(), FieldType.SHADOW, true); } - [OnDeserialized()] - private void OnDeserialized(StreamingContext context) { - InitGrippers(); - DoLayout(); + protected override void OnDeserialized(StreamingContext context) + { Init(); } protected void Init() { - // TODO: Remove the unneeded grippers (1, 2, 3, 5, 6, 7) + Adorners.Add(new MoveAdorner(this, Positions.TopLeft)); + Adorners.Add(new MoveAdorner(this, Positions.BottomRight)); } public override void Draw(Graphics graphics, RenderMode rm) { @@ -109,8 +109,6 @@ namespace Greenshot.Drawing { protected override ScaleHelper.IDoubleProcessor GetAngleRoundProcessor() { return ScaleHelper.LineAngleRoundBehavior.Instance; - } - - + } } } diff --git a/Greenshot/Drawing/ObfuscateContainer.cs b/Greenshot/Drawing/ObfuscateContainer.cs index 80f395c31..032291527 100644 --- a/Greenshot/Drawing/ObfuscateContainer.cs +++ b/Greenshot/Drawing/ObfuscateContainer.cs @@ -37,15 +37,16 @@ namespace Greenshot.Drawing { base.InitializeFields(); AddField(GetType(), FieldType.PREPARED_FILTER_OBFUSCATE, PreparedFilter.PIXELIZE); } - - [OnDeserialized] - private void OnDeserialized(StreamingContext context) { + + protected override void OnDeserialized(StreamingContext context) + { Init(); } private void Init() { FieldChanged += ObfuscateContainer_OnFieldChanged; ConfigurePreparedFilters(); + CreateDefaultAdorners(); } protected void ObfuscateContainer_OnFieldChanged(object sender, FieldChangedEventArgs e) { diff --git a/Greenshot/Drawing/RectangleContainer.cs b/Greenshot/Drawing/RectangleContainer.cs index c235346c5..e81ec6624 100644 --- a/Greenshot/Drawing/RectangleContainer.cs +++ b/Greenshot/Drawing/RectangleContainer.cs @@ -25,6 +25,7 @@ using System.Drawing.Drawing2D; using Greenshot.Drawing.Fields; using Greenshot.Helpers; using Greenshot.Plugin.Drawing; +using System.Runtime.Serialization; namespace Greenshot.Drawing { /// @@ -34,6 +35,22 @@ namespace Greenshot.Drawing { public class RectangleContainer : DrawableContainer { public RectangleContainer(Surface parent) : base(parent) { + Init(); + } + + /// + /// Do some logic to make sure all field are initiated correctly + /// + /// StreamingContext + protected override void OnDeserialized(StreamingContext streamingContext) + { + base.OnDeserialized(streamingContext); + Init(); + } + + private void Init() + { + CreateDefaultAdorners(); } protected override void InitializeFields() { diff --git a/Greenshot/Drawing/SpeechbubbleContainer.cs b/Greenshot/Drawing/SpeechbubbleContainer.cs index 6b2f6e7ba..1f9360fc3 100644 --- a/Greenshot/Drawing/SpeechbubbleContainer.cs +++ b/Greenshot/Drawing/SpeechbubbleContainer.cs @@ -21,17 +21,15 @@ using Greenshot.Drawing.Fields; using Greenshot.Helpers; -using Greenshot.Plugin; using Greenshot.Plugin.Drawing; using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Text; using System.Runtime.Serialization; -using System.Windows.Forms; -using log4net; -namespace Greenshot.Drawing { +namespace Greenshot.Drawing +{ /// /// Description of SpeechbubbleContainer. /// @@ -59,8 +57,8 @@ namespace Greenshot.Drawing { /// Restore the target gripper /// /// - [OnDeserialized] - private void SetValuesOnDeserialized(StreamingContext context) { + protected override void OnDeserialized(StreamingContext context) + { InitTargetGripper(Color.Green, _storedTargetGripperLocation); } #endregion diff --git a/Greenshot/Drawing/StepLabelContainer.cs b/Greenshot/Drawing/StepLabelContainer.cs index 79583c5ab..6dff35dcf 100644 --- a/Greenshot/Drawing/StepLabelContainer.cs +++ b/Greenshot/Drawing/StepLabelContainer.cs @@ -45,6 +45,12 @@ namespace Greenshot.Drawing { public StepLabelContainer(Surface parent) : base(parent) { parent.AddStepLabel(this); InitContent(); + Init(); + } + + private void Init() + { + CreateDefaultAdorners(); } #region Number serializing @@ -75,8 +81,9 @@ namespace Greenshot.Drawing { /// Restore values that don't serialize /// /// - [OnDeserialized] - private void SetValuesOnDeserialized(StreamingContext context) { + protected override void OnDeserialized(StreamingContext context) + { + Init(); _stringFormat = new StringFormat(); _stringFormat.Alignment = StringAlignment.Center; _stringFormat.LineAlignment = StringAlignment.Center; diff --git a/Greenshot/Drawing/Surface.cs b/Greenshot/Drawing/Surface.cs index 71ebc154a..99f34824e 100644 --- a/Greenshot/Drawing/Surface.cs +++ b/Greenshot/Drawing/Surface.cs @@ -21,7 +21,6 @@ using Greenshot.Configuration; using Greenshot.Core; -using Greenshot.Drawing.Adorners; using Greenshot.Drawing.Fields; using Greenshot.Helpers; using Greenshot.IniFile; @@ -42,7 +41,8 @@ using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Windows.Forms; -namespace Greenshot.Drawing { +namespace Greenshot.Drawing +{ /// /// Description of Surface. @@ -1300,8 +1300,10 @@ namespace Greenshot.Drawing { _elements.Draw(targetGraphics, null, RenderMode.EDIT, clipRectangle); } + // No clipping for the adorners + targetGraphics.ResetClip(); // Draw adorners last - foreach(var drawableContainer in selectedElements) + foreach (var drawableContainer in selectedElements) { foreach(var adorner in drawableContainer.Adorners) { diff --git a/Greenshot/Drawing/TextContainer.cs b/Greenshot/Drawing/TextContainer.cs index 110c40775..06ab4d5c4 100644 --- a/Greenshot/Drawing/TextContainer.cs +++ b/Greenshot/Drawing/TextContainer.cs @@ -98,9 +98,13 @@ namespace Greenshot.Drawing { AddField(GetType(), FieldType.TEXT_HORIZONTAL_ALIGNMENT, StringAlignment.Center); AddField(GetType(), FieldType.TEXT_VERTICAL_ALIGNMENT, StringAlignment.Center); } - - [OnDeserialized] - private void OnDeserialized(StreamingContext context) { + + /// + /// Do some logic to make sure all field are initiated correctly + /// + /// StreamingContext + protected override void OnDeserialized(StreamingContext streamingContext) { + base.OnDeserialized(streamingContext); Init(); } diff --git a/Greenshot/Greenshot.csproj b/Greenshot/Greenshot.csproj index d92465c41..0fc6043a0 100644 --- a/Greenshot/Greenshot.csproj +++ b/Greenshot/Greenshot.csproj @@ -76,7 +76,8 @@ - + + diff --git a/GreenshotPlugin/Interfaces/Drawing/Container.cs b/GreenshotPlugin/Interfaces/Drawing/Container.cs index cd96f774b..afae80489 100644 --- a/GreenshotPlugin/Interfaces/Drawing/Container.cs +++ b/GreenshotPlugin/Interfaces/Drawing/Container.cs @@ -26,6 +26,7 @@ using System.Windows.Forms; using System.ComponentModel; using System.Collections.Generic; using Greenshot.Plugin.Drawing.Adorners; +using System.Runtime.Serialization; namespace Greenshot.Plugin.Drawing { public enum RenderMode {EDIT, EXPORT}; @@ -77,8 +78,6 @@ namespace Greenshot.Plugin.Drawing { } void ApplyBounds(RectangleF newBounds); - - void DoLayout(); bool hasFilters { get; From 8aa4475d8ff411c4372c6beca357b63f5b70f16a Mon Sep 17 00:00:00 2001 From: Robin Date: Sun, 22 May 2016 13:16:28 +0200 Subject: [PATCH 17/19] Enhanced log statement [skip ci] --- GreenshotPlugin/Core/WindowsHelper.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GreenshotPlugin/Core/WindowsHelper.cs b/GreenshotPlugin/Core/WindowsHelper.cs index 1cd77fb91..855dd79be 100644 --- a/GreenshotPlugin/Core/WindowsHelper.cs +++ b/GreenshotPlugin/Core/WindowsHelper.cs @@ -856,7 +856,7 @@ namespace GreenshotPlugin.Core { if (GetClientRect(out clientRect)) { Win32Error error = Win32.GetLastErrorCode(); - LOG.WarnFormat("Couldn't retrieve the client rectangle: {0}", Win32.GetMessage(error)); + LOG.WarnFormat("Couldn't retrieve the client rectangle for {0}, error: {1}", Text, Win32.GetMessage(error)); } return clientRect; } From 9702ac730f73d07f4ac4bb038fd05b6d1ef615ca Mon Sep 17 00:00:00 2001 From: Robin Date: Mon, 23 May 2016 23:34:17 +0200 Subject: [PATCH 18/19] Fixed SpeechbubbleContainer --- Greenshot/Drawing/SpeechbubbleContainer.cs | 4 +++- Greenshot/Greenshot.sln | 8 +++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/Greenshot/Drawing/SpeechbubbleContainer.cs b/Greenshot/Drawing/SpeechbubbleContainer.cs index f49768329..e86c52be5 100644 --- a/Greenshot/Drawing/SpeechbubbleContainer.cs +++ b/Greenshot/Drawing/SpeechbubbleContainer.cs @@ -178,7 +178,8 @@ namespace Greenshot.Drawing 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 tailWidth = (Math.Abs(rect.Width) + Math.Abs(rect.Height)) / 20; + int tailLength = GeometryHelper.Distance2D(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2), TargetGripper.Location.X, TargetGripper.Location.Y); + int tailWidth = (Math.Abs(rect.Width) + Math.Abs(rect.Height)) / 20; // This should fix a problem with the tail being to wide tailWidth = Math.Min(Math.Abs(rect.Width) / 2, tailWidth); @@ -189,6 +190,7 @@ namespace Greenshot.Drawing 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.Location.X, TargetGripper.Location.Y); using (Matrix tailMatrix = new Matrix()) { tailMatrix.Translate(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2); diff --git a/Greenshot/Greenshot.sln b/Greenshot/Greenshot.sln index e49aeb8c5..38a4f572c 100644 --- a/Greenshot/Greenshot.sln +++ b/Greenshot/Greenshot.sln @@ -1,7 +1,8 @@  -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -# SharpDevelop 4.2.2.8818 +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25123.0 +MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Greenshot", "Greenshot.csproj", "{CD642BF4-D815-4D67-A0B5-C69F0B8231AF}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotPlugin", "..\GreenshotPlugin\GreenshotPlugin.csproj", "{5B924697-4DCD-4F98-85F1-105CB84B7341}" @@ -107,6 +108,7 @@ Global {C6988EE8-2FEE-4349-9F09-F9628A0D8965}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {C6988EE8-2FEE-4349-9F09-F9628A0D8965}.Release|x86.ActiveCfg = Release|x86 {D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|Any CPU.ActiveCfg = Debug|x86 + {D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|Any CPU.Build.0 = Debug|x86 {D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 {D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|x86.ActiveCfg = Debug|x86 {D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|x86.Build.0 = Debug|x86 From 45615275cf7ed64f2d0e57814edf3bc98a05d329 Mon Sep 17 00:00:00 2001 From: Robin Date: Tue, 24 May 2016 12:48:11 +0200 Subject: [PATCH 19/19] Made the re/undo code from the branch work in this, this is a manual copy as something went horribly wrong with the repository. Before building I first want to check if everything is there.[skip ci] --- .../Configuration/EditorConfiguration.cs | 13 +- Greenshot/Drawing/CropContainer.cs | 7 +- Greenshot/Drawing/DrawableContainer.cs | 54 +- Greenshot/Drawing/DrawableContainerList.cs | 137 +- .../Drawing/Fields/AbstractFieldHolder.cs | 150 ++- .../Fields/AbstractFieldHolderWithChildren.cs | 120 +- Greenshot/Drawing/Fields/Field.cs | 107 +- Greenshot/Drawing/Fields/FieldAggregator.cs | 167 ++- Greenshot/Drawing/Fields/FieldType.cs | 105 +- Greenshot/Drawing/Filters/IFilter.cs | 6 +- Greenshot/Drawing/HighlightContainer.cs | 1 + Greenshot/Drawing/ImageContainer.cs | 1 + Greenshot/Drawing/ObfuscateContainer.cs | 1 + Greenshot/Drawing/SpeechbubbleContainer.cs | 20 +- Greenshot/Drawing/StepLabelContainer.cs | 4 + Greenshot/Drawing/Surface.cs | 1100 +++++++++++------ Greenshot/Drawing/TextContainer.cs | 1 + Greenshot/Forms/ImageEditorForm.cs | 13 +- Greenshot/Greenshot.csproj | 4 +- Greenshot/Memento/AddElementMemento.cs | 6 - Greenshot/Memento/AddElementsMemento.cs | 77 ++ Greenshot/Memento/ChangeFieldHolderMemento.cs | 76 +- Greenshot/Memento/DeleteElementMemento.cs | 7 - Greenshot/Memento/DeleteElementsMemento.cs | 72 ++ .../DrawableContainerBoundsChangeMemento.cs | 79 +- .../Memento/SurfaceBackgroundChangeMemento.cs | 8 - Greenshot/Memento/TextChangeMemento.cs | 7 - .../Core/OperatingSystemExtensions.cs | 4 +- GreenshotPlugin/Core/WindowsHelper.cs | 6 +- GreenshotPlugin/GreenshotPlugin.csproj | 3 + .../Interfaces/Drawing/Container.cs | 149 ++- GreenshotPlugin/Interfaces/Drawing/IField.cs | 84 ++ .../Interfaces/Drawing/IFieldholder.cs | 56 + .../Interfaces/Drawing/IMemento.cs | 43 + GreenshotPlugin/Interfaces/Generic.cs | 124 +- 35 files changed, 1890 insertions(+), 922 deletions(-) create mode 100644 Greenshot/Memento/AddElementsMemento.cs create mode 100644 Greenshot/Memento/DeleteElementsMemento.cs create mode 100644 GreenshotPlugin/Interfaces/Drawing/IField.cs create mode 100644 GreenshotPlugin/Interfaces/Drawing/IFieldholder.cs create mode 100644 GreenshotPlugin/Interfaces/Drawing/IMemento.cs diff --git a/Greenshot/Configuration/EditorConfiguration.cs b/Greenshot/Configuration/EditorConfiguration.cs index 3d3240273..52039eac2 100644 --- a/Greenshot/Configuration/EditorConfiguration.cs +++ b/Greenshot/Configuration/EditorConfiguration.cs @@ -26,6 +26,7 @@ using Greenshot.Drawing.Fields; using GreenshotPlugin.UnmanagedHelpers; using Greenshot.IniFile; using Greenshot.Core; +using GreenshotPlugin.Interfaces.Drawing; namespace Greenshot.Configuration { /// @@ -75,7 +76,8 @@ namespace Greenshot.Configuration { /// 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) { + public IField CreateField(Type requestingType, IFieldType fieldType, object preferredDefaultValue) + { string requestingTypeName = requestingType.Name; string requestedField = requestingTypeName + "." + fieldType.Name; object fieldValue = preferredDefaultValue; @@ -101,8 +103,9 @@ namespace Greenshot.Configuration { returnField.Value = fieldValue; return returnField; } - - public void UpdateLastFieldValue(Field field) { + + public void UpdateLastFieldValue(IField field) + { string requestedField = field.Scope + "." + field.FieldType.Name; // Check if the configuration exists if (LastUsedFieldValues == null) { @@ -110,9 +113,9 @@ namespace Greenshot.Configuration { } // check if settings for the requesting type exist, if not create! if (LastUsedFieldValues.ContainsKey(requestedField)) { - LastUsedFieldValues[requestedField] = field.myValue; + LastUsedFieldValues[requestedField] = field.Value; } else { - LastUsedFieldValues.Add(requestedField, field.myValue); + LastUsedFieldValues.Add(requestedField, field.Value); } } diff --git a/Greenshot/Drawing/CropContainer.cs b/Greenshot/Drawing/CropContainer.cs index e1bf7a78a..96b03d3b5 100644 --- a/Greenshot/Drawing/CropContainer.cs +++ b/Greenshot/Drawing/CropContainer.cs @@ -24,6 +24,7 @@ using System.Runtime.Serialization; using Greenshot.Drawing.Fields; using Greenshot.Helpers; using Greenshot.Plugin.Drawing; +using GreenshotPlugin.Interfaces.Drawing; namespace Greenshot.Drawing { /// @@ -45,10 +46,14 @@ namespace Greenshot.Drawing { CreateDefaultAdorners(); } protected override void InitializeFields() { - AddField(GetType(), FieldType.FLAGS, FieldType.Flag.CONFIRMABLE); + AddField(GetType(), FieldType.FLAGS, FieldFlag.CONFIRMABLE); } public override void Invalidate() { + if (_parent == null) + { + return; + } _parent.Invalidate(); } diff --git a/Greenshot/Drawing/DrawableContainer.cs b/Greenshot/Drawing/DrawableContainer.cs index f65480b2b..1c42a066d 100644 --- a/Greenshot/Drawing/DrawableContainer.cs +++ b/Greenshot/Drawing/DrawableContainer.cs @@ -29,6 +29,7 @@ using Greenshot.Memento; using Greenshot.Plugin; using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing.Adorners; +using GreenshotPlugin.Interfaces.Drawing; using log4net; using System; using System.Collections.Generic; @@ -104,7 +105,7 @@ namespace Greenshot.Drawing remove{ _propertyChanged -= value; } } - public List Filters { + public IList Filters { get { List ret = new List(); foreach(IFieldHolder c in Children) { @@ -124,10 +125,10 @@ namespace Greenshot.Drawing } [NonSerialized] - private TargetAdorner _targetGripper; - public TargetAdorner TargetGripper { + private TargetAdorner _targetAdorner; + public TargetAdorner TargetAdorner { get { - return _targetGripper; + return _targetAdorner; } } @@ -305,7 +306,10 @@ namespace Greenshot.Drawing } public void AlignToParent(HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment) { - + if (_parent == null) + { + return; + } int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS); if (horizontalAlignment == HorizontalAlignment.Left) { Left = lineThickness/2; @@ -335,9 +339,9 @@ namespace Greenshot.Drawing /// /// Initialize a target gripper /// - protected void InitTargetGripper(Color gripperColor, Point location) { - _targetGripper = new TargetAdorner(this, location); - Adorners.Add(_targetGripper); + protected void InitAdorner(Color gripperColor, Point location) { + _targetAdorner = new TargetAdorner(this, location); + Adorners.Add(_targetAdorner); } /// @@ -478,6 +482,19 @@ namespace Greenshot.Drawing } protected virtual void SwitchParent(Surface newParent) { + if (newParent == Parent) + { + return; + } + if (_parent != null) + { + // Remove FieldAggregator + FieldAggregator fieldAggregator = _parent.FieldAggregator; + if (fieldAggregator != null) + { + fieldAggregator.UnbindElement(this); + } + } _parent = newParent; foreach(IFilter filter in Filters) { @@ -485,24 +502,6 @@ namespace Greenshot.Drawing } } - // drawablecontainers are regarded equal if they are of the same type and their bounds are equal. this should be sufficient. - public override bool Equals(object obj) { - bool ret = false; - if (obj != null && GetType() == obj.GetType()) { - DrawableContainer other = obj as DrawableContainer; - if (other != null && left==other.left && top==other.top && width==other.width && height==other.height) { - ret = true; - } - } - return ret; - } - - 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(); - } - protected void OnPropertyChanged(string propertyName) { if (_propertyChanged != null) { _propertyChanged(this, new PropertyChangedEventArgs(propertyName)); @@ -516,7 +515,7 @@ namespace Greenshot.Drawing /// /// The field to be changed /// The new value - public virtual void BeforeFieldChange(Field fieldToBeChanged, object newValue) { + public virtual void BeforeFieldChange(IField fieldToBeChanged, object newValue) { _parent.MakeUndoable(new ChangeFieldHolderMemento(this, fieldToBeChanged), true); Invalidate(); } @@ -531,7 +530,6 @@ namespace Greenshot.Drawing if (e.Field.FieldType == FieldType.SHADOW) { accountForShadowChange = true; } - Invalidate(); } /// diff --git a/Greenshot/Drawing/DrawableContainerList.cs b/Greenshot/Drawing/DrawableContainerList.cs index 692295966..597db8f3e 100644 --- a/Greenshot/Drawing/DrawableContainerList.cs +++ b/Greenshot/Drawing/DrawableContainerList.cs @@ -25,6 +25,7 @@ using Greenshot.Memento; using Greenshot.Plugin; using Greenshot.Plugin.Drawing; using GreenshotPlugin.Core; +using GreenshotPlugin.Interfaces.Drawing; using System; using System.Collections.Generic; using System.ComponentModel; @@ -38,7 +39,8 @@ namespace Greenshot.Drawing { /// Dispatches most of a DrawableContainer's public properties and methods to a list of DrawableContainers. /// [Serializable] - public class DrawableContainerList : List { + public class DrawableContainerList : List, IDrawableContainerList + { private static readonly ComponentResourceManager editorFormResources = new ComponentResourceManager(typeof(ImageEditorForm)); public Guid ParentID { @@ -116,14 +118,11 @@ namespace Greenshot.Drawing { /// /// true means allow the moves to be merged public void MakeBoundsChangeUndoable(bool allowMerge) { - List movingList = new List(); - Surface surface = null; - foreach(DrawableContainer dc in this) { - movingList.Add(dc); - surface = dc._parent; - } - if (movingList.Count > 0 && surface != null) { - surface.MakeUndoable(new DrawableContainerBoundsChangeMemento(movingList), allowMerge); + if (Count > 0 && Parent != null) + { + var clone = new DrawableContainerList(); + clone.AddRange(this); + Parent.MakeUndoable(new DrawableContainerBoundsChangeMemento(clone), allowMerge); } } @@ -246,9 +245,19 @@ namespace Greenshot.Drawing { /// the rendermode in which the element is to be drawn /// public void Draw(Graphics g, Bitmap bitmap, RenderMode renderMode, Rectangle clipRectangle) { - foreach(var drawableContainer in this) { - var dc = (DrawableContainer) drawableContainer; - if (dc.DrawingBounds.IntersectsWith(clipRectangle)) { + if (Parent == null) + { + return; + } + foreach (var drawableContainer in this) + { + var dc = (DrawableContainer)drawableContainer; + if (dc.Parent == null) + { + continue; + } + if (dc.DrawingBounds.IntersectsWith(clipRectangle)) + { dc.DrawContent(g, bitmap, renderMode, clipRectangle); } } @@ -270,9 +279,16 @@ namespace Greenshot.Drawing { /// Invalidate the bounds of all the DC's in this list /// public void Invalidate() { - foreach(var dc in this) { - dc.Invalidate(); + if (Parent == null) + { + return; } + Rectangle region = Rectangle.Empty; + foreach (var dc in this) + { + region = Rectangle.Union(region, dc.DrawingBounds); + } + Parent.Invalidate(region); } /// /// Indicates whether the given list of elements can be pulled up, @@ -280,7 +296,7 @@ namespace Greenshot.Drawing { /// /// list of elements to pull up /// true if the elements could be pulled up - public bool CanPullUp(DrawableContainerList elements) { + public bool CanPullUp(IDrawableContainerList elements) { if (elements.Count == 0 || elements.Count == Count) { return false; } @@ -296,7 +312,7 @@ namespace Greenshot.Drawing { /// Pulls one or several elements up one level in hierarchy (z-index). /// /// list of elements to pull up - public void PullElementsUp(DrawableContainerList elements) { + public void PullElementsUp(IDrawableContainerList elements) { for(int i=Count-1; i>=0; i--) { var dc = this[i]; if (!elements.Contains(dc)) { @@ -312,7 +328,7 @@ namespace Greenshot.Drawing { /// Pulls one or several elements up to the topmost level(s) in hierarchy (z-index). /// /// of elements to pull to top - public void PullElementsToTop(DrawableContainerList elements) { + public void PullElementsToTop(IDrawableContainerList elements) { var dcs = ToArray(); for(int i=0; i /// list of elements to push down /// true if the elements could be pushed down - public bool CanPushDown(DrawableContainerList elements) { + public bool CanPushDown(IDrawableContainerList elements) { if (elements.Count == 0 || elements.Count == Count) { return false; } @@ -347,7 +363,7 @@ namespace Greenshot.Drawing { /// Pushes one or several elements down one level in hierarchy (z-index). /// /// list of elements to push down - public void PushElementsDown(DrawableContainerList elements) { + public void PushElementsDown(IDrawableContainerList elements) { for(int i=0; i /// of elements to push to bottom - public void PushElementsToBottom(DrawableContainerList elements) { + public void PushElementsToBottom(IDrawableContainerList elements) { var dcs = ToArray(); for(int i=dcs.Length-1; i>=0; i--) { var dc = dcs[i]; @@ -397,7 +413,7 @@ namespace Greenshot.Drawing { /// /// /// - public virtual void AddContextMenuItems(ContextMenuStrip menu, Surface surface) { + public virtual void AddContextMenuItems(ContextMenuStrip menu, ISurface surface) { bool push = surface.Elements.CanPushDown(this); bool pull = surface.Elements.CanPullUp(this); @@ -437,7 +453,7 @@ namespace Greenshot.Drawing { // Duplicate item = new ToolStripMenuItem(Language.GetString(LangKey.editor_duplicate)); item.Click += delegate { - DrawableContainerList dcs = this.Clone(); + IDrawableContainerList dcs = this.Clone(); dcs.Parent = surface; dcs.MoveBy(10, 10); surface.AddElements(dcs); @@ -448,48 +464,36 @@ namespace Greenshot.Drawing { // Copy item = new ToolStripMenuItem(Language.GetString(LangKey.editor_copytoclipboard)); - item.Image = (Image)editorFormResources.GetObject("copyToolStripMenuItem.Image"); + item.Image = ((Image)(editorFormResources.GetObject("copyToolStripMenuItem.Image"))); item.Click += delegate { - ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), this); + ClipboardHelper.SetClipboardData(typeof(IDrawableContainerList), this); }; menu.Items.Add(item); // Cut item = new ToolStripMenuItem(Language.GetString(LangKey.editor_cuttoclipboard)); - item.Image = (Image)editorFormResources.GetObject("btnCut.Image"); + item.Image = ((Image)(editorFormResources.GetObject("btnCut.Image"))); item.Click += delegate { - ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), this); - List containersToDelete = new List(); - foreach (var drawableContainer in this) { - var container = (DrawableContainer) drawableContainer; - containersToDelete.Add(container); - } - foreach (var container in containersToDelete) { - surface.RemoveElement(container, true); - } + ClipboardHelper.SetClipboardData(typeof(IDrawableContainerList), this); + surface.RemoveElements(this, true); }; menu.Items.Add(item); // Delete item = new ToolStripMenuItem(Language.GetString(LangKey.editor_deleteelement)); - item.Image = (Image)editorFormResources.GetObject("removeObjectToolStripMenuItem.Image"); + item.Image = ((Image)(editorFormResources.GetObject("removeObjectToolStripMenuItem.Image"))); item.Click += delegate { - List containersToDelete = new List(); - foreach(var drawableContainer in this) { - var container = (DrawableContainer) drawableContainer; - containersToDelete.Add(container); - } - foreach (DrawableContainer container in containersToDelete) { - surface.RemoveElement(container, true); - } + surface.RemoveElements(this, true); }; menu.Items.Add(item); // Reset bool canReset = false; - foreach (var drawableContainer in this) { - var container = (DrawableContainer) drawableContainer; - if (container.HasDefaultSize) { + foreach (var drawableContainer in this) + { + var container = (DrawableContainer)drawableContainer; + if (container.HasDefaultSize) + { canReset = true; } } @@ -497,24 +501,29 @@ namespace Greenshot.Drawing { item = new ToolStripMenuItem(Language.GetString(LangKey.editor_resetsize)); //item.Image = ((System.Drawing.Image)(editorFormResources.GetObject("removeObjectToolStripMenuItem.Image"))); item.Click += delegate { + MakeBoundsChangeUndoable(false); foreach (var drawableContainer in this) { var container = (DrawableContainer) drawableContainer; if (!container.HasDefaultSize) { continue; } Size defaultSize = container.DefaultSize; - container.Invalidate(); container.MakeBoundsChangeUndoable(false); container.Width = defaultSize.Width; container.Height = defaultSize.Height; - container.Invalidate(); } + surface.Invalidate(); }; menu.Items.Add(item); } } - public virtual void ShowContextMenu(MouseEventArgs e, Surface surface) { + public virtual void ShowContextMenu(MouseEventArgs e, ISurface surface) + { + if (!(surface is Surface)) + { + return; + } bool hasMenu = false; foreach (var drawableContainer in this) { var container = (DrawableContainer) drawableContainer; @@ -528,7 +537,8 @@ namespace Greenshot.Drawing { ContextMenuStrip menu = new ContextMenuStrip(); AddContextMenuItems(menu, surface); if (menu.Items.Count > 0) { - menu.Show(surface, e.Location); + // TODO: cast should be somehow avoided + menu.Show((Surface)surface, e.Location); while (true) { if (menu.Visible) { Application.DoEvents(); @@ -541,5 +551,32 @@ namespace Greenshot.Drawing { } } } + + #region IDisposable Support + private bool _disposedValue = false; // To detect redundant calls + + protected virtual void Dispose(bool disposing) + { + if (!_disposedValue) + { + if (disposing) + { + foreach (var drawableContainer in this) + { + drawableContainer.Dispose(); + } + } + + _disposedValue = true; + } + } + + // This code added to correctly implement the disposable pattern. + public void Dispose() + { + // Do not change this code. Put cleanup code in Dispose(bool disposing) above. + Dispose(true); + } + #endregion } } diff --git a/Greenshot/Drawing/Fields/AbstractFieldHolder.cs b/Greenshot/Drawing/Fields/AbstractFieldHolder.cs index 1c4a98037..203f590c3 100644 --- a/Greenshot/Drawing/Fields/AbstractFieldHolder.cs +++ b/Greenshot/Drawing/Fields/AbstractFieldHolder.cs @@ -3,7 +3,7 @@ * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * * For more information see: http://getgreenshot.org/ - * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/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 @@ -26,39 +26,48 @@ using System.Runtime.Serialization; using Greenshot.Configuration; using Greenshot.IniFile; using log4net; +using GreenshotPlugin.Interfaces.Drawing; -namespace Greenshot.Drawing.Fields { +namespace Greenshot.Drawing.Fields +{ /// /// Basic IFieldHolder implementation, providing access to a set of fields /// [Serializable] - public abstract class AbstractFieldHolder : IFieldHolder { + public abstract class AbstractFieldHolder : IFieldHolder + { private static readonly ILog LOG = LogManager.GetLogger(typeof(AbstractFieldHolder)); - private static readonly EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); + private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); /// /// called when a field's value has changed /// [NonSerialized] private FieldChangedEventHandler fieldChanged; - public event FieldChangedEventHandler FieldChanged { + public event FieldChangedEventHandler FieldChanged + { add { fieldChanged += value; } - remove{ fieldChanged -= value; } + remove { fieldChanged -= value; } } - + // we keep two Collections of our fields, dictionary for quick access, list for serialization // this allows us to use default serialization [NonSerialized] - private Dictionary fieldsByType = new Dictionary(); - private readonly List fields = new List(); + private IDictionary fieldsByType = new Dictionary(); + private IList fields = new List(); + + public AbstractFieldHolder() { } [OnDeserialized] - private void OnFieldHolderDeserialized(StreamingContext context) { - fieldsByType = new Dictionary(); + private void OnDeserialized(StreamingContext context) + { + fieldsByType = new Dictionary(); // listen to changing properties - foreach(Field field in fields) { + foreach (Field field in fields) + { field.PropertyChanged += delegate { - if (fieldChanged != null) { + if (fieldChanged != null) + { fieldChanged(this, new FieldChangedEventArgs(field)); } }; @@ -66,97 +75,124 @@ namespace Greenshot.Drawing.Fields { } } - public void AddField(Type requestingType, FieldType fieldType, object fieldValue) { + public void AddField(Type requestingType, IFieldType fieldType, object fieldValue) + { AddField(editorConfiguration.CreateField(requestingType, fieldType, fieldValue)); } - public virtual void AddField(Field field) { - if (fieldsByType != null && fieldsByType.ContainsKey(field.FieldType)) { - if (LOG.IsDebugEnabled) { + public virtual void AddField(IField field) + { + if (fieldsByType != null && fieldsByType.ContainsKey(field.FieldType)) + { + if (LOG.IsDebugEnabled) + { LOG.DebugFormat("A field with of type '{0}' already exists in this {1}, will overwrite.", field.FieldType, GetType()); } - } - + } + fields.Add(field); fieldsByType[field.FieldType] = field; - field.PropertyChanged += delegate { if(fieldChanged != null) fieldChanged(this, new FieldChangedEventArgs(field)); }; + field.PropertyChanged += delegate { if (fieldChanged != null) fieldChanged(this, new FieldChangedEventArgs(field)); }; } - - public void RemoveField(Field field) { + + public void RemoveField(IField field) + { fields.Remove(field); fieldsByType.Remove(field.FieldType); field.PropertyChanged -= delegate { - if (fieldChanged != null) { + if (fieldChanged != null) + { fieldChanged(this, new FieldChangedEventArgs(field)); } }; } - - public List GetFields() { + + public IList GetFields() + { return fields; } - - public Field GetField(FieldType fieldType) { - try { + + public IField GetField(IFieldType fieldType) + { + try + { return fieldsByType[fieldType]; - } catch(KeyNotFoundException e) { + } + catch (KeyNotFoundException e) + { throw new ArgumentException("Field '" + fieldType + "' does not exist in " + GetType(), e); } } - - public object GetFieldValue(FieldType fieldType) { + + public object GetFieldValue(IFieldType fieldType) + { return GetField(fieldType).Value; } - + #region convenience methods to save us some casts outside - public string GetFieldValueAsString(FieldType fieldType) { + public string GetFieldValueAsString(IFieldType fieldType) + { return Convert.ToString(GetFieldValue(fieldType)); } - - public int GetFieldValueAsInt(FieldType fieldType) { + + public int GetFieldValueAsInt(IFieldType fieldType) + { return Convert.ToInt32(GetFieldValue(fieldType)); } - - public decimal GetFieldValueAsDecimal(FieldType fieldType) { + + public decimal GetFieldValueAsDecimal(IFieldType fieldType) + { return Convert.ToDecimal(GetFieldValue(fieldType)); } - - public double GetFieldValueAsDouble(FieldType fieldType) { + + public double GetFieldValueAsDouble(IFieldType fieldType) + { return Convert.ToDouble(GetFieldValue(fieldType)); } - - public float GetFieldValueAsFloat(FieldType fieldType) { + + public float GetFieldValueAsFloat(IFieldType fieldType) + { return Convert.ToSingle(GetFieldValue(fieldType)); } - - public bool GetFieldValueAsBool(FieldType fieldType) { + + public bool GetFieldValueAsBool(IFieldType fieldType) + { return Convert.ToBoolean(GetFieldValue(fieldType)); } - - public Color GetFieldValueAsColor(FieldType fieldType) { + + public Color GetFieldValueAsColor(IFieldType fieldType) + { return (Color)GetFieldValue(fieldType); } #endregion - - public bool HasField(FieldType fieldType) { + + public bool HasField(IFieldType fieldType) + { return fieldsByType.ContainsKey(fieldType); } - - public bool HasFieldValue(FieldType fieldType) { + + public bool HasFieldValue(IFieldType fieldType) + { return HasField(fieldType) && fieldsByType[fieldType].HasValue; } - - public void SetFieldValue(FieldType fieldType, object value) { - try { + + public void SetFieldValue(IFieldType fieldType, object value) + { + try + { fieldsByType[fieldType].Value = value; - } catch(KeyNotFoundException e) { - throw new ArgumentException("Field '"+fieldType+"' does not exist in " + GetType(), e); + } + catch (KeyNotFoundException e) + { + throw new ArgumentException("Field '" + fieldType + "' does not exist in " + GetType(), e); } } - - protected void OnFieldChanged(object sender, FieldChangedEventArgs e){ - if (fieldChanged != null) { + + protected void OnFieldChanged(object sender, FieldChangedEventArgs e) + { + if (fieldChanged != null) + { fieldChanged(sender, e); } } diff --git a/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs b/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs index a81308d0e..ae610a5fa 100644 --- a/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs +++ b/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs @@ -3,7 +3,7 @@ * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * * For more information see: http://getgreenshot.org/ - * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/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 @@ -18,86 +18,110 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ + +using GreenshotPlugin.Interfaces.Drawing; using System; using System.Collections.Generic; using System.Runtime.Serialization; -namespace Greenshot.Drawing.Fields { +namespace Greenshot.Drawing.Fields +{ /// /// Basic IFieldHolderWithChildren implementation. Similar to IFieldHolder, /// but has a List of children. /// Field values are passed to and from children as well. /// - [Serializable()] - public abstract class AbstractFieldHolderWithChildren : AbstractFieldHolder { - readonly FieldChangedEventHandler fieldChangedEventHandler; - + [Serializable()] + public abstract class AbstractFieldHolderWithChildren : AbstractFieldHolder + { + + FieldChangedEventHandler fieldChangedEventHandler; + [NonSerialized] private EventHandler childrenChanged; - public event EventHandler ChildrenChanged { + public event EventHandler ChildrenChanged + { add { childrenChanged += value; } remove { childrenChanged -= value; } } - + public List Children = new List(); - - public AbstractFieldHolderWithChildren() { + + public AbstractFieldHolderWithChildren() + { fieldChangedEventHandler = OnFieldChanged; } - - [OnDeserialized] - private void OnFieldHolderWithChildrenDeserialized(StreamingContext context) { + + [OnDeserialized()] + private void OnDeserialized(StreamingContext context) + { // listen to changing properties - foreach(IFieldHolder fieldHolder in Children) { + foreach (IFieldHolder fieldHolder in Children) + { fieldHolder.FieldChanged += fieldChangedEventHandler; } - if(childrenChanged != null) childrenChanged(this, EventArgs.Empty); + if (childrenChanged != null) childrenChanged(this, EventArgs.Empty); } - - public void AddChild(IFieldHolder fieldHolder) { + + public void AddChild(IFieldHolder fieldHolder) + { Children.Add(fieldHolder); fieldHolder.FieldChanged += fieldChangedEventHandler; - if(childrenChanged != null) childrenChanged(this, EventArgs.Empty); + if (childrenChanged != null) childrenChanged(this, EventArgs.Empty); } - - public void RemoveChild(IFieldHolder fieldHolder) { + + public void RemoveChild(IFieldHolder fieldHolder) + { Children.Remove(fieldHolder); fieldHolder.FieldChanged -= fieldChangedEventHandler; - if(childrenChanged != null) childrenChanged(this, EventArgs.Empty); + if (childrenChanged != null) childrenChanged(this, EventArgs.Empty); } - - public new List GetFields() { - List ret = new List(); + + public new IList GetFields() + { + List ret = new List(); ret.AddRange(base.GetFields()); - foreach(IFieldHolder fh in Children) { + foreach (IFieldHolder fh in Children) + { ret.AddRange(fh.GetFields()); } return ret; } - - public new Field GetField(FieldType fieldType) { - Field ret = null; - if(base.HasField(fieldType)) { + + public new IField GetField(IFieldType fieldType) + { + IField ret = null; + if (base.HasField(fieldType)) + { ret = base.GetField(fieldType); - } else { - foreach(IFieldHolder fh in Children) { - if(fh.HasField(fieldType)) { + } + else + { + foreach (IFieldHolder fh in Children) + { + if (fh.HasField(fieldType)) + { ret = fh.GetField(fieldType); break; } } } - if(ret == null) { - throw new ArgumentException("Field '"+fieldType+"' does not exist in " + GetType()); + if (ret == null) + { + throw new ArgumentException("Field '" + fieldType + "' does not exist in " + GetType()); } return ret; } - - public new bool HasField(FieldType fieldType) { + + public new bool HasField(IFieldType fieldType) + { bool ret = base.HasField(fieldType); - if(!ret) { - foreach(IFieldHolder fh in Children) { - if(fh.HasField(fieldType)) { + if (!ret) + { + foreach (IFieldHolder fh in Children) + { + if (fh.HasField(fieldType)) + { ret = true; break; } @@ -105,16 +129,18 @@ namespace Greenshot.Drawing.Fields { } return ret; } - - public new bool HasFieldValue(FieldType fieldType) { - Field f = GetField(fieldType); + + public new bool HasFieldValue(IFieldType fieldType) + { + IField f = GetField(fieldType); return f != null && f.HasValue; } - - public new void SetFieldValue(FieldType fieldType, object value) { - Field f = GetField(fieldType); - if(f != null) f.Value = value; + + public new void SetFieldValue(IFieldType fieldType, object value) + { + IField f = GetField(fieldType); + if (f != null) f.Value = value; } - + } } diff --git a/Greenshot/Drawing/Fields/Field.cs b/Greenshot/Drawing/Fields/Field.cs index 28246a6cc..cee59f0c6 100644 --- a/Greenshot/Drawing/Fields/Field.cs +++ b/Greenshot/Drawing/Fields/Field.cs @@ -3,7 +3,7 @@ * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * * For more information see: http://getgreenshot.org/ - * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/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 @@ -18,36 +18,53 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ + +using GreenshotPlugin.Interfaces.Drawing; using System; using System.ComponentModel; -namespace Greenshot.Drawing.Fields { +namespace Greenshot.Drawing.Fields +{ /// /// Represents a single field of a drawable element, i.e. /// line thickness of a rectangle. /// [Serializable] - public class Field : INotifyPropertyChanged { - [field:NonSerialized] + public class Field : IField + { + [field: NonSerialized] public event PropertyChangedEventHandler PropertyChanged; - - public object myValue; - public object Value { - get { - return myValue; + + private object _myValue; + public object Value + { + get + { + return _myValue; } - set { - if (!Equals(myValue,value)) { - myValue = value; - if (PropertyChanged!=null) { + set + { + if (!Equals(_myValue, value)) + { + _myValue = value; + if (PropertyChanged != null) + { PropertyChanged(this, new PropertyChangedEventArgs("Value")); } } } } - public FieldType FieldType; - public string Scope; - + public IFieldType FieldType + { + get; + set; + } + public string Scope + { + get; + set; + } + /// /// Constructs a new Field instance, usually you should be using FieldFactory /// to create Fields. @@ -59,70 +76,64 @@ namespace Greenshot.Drawing.Fields { /// When scope is set to a Type (e.g. typeof(RectangleContainer)), its value /// should not be reused for FieldHolders of another Type (e.g. typeof(EllipseContainer)) /// - public Field(FieldType fieldType, Type scope) { + public Field(IFieldType fieldType, Type scope) + { FieldType = fieldType; Scope = scope.Name; } - public Field(FieldType fieldType, string scope) { + public Field(IFieldType fieldType, string scope) + { FieldType = fieldType; Scope = scope; } - public Field(FieldType fieldType) { + public Field(IFieldType fieldType) + { FieldType = fieldType; } /// /// Returns true if this field holds a value other than null. /// - public bool HasValue { - get{ return Value != null; } + public bool HasValue + { + get { return Value != null; } } - + /// /// Creates a flat clone of this Field. The fields value itself is not cloned. /// /// - public Field Clone() { + public Field Clone() + { Field ret = new Field(FieldType, Scope); ret.Value = Value; return ret; } - - public override int GetHashCode() { + + public override int GetHashCode() + { int hashCode = 0; - unchecked { + unchecked + { hashCode += 1000000009 * FieldType.GetHashCode(); if (Scope != null) hashCode += 1000000021 * Scope.GetHashCode(); } return hashCode; } - - public override bool Equals(object obj) { + + public override bool Equals(object obj) + { Field other = obj as Field; - if (other == null) { + if (other == null) + { return false; } return FieldType == other.FieldType && Equals(Scope, other.Scope); } - - public override string ToString() { - return string.Format("[Field FieldType={1} Value={0} Scope={2}]", myValue, FieldType, Scope); - } - } - - - /// - /// EventHandler to be used when a field value changes - /// - public delegate void FieldChangedEventHandler(object sender, FieldChangedEventArgs e); - - /// - /// EventArgs to be used with FieldChangedEventHandler - /// - public class FieldChangedEventArgs : EventArgs { - public readonly Field Field; - public FieldChangedEventArgs(Field field) { - Field = field; + + public override string ToString() + { + return string.Format("[Field FieldType={1} Value={0} Scope={2}]", _myValue, FieldType, Scope); } } } diff --git a/Greenshot/Drawing/Fields/FieldAggregator.cs b/Greenshot/Drawing/Fields/FieldAggregator.cs index 476233f73..7c2e7558f 100644 --- a/Greenshot/Drawing/Fields/FieldAggregator.cs +++ b/Greenshot/Drawing/Fields/FieldAggregator.cs @@ -3,7 +3,7 @@ * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * * For more information see: http://getgreenshot.org/ - * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/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 @@ -19,14 +19,18 @@ * along with this program. If not, see . */ +using Greenshot.Configuration; +using Greenshot.IniFile; +using Greenshot.Plugin; +using Greenshot.Plugin.Drawing; +using GreenshotPlugin.Interfaces; +using GreenshotPlugin.Interfaces.Drawing; +using log4net; using System.Collections.Generic; using System.ComponentModel; -using Greenshot.Configuration; -using Greenshot.IniFile; -using Greenshot.Plugin.Drawing; - -namespace Greenshot.Drawing.Fields { +namespace Greenshot.Drawing.Fields +{ /// /// Represents the current set of properties for the editor. /// When one of EditorProperties' properties is updated, the change will be promoted @@ -38,35 +42,47 @@ namespace Greenshot.Drawing.Fields { /// Properties that do not apply for ALL selected elements are null (or 0 respectively) /// If the property values of the selected elements differ, the value of the last bound element wins. /// - public class FieldAggregator : AbstractFieldHolder { - - private readonly List boundContainers; - private bool internalUpdateRunning; + public class FieldAggregator : AbstractFieldHolder + { - private static readonly EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); + private IDrawableContainerList boundContainers; + private bool internalUpdateRunning = false; - public FieldAggregator() { - foreach(FieldType fieldType in FieldType.Values) { + enum Status { IDLE, BINDING, UPDATING }; + + private static readonly ILog LOG = LogManager.GetLogger(typeof(FieldAggregator)); + private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); + + public FieldAggregator(ISurface parent) + { + foreach (FieldType fieldType in FieldType.Values) + { Field field = new Field(fieldType, GetType()); AddField(field); } - boundContainers = new List(); + boundContainers = new DrawableContainerList(); + boundContainers.Parent = parent; } - - public override void AddField(Field field) { + + public override void AddField(IField field) + { base.AddField(field); field.PropertyChanged += OwnPropertyChanged; } - - public void BindElements(DrawableContainerList dcs) { - foreach(DrawableContainer dc in dcs) { + + public void BindElements(IDrawableContainerList dcs) + { + foreach (DrawableContainer dc in dcs) + { BindElement(dc); } } - public void BindElement(IDrawableContainer dc) { + public void BindElement(IDrawableContainer dc) + { DrawableContainer container = dc as DrawableContainer; - if (container != null && !boundContainers.Contains(container)) { + if (container != null && !boundContainers.Contains(container)) + { boundContainers.Add(container); container.ChildrenChanged += delegate { UpdateFromBoundElements(); @@ -74,101 +90,126 @@ namespace Greenshot.Drawing.Fields { UpdateFromBoundElements(); } } - - public void BindAndUpdateElement(IDrawableContainer dc) { + + public void BindAndUpdateElement(IDrawableContainer dc) + { UpdateElement(dc); BindElement(dc); } - - public void UpdateElement(IDrawableContainer dc) { + + public void UpdateElement(IDrawableContainer dc) + { DrawableContainer container = dc as DrawableContainer; - if (container == null) { + if (container == null) + { return; } internalUpdateRunning = true; - foreach(Field field in GetFields()) { - if (container.HasField(field.FieldType) && field.HasValue) { + foreach (Field field in GetFields()) + { + if (container.HasField(field.FieldType) && field.HasValue) + { //if(LOG.IsDebugEnabled) LOG.Debug(" "+field+ ": "+field.Value); container.SetFieldValue(field.FieldType, field.Value); } } internalUpdateRunning = false; } - - public void UnbindElement(IDrawableContainer dc) { - if (boundContainers.Contains(dc)) { + + public void UnbindElement(IDrawableContainer dc) + { + if (boundContainers.Contains(dc)) + { boundContainers.Remove(dc); UpdateFromBoundElements(); } } - - public void Clear() { + + public void Clear() + { ClearFields(); - boundContainers.Clear(); + boundContainers.Clear(); UpdateFromBoundElements(); } - + /// /// sets all field values to null, however does not remove fields /// - private void ClearFields() { + private void ClearFields() + { internalUpdateRunning = true; - foreach(Field field in GetFields()) { + foreach (Field field in GetFields()) + { field.Value = null; } internalUpdateRunning = false; } - + /// /// Updates this instance using the respective fields from the bound elements. /// Fields that do not apply to every bound element are set to null, or 0 respectively. /// All other fields will be set to the field value of the least bound element. /// - private void UpdateFromBoundElements() { + private void UpdateFromBoundElements() + { ClearFields(); internalUpdateRunning = true; - foreach(Field field in FindCommonFields()) { + foreach (Field field in FindCommonFields()) + { SetFieldValue(field.FieldType, field.Value); } internalUpdateRunning = false; } - - private List FindCommonFields() { - List returnFields = null; - if (boundContainers.Count > 0) { + + private IList FindCommonFields() + { + IList returnFields = null; + if (boundContainers.Count > 0) + { // take all fields from the least selected container... DrawableContainer leastSelectedContainer = boundContainers[boundContainers.Count - 1] as DrawableContainer; - if (leastSelectedContainer != null) { + if (leastSelectedContainer != null) + { returnFields = leastSelectedContainer.GetFields(); - for (int i = 0; i < boundContainers.Count - 1; i++) { + for (int i = 0; i < boundContainers.Count - 1; i++) + { DrawableContainer dc = boundContainers[i] as DrawableContainer; - if (dc != null) { - List fieldsToRemove = new List(); - foreach (Field f in returnFields) { + if (dc != null) + { + IList fieldsToRemove = new List(); + foreach (IField field in returnFields) + { // ... throw out those that do not apply to one of the other containers - if (!dc.HasField(f.FieldType)) { - fieldsToRemove.Add(f); + if (!dc.HasField(field.FieldType)) + { + fieldsToRemove.Add(field); } } - foreach (Field f in fieldsToRemove) { - returnFields.Remove(f); + foreach (IField field in fieldsToRemove) + { + returnFields.Remove(field); } } } } } - if (returnFields == null) { - returnFields = new List(); + if (returnFields == null) + { + returnFields = new List(); } return returnFields; } - - public void OwnPropertyChanged(object sender, PropertyChangedEventArgs ea) { - Field field = (Field) sender; - if (!internalUpdateRunning && field.Value != null) { - foreach(DrawableContainer drawableContainer in boundContainers) { - if (drawableContainer.HasField(field.FieldType)) { - Field drawableContainerField = drawableContainer.GetField(field.FieldType); + + public void OwnPropertyChanged(object sender, PropertyChangedEventArgs ea) + { + IField field = (IField)sender; + if (!internalUpdateRunning && field.Value != null) + { + foreach (DrawableContainer drawableContainer in boundContainers) + { + if (drawableContainer.HasField(field.FieldType)) + { + IField drawableContainerField = drawableContainer.GetField(field.FieldType); // Notify before change, so we can e.g. invalidate the area drawableContainer.BeforeFieldChange(drawableContainerField, field.Value); @@ -180,5 +221,5 @@ namespace Greenshot.Drawing.Fields { } } - } + } } diff --git a/Greenshot/Drawing/Fields/FieldType.cs b/Greenshot/Drawing/Fields/FieldType.cs index 4469f86cf..3090e3e51 100644 --- a/Greenshot/Drawing/Fields/FieldType.cs +++ b/Greenshot/Drawing/Fields/FieldType.cs @@ -3,7 +3,7 @@ * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * * For more information see: http://getgreenshot.org/ - * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/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 @@ -18,38 +18,41 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ +using GreenshotPlugin.Interfaces.Drawing; using System; -namespace Greenshot.Drawing.Fields { +namespace Greenshot.Drawing.Fields +{ /// /// Defines all FieldTypes + their default value. /// (The additional value is why this is not an enum) /// [Serializable] - public class FieldType { - - public static readonly FieldType ARROWHEADS = new FieldType("ARROWHEADS"); - public static readonly FieldType BLUR_RADIUS = new FieldType("BLUR_RADIUS"); - public static readonly FieldType BRIGHTNESS = new FieldType("BRIGHTNESS"); - public static readonly FieldType FILL_COLOR = new FieldType("FILL_COLOR"); - public static readonly FieldType FONT_BOLD = new FieldType("FONT_BOLD"); - public static readonly FieldType FONT_FAMILY = new FieldType("FONT_FAMILY"); - public static readonly FieldType FONT_ITALIC = new FieldType("FONT_ITALIC"); - public static readonly FieldType FONT_SIZE = new FieldType("FONT_SIZE"); - public static readonly FieldType TEXT_HORIZONTAL_ALIGNMENT = new FieldType("TEXT_HORIZONTAL_ALIGNMENT"); - public static readonly FieldType TEXT_VERTICAL_ALIGNMENT = new FieldType("TEXT_VERTICAL_ALIGNMENT"); - public static readonly FieldType HIGHLIGHT_COLOR = new FieldType("HIGHLIGHT_COLOR"); - public static readonly FieldType LINE_COLOR = new FieldType("LINE_COLOR"); - public static readonly FieldType LINE_THICKNESS = new FieldType("LINE_THICKNESS"); - public static readonly FieldType MAGNIFICATION_FACTOR = new FieldType("MAGNIFICATION_FACTOR"); - public static readonly FieldType PIXEL_SIZE = new FieldType("PIXEL_SIZE"); - public static readonly FieldType PREVIEW_QUALITY = new FieldType("PREVIEW_QUALITY"); - public static readonly FieldType SHADOW = new FieldType("SHADOW"); - public static readonly FieldType PREPARED_FILTER_OBFUSCATE = new FieldType("PREPARED_FILTER_OBFUSCATE"); - public static readonly FieldType PREPARED_FILTER_HIGHLIGHT = new FieldType("PREPARED_FILTER_HIGHLIGHT"); - public static readonly FieldType FLAGS = new FieldType("FLAGS"); - - public static FieldType[] Values = new FieldType[]{ + public class FieldType : IFieldType + { + + public static readonly IFieldType ARROWHEADS = new FieldType("ARROWHEADS"); + public static readonly IFieldType BLUR_RADIUS = new FieldType("BLUR_RADIUS"); + public static readonly IFieldType BRIGHTNESS = new FieldType("BRIGHTNESS"); + public static readonly IFieldType FILL_COLOR = new FieldType("FILL_COLOR"); + public static readonly IFieldType FONT_BOLD = new FieldType("FONT_BOLD"); + public static readonly IFieldType FONT_FAMILY = new FieldType("FONT_FAMILY"); + public static readonly IFieldType FONT_ITALIC = new FieldType("FONT_ITALIC"); + public static readonly IFieldType FONT_SIZE = new FieldType("FONT_SIZE"); + public static readonly IFieldType TEXT_HORIZONTAL_ALIGNMENT = new FieldType("TEXT_HORIZONTAL_ALIGNMENT"); + public static readonly IFieldType TEXT_VERTICAL_ALIGNMENT = new FieldType("TEXT_VERTICAL_ALIGNMENT"); + public static readonly IFieldType HIGHLIGHT_COLOR = new FieldType("HIGHLIGHT_COLOR"); + public static readonly IFieldType LINE_COLOR = new FieldType("LINE_COLOR"); + public static readonly IFieldType LINE_THICKNESS = new FieldType("LINE_THICKNESS"); + public static readonly IFieldType MAGNIFICATION_FACTOR = new FieldType("MAGNIFICATION_FACTOR"); + public static readonly IFieldType PIXEL_SIZE = new FieldType("PIXEL_SIZE"); + public static readonly IFieldType PREVIEW_QUALITY = new FieldType("PREVIEW_QUALITY"); + public static readonly IFieldType SHADOW = new FieldType("SHADOW"); + public static readonly IFieldType PREPARED_FILTER_OBFUSCATE = new FieldType("PREPARED_FILTER_OBFUSCATE"); + public static readonly IFieldType PREPARED_FILTER_HIGHLIGHT = new FieldType("PREPARED_FILTER_HIGHLIGHT"); + public static readonly IFieldType FLAGS = new FieldType("FLAGS"); + + public static IFieldType[] Values = new IFieldType[]{ ARROWHEADS, BLUR_RADIUS, BRIGHTNESS, @@ -66,53 +69,55 @@ namespace Greenshot.Drawing.Fields { MAGNIFICATION_FACTOR, PIXEL_SIZE, PREVIEW_QUALITY, - SHADOW, + SHADOW, PREPARED_FILTER_OBFUSCATE, - PREPARED_FILTER_HIGHLIGHT, + PREPARED_FILTER_HIGHLIGHT, FLAGS }; - - [Flags] - public enum Flag { - NONE = 0, - CONFIRMABLE = 1 + + public string Name + { + get; + set; } - - - public string Name; - private FieldType(string name) { + + private FieldType(string name) + { Name = name; } - public override string ToString() { + public override string ToString() + { return Name; } public override int GetHashCode() { int hashCode = 0; - unchecked { + unchecked + { if (Name != null) hashCode += 1000000009 * Name.GetHashCode(); } return hashCode; } - + public override bool Equals(object obj) { FieldType other = obj as FieldType; if (other == null) + { return false; - return Equals(Name,other.Name); + } + return Equals(Name, other.Name); } - - public static bool operator ==(FieldType a, FieldType b) { - return Equals(a,b); + + public static bool operator ==(FieldType a, FieldType b) + { + return Equals(a, b); } - - public static bool operator !=(FieldType a, FieldType b) { - return !Equals(a,b); + + public static bool operator !=(FieldType a, FieldType b) + { + return !Equals(a, b); } - } - - } diff --git a/Greenshot/Drawing/Filters/IFilter.cs b/Greenshot/Drawing/Filters/IFilter.cs index 5840e9650..f2ff0640c 100644 --- a/Greenshot/Drawing/Filters/IFilter.cs +++ b/Greenshot/Drawing/Filters/IFilter.cs @@ -21,11 +21,11 @@ using System.ComponentModel; using System.Drawing; - -using Greenshot.Drawing.Fields; using Greenshot.Plugin.Drawing; +using GreenshotPlugin.Interfaces.Drawing; -namespace Greenshot.Drawing.Filters { +namespace Greenshot.Drawing.Filters +{ public interface IFilter : INotifyPropertyChanged, IFieldHolder { DrawableContainer Parent {get; set; } void Apply(Graphics graphics, Bitmap bmp, Rectangle rect, RenderMode renderMode); diff --git a/Greenshot/Drawing/HighlightContainer.cs b/Greenshot/Drawing/HighlightContainer.cs index 5b8b783e2..fc871e4fe 100644 --- a/Greenshot/Drawing/HighlightContainer.cs +++ b/Greenshot/Drawing/HighlightContainer.cs @@ -23,6 +23,7 @@ using System.Runtime.Serialization; using Greenshot.Drawing.Fields; using Greenshot.Drawing.Filters; +using GreenshotPlugin.Interfaces.Drawing; namespace Greenshot.Drawing { /// diff --git a/Greenshot/Drawing/ImageContainer.cs b/Greenshot/Drawing/ImageContainer.cs index ca1742195..0b286fcea 100644 --- a/Greenshot/Drawing/ImageContainer.cs +++ b/Greenshot/Drawing/ImageContainer.cs @@ -28,6 +28,7 @@ using System.Drawing.Drawing2D; using Greenshot.Core; using log4net; using System.Runtime.Serialization; +using GreenshotPlugin.Interfaces.Drawing; namespace Greenshot.Drawing { /// diff --git a/Greenshot/Drawing/ObfuscateContainer.cs b/Greenshot/Drawing/ObfuscateContainer.cs index 032291527..1805f86d2 100644 --- a/Greenshot/Drawing/ObfuscateContainer.cs +++ b/Greenshot/Drawing/ObfuscateContainer.cs @@ -22,6 +22,7 @@ using System; using System.Runtime.Serialization; using Greenshot.Drawing.Fields; using Greenshot.Drawing.Filters; +using GreenshotPlugin.Interfaces.Drawing; namespace Greenshot.Drawing { /// diff --git a/Greenshot/Drawing/SpeechbubbleContainer.cs b/Greenshot/Drawing/SpeechbubbleContainer.cs index e86c52be5..e3e74e113 100644 --- a/Greenshot/Drawing/SpeechbubbleContainer.cs +++ b/Greenshot/Drawing/SpeechbubbleContainer.cs @@ -48,8 +48,8 @@ namespace Greenshot.Drawing /// [OnSerializing] private void SetValuesOnSerializing(StreamingContext context) { - if (TargetGripper != null) { - _storedTargetGripperLocation = TargetGripper.Location; + if (TargetAdorner != null) { + _storedTargetGripperLocation = TargetAdorner.Location; } } @@ -59,7 +59,7 @@ namespace Greenshot.Drawing /// protected override void OnDeserialized(StreamingContext context) { - InitTargetGripper(Color.Green, _storedTargetGripperLocation); + InitAdorner(Color.Green, _storedTargetGripperLocation); } #endregion @@ -88,9 +88,9 @@ namespace Greenshot.Drawing /// /// true if the surface doesn't need to handle the event public override bool HandleMouseDown(int mouseX, int mouseY) { - if (TargetGripper == null) { + if (TargetAdorner == null) { _initialGripperPoint = new Point(mouseX, mouseY); - InitTargetGripper(Color.Green, new Point(mouseX, mouseY)); + InitAdorner(Color.Green, new Point(mouseX, mouseY)); } return base.HandleMouseDown(mouseX, mouseY); } @@ -114,9 +114,9 @@ namespace Greenshot.Drawing Point newGripperLocation = _initialGripperPoint; newGripperLocation.Offset(xOffset, yOffset); - if (TargetGripper.Location != newGripperLocation) { + if (TargetAdorner.Location != newGripperLocation) { Invalidate(); - TargetGripper.Location = newGripperLocation; + TargetAdorner.Location = newGripperLocation; Invalidate(); } return returnValue; @@ -178,7 +178,7 @@ namespace Greenshot.Drawing 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.Location.X, TargetGripper.Location.Y); + int tailLength = GeometryHelper.Distance2D(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2), TargetAdorner.Location.X, TargetAdorner.Location.Y); int tailWidth = (Math.Abs(rect.Width) + Math.Abs(rect.Height)) / 20; // This should fix a problem with the tail being to wide @@ -190,7 +190,7 @@ namespace Greenshot.Drawing 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.Location.X, TargetGripper.Location.Y); + int tailAngle = 90 + (int)GeometryHelper.Angle2D(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2, TargetAdorner.Location.X, TargetAdorner.Location.Y); using (Matrix tailMatrix = new Matrix()) { tailMatrix.Translate(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2); @@ -207,7 +207,7 @@ namespace Greenshot.Drawing /// /// public override void Draw(Graphics graphics, RenderMode renderMode) { - if (TargetGripper == null) { + if (TargetAdorner == null) { return; } graphics.SmoothingMode = SmoothingMode.HighQuality; diff --git a/Greenshot/Drawing/StepLabelContainer.cs b/Greenshot/Drawing/StepLabelContainer.cs index 636fd4540..45dce668e 100644 --- a/Greenshot/Drawing/StepLabelContainer.cs +++ b/Greenshot/Drawing/StepLabelContainer.cs @@ -94,6 +94,10 @@ namespace Greenshot.Drawing { /// /// protected override void SwitchParent(Surface newParent) { + if (newParent == Parent) + { + return; + } if (Parent != null) { ((Surface)Parent).RemoveStepLabel(this); } diff --git a/Greenshot/Drawing/Surface.cs b/Greenshot/Drawing/Surface.cs index 13dec90c0..8b56d16f3 100644 --- a/Greenshot/Drawing/Surface.cs +++ b/Greenshot/Drawing/Surface.cs @@ -3,7 +3,7 @@ * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * * For more information see: http://getgreenshot.org/ - * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/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 @@ -30,10 +30,10 @@ using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing.Adorners; using GreenshotPlugin.Controls; using GreenshotPlugin.Core; +using GreenshotPlugin.Interfaces.Drawing; using log4net; using System; using System.Collections.Generic; -using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; @@ -43,14 +43,14 @@ using System.Windows.Forms; namespace Greenshot.Drawing { - /// /// Description of Surface. /// - public class Surface : Control, ISurface { - private static readonly ILog LOG = LogManager.GetLogger(typeof(Surface)); - public static int Count; - private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); + public class Surface : Control, ISurface + { + private static ILog LOG = LogManager.GetLogger(typeof(Surface)); + public static int Count = 0; + private static CoreConfiguration conf = IniConfig.GetIniSection(); // Property to identify the Surface ID private Guid _uniqueId = Guid.NewGuid(); @@ -58,11 +58,14 @@ namespace Greenshot.Drawing /// /// The GUID of the surface /// - public Guid ID { - get { + public Guid ID + { + get + { return _uniqueId; } - set { + set + { _uniqueId = value; } } @@ -72,41 +75,53 @@ namespace Greenshot.Drawing /// [NonSerialized] private SurfaceElementEventHandler _movingElementChanged; - public event SurfaceElementEventHandler MovingElementChanged { - add { + public event SurfaceElementEventHandler MovingElementChanged + { + add + { _movingElementChanged += value; } - remove { + remove + { _movingElementChanged -= value; } } [NonSerialized] private SurfaceDrawingModeEventHandler _drawingModeChanged; - public event SurfaceDrawingModeEventHandler DrawingModeChanged { - add { + public event SurfaceDrawingModeEventHandler DrawingModeChanged + { + add + { _drawingModeChanged += value; } - remove { + remove + { _drawingModeChanged -= value; } } [NonSerialized] private SurfaceSizeChangeEventHandler _surfaceSizeChanged; - public event SurfaceSizeChangeEventHandler SurfaceSizeChanged { - add { + public event SurfaceSizeChangeEventHandler SurfaceSizeChanged + { + add + { _surfaceSizeChanged += value; } - remove { + remove + { _surfaceSizeChanged -= value; } } [NonSerialized] private SurfaceMessageEventHandler _surfaceMessage; - public event SurfaceMessageEventHandler SurfaceMessage { - add { + public event SurfaceMessageEventHandler SurfaceMessage + { + add + { _surfaceMessage += value; } - remove { + remove + { _surfaceMessage -= value; } } @@ -171,7 +186,7 @@ namespace Greenshot.Drawing /// all selected elements, do not serialize /// [NonSerialized] - private readonly DrawableContainerList selectedElements; + private readonly IDrawableContainerList selectedElements; /// /// the element we are drawing with, do not serialize @@ -212,10 +227,15 @@ namespace Greenshot.Drawing /// private readonly List _stepLabels = new List(); - public void AddStepLabel(StepLabelContainer stepLabel) { - _stepLabels.Add(stepLabel); + public void AddStepLabel(StepLabelContainer stepLabel) + { + if (!_stepLabels.Contains(stepLabel)) + { + _stepLabels.Add(stepLabel); + } } - public void RemoveStepLabel(StepLabelContainer stepLabel) { + public void RemoveStepLabel(StepLabelContainer stepLabel) + { _stepLabels.Remove(stepLabel); } @@ -224,13 +244,17 @@ namespace Greenshot.Drawing /// /// can be null, if not the counting stops here /// number of steplabels before the supplied container - public int CountStepLabels(IDrawableContainer stopAtContainer) { + public int CountStepLabels(IDrawableContainer stopAtContainer) + { int number = 1; - foreach (var possibleThis in _stepLabels) { - if (possibleThis.Equals(stopAtContainer)) { + foreach (var possibleThis in _stepLabels) + { + if (possibleThis.Equals(stopAtContainer)) + { break; } - if (IsOnSurface(possibleThis)) { + if (IsOnSurface(possibleThis)) + { number++; } } @@ -240,12 +264,12 @@ namespace Greenshot.Drawing /// /// all elements on the surface, needed with serialization /// - private readonly DrawableContainerList _elements; + private readonly IDrawableContainerList _elements; /// /// all elements on the surface, needed with serialization /// - private FieldAggregator _fieldAggregator = new FieldAggregator(); + private FieldAggregator _fieldAggregator; /// /// the cursor container, needed with serialization as we need a direct acces to it. @@ -269,11 +293,14 @@ namespace Greenshot.Drawing /// The image is the actual captured image, needed with serialization /// private Image _image; - public Image Image { - get { + public Image Image + { + get + { return _image; } - set { + set + { _image = value; Size = _image.Size; } @@ -283,11 +310,14 @@ namespace Greenshot.Drawing /// The field aggregator is that which is used to have access to all the fields inside the currently selected elements. /// e.g. used to decided if and which line thickness is shown when multiple elements are selected. /// - public FieldAggregator FieldAggregator { - get { + public FieldAggregator FieldAggregator + { + get + { return _fieldAggregator; } - set { + set + { _fieldAggregator = value; } } @@ -295,8 +325,10 @@ namespace Greenshot.Drawing /// /// The cursor container has it's own accessor so we can find and remove this (when needed) /// - public IDrawableContainer CursorContainer { - get { + public IDrawableContainer CursorContainer + { + get + { return _cursorContainer; } } @@ -304,8 +336,10 @@ namespace Greenshot.Drawing /// /// A simple getter to ask if this surface has a cursor /// - public bool HasCursor { - get { + public bool HasCursor + { + get + { return _cursorContainer != null; } } @@ -313,7 +347,8 @@ namespace Greenshot.Drawing /// /// A simple helper method to remove the cursor from the surface /// - public void RemoveCursor() { + public void RemoveCursor() + { RemoveElement(_cursorContainer, true); _cursorContainer = null; } @@ -321,11 +356,14 @@ namespace Greenshot.Drawing /// /// The brush which is used to draw the transparent background /// - public Brush TransparencyBackgroundBrush { - get { + public Brush TransparencyBackgroundBrush + { + get + { return _transparencyBackgroundBrush; } - set { + set + { _transparencyBackgroundBrush = value; } } @@ -333,11 +371,14 @@ namespace Greenshot.Drawing /// /// Are the keys on this surface locked? /// - public bool KeysLocked { - get { + public bool KeysLocked + { + get + { return _keysLocked; } - set { + set + { _keysLocked = value; } } @@ -345,11 +386,14 @@ namespace Greenshot.Drawing /// /// Is this surface modified? This is only true if the surface has not been exported. /// - public bool Modified { - get { + public bool Modified + { + get + { return _modified; } - set { + set + { _modified = value; } } @@ -357,11 +401,14 @@ namespace Greenshot.Drawing /// /// The DrawingMode property specifies the mode for drawing, more or less the element type. /// - public DrawingModes DrawingMode { - get {return _drawingMode;} - set { + public DrawingModes DrawingMode + { + get { return _drawingMode; } + set + { _drawingMode = value; - if (_drawingModeChanged != null) { + if (_drawingModeChanged != null) + { SurfaceDrawingModeEventArgs eventArgs = new SurfaceDrawingModeEventArgs(); eventArgs.DrawingMode = _drawingMode; _drawingModeChanged.Invoke(this, eventArgs); @@ -374,11 +421,14 @@ namespace Greenshot.Drawing /// /// Property for accessing the last save "full" path /// - public string LastSaveFullPath { - get { + public string LastSaveFullPath + { + get + { return _lastSaveFullPath; } - set { + set + { _lastSaveFullPath = value; } } @@ -386,7 +436,8 @@ namespace Greenshot.Drawing /// /// Property for accessing the URL to which the surface was recently uploaded /// - public string UploadURL { + public string UploadURL + { get; set; } @@ -394,11 +445,14 @@ namespace Greenshot.Drawing /// /// Property for accessing the capture details /// - public ICaptureDetails CaptureDetails { - get { + public ICaptureDetails CaptureDetails + { + get + { return _captureDetails; } - set { + set + { _captureDetails = value; } } @@ -406,7 +460,9 @@ namespace Greenshot.Drawing /// /// Base Surface constructor /// - public Surface() : base(){ + public Surface() : base() + { + _fieldAggregator = new FieldAggregator(this); Count++; _elements = new DrawableContainerList(_uniqueId); selectedElements = new DrawableContainerList(_uniqueId); @@ -429,15 +485,17 @@ namespace Greenshot.Drawing DoubleBuffered = true; SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw | ControlStyles.ContainerControl | ControlStyles.OptimizedDoubleBuffer | ControlStyles.SupportsTransparentBackColor, true); } - + /// /// Private method, the current image is disposed the new one will stay. /// /// The new image /// true if the old image needs to be disposed, when using undo this should not be true!! - private void SetImage(Image newImage, bool dispose) { + private void SetImage(Image newImage, bool dispose) + { // Dispose - if (_image != null && dispose) { + if (_image != null && dispose) + { _image.Dispose(); } @@ -452,7 +510,8 @@ namespace Greenshot.Drawing /// Surface constructor with an image /// /// - public Surface(Image newImage) : this() { + public Surface(Image newImage) : this() + { LOG.DebugFormat("Got image with dimensions {0} and format {1}", newImage.Size, newImage.PixelFormat); SetImage(newImage, true); } @@ -461,13 +520,16 @@ namespace Greenshot.Drawing /// Surface contructor with a capture /// /// - public Surface(ICapture capture) : this(capture.Image) { + public Surface(ICapture capture) : this(capture.Image) + { // check if cursor is captured, and visible - if (capture.Cursor != null && capture.CursorVisible) { + if (capture.Cursor != null && capture.CursorVisible) + { Rectangle cursorRect = new Rectangle(capture.CursorLocation, capture.Cursor.Size); Rectangle captureRect = new Rectangle(Point.Empty, capture.Image.Size); // check if cursor is on the capture, otherwise we leave it out. - if (cursorRect.IntersectsWith(captureRect)) { + if (cursorRect.IntersectsWith(captureRect)) + { _cursorContainer = AddIconContainer(capture.Cursor, capture.CursorLocation.X, capture.CursorLocation.Y); SelectElement(_cursorContainer); } @@ -478,34 +540,43 @@ namespace Greenshot.Drawing _captureDetails = capture.CaptureDetails; } - protected override void Dispose(bool disposing) { - if (disposing) { + protected override void Dispose(bool disposing) + { + if (disposing) + { Count--; LOG.Debug("Disposing surface!"); - if (_buffer != null) { + if (_buffer != null) + { _buffer.Dispose(); _buffer = null; } - if (_transparencyBackgroundBrush != null) { + if (_transparencyBackgroundBrush != null) + { _transparencyBackgroundBrush.Dispose(); _transparencyBackgroundBrush = null; } // Cleanup undo/redo stacks - while (_undoStack != null && _undoStack.Count > 0) { + while (_undoStack != null && _undoStack.Count > 0) + { _undoStack.Pop().Dispose(); } - while (_redoStack != null && _redoStack.Count > 0) { + while (_redoStack != null && _redoStack.Count > 0) + { _redoStack.Pop().Dispose(); } - foreach (IDrawableContainer container in _elements) { + foreach (IDrawableContainer container in _elements) + { container.Dispose(); } - if (_undrawnElement != null) { + if (_undrawnElement != null) + { _undrawnElement.Dispose(); _undrawnElement = null; } - if (_cropContainer != null) { + if (_cropContainer != null) + { _cropContainer.Dispose(); _cropContainer = null; } @@ -516,32 +587,38 @@ namespace Greenshot.Drawing /// /// Undo the last action /// - public void Undo() { - if (_undoStack.Count > 0) { + public void Undo() + { + if (_undoStack.Count > 0) + { _inUndoRedo = true; IMemento top = _undoStack.Pop(); _redoStack.Push(top.Restore()); _inUndoRedo = false; } - } + } /// /// Undo an undo (=redo) /// - public void Redo() { - if (_redoStack.Count > 0) { + public void Redo() + { + if (_redoStack.Count > 0) + { _inUndoRedo = true; IMemento top = _redoStack.Pop(); _undoStack.Push(top.Restore()); _inUndoRedo = false; } } - + /// /// Returns if the surface can do a undo /// - public bool CanUndo { - get { + public bool CanUndo + { + get + { return _undoStack.Count > 0; } } @@ -549,8 +626,10 @@ namespace Greenshot.Drawing /// /// Returns if the surface can do a redo /// - public bool CanRedo { - get { + public bool CanRedo + { + get + { return _redoStack.Count > 0; } } @@ -558,11 +637,10 @@ namespace Greenshot.Drawing /// /// Get the language key for the undo action /// - public LangKey UndoActionLanguageKey { - get { - if (CanUndo) { - return _undoStack.Peek().ActionLanguageKey; - } + public LangKey UndoActionLanguageKey + { + get + { return LangKey.none; } } @@ -570,11 +648,10 @@ namespace Greenshot.Drawing /// /// Get the language key for redo action /// - public LangKey RedoActionLanguageKey { - get { - if (CanRedo) { - return _redoStack.Peek().ActionLanguageKey; - } + public LangKey RedoActionLanguageKey + { + get + { return LangKey.none; } } @@ -584,19 +661,25 @@ namespace Greenshot.Drawing /// /// The memento implementing the undo /// Allow changes to be merged - public void MakeUndoable(IMemento memento, bool allowMerge) { - if (_inUndoRedo) { + public void MakeUndoable(IMemento memento, bool allowMerge) + { + if (_inUndoRedo) + { throw new InvalidOperationException("Invoking do within an undo/redo action."); } - if (memento != null) { + if (memento != null) + { bool allowPush = true; - if (_undoStack.Count > 0 && allowMerge) { + if (_undoStack.Count > 0 && allowMerge) + { // Check if merge is possible allowPush = !_undoStack.Peek().Merge(memento); } - if (allowPush) { + if (allowPush) + { // Clear the redo-stack and dispose - while(_redoStack.Count > 0) { + while (_redoStack.Count > 0) + { _redoStack.Pop().Dispose(); } _undoStack.Push(memento); @@ -610,14 +693,18 @@ namespace Greenshot.Drawing /// /// /// - public long SaveElementsToStream(Stream streamWrite) { + public long SaveElementsToStream(Stream streamWrite) + { long bytesWritten = 0; - try { + try + { long lengtBefore = streamWrite.Length; BinaryFormatter binaryWrite = new BinaryFormatter(); binaryWrite.Serialize(streamWrite, _elements); bytesWritten = streamWrite.Length - lengtBefore; - } catch (Exception e) { + } + catch (Exception e) + { LOG.Error("Error serializing elements to stream.", e); } return bytesWritten; @@ -627,20 +714,24 @@ namespace Greenshot.Drawing /// This loads elements from a stream, among others this is used to load a surface. /// /// - public void LoadElementsFromStream(Stream streamRead) { - try { + public void LoadElementsFromStream(Stream streamRead) + { + try + { BinaryFormatter binaryRead = new BinaryFormatter(); - DrawableContainerList loadedElements = (DrawableContainerList) binaryRead.Deserialize(streamRead); + IDrawableContainerList loadedElements = (IDrawableContainerList)binaryRead.Deserialize(streamRead); loadedElements.Parent = this; // Make sure the steplabels are sorted accoring to their number - _stepLabels.Sort(delegate(StepLabelContainer p1, StepLabelContainer p2) { + _stepLabels.Sort(delegate (StepLabelContainer p1, StepLabelContainer p2) { return p1.Number.CompareTo(p2.Number); }); DeselectAllElements(); AddElements(loadedElements); SelectElements(loadedElements); FieldAggregator.BindElements(loadedElements); - } catch (Exception e) { + } + catch (Exception e) + { LOG.Error("Error serializing elements from stream.", e); } } @@ -650,11 +741,14 @@ namespace Greenshot.Drawing /// But here an element is created which is not yet draw, thus "undrawnElement". /// The element is than used while drawing on the surface. /// - private void CreateUndrawnElement() { - if(_undrawnElement != null) { + private void CreateUndrawnElement() + { + if (_undrawnElement != null) + { FieldAggregator.UnbindElement(_undrawnElement); } - switch (DrawingMode) { + switch (DrawingMode) + { case DrawingModes.Rect: _undrawnElement = new RectangleContainer(this); break; @@ -696,13 +790,15 @@ namespace Greenshot.Drawing _undrawnElement = null; break; } - if (_undrawnElement != null) { + if (_undrawnElement != null) + { FieldAggregator.BindElement(_undrawnElement); } } #region Plugin interface implementations - public IImageContainer AddImageContainer(Image image, int x, int y) { + public IImageContainer AddImageContainer(Image image, int x, int y) + { ImageContainer bitmapContainer = new ImageContainer(this); bitmapContainer.Image = image; bitmapContainer.Left = x; @@ -711,7 +807,8 @@ namespace Greenshot.Drawing return bitmapContainer; } - public IImageContainer AddImageContainer(string filename, int x, int y) { + public IImageContainer AddImageContainer(string filename, int x, int y) + { ImageContainer bitmapContainer = new ImageContainer(this); bitmapContainer.Load(filename); bitmapContainer.Left = x; @@ -719,7 +816,8 @@ namespace Greenshot.Drawing AddElement(bitmapContainer); return bitmapContainer; } - public IIconContainer AddIconContainer(Icon icon, int x, int y) { + public IIconContainer AddIconContainer(Icon icon, int x, int y) + { IconContainer iconContainer = new IconContainer(this); iconContainer.Icon = icon; iconContainer.Left = x; @@ -727,7 +825,8 @@ namespace Greenshot.Drawing AddElement(iconContainer); return iconContainer; } - public IIconContainer AddIconContainer(string filename, int x, int y) { + public IIconContainer AddIconContainer(string filename, int x, int y) + { IconContainer iconContainer = new IconContainer(this); iconContainer.Load(filename); iconContainer.Left = x; @@ -735,7 +834,8 @@ namespace Greenshot.Drawing AddElement(iconContainer); return iconContainer; } - public ICursorContainer AddCursorContainer(Cursor cursor, int x, int y) { + public ICursorContainer AddCursorContainer(Cursor cursor, int x, int y) + { CursorContainer cursorContainer = new CursorContainer(this); cursorContainer.Cursor = cursor; cursorContainer.Left = x; @@ -743,7 +843,8 @@ namespace Greenshot.Drawing AddElement(cursorContainer); return cursorContainer; } - public ICursorContainer AddCursorContainer(string filename, int x, int y) { + public ICursorContainer AddCursorContainer(string filename, int x, int y) + { CursorContainer cursorContainer = new CursorContainer(this); cursorContainer.Load(filename); cursorContainer.Left = x; @@ -752,7 +853,8 @@ namespace Greenshot.Drawing return cursorContainer; } - public ITextContainer AddTextContainer(string text, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment, FontFamily family, float size, bool italic, bool bold, bool shadow, int borderSize, Color color, Color fillColor) { + public ITextContainer AddTextContainer(string text, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment, FontFamily family, float size, bool italic, bool bold, bool shadow, int borderSize, Color color, Color fillColor) + { TextContainer textContainer = new TextContainer(this); textContainer.Text = text; textContainer.SetFieldValue(FieldType.FONT_FAMILY, family.Name); @@ -776,19 +878,28 @@ namespace Greenshot.Drawing #region DragDrop - private void OnDragEnter(object sender, DragEventArgs e) { - if(LOG.IsDebugEnabled) { + private void OnDragEnter(object sender, DragEventArgs e) + { + if (LOG.IsDebugEnabled) + { LOG.Debug("DragEnter got following formats: "); - foreach(string format in ClipboardHelper.GetFormats(e.Data)) { + foreach (string format in ClipboardHelper.GetFormats(e.Data)) + { LOG.Debug(format); } } - if ((e.AllowedEffect & DragDropEffects.Copy) != DragDropEffects.Copy) { - e.Effect=DragDropEffects.None; - } else { - if (ClipboardHelper.ContainsImage(e.Data) || ClipboardHelper.ContainsFormat(e.Data, "DragImageBits")) { + if ((e.AllowedEffect & DragDropEffects.Copy) != DragDropEffects.Copy) + { + e.Effect = DragDropEffects.None; + } + else + { + if (ClipboardHelper.ContainsImage(e.Data) || ClipboardHelper.ContainsFormat(e.Data, "DragImageBits")) + { e.Effect = DragDropEffects.Copy; - } else { + } + else + { e.Effect = DragDropEffects.None; } } @@ -799,14 +910,19 @@ namespace Greenshot.Drawing /// /// /// - private void OnDragDrop(object sender, DragEventArgs e) { + private void OnDragDrop(object sender, DragEventArgs e) + { Point mouse = PointToClient(new Point(e.X, e.Y)); - if (e.Data.GetDataPresent("Text")) { + if (e.Data.GetDataPresent("Text")) + { string possibleUrl = ClipboardHelper.GetText(e.Data); // Test if it's an url and try to download the image so we have it in the original form - if (possibleUrl != null && possibleUrl.StartsWith("http")) { - using (Image image = NetworkHelper.DownloadImage(possibleUrl)) { - if (image != null) { + if (possibleUrl != null && possibleUrl.StartsWith("http")) + { + using (Image image = NetworkHelper.DownloadImage(possibleUrl)) + { + if (image != null) + { AddImageContainer(image, mouse.X, mouse.Y); return; } @@ -814,25 +930,29 @@ namespace Greenshot.Drawing } } - foreach (Image image in ClipboardHelper.GetImages(e.Data)) { + foreach (Image image in ClipboardHelper.GetImages(e.Data)) + { AddImageContainer(image, mouse.X, mouse.Y); mouse.Offset(10, 10); image.Dispose(); } } - + #endregion /// /// Auto crop the image /// /// true if cropped - public bool AutoCrop() { + public bool AutoCrop() + { Rectangle cropRectangle; - using (Image tmpImage = GetImageForExport()) { + using (Image tmpImage = GetImageForExport()) + { cropRectangle = ImageHelper.FindAutoCropRectangle(tmpImage, conf.AutoCropDifference); } - if (!IsCropPossible(ref cropRectangle)) { + if (!IsCropPossible(ref cropRectangle)) + { return false; } DeselectAllElements(); @@ -855,10 +975,12 @@ namespace Greenshot.Drawing /// A simple clear /// /// The color for the background - public void Clear(Color newColor) { + public void Clear(Color newColor) + { //create a blank bitmap the same size as original Bitmap newBitmap = ImageHelper.CreateEmptyLike(Image, Color.Empty); - if (newBitmap != null) { + if (newBitmap != null) + { // Make undoable MakeUndoable(new SurfaceBackgroundChangeMemento(this, null), false); SetImage(newBitmap, false); @@ -870,29 +992,37 @@ namespace Greenshot.Drawing /// Apply a bitmap effect to the surface /// /// - public void ApplyBitmapEffect(IEffect effect) { + public void ApplyBitmapEffect(IEffect effect) + { BackgroundForm backgroundForm = new BackgroundForm("Effect", "Please wait"); backgroundForm.Show(); Application.DoEvents(); - try { + try + { Rectangle imageRectangle = new Rectangle(Point.Empty, Image.Size); Matrix matrix = new Matrix(); Image newImage = ImageHelper.ApplyEffect(Image, effect, matrix); - if (newImage != null) { + if (newImage != null) + { // Make sure the elements move according to the offset the effect made the bitmap move _elements.Transform(matrix); // Make undoable MakeUndoable(new SurfaceBackgroundChangeMemento(this, matrix), false); SetImage(newImage, false); Invalidate(); - if (_surfaceSizeChanged != null && !imageRectangle.Equals(new Rectangle(Point.Empty, newImage.Size))) { + if (_surfaceSizeChanged != null && !imageRectangle.Equals(new Rectangle(Point.Empty, newImage.Size))) + { _surfaceSizeChanged(this, null); } - } else { + } + else + { // clean up matrix, as it hasn't been used in the undo stack. matrix.Dispose(); } - } finally { + } + finally + { // Always close the background form backgroundForm.CloseDialog(); } @@ -903,34 +1033,42 @@ namespace Greenshot.Drawing /// /// /// true if this is possible - public bool IsCropPossible(ref Rectangle cropRectangle) { + public bool IsCropPossible(ref Rectangle cropRectangle) + { cropRectangle = GuiRectangle.GetGuiRectangle(cropRectangle.Left, cropRectangle.Top, cropRectangle.Width, cropRectangle.Height); - if (cropRectangle.Left < 0) { + if (cropRectangle.Left < 0) + { cropRectangle = new Rectangle(0, cropRectangle.Top, cropRectangle.Width + cropRectangle.Left, cropRectangle.Height); } - if (cropRectangle.Top < 0) { + if (cropRectangle.Top < 0) + { cropRectangle = new Rectangle(cropRectangle.Left, 0, cropRectangle.Width, cropRectangle.Height + cropRectangle.Top); } - if (cropRectangle.Left + cropRectangle.Width > Width) { + if (cropRectangle.Left + cropRectangle.Width > Width) + { cropRectangle = new Rectangle(cropRectangle.Left, cropRectangle.Top, Width - cropRectangle.Left, cropRectangle.Height); } - if (cropRectangle.Top + cropRectangle.Height > Height) { + if (cropRectangle.Top + cropRectangle.Height > Height) + { cropRectangle = new Rectangle(cropRectangle.Left, cropRectangle.Top, cropRectangle.Width, Height - cropRectangle.Top); } - if (cropRectangle.Height > 0 && cropRectangle.Width > 0) { + if (cropRectangle.Height > 0 && cropRectangle.Width > 0) + { return true; } return false; } - + /// /// Use to send any registered SurfaceMessageEventHandler a message, e.g. used for the notification area /// /// Who send /// Type of message /// Message itself - public void SendMessageEvent(object source, SurfaceMessageTyp messageType, string message) { - if (_surfaceMessage != null) { + public void SendMessageEvent(object source, SurfaceMessageTyp messageType, string message) + { + if (_surfaceMessage != null) + { SurfaceMessageEventArgs eventArgs = new SurfaceMessageEventArgs(); eventArgs.Message = message; eventArgs.MessageType = messageType; @@ -944,14 +1082,19 @@ namespace Greenshot.Drawing /// /// /// - public bool ApplyCrop(Rectangle cropRectangle) { - if (IsCropPossible(ref cropRectangle)) { + public bool ApplyCrop(Rectangle cropRectangle) + { + if (IsCropPossible(ref cropRectangle)) + { Rectangle imageRectangle = new Rectangle(Point.Empty, Image.Size); Bitmap tmpImage; // Make sure we have information, this this fails - try { + try + { tmpImage = ImageHelper.CloneArea(Image, cropRectangle, PixelFormat.DontCare); - } catch (Exception ex) { + } + catch (Exception ex) + { ex.Data.Add("CropRectangle", cropRectangle); ex.Data.Add("Width", Image.Width); ex.Data.Add("Height", Image.Height); @@ -967,7 +1110,8 @@ namespace Greenshot.Drawing // Do not dispose otherwise we can't undo the image! SetImage(tmpImage, false); _elements.Transform(matrix); - if (_surfaceSizeChanged != null && !imageRectangle.Equals(new Rectangle(Point.Empty, tmpImage.Size))) { + if (_surfaceSizeChanged != null && !imageRectangle.Equals(new Rectangle(Point.Empty, tmpImage.Size))) + { _surfaceSizeChanged(this, null); } Invalidate(); @@ -982,17 +1126,19 @@ namespace Greenshot.Drawing /// /// /// - public void UndoBackgroundChange(Image previous, Matrix matrix) { + public void UndoBackgroundChange(Image previous, Matrix matrix) + { SetImage(previous, false); - if (matrix != null) { + if (matrix != null) + { _elements.Transform(matrix); } - if (_surfaceSizeChanged != null) { + if (_surfaceSizeChanged != null) + { _surfaceSizeChanged(this, null); } Invalidate(); } - /// /// Check if an adorner was "hit", and change the cursor if so /// @@ -1000,11 +1146,11 @@ namespace Greenshot.Drawing /// IAdorner private IAdorner FindActiveAdorner(MouseEventArgs mouseEventArgs) { - foreach(IDrawableContainer drawableContainer in selectedElements) + foreach (IDrawableContainer drawableContainer in selectedElements) { - foreach(IAdorner adorner in drawableContainer.Adorners) + foreach (IAdorner adorner in drawableContainer.Adorners) { - + if (adorner.IsActive || adorner.HitTest(mouseEventArgs.Location)) { if (adorner.Cursor != null) @@ -1023,7 +1169,8 @@ namespace Greenshot.Drawing /// /// /// - void SurfaceMouseDown(object sender, MouseEventArgs e) { + void SurfaceMouseDown(object sender, MouseEventArgs e) + { // Handle Adorners var adorner = FindActiveAdorner(e); @@ -1034,21 +1181,27 @@ namespace Greenshot.Drawing } _mouseStart = e.Location; - + // check contextmenu - if (e.Button == MouseButtons.Right) { - DrawableContainerList selectedList = null; - if (selectedElements != null && selectedElements.Count > 0) { + if (e.Button == MouseButtons.Right) + { + IDrawableContainerList selectedList = null; + if (selectedElements != null && selectedElements.Count > 0) + { selectedList = selectedElements; - } else { + } + else + { // Single element IDrawableContainer rightClickedContainer = _elements.ClickableElementAt(_mouseStart.X, _mouseStart.Y); - if (rightClickedContainer != null) { + if (rightClickedContainer != null) + { selectedList = new DrawableContainerList(ID); selectedList.Add(rightClickedContainer); } } - if (selectedList != null && selectedList.Count > 0) { + if (selectedList != null && selectedList.Count > 0) + { selectedList.ShowContextMenu(e, this); } return; @@ -1057,28 +1210,30 @@ namespace Greenshot.Drawing _mouseDown = true; _isSurfaceMoveMadeUndoable = false; - if (_cropContainer != null && ((_undrawnElement == null) || (_undrawnElement != null && DrawingMode != DrawingModes.Crop))) { + if (_cropContainer != null && ((_undrawnElement == null) || (_undrawnElement != null && DrawingMode != DrawingModes.Crop))) + { RemoveElement(_cropContainer, false); _cropContainer = null; _drawingElement = null; } - if (_drawingElement == null && DrawingMode != DrawingModes.None) { - if (_undrawnElement == null) { + if (_drawingElement == null && DrawingMode != DrawingModes.None) + { + if (_undrawnElement == null) + { DeselectAllElements(); - if (_undrawnElement == null) { + if (_undrawnElement == null) + { CreateUndrawnElement(); } } _drawingElement = _undrawnElement; // if a new element has been drawn, set location and register it - if (_drawingElement != null) { - if (_undrawnElement != null) + if (_drawingElement != null) + { + _drawingElement.Status = _undrawnElement.DefaultEditMode; + if (!_drawingElement.HandleMouseDown(_mouseStart.X, _mouseStart.Y)) { - _drawingElement.Status = _undrawnElement.DefaultEditMode; - } - _drawingElement.PropertyChanged += ElementPropertyChanged; - if (!_drawingElement.HandleMouseDown(_mouseStart.X, _mouseStart.Y)) { _drawingElement.Left = _mouseStart.X; _drawingElement.Top = _mouseStart.Y; } @@ -1086,13 +1241,16 @@ namespace Greenshot.Drawing _drawingElement.Selected = true; } _undrawnElement = null; - } else { + } + else + { // check whether an existing element was clicked // we save mouse down element separately from selectedElements (checked on mouse up), // since it could be moved around before it is actually selected _mouseDownElement = _elements.ClickableElementAt(_mouseStart.X, _mouseStart.Y); - if (_mouseDownElement != null) { + if (_mouseDownElement != null) + { _mouseDownElement.Status = EditStatus.MOVING; } } @@ -1103,7 +1261,8 @@ namespace Greenshot.Drawing /// /// /// - void SurfaceMouseUp(object sender, MouseEventArgs e) { + void SurfaceMouseUp(object sender, MouseEventArgs e) + { // Handle Adorners var adorner = FindActiveAdorner(e); @@ -1116,48 +1275,66 @@ namespace Greenshot.Drawing Point currentMouse = new Point(e.X, e.Y); _elements.Status = EditStatus.IDLE; - if (_mouseDownElement != null) { + if (_mouseDownElement != null) + { _mouseDownElement.Status = EditStatus.IDLE; } _mouseDown = false; _mouseDownElement = null; - if (DrawingMode == DrawingModes.None) { + if (DrawingMode == DrawingModes.None) + { // check whether an existing element was clicked IDrawableContainer element = _elements.ClickableElementAt(currentMouse.X, currentMouse.Y); bool shiftModifier = (ModifierKeys & Keys.Shift) == Keys.Shift; - if (element != null) { + if (element != null) + { element.Invalidate(); bool alreadySelected = selectedElements.Contains(element); - if (shiftModifier) { - if (alreadySelected) { + if (shiftModifier) + { + if (alreadySelected) + { DeselectElement(element); - } else { + } + else + { SelectElement(element); } - } else { - if (!alreadySelected) { + } + else + { + if (!alreadySelected) + { DeselectAllElements(); SelectElement(element); } } - } else if(!shiftModifier) { + } + else if (!shiftModifier) + { DeselectAllElements(); } } - - if (selectedElements.Count > 0) { + + if (selectedElements.Count > 0) + { selectedElements.Invalidate(); selectedElements.Selected = true; } - if (_drawingElement != null) { - if (!_drawingElement.InitContent()) { + if (_drawingElement != null) + { + if (!_drawingElement.InitContent()) + { _elements.Remove(_drawingElement); _drawingElement.Invalidate(); - } else { + } + else + { _drawingElement.HandleMouseUp(currentMouse.X, currentMouse.Y); _drawingElement.Invalidate(); - if (Math.Abs(_drawingElement.Width) < 5 && Math.Abs(_drawingElement.Height) < 5) { + if (Math.Abs(_drawingElement.Width) < 5 && Math.Abs(_drawingElement.Height) < 5) + { _drawingElement.Width = 25; _drawingElement.Height = 25; } @@ -1173,7 +1350,8 @@ namespace Greenshot.Drawing /// /// /// - void SurfaceMouseMove(object sender, MouseEventArgs e) { + void SurfaceMouseMove(object sender, MouseEventArgs e) + { // Handle Adorners var adorner = FindActiveAdorner(e); if (adorner != null) @@ -1184,27 +1362,37 @@ namespace Greenshot.Drawing Point currentMouse = e.Location; - if (DrawingMode != DrawingModes.None) { + if (DrawingMode != DrawingModes.None) + { Cursor = Cursors.Cross; - } else { + } + else + { Cursor = Cursors.Default; } - if (_mouseDown) { - if (_mouseDownElement != null) { // an element is currently dragged + if (_mouseDown) + { + if (_mouseDownElement != null) + { // an element is currently dragged _mouseDownElement.Invalidate(); selectedElements.Invalidate(); // Move the element - if (_mouseDownElement.Selected) { - if (!_isSurfaceMoveMadeUndoable) { + if (_mouseDownElement.Selected) + { + if (!_isSurfaceMoveMadeUndoable) + { // Only allow one undoable per mouse-down/move/up "cycle" _isSurfaceMoveMadeUndoable = true; selectedElements.MakeBoundsChangeUndoable(false); } // dragged element has been selected before -> move all selectedElements.MoveBy(currentMouse.X - _mouseStart.X, currentMouse.Y - _mouseStart.Y); - } else { - if (!_isSurfaceMoveMadeUndoable) { + } + else + { + if (!_isSurfaceMoveMadeUndoable) + { // Only allow one undoable per mouse-down/move/up "cycle" _isSurfaceMoveMadeUndoable = true; _mouseDownElement.MakeBoundsChangeUndoable(false); @@ -1215,19 +1403,22 @@ namespace Greenshot.Drawing _mouseStart = currentMouse; _mouseDownElement.Invalidate(); _modified = true; - } else if (_drawingElement != null) { + } + else if (_drawingElement != null) + { _drawingElement.HandleMouseMove(currentMouse.X, currentMouse.Y); _modified = true; } } } - + /// /// This event handler is called when the surface is double clicked. /// /// /// - void SurfaceDoubleClick(object sender, MouseEventArgs e) { + void SurfaceDoubleClick(object sender, MouseEventArgs e) + { selectedElements.OnDoubleClick(); selectedElements.Invalidate(); } @@ -1237,11 +1428,13 @@ namespace Greenshot.Drawing /// /// /// - private Image GetImage(RenderMode renderMode) { + private Image GetImage(RenderMode renderMode) + { // Generate a copy of the original image with a dpi equal to the default... Bitmap clone = ImageHelper.Clone(_image, PixelFormat.DontCare); // otherwise we would have a problem drawing the image to the surface... :( - using (Graphics graphics = Graphics.FromImage(clone)) { + using (Graphics graphics = Graphics.FromImage(clone)) + { // Do not set the following, the containers need to decide themselves //graphics.SmoothingMode = SmoothingMode.HighQuality; //graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; @@ -1256,7 +1449,8 @@ namespace Greenshot.Drawing /// This returns the image "result" of this surface, with all the elements rendered on it. /// /// - public Image GetImageForExport() { + public Image GetImageForExport() + { return GetImage(RenderMode.EXPORT); } @@ -1265,27 +1459,34 @@ namespace Greenshot.Drawing /// /// /// PaintEventArgs - void SurfacePaint(object sender, PaintEventArgs paintEventArgs) { + void SurfacePaint(object sender, PaintEventArgs paintEventArgs) + { Graphics targetGraphics = paintEventArgs.Graphics; Rectangle clipRectangle = paintEventArgs.ClipRectangle; - if (Rectangle.Empty.Equals(clipRectangle)) { + if (Rectangle.Empty.Equals(clipRectangle)) + { LOG.Debug("Empty cliprectangle??"); return; } - if (_elements.HasIntersectingFilters(clipRectangle)) { - if (_buffer != null) { - if (_buffer.Width != Image.Width || _buffer.Height != Image.Height || _buffer.PixelFormat != Image.PixelFormat) { + if (_elements.HasIntersectingFilters(clipRectangle)) + { + if (_buffer != null) + { + if (_buffer.Width != Image.Width || _buffer.Height != Image.Height || _buffer.PixelFormat != Image.PixelFormat) + { _buffer.Dispose(); _buffer = null; } } - if (_buffer == null) { + if (_buffer == null) + { _buffer = ImageHelper.CreateEmpty(Image.Width, Image.Height, Image.PixelFormat, Color.Empty, Image.HorizontalResolution, Image.VerticalResolution); LOG.DebugFormat("Created buffer with size: {0}x{1}", Image.Width, Image.Height); } // Elements might need the bitmap, so we copy the part we need - using (Graphics graphics = Graphics.FromImage(_buffer)) { + using (Graphics graphics = Graphics.FromImage(_buffer)) + { // do not set the following, the containers need to decide this themselves! //graphics.SmoothingMode = SmoothingMode.HighQuality; //graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; @@ -1297,7 +1498,9 @@ namespace Greenshot.Drawing _elements.Draw(graphics, _buffer, RenderMode.EDIT, clipRectangle); } targetGraphics.DrawImage(_buffer, clipRectangle, clipRectangle, GraphicsUnit.Pixel); - } else { + } + else + { DrawBackground(targetGraphics, clipRectangle); targetGraphics.DrawImage(Image, clipRectangle, clipRectangle, GraphicsUnit.Pixel); _elements.Draw(targetGraphics, null, RenderMode.EDIT, clipRectangle); @@ -1308,35 +1511,32 @@ namespace Greenshot.Drawing // Draw adorners last foreach (var drawableContainer in selectedElements) { - foreach(var adorner in drawableContainer.Adorners) + foreach (var adorner in drawableContainer.Adorners) { adorner.Paint(paintEventArgs); } } } - private void DrawBackground(Graphics targetGraphics, Rectangle clipRectangle) { + private void DrawBackground(Graphics targetGraphics, Rectangle clipRectangle) + { // check if we need to draw the checkerboard - if (Image.IsAlphaPixelFormat(Image.PixelFormat) && _transparencyBackgroundBrush != null) { + if (Image.IsAlphaPixelFormat(Image.PixelFormat) && _transparencyBackgroundBrush != null) + { targetGraphics.FillRectangle(_transparencyBackgroundBrush, clipRectangle); - } else { + } + else + { targetGraphics.Clear(BackColor); } } - + /// /// Draw a checkboard when capturing with transparency /// /// PaintEventArgs - protected override void OnPaintBackground(PaintEventArgs e) { - } - - /// - /// Wrapper for makeUndoable flag which was introduced later, will call AddElement with makeundoable set to true - /// - /// the new element - public void AddElement(IDrawableContainer element) { - AddElement(element, true); + protected override void OnPaintBackground(PaintEventArgs e) + { } /// @@ -1344,39 +1544,88 @@ namespace Greenshot.Drawing /// /// the new element /// true if the adding should be undoable - public void AddElement(IDrawableContainer element, bool makeUndoable) { + /// true if invalidate needs to be called + public void AddElement(IDrawableContainer element, bool makeUndoable = true, bool invalidate = true) + { _elements.Add(element); DrawableContainer container = element as DrawableContainer; - if (container != null) { + if (container != null) + { container.FieldChanged += element_FieldChanged; } - element.PropertyChanged += ElementPropertyChanged; - if (element.Status == EditStatus.UNDRAWN) { + element.Parent = this; + if (element.Status == EditStatus.UNDRAWN) + { element.Status = EditStatus.IDLE; } - element.Invalidate(); - if (makeUndoable) { + if (element.Selected) + { + // Use false, as the element is invalidated when invalidate == true anyway + SelectElement(element, false); + } + if (invalidate) + { + element.Invalidate(); + } + if (makeUndoable) + { MakeUndoable(new AddElementMemento(this, element), false); } _modified = true; } + /// + /// Remove the list of elements + /// + /// IDrawableContainerList + /// flag specifying if the remove needs to be undoable + public void RemoveElements(IDrawableContainerList elementsToRemove, bool makeUndoable = true) + { + // fix potential issues with iterating a changing list + DrawableContainerList cloned = new DrawableContainerList(); + cloned.AddRange(elementsToRemove); + if (makeUndoable) + { + MakeUndoable(new DeleteElementsMemento(this, cloned), false); + } + SuspendLayout(); + foreach (var drawableContainer in cloned) + { + RemoveElement(drawableContainer, false, false, false); + } + ResumeLayout(); + Invalidate(); + if (_movingElementChanged != null) + { + SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs(); + eventArgs.Elements = cloned; + _movingElementChanged(this, eventArgs); + } + } + /// /// Remove an element of the elements list /// /// Element to remove /// flag specifying if the remove needs to be undoable - public void RemoveElement(IDrawableContainer elementToRemove, bool makeUndoable) { - DeselectElement(elementToRemove); + /// flag specifying if an surface invalidate needs to be called + public void RemoveElement(IDrawableContainer elementToRemove, bool makeUndoable = true, bool invalidate = true, bool generateEvents = true) + { + DeselectElement(elementToRemove, generateEvents); _elements.Remove(elementToRemove); DrawableContainer element = elementToRemove as DrawableContainer; - if (element != null) { + if (element != null) + { element.FieldChanged -= element_FieldChanged; } - elementToRemove.PropertyChanged -= ElementPropertyChanged; + element.Parent = null; // Do not dispose, the memento should!! element.Dispose(); - Invalidate(); - if (makeUndoable) { + if (invalidate) + { + Invalidate(); + } + if (makeUndoable) + { MakeUndoable(new DeleteElementMemento(this, elementToRemove), false); } _modified = true; @@ -1385,43 +1634,52 @@ namespace Greenshot.Drawing /// /// Add the supplied elements to the surface /// - /// - public void AddElements(DrawableContainerList elementsToAdd) { - foreach(IDrawableContainer element in elementsToAdd) { - AddElement(element, true); + /// DrawableContainerList + /// true if the adding should be undoable + /// true if invalidate needs to be called + public void AddElements(IDrawableContainerList elementsToAdd, bool makeUndoable = true) + { + // fix potential issues with iterating a changing list + DrawableContainerList cloned = new DrawableContainerList(); + cloned.AddRange(elementsToAdd); + if (makeUndoable) + { + MakeUndoable(new AddElementsMemento(this, cloned), false); } + SuspendLayout(); + foreach (var element in cloned) + { + element.Selected = true; + AddElement(element, false, false); + } + ResumeLayout(); + Invalidate(); } /// /// Returns if this surface has selected elements /// /// - public bool HasSelectedElements { - get { - return selectedElements != null && selectedElements.Count > 0; + public bool HasSelectedElements + { + get + { + return (selectedElements != null && selectedElements.Count > 0); } } /// /// Remove all the selected elements /// - public void RemoveSelectedElements() { - if (HasSelectedElements) { - // As RemoveElement will remove the element from the selectedElements list we need to copy the element - // to another list. - List elementsToRemove = new List(); - foreach (DrawableContainer element in selectedElements) { - // Collect to remove later - elementsToRemove.Add(element); - } - // Remove now - foreach(DrawableContainer element in elementsToRemove) { - RemoveElement(element, true); - } - selectedElements.Clear(); - if (_movingElementChanged != null) { + public void RemoveSelectedElements() + { + if (HasSelectedElements) + { + // As RemoveElement will remove the element from the selectedElements list we need to copy the element to another list. + RemoveElements(selectedElements); + if (_movingElementChanged != null) + { SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs(); - eventArgs.Elements = selectedElements; _movingElementChanged(this, eventArgs); } } @@ -1430,9 +1688,11 @@ namespace Greenshot.Drawing /// /// Cut the selected elements from the surface to the clipboard /// - public void CutSelectedElements() { - if (HasSelectedElements) { - ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), selectedElements); + public void CutSelectedElements() + { + if (HasSelectedElements) + { + ClipboardHelper.SetClipboardData(typeof(IDrawableContainerList), selectedElements); RemoveSelectedElements(); } } @@ -1440,9 +1700,11 @@ namespace Greenshot.Drawing /// /// Copy the selected elements to the clipboard /// - public void CopySelectedElements() { - if (HasSelectedElements) { - ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), selectedElements); + public void CopySelectedElements() + { + if (HasSelectedElements) + { + ClipboardHelper.SetClipboardData(typeof(IDrawableContainerList), selectedElements); } } @@ -1451,24 +1713,23 @@ namespace Greenshot.Drawing /// Called when pressing enter or using the "check" in the editor. /// /// - public void ConfirmSelectedConfirmableElements(bool confirm){ + 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) + foreach (IDrawableContainer dc in selectedDCs) { - return; - } - foreach (IDrawableContainer dc in selectedDCs){ - if (dc.Equals(_cropContainer)){ + if (dc.Equals(_cropContainer)) + { DrawingMode = DrawingModes.None; // No undo memento for the cropcontainer itself, only for the effect RemoveElement(_cropContainer, false); - if (confirm) { + if (confirm) + { ApplyCrop(_cropContainer.Bounds); } _cropContainer.Dispose(); _cropContainer = null; - break; } } } @@ -1476,78 +1737,106 @@ namespace Greenshot.Drawing /// /// Paste all the elements that are on the clipboard /// - public void PasteElementFromClipboard() { + public void PasteElementFromClipboard() + { IDataObject clipboard = ClipboardHelper.GetDataObject(); List formats = ClipboardHelper.GetFormats(clipboard); - if (formats == null || formats.Count == 0) { + if (formats == null || formats.Count == 0) + { return; } - if (LOG.IsDebugEnabled) { + if (LOG.IsDebugEnabled) + { LOG.Debug("List of clipboard formats available for pasting:"); - foreach(string format in formats) { + foreach (string format in formats) + { LOG.Debug("\tgot format: " + format); } } - if (formats.Contains(typeof(DrawableContainerList).FullName)) { - DrawableContainerList dcs = (DrawableContainerList)ClipboardHelper.GetFromDataObject(clipboard, typeof(DrawableContainerList)); - if (dcs != null) { + if (formats.Contains(typeof(IDrawableContainerList).FullName)) + { + IDrawableContainerList dcs = (IDrawableContainerList)ClipboardHelper.GetFromDataObject(clipboard, typeof(IDrawableContainerList)); + if (dcs != null) + { // 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) { + if (isSameSurface) + { moveOffset = new Point(10, 10); - } else { + } + else + { moveOffset = Point.Empty; } - // Here a fix for bug #1475, first calculate the bounds of the complete DrawableContainerList + // Here a fix for bug #1475, first calculate the bounds of the complete IDrawableContainerList Rectangle drawableContainerListBounds = Rectangle.Empty; - foreach (IDrawableContainer element in dcs) { - if (drawableContainerListBounds == Rectangle.Empty) { + foreach (IDrawableContainer element in dcs) + { + if (drawableContainerListBounds == Rectangle.Empty) + { drawableContainerListBounds = element.DrawingBounds; - } else { + } + else + { drawableContainerListBounds = Rectangle.Union(drawableContainerListBounds, element.DrawingBounds); } } // And find a location inside the target surface to paste to bool containersCanFit = drawableContainerListBounds.Width < Bounds.Width && drawableContainerListBounds.Height < Bounds.Height; - if (!containersCanFit) { + if (!containersCanFit) + { Point containersLocation = drawableContainerListBounds.Location; containersLocation.Offset(moveOffset); - if (!Bounds.Contains(containersLocation)) { + if (!Bounds.Contains(containersLocation)) + { // Easy fix for same surface - if (isSameSurface) { + if (isSameSurface) + { moveOffset = new Point(-10, -10); - } else { + } + else + { // For different surface, which is most likely smaller, we move to "10,10" moveOffset = new Point(-drawableContainerListBounds.Location.X + 10, -drawableContainerListBounds.Location.Y + 10); } } - } else { + } + else + { Rectangle moveContainerListBounds = drawableContainerListBounds; moveContainerListBounds.Offset(moveOffset); // check if the element is inside - if (!Bounds.Contains(moveContainerListBounds)) { + if (!Bounds.Contains(moveContainerListBounds)) + { // Easy fix for same surface - if (isSameSurface) { + if (isSameSurface) + { moveOffset = new Point(-10, -10); - } else { + } + else + { // For different surface, which is most likely smaller int offsetX = 0; int offsetY = 0; - if (drawableContainerListBounds.Right > Bounds.Right) { + if (drawableContainerListBounds.Right > Bounds.Right) + { offsetX = Bounds.Right - drawableContainerListBounds.Right; // Correction for the correction - if (drawableContainerListBounds.Left + offsetX < 0) { + if (drawableContainerListBounds.Left + offsetX < 0) + { offsetX += Math.Abs(drawableContainerListBounds.Left + offsetX); } } - if (drawableContainerListBounds.Bottom > Bounds.Bottom) { + if (drawableContainerListBounds.Bottom > Bounds.Bottom) + { offsetY = Bounds.Bottom - drawableContainerListBounds.Bottom; // Correction for the correction - if (drawableContainerListBounds.Top + offsetY < 0) { + if (drawableContainerListBounds.Top + offsetY < 0) + { offsetY += Math.Abs(drawableContainerListBounds.Top + offsetY); } } @@ -1561,11 +1850,15 @@ namespace Greenshot.Drawing DeselectAllElements(); SelectElements(dcs); } - } else if (ClipboardHelper.ContainsImage(clipboard)) { + } + else if (ClipboardHelper.ContainsImage(clipboard)) + { int x = 10; int y = 10; - foreach (Image clipboardImage in ClipboardHelper.GetImages(clipboard)) { - if (clipboardImage != null) { + foreach (Image clipboardImage in ClipboardHelper.GetImages(clipboard)) + { + if (clipboardImage != null) + { DeselectAllElements(); IImageContainer container = AddImageContainer(clipboardImage as Bitmap, x, y); SelectElement(container); @@ -1574,9 +1867,12 @@ namespace Greenshot.Drawing y += 10; } } - } else if (ClipboardHelper.ContainsText(clipboard)) { + } + else if (ClipboardHelper.ContainsText(clipboard)) + { string text = ClipboardHelper.GetText(clipboard); - if (text != null) { + if (text != null) + { DeselectAllElements(); ITextContainer textContainer = AddTextContainer(text, HorizontalAlignment.Center, VerticalAlignment.CENTER, FontFamily.GenericSansSerif, 12f, false, false, false, 2, Color.Black, Color.Transparent); @@ -1584,78 +1880,99 @@ namespace Greenshot.Drawing } } } - + /// /// Duplicate all the selecteded elements /// - public void DuplicateSelectedElements() { + public void DuplicateSelectedElements() + { LOG.DebugFormat("Duplicating {0} selected elements", selectedElements.Count); - DrawableContainerList dcs = selectedElements.Clone(); + IDrawableContainerList dcs = selectedElements.Clone(); dcs.Parent = this; - dcs.MoveBy(10,10); + dcs.MoveBy(10, 10); AddElements(dcs); DeselectAllElements(); SelectElements(dcs); } - + /// /// Deselect the specified element /// /// - public void DeselectElement(IDrawableContainer container) { + public void DeselectElement(IDrawableContainer container, bool generateEvents = true) + { container.Selected = false; selectedElements.Remove(container); - container.Invalidate(); FieldAggregator.UnbindElement(container); - if (_movingElementChanged != null) { + if (generateEvents && _movingElementChanged != null) + { SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs(); eventArgs.Elements = selectedElements; _movingElementChanged(this, eventArgs); } } + /// + /// Deselect the specified elements + /// + /// + public void DeselectElements(IDrawableContainerList elements) + { + if (elements.Count == 0) + { + return; + } + while (elements.Count > 0) + { + var element = elements[0]; + DeselectElement(element, false); + } + if (_movingElementChanged != null) + { + SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs(); + eventArgs.Elements = selectedElements; + _movingElementChanged(this, eventArgs); + } + Invalidate(); + } + /// /// Deselect all the selected elements /// - public void DeselectAllElements() { - if (HasSelectedElements) { - while(selectedElements.Count > 0) { - IDrawableContainer element = selectedElements[0]; - element.Selected = false; - selectedElements.Remove(element); - element.Invalidate(); - FieldAggregator.UnbindElement(element); - } - if (_movingElementChanged != null) { - SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs(); - eventArgs.Elements = selectedElements; - _movingElementChanged(this, eventArgs); - } - } + public void DeselectAllElements() + { + DeselectElements(selectedElements); } /// /// Select the supplied element /// /// - public void SelectElement(IDrawableContainer container) { - if (!selectedElements.Contains(container)) { + public void SelectElement(IDrawableContainer container, bool invalidate = true, bool generateEvents = true) + { + if (!selectedElements.Contains(container)) + { selectedElements.Add(container); container.Selected = true; FieldAggregator.BindElement(container); - if (_movingElementChanged != null) { + if (generateEvents && _movingElementChanged != null) + { SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs(); eventArgs.Elements = selectedElements; _movingElementChanged(this, eventArgs); } - container.Invalidate(); + if (invalidate) + { + container.Invalidate(); + } } } /// /// Select all elements, this is called when Ctrl+A is pressed /// - public void SelectAllElements() { + public void SelectAllElements() + { SelectElements(_elements); } @@ -1663,10 +1980,21 @@ namespace Greenshot.Drawing /// Select the supplied elements /// /// - public void SelectElements(DrawableContainerList elements) { - foreach(DrawableContainer element in elements) { - SelectElement(element); + public void SelectElements(IDrawableContainerList elements) + { + SuspendLayout(); + foreach (DrawableContainer element in elements) + { + SelectElement(element, false, false); } + if (_movingElementChanged != null) + { + SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs(); + eventArgs.Elements = selectedElements; + _movingElementChanged(this, eventArgs); + } + ResumeLayout(); + Invalidate(); } /// @@ -1674,13 +2002,16 @@ namespace Greenshot.Drawing /// /// Keys /// false if no keys were processed - public bool ProcessCmdKey(Keys k) { - if (selectedElements.Count > 0) { + public bool ProcessCmdKey(Keys k) + { + if (selectedElements.Count > 0) + { bool shiftModifier = (ModifierKeys & Keys.Shift) == Keys.Shift; int px = shiftModifier ? 10 : 1; Point moveBy = Point.Empty; - - switch (k) { + + switch (k) + { case Keys.Left: case Keys.Left | Keys.Shift: moveBy = new Point(-px, 0); @@ -1721,7 +2052,8 @@ namespace Greenshot.Drawing default: return false; } - if (!Point.Empty.Equals(moveBy)) { + if (!Point.Empty.Equals(moveBy)) + { selectedElements.MakeBoundsChangeUndoable(true); selectedElements.MoveBy(moveBy.X, moveBy.Y); } @@ -1733,8 +2065,10 @@ namespace Greenshot.Drawing /// /// Property for accessing the elements on the surface /// - public DrawableContainerList Elements { - get { + public IDrawableContainerList Elements + { + get + { return _elements; } } @@ -1742,60 +2076,64 @@ namespace Greenshot.Drawing /// /// pulls selected elements up one level in hierarchy /// - public void PullElementsUp() { + public void PullElementsUp() + { _elements.PullElementsUp(selectedElements); _elements.Invalidate(); } - + /// /// pushes selected elements up to top in hierarchy /// - public void PullElementsToTop() { + public void PullElementsToTop() + { _elements.PullElementsToTop(selectedElements); _elements.Invalidate(); } - + /// /// pushes selected elements down one level in hierarchy /// - public void PushElementsDown() { + public void PushElementsDown() + { _elements.PushElementsDown(selectedElements); _elements.Invalidate(); } - + /// /// pushes selected elements down to bottom in hierarchy /// - public void PushElementsToBottom() { + public void PushElementsToBottom() + { _elements.PushElementsToBottom(selectedElements); _elements.Invalidate(); } - + /// /// indicates whether the selected elements could be pulled up in hierarchy /// /// true if selected elements could be pulled up, false otherwise - public bool CanPullSelectionUp() { + public bool CanPullSelectionUp() + { return _elements.CanPullUp(selectedElements); } - + /// /// indicates whether the selected elements could be pushed down in hierarchy /// /// true if selected elements could be pushed down, false otherwise - public bool CanPushSelectionDown() { + public bool CanPushSelectionDown() + { return _elements.CanPushDown(selectedElements); } - - public void ElementPropertyChanged(object sender, PropertyChangedEventArgs e) { - //Invalidate(); - } - - public void element_FieldChanged(object sender, FieldChangedEventArgs e) { + + public void element_FieldChanged(object sender, FieldChangedEventArgs e) + { selectedElements.HandleFieldChangedEvent(sender, e); } - public bool IsOnSurface(IDrawableContainer container) { + public bool IsOnSurface(IDrawableContainer container) + { return _elements.Contains(container); } } diff --git a/Greenshot/Drawing/TextContainer.cs b/Greenshot/Drawing/TextContainer.cs index 1b369ea78..96792de69 100644 --- a/Greenshot/Drawing/TextContainer.cs +++ b/Greenshot/Drawing/TextContainer.cs @@ -23,6 +23,7 @@ using Greenshot.Drawing.Fields; using Greenshot.Helpers; using Greenshot.Memento; using Greenshot.Plugin.Drawing; +using GreenshotPlugin.Interfaces.Drawing; using System; using System.ComponentModel; using System.Drawing; diff --git a/Greenshot/Forms/ImageEditorForm.cs b/Greenshot/Forms/ImageEditorForm.cs index e72052944..5f8252549 100644 --- a/Greenshot/Forms/ImageEditorForm.cs +++ b/Greenshot/Forms/ImageEditorForm.cs @@ -30,8 +30,10 @@ using Greenshot.Help; using Greenshot.Helpers; using Greenshot.IniFile; using Greenshot.Plugin; +using Greenshot.Plugin.Drawing; using GreenshotPlugin.Controls; using GreenshotPlugin.Core; +using GreenshotPlugin.Interfaces.Drawing; using GreenshotPlugin.UnmanagedHelpers; using log4net; using System; @@ -56,7 +58,7 @@ namespace Greenshot { private Surface _surface; private GreenshotToolStripButton[] _toolbarButtons; - private static readonly string[] SupportedClipboardFormats = {typeof(string).FullName, "Text", typeof(DrawableContainerList).FullName}; + private static readonly string[] SupportedClipboardFormats = {typeof(string).FullName, "Text", typeof(IDrawableContainerList).FullName}; private bool _originalBoldCheckState; private bool _originalItalicCheckState; @@ -1045,8 +1047,8 @@ namespace Greenshot { textVerticalAlignmentButton.Visible = props.HasFieldValue(FieldType.TEXT_VERTICAL_ALIGNMENT); shadowButton.Visible = props.HasFieldValue(FieldType.SHADOW); btnConfirm.Visible = btnCancel.Visible = props.HasFieldValue(FieldType.FLAGS) - && ((FieldType.Flag)props.GetFieldValue(FieldType.FLAGS)&FieldType.Flag.CONFIRMABLE) == FieldType.Flag.CONFIRMABLE; - + && ((FieldFlag)props.GetFieldValue(FieldType.FLAGS) & FieldFlag.CONFIRMABLE) == FieldFlag.CONFIRMABLE; + obfuscateModeButton.Visible = props.HasFieldValue(FieldType.PREPARED_FILTER_OBFUSCATE); highlightModeButton.Visible = props.HasFieldValue(FieldType.PREPARED_FILTER_HIGHLIGHT); } else { @@ -1078,9 +1080,10 @@ namespace Greenshot { 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) { + if (props.HasFieldValue(FieldType.FLAGS) && ((FieldFlag)props.GetFieldValue(FieldType.FLAGS) & FieldFlag.CONFIRMABLE) == FieldFlag.CONFIRMABLE) + { // disable most controls - if(!_controlsDisabledDueToConfirmable) { + if (!_controlsDisabledDueToConfirmable) { ToolStripItemEndisabler.Disable(menuStrip1); ToolStripItemEndisabler.Disable(destinationsToolStrip); ToolStripItemEndisabler.Disable(toolsToolStrip); diff --git a/Greenshot/Greenshot.csproj b/Greenshot/Greenshot.csproj index 0fc6043a0..8e743d8b7 100644 --- a/Greenshot/Greenshot.csproj +++ b/Greenshot/Greenshot.csproj @@ -112,7 +112,6 @@ - @@ -215,13 +214,14 @@ + + - diff --git a/Greenshot/Memento/AddElementMemento.cs b/Greenshot/Memento/AddElementMemento.cs index 98a70214e..c7f21dbde 100644 --- a/Greenshot/Memento/AddElementMemento.cs +++ b/Greenshot/Memento/AddElementMemento.cs @@ -47,12 +47,6 @@ namespace Greenshot.Memento { _surface = null; } - public LangKey ActionLanguageKey { - get { - return LangKey.none; - } - } - public bool Merge(IMemento otherMemento) { return false; } diff --git a/Greenshot/Memento/AddElementsMemento.cs b/Greenshot/Memento/AddElementsMemento.cs new file mode 100644 index 000000000..ce566c3c2 --- /dev/null +++ b/Greenshot/Memento/AddElementsMemento.cs @@ -0,0 +1,77 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/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 Greenshot.Drawing; +using Greenshot.Plugin.Drawing; + +namespace Greenshot.Memento +{ + /// + /// The AddElementMemento makes it possible to undo adding an element + /// + public class AddElementsMemento : IMemento + { + private IDrawableContainerList _containerList; + private Surface _surface; + + public AddElementsMemento(Surface surface, IDrawableContainerList containerList) + { + _surface = surface; + _containerList = containerList; + } + + public void Dispose() + { + Dispose(true); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + if (_containerList != null) + { + _containerList.Dispose(); + } + } + _containerList = null; + _surface = null; + } + + public bool Merge(IMemento otherMemento) + { + return false; + } + + public IMemento Restore() + { + // Store the selected state, as it's overwritten by the RemoveElement + bool selected = _containerList.Selected; + + var oldState = new DeleteElementsMemento(_surface, _containerList); + + _surface.RemoveElements(_containerList, false); + + // After, so everything is gone + _surface.Invalidate(); + return oldState; + } + } +} diff --git a/Greenshot/Memento/ChangeFieldHolderMemento.cs b/Greenshot/Memento/ChangeFieldHolderMemento.cs index 03a04ab5d..7314f097a 100644 --- a/Greenshot/Memento/ChangeFieldHolderMemento.cs +++ b/Greenshot/Memento/ChangeFieldHolderMemento.cs @@ -3,7 +3,7 @@ * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * * For more information see: http://getgreenshot.org/ - * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/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 @@ -18,47 +18,54 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; -using Greenshot.Plugin.Drawing; -using Greenshot.Drawing.Fields; -using Greenshot.Configuration; -namespace Greenshot.Memento { +using Greenshot.Plugin.Drawing; +using GreenshotPlugin.Interfaces.Drawing; + +namespace Greenshot.Memento +{ /// /// The ChangeFieldHolderMemento makes it possible to undo-redo an IDrawableContainer move /// - public class ChangeFieldHolderMemento : IMemento { - private IDrawableContainer drawableContainer; - private readonly Field fieldToBeChanged; - private readonly object oldValue; - - public ChangeFieldHolderMemento(IDrawableContainer drawableContainer, Field fieldToBeChanged) { - this.drawableContainer = drawableContainer; - this.fieldToBeChanged = fieldToBeChanged; - oldValue = fieldToBeChanged.Value; + public class ChangeFieldHolderMemento : IMemento + { + private IDrawableContainer _drawableContainer; + private IField _fieldToBeChanged; + private object _oldValue; + + public ChangeFieldHolderMemento(IDrawableContainer drawableContainer, IField fieldToBeChanged) + { + _drawableContainer = drawableContainer; + _fieldToBeChanged = fieldToBeChanged; + _oldValue = fieldToBeChanged.Value; } - public void Dispose() { + public void Dispose() + { Dispose(true); - GC.SuppressFinalize(this); } - protected virtual void Dispose(bool disposing) { - //if (disposing) { } - drawableContainer = null; - } - - public LangKey ActionLanguageKey { - get { - return LangKey.none; + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + if (_drawableContainer != null) + { + _drawableContainer.Dispose(); + } } + _drawableContainer = null; } - public bool Merge(IMemento otherMemento) { + public bool Merge(IMemento otherMemento) + { ChangeFieldHolderMemento other = otherMemento as ChangeFieldHolderMemento; - if (other != null) { - if (other.drawableContainer.Equals(drawableContainer)) { - if (other.fieldToBeChanged.Equals(fieldToBeChanged)) { + if (other != null) + { + if (other._drawableContainer.Equals(_drawableContainer)) + { + if (other._fieldToBeChanged.Equals(_fieldToBeChanged)) + { // Match, do not store anything as the initial state is what we want. return true; } @@ -67,13 +74,14 @@ namespace Greenshot.Memento { return false; } - public IMemento Restore() { + public IMemento Restore() + { // Before - drawableContainer.Invalidate(); - ChangeFieldHolderMemento oldState = new ChangeFieldHolderMemento(drawableContainer, fieldToBeChanged); - fieldToBeChanged.Value = oldValue; + _drawableContainer.Invalidate(); + ChangeFieldHolderMemento oldState = new ChangeFieldHolderMemento(_drawableContainer, _fieldToBeChanged); + _fieldToBeChanged.Value = _oldValue; // After - drawableContainer.Invalidate(); + _drawableContainer.Invalidate(); return oldState; } } diff --git a/Greenshot/Memento/DeleteElementMemento.cs b/Greenshot/Memento/DeleteElementMemento.cs index b715e26a8..dc1d012de 100644 --- a/Greenshot/Memento/DeleteElementMemento.cs +++ b/Greenshot/Memento/DeleteElementMemento.cs @@ -50,13 +50,6 @@ namespace Greenshot.Memento { } } - public LangKey ActionLanguageKey { - get { - //return LangKey.editor_deleteelement; - return LangKey.none; - } - } - public bool Merge(IMemento otherMemento) { return false; } diff --git a/Greenshot/Memento/DeleteElementsMemento.cs b/Greenshot/Memento/DeleteElementsMemento.cs new file mode 100644 index 000000000..d01bc3089 --- /dev/null +++ b/Greenshot/Memento/DeleteElementsMemento.cs @@ -0,0 +1,72 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/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 Greenshot.Drawing; +using Greenshot.Plugin.Drawing; + +namespace Greenshot.Memento +{ + /// + /// The DeleteElementMemento makes it possible to undo deleting an element + /// + public class DeleteElementsMemento : IMemento + { + private IDrawableContainerList _containerList; + private Surface _surface; + + public DeleteElementsMemento(Surface surface, IDrawableContainerList containerList) + { + _surface = surface; + _containerList = containerList; + } + + public void Dispose() + { + Dispose(true); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + if (_containerList != null) + { + _containerList.Dispose(); + } + } + _containerList = null; + _surface = null; + } + + public bool Merge(IMemento otherMemento) + { + return false; + } + + public IMemento Restore() + { + AddElementsMemento oldState = new AddElementsMemento(_surface, _containerList); + _surface.AddElements(_containerList, false); + // After + _surface.Invalidate(); + return oldState; + } + } +} diff --git a/Greenshot/Memento/DrawableContainerBoundsChangeMemento.cs b/Greenshot/Memento/DrawableContainerBoundsChangeMemento.cs index 940fbd4ee..123d260f0 100644 --- a/Greenshot/Memento/DrawableContainerBoundsChangeMemento.cs +++ b/Greenshot/Memento/DrawableContainerBoundsChangeMemento.cs @@ -3,7 +3,7 @@ * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * * For more information see: http://getgreenshot.org/ - * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/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 @@ -18,61 +18,70 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -using System; +using Greenshot.Drawing; +using Greenshot.Plugin.Drawing; +using GreenshotPlugin.Core; using System.Collections.Generic; using System.Drawing; -using Greenshot.Configuration; -using Greenshot.Plugin.Drawing; -using GreenshotPlugin.Core; - -namespace Greenshot.Memento { +namespace Greenshot.Memento +{ /// /// The DrawableContainerBoundsChangeMemento makes it possible to undo-redo an IDrawableContainer resize & move /// - public class DrawableContainerBoundsChangeMemento : IMemento { - readonly List points = new List(); - readonly List sizes = new List(); - List listOfdrawableContainer; - - private void StoreBounds() { - foreach(IDrawableContainer drawableContainer in listOfdrawableContainer) { + public class DrawableContainerBoundsChangeMemento : IMemento + { + List points = new List(); + List sizes = new List(); + IDrawableContainerList listOfdrawableContainer; + + private void StoreBounds() + { + foreach (IDrawableContainer drawableContainer in listOfdrawableContainer) + { points.Add(drawableContainer.Location); sizes.Add(drawableContainer.Size); } } - public DrawableContainerBoundsChangeMemento(List listOfdrawableContainer) { + public DrawableContainerBoundsChangeMemento(IDrawableContainerList listOfdrawableContainer) + { this.listOfdrawableContainer = listOfdrawableContainer; StoreBounds(); } - public DrawableContainerBoundsChangeMemento(IDrawableContainer drawableContainer) { - listOfdrawableContainer = new List(); + public DrawableContainerBoundsChangeMemento(IDrawableContainer drawableContainer) + { + listOfdrawableContainer = new DrawableContainerList(); listOfdrawableContainer.Add(drawableContainer); + listOfdrawableContainer.Parent = drawableContainer.Parent; StoreBounds(); } - public void Dispose() { + public void Dispose() + { Dispose(true); - GC.SuppressFinalize(this); } - protected virtual void Dispose(bool disposing) { - // if (disposing) { } + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + if (listOfdrawableContainer != null) + { + listOfdrawableContainer.Dispose(); + } + } listOfdrawableContainer = null; } - public LangKey ActionLanguageKey { - get { - return LangKey.none; - } - } - - public bool Merge(IMemento otherMemento) { - DrawableContainerBoundsChangeMemento other = otherMemento as DrawableContainerBoundsChangeMemento; - if (other != null) { - if (Objects.CompareLists(listOfdrawableContainer, other.listOfdrawableContainer)) { + public bool Merge(IMemento otherMemento) + { + var other = otherMemento as DrawableContainerBoundsChangeMemento; + if (other != null) + { + if (Objects.CompareLists(listOfdrawableContainer, other.listOfdrawableContainer)) + { // Lists are equal, as we have the state already we can ignore the new memento return true; } @@ -80,9 +89,11 @@ namespace Greenshot.Memento { return false; } - public IMemento Restore() { - DrawableContainerBoundsChangeMemento oldState = new DrawableContainerBoundsChangeMemento(listOfdrawableContainer); - for(int index = 0; index < listOfdrawableContainer.Count; index++) { + public IMemento Restore() + { + var oldState = new DrawableContainerBoundsChangeMemento(listOfdrawableContainer); + for (int index = 0; index < listOfdrawableContainer.Count; index++) + { IDrawableContainer drawableContainer = listOfdrawableContainer[index]; // Before drawableContainer.Invalidate(); diff --git a/Greenshot/Memento/SurfaceBackgroundChangeMemento.cs b/Greenshot/Memento/SurfaceBackgroundChangeMemento.cs index 9c8935abc..32f371261 100644 --- a/Greenshot/Memento/SurfaceBackgroundChangeMemento.cs +++ b/Greenshot/Memento/SurfaceBackgroundChangeMemento.cs @@ -44,7 +44,6 @@ namespace Greenshot.Memento { public void Dispose() { Dispose(true); - GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { @@ -64,13 +63,6 @@ namespace Greenshot.Memento { public bool Merge(IMemento otherMemento) { return false; } - - public LangKey ActionLanguageKey { - get { - //return LangKey.editor_crop; - return LangKey.none; - } - } public IMemento Restore() { SurfaceBackgroundChangeMemento oldState = new SurfaceBackgroundChangeMemento(_surface, _matrix); diff --git a/Greenshot/Memento/TextChangeMemento.cs b/Greenshot/Memento/TextChangeMemento.cs index 716b9e171..d7b9a8d54 100644 --- a/Greenshot/Memento/TextChangeMemento.cs +++ b/Greenshot/Memento/TextChangeMemento.cs @@ -37,7 +37,6 @@ namespace Greenshot.Memento { public void Dispose() { Dispose(true); - GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { @@ -46,12 +45,6 @@ namespace Greenshot.Memento { } } - public LangKey ActionLanguageKey { - get { - return LangKey.none; - } - } - public bool Merge(IMemento otherMemento) { TextChangeMemento other = otherMemento as TextChangeMemento; if (other != null) { diff --git a/GreenshotPlugin/Core/OperatingSystemExtensions.cs b/GreenshotPlugin/Core/OperatingSystemExtensions.cs index 769547e03..ffe07bc6f 100644 --- a/GreenshotPlugin/Core/OperatingSystemExtensions.cs +++ b/GreenshotPlugin/Core/OperatingSystemExtensions.cs @@ -55,7 +55,7 @@ namespace GreenshotPlugin.Core /// 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; + return (operatingSystem.Version.Major == 6 && operatingSystem.Version.Minor >= 2) || operatingSystem.Version.Major > 6; } /// @@ -65,7 +65,7 @@ namespace GreenshotPlugin.Core /// 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; + return (operatingSystem.Version.Major == 6 && operatingSystem.Version.Minor >= 1) || operatingSystem.Version.Major > 6; } /// diff --git a/GreenshotPlugin/Core/WindowsHelper.cs b/GreenshotPlugin/Core/WindowsHelper.cs index 855dd79be..1a829b4a5 100644 --- a/GreenshotPlugin/Core/WindowsHelper.cs +++ b/GreenshotPlugin/Core/WindowsHelper.cs @@ -1017,7 +1017,11 @@ namespace GreenshotPlugin.Core { // and subtracting the border from the size (2 times, as we move right/down for the capture without resizing) captureRectangle.Inflate(borderSize.Width, borderSize.Height); } else { - captureRectangle.Inflate(-1, -1); + // TODO: Also 8.x? + if (Environment.OSVersion.IsWindows10()) + { + captureRectangle.Inflate(-1, -1); + } if (autoMode) { // check if the capture fits diff --git a/GreenshotPlugin/GreenshotPlugin.csproj b/GreenshotPlugin/GreenshotPlugin.csproj index 8bc85a253..86922e91e 100644 --- a/GreenshotPlugin/GreenshotPlugin.csproj +++ b/GreenshotPlugin/GreenshotPlugin.csproj @@ -68,6 +68,9 @@ + + + diff --git a/GreenshotPlugin/Interfaces/Drawing/Container.cs b/GreenshotPlugin/Interfaces/Drawing/Container.cs index afae80489..02e52cd65 100644 --- a/GreenshotPlugin/Interfaces/Drawing/Container.cs +++ b/GreenshotPlugin/Interfaces/Drawing/Container.cs @@ -3,7 +3,7 @@ * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * * For more information see: http://getgreenshot.org/ - * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/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 @@ -25,65 +25,80 @@ using System.Drawing.Imaging; using System.Windows.Forms; using System.ComponentModel; using System.Collections.Generic; +using GreenshotPlugin.Interfaces.Drawing; using Greenshot.Plugin.Drawing.Adorners; -using System.Runtime.Serialization; -namespace Greenshot.Plugin.Drawing { - public enum RenderMode {EDIT, EXPORT}; - public enum EditStatus {UNDRAWN, DRAWING, MOVING, RESIZING, IDLE}; +namespace Greenshot.Plugin.Drawing +{ + public enum RenderMode { EDIT, EXPORT }; + public enum EditStatus { UNDRAWN, DRAWING, MOVING, RESIZING, IDLE }; - public interface IDrawableContainer : INotifyPropertyChanged, IDisposable { - ISurface Parent { - get; - } - bool Selected { + public interface IDrawableContainer : INotifyPropertyChanged, IDisposable + { + ISurface Parent + { get; set; } - - int Left { + bool Selected + { get; set; } - - int Top { + + int Left + { get; set; } - - int Width { + + int Top + { get; set; } - - int Height { + + int Width + { get; set; } - - Point Location { + + int Height + { + get; + set; + } + + Point Location + { get; } - Size Size { - get; - } - - Rectangle Bounds { + Size Size + { get; } - Rectangle DrawingBounds { + Rectangle Bounds + { + get; + } + + Rectangle DrawingBounds + { get; } void ApplyBounds(RectangleF newBounds); - - bool hasFilters { + + bool hasFilters + { get; } - EditStatus Status { + EditStatus Status + { get; set; } @@ -97,7 +112,8 @@ namespace Greenshot.Plugin.Drawing { bool HandleMouseMove(int x, int y); bool InitContent(); void MakeBoundsChangeUndoable(bool allowMerge); - EditStatus DefaultEditMode { + EditStatus DefaultEditMode + { get; } @@ -107,38 +123,91 @@ namespace Greenshot.Plugin.Drawing { IList Adorners { get; } } - public interface ITextContainer: IDrawableContainer { - string Text { + public interface IDrawableContainerList : IList, IDisposable + { + Guid ParentID + { + get; + } + + bool Selected + { + get; + set; + } + + ISurface Parent + { + get; + set; + } + EditStatus Status + { + get; + set; + } + void MakeBoundsChangeUndoable(bool allowMerge); + void Transform(Matrix matrix); + void MoveBy(int dx, int dy); + bool ClickableAt(int x, int y); + IDrawableContainer ClickableElementAt(int x, int y); + void OnDoubleClick(); + bool HasIntersectingFilters(Rectangle clipRectangle); + bool IntersectsWith(Rectangle clipRectangle); + void Draw(Graphics g, Bitmap bitmap, RenderMode renderMode, Rectangle clipRectangle); + void Invalidate(); + void PullElementsToTop(IDrawableContainerList elements); + bool CanPushDown(IDrawableContainerList elements); + void PullElementsUp(IDrawableContainerList elements); + bool CanPullUp(IDrawableContainerList elements); + void PushElementsDown(IDrawableContainerList elements); + void PushElementsToBottom(IDrawableContainerList elements); + void ShowContextMenu(MouseEventArgs e, ISurface surface); + void HandleFieldChangedEvent(object sender, FieldChangedEventArgs e); + } + + public interface ITextContainer : IDrawableContainer + { + string Text + { get; set; } void FitToText(); } - public interface IImageContainer: IDrawableContainer { - Image Image { + public interface IImageContainer : IDrawableContainer + { + Image Image + { get; set; } void Load(string filename); } - public interface ICursorContainer: IDrawableContainer { - Cursor Cursor { + public interface ICursorContainer : IDrawableContainer + { + Cursor Cursor + { get; set; } void Load(string filename); } - public interface IIconContainer: IDrawableContainer { - Icon Icon { + public interface IIconContainer : IDrawableContainer + { + Icon Icon + { get; set; } void Load(string filename); } - public interface IMetafileContainer: IDrawableContainer { - Metafile Metafile { + public interface IMetafileContainer : IDrawableContainer + { + Metafile Metafile + { get; set; } diff --git a/GreenshotPlugin/Interfaces/Drawing/IField.cs b/GreenshotPlugin/Interfaces/Drawing/IField.cs new file mode 100644 index 000000000..515c8b107 --- /dev/null +++ b/GreenshotPlugin/Interfaces/Drawing/IField.cs @@ -0,0 +1,84 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/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; +using System.ComponentModel; + +namespace GreenshotPlugin.Interfaces.Drawing +{ + [Flags] + public enum FieldFlag + { + NONE = 0, + CONFIRMABLE = 1 + } + public interface IFieldType + { + string Name + { + get; + set; + } + } + + public interface IField : INotifyPropertyChanged + { + object Value + { + get; + set; + } + IFieldType FieldType + { + get; + set; + } + string Scope + { + get; + set; + } + bool HasValue + { + get; + } + } + /// + /// EventHandler to be used when a field value changes + /// + public delegate void FieldChangedEventHandler(object sender, FieldChangedEventArgs e); + + /// + /// EventArgs to be used with FieldChangedEventHandler + /// + public class FieldChangedEventArgs : EventArgs + { + public IField Field + { + get; + private set; + } + public FieldChangedEventArgs(IField field) + { + Field = field; + } + } +} diff --git a/GreenshotPlugin/Interfaces/Drawing/IFieldholder.cs b/GreenshotPlugin/Interfaces/Drawing/IFieldholder.cs new file mode 100644 index 000000000..5e6f9e15b --- /dev/null +++ b/GreenshotPlugin/Interfaces/Drawing/IFieldholder.cs @@ -0,0 +1,56 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/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.Collections.Generic; + +namespace GreenshotPlugin.Interfaces.Drawing +{ + /// + /// Any element holding Fields must provide access to it. + /// AbstractFieldHolder is the basic implementation. + /// If you need the fieldHolder to have child fieldHolders, + /// you should consider using IFieldHolderWithChildren. + /// + public interface IFieldHolder + { + + event FieldChangedEventHandler FieldChanged; + + void AddField(IField field); + void RemoveField(IField field); + IList GetFields(); + IField GetField(IFieldType fieldType); + bool HasField(IFieldType fieldType); + void SetFieldValue(IFieldType fieldType, object value); + } + + /// + /// Extended fieldHolder which has fieldHolder children. + /// Implementations should pass field values to and from + /// their children. + /// AbstractFieldHolderWithChildren is the basic implementation. + /// + public interface IFieldHolderWithChildren : IFieldHolder + { + void AddChild(IFieldHolder fieldHolder); + void RemoveChild(IFieldHolder fieldHolder); + } +} diff --git a/GreenshotPlugin/Interfaces/Drawing/IMemento.cs b/GreenshotPlugin/Interfaces/Drawing/IMemento.cs new file mode 100644 index 000000000..1d5971c55 --- /dev/null +++ b/GreenshotPlugin/Interfaces/Drawing/IMemento.cs @@ -0,0 +1,43 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/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 Greenshot.Memento { + /// + /// Description of IMemento. + /// + public interface IMemento : IDisposable { + /// + /// Restores target to the state memorized by this memento. + /// + /// + /// A memento of the state before restoring + /// + IMemento Restore(); + + /// + /// Try to merge the current memento with another, preventing loads of items on the stack + /// + /// The memento to try to merge with + /// + bool Merge(IMemento other); + } +} diff --git a/GreenshotPlugin/Interfaces/Generic.cs b/GreenshotPlugin/Interfaces/Generic.cs index 29a66597f..ca0ea04b7 100644 --- a/GreenshotPlugin/Interfaces/Generic.cs +++ b/GreenshotPlugin/Interfaces/Generic.cs @@ -3,7 +3,7 @@ * Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom * * For more information see: http://getgreenshot.org/ - * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/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 @@ -18,63 +18,74 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ +using Greenshot.Core; +using Greenshot.Memento; +using Greenshot.Plugin.Drawing; +using GreenshotPlugin.Interfaces.Drawing; using System; using System.Drawing; +using System.IO; using System.Windows.Forms; -using Greenshot.Plugin.Drawing; -using System.IO; -using System.Collections.Generic; -using Greenshot.Core; - -namespace Greenshot.Plugin { +namespace Greenshot.Plugin +{ /// /// Alignment Enums for possitioning /// //public enum HorizontalAlignment {LEFT, CENTER, RIGHT}; - public enum VerticalAlignment {TOP, CENTER, BOTTOM}; + public enum VerticalAlignment { TOP, CENTER, BOTTOM }; - public enum SurfaceMessageTyp { + public enum SurfaceMessageTyp + { FileSaved, Error, Info, UploadedUri } - public class SurfaceMessageEventArgs : EventArgs { - public SurfaceMessageTyp MessageType { + public class SurfaceMessageEventArgs : EventArgs + { + public SurfaceMessageTyp MessageType + { get; set; } - public string Message { + public string Message + { get; set; } - public ISurface Surface { + public ISurface Surface + { get; set; } } - public class SurfaceElementEventArgs : EventArgs { - public IList Elements { + public class SurfaceElementEventArgs : EventArgs + { + public IDrawableContainerList Elements + { get; set; } } - public class SurfaceDrawingModeEventArgs : EventArgs { - public DrawingModes DrawingMode { + public class SurfaceDrawingModeEventArgs : EventArgs + { + public DrawingModes DrawingMode + { get; set; } } - + public delegate void SurfaceSizeChangeEventHandler(object sender, EventArgs e); public delegate void SurfaceMessageEventHandler(object sender, SurfaceMessageEventArgs e); public delegate void SurfaceElementEventHandler(object sender, SurfaceElementEventArgs e); public delegate void SurfaceDrawingModeEventHandler(object sender, SurfaceDrawingModeEventArgs e); - public enum DrawingModes { + public enum DrawingModes + { None, Rect, Ellipse, @@ -93,7 +104,8 @@ namespace Greenshot.Plugin { /// /// The interface to the Surface object, so Plugins can use it. /// - public interface ISurface : IDisposable { + public interface ISurface : IDisposable + { event SurfaceSizeChangeEventHandler SurfaceSizeChanged; event SurfaceMessageEventHandler SurfaceMessage; event SurfaceDrawingModeEventHandler DrawingModeChanged; @@ -102,11 +114,17 @@ namespace Greenshot.Plugin { /// /// Unique ID of the Surface /// - Guid ID { + Guid ID + { get; set; } + IDrawableContainerList Elements + { + get; + } + /// /// Get/Set the image to the Surface /// get will give the image as is currently visible @@ -116,18 +134,19 @@ namespace Greenshot.Plugin { /// The setter will clone the passed bitmap and dispose it when the Surface is disposed /// This means that the supplied image needs to be disposed by the calling code (if needed!) /// - Image Image { + Image Image + { get; set; } - + /// /// Get the current Image from the Editor for Exporting (save/upload etc) /// Don't forget to call image.Dispose() when finished!!! /// /// Bitmap Image GetImageForExport(); - + /// /// Add a TextContainer, at the given location, to the Surface. /// The TextContainer will be "re"sized to the text size. @@ -154,7 +173,8 @@ namespace Greenshot.Plugin { long SaveElementsToStream(Stream stream); void LoadElementsFromStream(Stream stream); - bool HasSelectedElements { + bool HasSelectedElements + { get; } void RemoveSelectedElements(); @@ -162,9 +182,32 @@ namespace Greenshot.Plugin { void CopySelectedElements(); void PasteElementFromClipboard(); void DuplicateSelectedElements(); - void DeselectElement(IDrawableContainer container); + void DeselectElement(IDrawableContainer container, bool generateEvents = true); void DeselectAllElements(); - void SelectElement(IDrawableContainer container); + + /// + /// Add an element to the surface + /// + /// IDrawableContainerList + /// Should it be placed on the undo stack? + void AddElements(IDrawableContainerList elements, bool makeUndoable = true); + void RemoveElements(IDrawableContainerList elements, bool makeUndoable = true); + void SelectElements(IDrawableContainerList elements); + + /// + /// Add an element to the surface + /// + /// IDrawableContainer + /// Should it be placed on the undo stack? + /// Should it be invalidated (draw) + void AddElement(IDrawableContainer element, bool makeUndoable = true, bool invalidate = true); + + /// + /// Select the supplied container + /// + /// IDrawableContainer + /// false to skip invalidation + void SelectElement(IDrawableContainer container, bool invalidate = true, bool generateEvents = true); /// /// Is the supplied container "on" the surface? /// @@ -173,31 +216,46 @@ namespace Greenshot.Plugin { bool IsOnSurface(IDrawableContainer container); void Invalidate(Rectangle rectangleToInvalidate); void Invalidate(); - bool Modified { + bool Modified + { get; set; } - string LastSaveFullPath { + string LastSaveFullPath + { get; set; } - string UploadURL { + string UploadURL + { get; set; } - void RemoveElement(IDrawableContainer elementToRemove, bool makeUndoable); + /// + /// Remove an element of the elements list + /// + /// Element to remove + /// flag specifying if the remove needs to be undoable + /// flag specifying if an surface invalidate needs to be called + /// flag specifying if the deselect needs to generate an event + void RemoveElement(IDrawableContainer elementToRemove, bool makeUndoable = true, bool invalidate = true, bool generateEvents = true); + void SendMessageEvent(object source, SurfaceMessageTyp messageType, string message); void ApplyBitmapEffect(IEffect effect); void RemoveCursor(); - bool HasCursor { + bool HasCursor + { get; } - ICaptureDetails CaptureDetails { + ICaptureDetails CaptureDetails + { get; set; } int Width { get; } int Height { get; } + + void MakeUndoable(IMemento memento, bool allowMerge); } } \ No newline at end of file