diff --git a/Greenshot/AssemblyInfo.cs b/Greenshot/AssemblyInfo.cs index 8faad06ca..584345572 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/Configuration/EditorConfiguration.cs b/Greenshot/Configuration/EditorConfiguration.cs index c74592a8d..c23d3118a 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 { /// @@ -73,9 +74,10 @@ 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) { + 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/Controls/BindableToolStripButton.cs b/Greenshot/Controls/BindableToolStripButton.cs index 3d2fa28b6..e0edd9389 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 0b991e4c6..8af03e193 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 a50139e00..b0489f846 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 a159283b4..5970b115b 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 { @@ -30,7 +29,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 f25355fb3..18d2743c2 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 a4ead03fe..d2db0388c 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 bab51077b..3cc10d44b 100644 --- a/Greenshot/Controls/NonJumpingPanel.cs +++ b/Greenshot/Controls/NonJumpingPanel.cs @@ -19,19 +19,36 @@ * 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 // 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); + } + } } } diff --git a/Greenshot/Controls/Pipette.cs b/Greenshot/Controls/Pipette.cs index d54e56d78..179642335 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 38e1aa737..d8d319fc3 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 fecebc33e..d6ec85b9b 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 41cb39bae..e44373aa9 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 00b5dfc90..3d0cd7655 100644 --- a/Greenshot/Destinations/EmailDestination.cs +++ b/Greenshot/Destinations/EmailDestination.cs @@ -26,19 +26,15 @@ 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 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 149173722..076cb1d67 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 151ba4d97..cf4733e7f 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 af44cd910..4b584add4 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/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/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/ResizeAdorner.cs b/Greenshot/Drawing/Adorners/ResizeAdorner.cs new file mode 100644 index 000000000..da536b1f5 --- /dev/null +++ b/Greenshot/Drawing/Adorners/ResizeAdorner.cs @@ -0,0 +1,186 @@ +/* + * 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 default "legacy" gripper adorner, not the one used for the tail in the speech-bubble + /// + public class ResizeAdorner : AbstractAdorner + { + private Rectangle _boundsBeforeResize = Rectangle.Empty; + private RectangleF _boundsAfterResize = RectangleF.Empty; + + public Positions Position { get; private set; } + + public ResizeAdorner(IDrawableContainer owner, Positions position) : base(owner) + { + Position = position; + } + + /// + /// Returns the cursor for when the mouse is over the adorner + /// + public override Cursor Cursor + { + get + { + bool isNotSwitched = Owner.Width >= 0; + if (Owner.Height < 0) + { + isNotSwitched = !isNotSwitched; + } + switch (Position) + { + case Positions.TopLeft: + case Positions.BottomRight: + return isNotSwitched ? Cursors.SizeNWSE : Cursors.SizeNESW; + case Positions.TopRight: + case Positions.BottomLeft: + return isNotSwitched ? 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; + } + } + } + + /// + /// 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/TargetAdorner.cs b/Greenshot/Drawing/Adorners/TargetAdorner.cs new file mode 100644 index 000000000..27e499bac --- /dev/null +++ b/Greenshot/Drawing/Adorners/TargetAdorner.cs @@ -0,0 +1,119 @@ +/* + * 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 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 : AbstractAdorner + { + + public TargetAdorner(IDrawableContainer owner, Point location) : base(owner) + { + Location = location; + } + + /// + /// Handle the mouse down + /// + /// + /// + public override void MouseDown(object sender, MouseEventArgs mouseEventArgs) + { + EditStatus = EditStatus.MOVING; + } + + /// + /// Handle the mouse move + /// + /// + /// + 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); + // 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(); + } + + /// + /// Draw the adorner + /// + /// PaintEventArgs + public override void Paint(PaintEventArgs paintEventArgs) + { + Graphics targetGraphics = paintEventArgs.Graphics; + Rectangle clipRectangle = paintEventArgs.ClipRectangle; + + var bounds = Bounds; + targetGraphics.FillRectangle(Brushes.Green, bounds.X, bounds.Y, bounds.Width, bounds.Height); + } + + /// + /// Made sure this adorner is transformed + /// + /// Matrix + public override void Transform(Matrix matrix) + { + if (matrix == null) + { + return; + } + Point[] points = new[] { Location }; + matrix.TransformPoints(points); + Location = points[0]; + } + } +} diff --git a/Greenshot/Drawing/ArrowContainer.cs b/Greenshot/Drawing/ArrowContainer.cs index fc39c61d9..93c05f5d5 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/CropContainer.cs b/Greenshot/Drawing/CropContainer.cs index e7588d7e8..5bf51021d 100644 --- a/Greenshot/Drawing/CropContainer.cs +++ b/Greenshot/Drawing/CropContainer.cs @@ -20,9 +20,11 @@ */ using System.Drawing; +using System.Runtime.Serialization; using Greenshot.Drawing.Fields; using Greenshot.Helpers; using Greenshot.Plugin.Drawing; +using GreenshotPlugin.Interfaces.Drawing; namespace Greenshot.Drawing { /// @@ -30,13 +32,28 @@ 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); + AddField(GetType(), FieldType.FLAGS, FieldFlag.CONFIRMABLE); } public override void Invalidate() { + if (_parent == null) + { + return; + } _parent.Invalidate(); } diff --git a/Greenshot/Drawing/CursorContainer.cs b/Greenshot/Drawing/CursorContainer.cs index fbc37d0b1..58901cbf3 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 { /// @@ -33,14 +34,26 @@ 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; 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 4699375ea..b1bdecbec 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,15 +28,19 @@ using Greenshot.IniFile; 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; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; +using System.Runtime.Serialization; 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 @@ -46,12 +51,23 @@ 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 const int M11 = 0; - private const int M12 = 1; - 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 { @@ -73,16 +89,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); @@ -99,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) { @@ -117,16 +123,12 @@ namespace Greenshot.Drawing { get { return _parent; } set { SwitchParent((Surface)value); } } - [NonSerialized] - protected Gripper[] _grippers; - private bool layoutSuspended; [NonSerialized] - private Gripper _targetGripper; - - public Gripper TargetGripper { + private TargetAdorner _targetAdorner; + public TargetAdorner TargetAdorner { get { - return _targetGripper; + return _targetAdorner; } } @@ -160,7 +162,6 @@ namespace Greenshot.Drawing { return; } left = value; - DoLayout(); } } @@ -172,7 +173,6 @@ namespace Greenshot.Drawing { return; } top = value; - DoLayout(); } } @@ -184,7 +184,6 @@ namespace Greenshot.Drawing { return; } width = value; - DoLayout(); } } @@ -196,7 +195,6 @@ namespace Greenshot.Drawing { return; } height = value; - DoLayout(); } } @@ -220,6 +218,19 @@ namespace Greenshot.Drawing { } } + /// + /// List of available Adorners + /// + [NonSerialized] + private IList _adorners = new List(); + public IList Adorners + { + get + { + return _adorners; + } + } + [NonSerialized] // will store current bounds of this DrawableContainer before starting a resize protected Rectangle _boundsBeforeResize = Rectangle.Empty; @@ -248,7 +259,6 @@ namespace Greenshot.Drawing { public DrawableContainer(Surface parent) { InitializeFields(); _parent = parent; - InitControls(); } public void Add(IFilter filter) { @@ -296,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; @@ -322,188 +335,35 @@ namespace Greenshot.Drawing { public virtual bool InitContent() { return true; } public virtual void OnDoubleClick() {} - - private void InitControls() { - InitGrippers(); - - 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 - } + protected void InitAdorner(Color gripperColor, Point location) { + _targetAdorner = new TargetAdorner(this, location); + Adorners.Add(_targetAdorner); } - 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 - } - } - - public void SuspendLayout() { - layoutSuspended = true; - } - - public void ResumeLayout() { - layoutSuspended = false; - 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}; + /// + /// Create the default adorners for a rectangle based container + /// - _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; - } + protected void CreateDefaultAdorners() { + if (Adorners.Count > 0) + { + LOG.Warn("Adorners are already defined!"); } - } - - 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; + // Create the GripperAdorners + 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)); } - 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 { get { return Filters.Count > 0; @@ -558,43 +418,10 @@ 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; Height = height; - ResumeLayout(); } /// @@ -606,10 +433,8 @@ namespace Greenshot.Drawing { } public void MoveBy(int dx, int dy) { - SuspendLayout(); Left += dx; Top += dy; - ResumeLayout(); } /// @@ -632,7 +457,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; @@ -645,7 +469,6 @@ namespace Greenshot.Drawing { // apply scaled bounds to this DrawableContainer ApplyBounds(_boundsAfterResize); - ResumeLayout(); Invalidate(); return true; } @@ -659,49 +482,26 @@ namespace Greenshot.Drawing { } protected virtual void SwitchParent(Surface newParent) { - // Target gripper - if (_parent != null && _targetGripper != null) { - _parent.Controls.Remove(_targetGripper); + if (newParent == Parent) + { + return; } - // Normal grippers - if (_parent != null && _grippers != null) { - for (int i=0; i<_grippers.Length; i++) { - _parent.Controls.Remove(_grippers[i]); + if (_parent != null) + { + // Remove FieldAggregator + FieldAggregator fieldAggregator = _parent.FieldAggregator; + if (fieldAggregator != null) + { + fieldAggregator.UnbindElement(this); } - } 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); } + _parent = newParent; foreach(IFilter filter in Filters) { filter.Parent = this; } } - // 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() { - return left.GetHashCode() ^ top.GetHashCode() ^ width.GetHashCode() ^ height.GetHashCode() ^ GetFields().GetHashCode(); - } - protected void OnPropertyChanged(string propertyName) { if (_propertyChanged != null) { _propertyChanged(this, new PropertyChangedEventArgs(propertyName)); @@ -715,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(); } @@ -730,7 +530,6 @@ namespace Greenshot.Drawing { if (e.Field.FieldType == FieldType.SHADOW) { accountForShadowChange = true; } - Invalidate(); } /// @@ -775,26 +574,16 @@ namespace Greenshot.Drawing { if (matrix == null) { return; } - 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(); + } protected virtual ScaleHelper.IDoubleProcessor GetAngleRoundProcessor() { diff --git a/Greenshot/Drawing/DrawableContainerList.cs b/Greenshot/Drawing/DrawableContainerList.cs index 56dc2b281..60a25cf24 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); } } @@ -171,26 +170,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 /// @@ -266,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); } } @@ -290,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, @@ -300,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; } @@ -316,13 +312,13 @@ 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)) { continue; } - if (Count > (i+1) && !elements.Contains(this[i+1])) { + if (Count > i+1 && !elements.Contains(this[i+1])) { SwapElements(i,i+1); } } @@ -332,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; } @@ -367,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]; @@ -417,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); @@ -457,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); @@ -470,7 +466,7 @@ namespace Greenshot.Drawing { item = new ToolStripMenuItem(Language.GetString(LangKey.editor_copytoclipboard)); item.Image = ((Image)(editorFormResources.GetObject("copyToolStripMenuItem.Image"))); item.Click += delegate { - ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), this); + ClipboardHelper.SetClipboardData(typeof(IDrawableContainerList), this); }; menu.Items.Add(item); @@ -478,15 +474,8 @@ namespace Greenshot.Drawing { item = new ToolStripMenuItem(Language.GetString(LangKey.editor_cuttoclipboard)); 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); @@ -494,22 +483,17 @@ namespace Greenshot.Drawing { item = new ToolStripMenuItem(Language.GetString(LangKey.editor_deleteelement)); 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; } } @@ -517,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; @@ -548,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(); @@ -561,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/EllipseContainer.cs b/Greenshot/Drawing/EllipseContainer.cs index 3a4651494..5389de37e 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() { @@ -59,12 +60,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 4e0fa10e4..203f590c3 100644 --- a/Greenshot/Drawing/Fields/AbstractFieldHolder.cs +++ b/Greenshot/Drawing/Fields/AbstractFieldHolder.cs @@ -26,13 +26,16 @@ 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 EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); @@ -41,26 +44,30 @@ namespace Greenshot.Drawing.Fields { /// [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 List fields = new List(); - - public AbstractFieldHolder() {} - + private IDictionary fieldsByType = new Dictionary(); + private IList fields = new List(); + + public AbstractFieldHolder() { } + [OnDeserialized] - private void OnDeserialized(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)); } }; @@ -68,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 c0754175f..ae610a5fa 100644 --- a/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs +++ b/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs @@ -18,87 +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 { - + [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 OnDeserialized(StreamingContext context) { + 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; } @@ -106,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/Binding/AbstractBindingConverter.cs b/Greenshot/Drawing/Fields/Binding/AbstractBindingConverter.cs index 684f54716..6ec6bfd55 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 e67f0ee21..2b7bb5fd9 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. */ + +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 c40edc993..7c2e7558f 100644 --- a/Greenshot/Drawing/Fields/FieldAggregator.cs +++ b/Greenshot/Drawing/Fields/FieldAggregator.cs @@ -19,15 +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; -using log4net; - -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 @@ -39,38 +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 List boundContainers; + public class FieldAggregator : AbstractFieldHolder + { + + private IDrawableContainerList boundContainers; private bool internalUpdateRunning = false; - - enum Status {IDLE, BINDING, UPDATING}; - + + enum Status { IDLE, BINDING, UPDATING }; + private static readonly ILog LOG = LogManager.GetLogger(typeof(FieldAggregator)); private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); - public FieldAggregator() { - foreach(FieldType fieldType in FieldType.Values) { + 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(); @@ -78,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); @@ -184,5 +221,5 @@ namespace Greenshot.Drawing.Fields { } } - } + } } diff --git a/Greenshot/Drawing/Fields/FieldType.cs b/Greenshot/Drawing/Fields/FieldType.cs index f51de36a9..3090e3e51 100644 --- a/Greenshot/Drawing/Fields/FieldType.cs +++ b/Greenshot/Drawing/Fields/FieldType.cs @@ -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/FilterContainer.cs b/Greenshot/Drawing/FilterContainer.cs index 3793bf5fc..13bf98888 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() { @@ -52,7 +65,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 +82,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 d784c5b93..af9f8cb9f 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 0402bd521..92602695a 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/IFilter.cs b/Greenshot/Drawing/Filters/IFilter.cs index c5bc7d0ad..87e713cb5 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/Filters/MagnifierFilter.cs b/Greenshot/Drawing/Filters/MagnifierFilter.cs index f5e96be30..79165133b 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 53853d7a5..87e684884 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 23ea7f408..23de535f6 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,21 +34,19 @@ 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 /// public FreehandContainer(Surface parent) : base(parent) { - Init(); Width = parent.Width; Height = parent.Height; Top = 0; @@ -61,16 +58,6 @@ namespace Greenshot.Drawing { AddField(GetType(), FieldType.LINE_COLOR, Color.Red); } - - protected void Init() { - if (_grippers != null) { - for (int i = 0; i < _grippers.Length; i++) { - _grippers[i].Enabled = false; - _grippers[i].Visible = false; - } - } - } - public override void Transform(Matrix matrix) { Point[] points = capturePoints.ToArray(); @@ -80,11 +67,7 @@ namespace Greenshot.Drawing { RecalculatePath(); } - [OnDeserialized] - private void OnDeserialized(StreamingContext context) { - InitGrippers(); - DoLayout(); - Init(); + protected override void OnDeserialized(StreamingContext context) { RecalculatePath(); } @@ -119,7 +102,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 +215,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); } @@ -258,17 +241,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/HighlightContainer.cs b/Greenshot/Drawing/HighlightContainer.cs index 5dc015495..8f5ce953c 100644 --- a/Greenshot/Drawing/HighlightContainer.cs +++ b/Greenshot/Drawing/HighlightContainer.cs @@ -19,11 +19,11 @@ * along with this program. If not, see . */ using System; -using System.Drawing; using System.Runtime.Serialization; using Greenshot.Drawing.Fields; using Greenshot.Drawing.Filters; +using GreenshotPlugin.Interfaces.Drawing; namespace Greenshot.Drawing { /// @@ -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 e2ab3c27d..0ef03b688 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 { /// @@ -31,11 +32,23 @@ 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; 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 3cec536d2..188588cc8 100644 --- a/Greenshot/Drawing/ImageContainer.cs +++ b/Greenshot/Drawing/ImageContainer.cs @@ -27,6 +27,8 @@ using GreenshotPlugin.Core; using System.Drawing.Drawing2D; using Greenshot.Core; using log4net; +using System.Runtime.Serialization; +using GreenshotPlugin.Interfaces.Drawing; namespace Greenshot.Drawing { /// @@ -34,7 +36,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; @@ -58,6 +60,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 1cf4ef4c1..d8e458206 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,19 +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() { - if (_grippers != null) { - foreach (int index in new[] { 1, 2, 3, 5, 6, 7 }) { - _grippers[index].Enabled = false; - } - } + Adorners.Add(new MoveAdorner(this, Positions.TopLeft)); + Adorners.Add(new MoveAdorner(this, Positions.BottomRight)); } public override void Draw(Graphics graphics, RenderMode rm) { @@ -86,7 +82,7 @@ namespace Greenshot.Drawing { Top + currentStep + Height); currentStep++; - alpha = alpha - (basealpha / steps); + alpha = alpha - basealpha / steps; } } } @@ -113,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 fcb6afbca..57a2e5bd0 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 { /// @@ -37,15 +38,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/Positions.cs b/Greenshot/Drawing/Positions.cs new file mode 100644 index 000000000..63d7cb759 --- /dev/null +++ b/Greenshot/Drawing/Positions.cs @@ -0,0 +1,38 @@ +/* + * 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 . + */ + +namespace Greenshot.Drawing +{ + /// + /// Position + /// + 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/RectangleContainer.cs b/Greenshot/Drawing/RectangleContainer.cs index 5bf16de04..de06c9b78 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() { @@ -69,7 +86,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 +103,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 b38e48330..08b85632d 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 b0cdf3f76..f90643ae9 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. /// @@ -50,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,9 +57,9 @@ namespace Greenshot.Drawing { /// Restore the target gripper /// /// - [OnDeserialized] - private void SetValuesOnDeserialized(StreamingContext context) { - InitTargetGripper(Color.Green, _storedTargetGripperLocation); + protected override void OnDeserialized(StreamingContext context) + { + InitAdorner(Color.Green, _storedTargetGripperLocation); } #endregion @@ -90,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); } @@ -116,9 +114,9 @@ namespace Greenshot.Drawing { Point newGripperLocation = _initialGripperPoint; newGripperLocation.Offset(xOffset, yOffset); - if (TargetGripper.Location != newGripperLocation) { + if (TargetAdorner.Location != newGripperLocation) { Invalidate(); - TargetGripperMove(newGripperLocation.X, newGripperLocation.Y); + TargetAdorner.Location = newGripperLocation; Invalidate(); } return returnValue; @@ -180,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.Left, TargetGripper.Top); + 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 @@ -192,10 +190,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, TargetAdorner.Location.X, TargetAdorner.Location.Y); 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); } @@ -209,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; @@ -223,7 +221,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 +251,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 e4a1bb337..386a23787 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; @@ -87,6 +94,10 @@ namespace Greenshot.Drawing { /// /// protected override void SwitchParent(Surface newParent) { + if (newParent == Parent) + { + return; + } if (Parent != null) { ((Surface)Parent).RemoveStepLabel(this); } @@ -118,7 +129,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 +157,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 +178,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 1eea446cc..8b56d16f3 100644 --- a/Greenshot/Drawing/Surface.cs +++ b/Greenshot/Drawing/Surface.cs @@ -27,12 +27,13 @@ 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 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; @@ -40,12 +41,13 @@ using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Windows.Forms; -namespace Greenshot.Drawing { - +namespace Greenshot.Drawing +{ /// /// Description of Surface. /// - public class Surface : Control, ISurface { + public class Surface : Control, ISurface + { private static ILog LOG = LogManager.GetLogger(typeof(Surface)); public static int Count = 0; private static CoreConfiguration conf = IniConfig.GetIniSection(); @@ -56,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; } } @@ -70,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; } } @@ -169,7 +186,7 @@ namespace Greenshot.Drawing { /// all selected elements, do not serialize /// [NonSerialized] - private DrawableContainerList selectedElements; + private readonly IDrawableContainerList selectedElements; /// /// the element we are drawing with, do not serialize @@ -208,12 +225,17 @@ 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); + 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); } @@ -222,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 == stopAtContainer) { + foreach (var possibleThis in _stepLabels) + { + if (possibleThis.Equals(stopAtContainer)) + { break; } - if (IsOnSurface(possibleThis)) { + if (IsOnSurface(possibleThis)) + { number++; } } @@ -238,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. @@ -267,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; } @@ -281,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; } } @@ -293,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; } } @@ -302,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; } } @@ -311,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; } @@ -319,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; } } @@ -331,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; } } @@ -343,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; } } @@ -355,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); @@ -372,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; } } @@ -384,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; } @@ -392,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; } } @@ -404,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); @@ -427,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(); } @@ -450,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); } @@ -459,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); } @@ -476,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; } @@ -514,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; } } @@ -547,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; } } @@ -556,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; } } @@ -568,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; } } @@ -582,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); @@ -608,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; @@ -625,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); } } @@ -648,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; @@ -694,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; @@ -709,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; @@ -717,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; @@ -725,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; @@ -733,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; @@ -741,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; @@ -750,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); @@ -774,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; } } @@ -797,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; } @@ -812,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(); @@ -853,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); @@ -868,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(); } @@ -901,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; @@ -942,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); @@ -965,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(); @@ -980,39 +1126,82 @@ 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 + /// + /// MouseEventArgs + /// IAdorner + private IAdorner FindActiveAdorner(MouseEventArgs mouseEventArgs) + { + foreach (IDrawableContainer drawableContainer in selectedElements) + { + foreach (IAdorner adorner in drawableContainer.Adorners) + { + + if (adorner.IsActive || 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) { + void SurfaceMouseDown(object sender, MouseEventArgs e) + { + + // Handle Adorners + var adorner = FindActiveAdorner(e); + if (adorner != null) + { + adorner.MouseDown(sender, e); + return; + } + _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; @@ -1021,25 +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 (_drawingElement != null) + { _drawingElement.Status = _undrawnElement.DefaultEditMode; - _drawingElement.PropertyChanged += ElementPropertyChanged; - if (!_drawingElement.HandleMouseDown(_mouseStart.X, _mouseStart.Y)) { + if (!_drawingElement.HandleMouseDown(_mouseStart.X, _mouseStart.Y)) + { _drawingElement.Left = _mouseStart.X; _drawingElement.Top = _mouseStart.Y; } @@ -1047,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; } } @@ -1064,52 +1261,80 @@ namespace Greenshot.Drawing { /// /// /// - void SurfaceMouseUp(object sender, MouseEventArgs e) { + void SurfaceMouseUp(object sender, MouseEventArgs e) + { + + // Handle Adorners + var adorner = FindActiveAdorner(e); + if (adorner != null) + { + adorner.MouseUp(sender, e); + return; + } + 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) { - selectedElements.ShowGrippers(); + + 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; } @@ -1125,30 +1350,49 @@ namespace Greenshot.Drawing { /// /// /// - void SurfaceMouseMove(object sender, MouseEventArgs e) { + void SurfaceMouseMove(object sender, MouseEventArgs e) + { + // Handle Adorners + var adorner = FindActiveAdorner(e); + if (adorner != null) + { + adorner.MouseMove(sender, e); + return; + } + 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.HideGrippers(); + 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); @@ -1159,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(); } @@ -1181,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; @@ -1200,36 +1449,44 @@ 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); } - + /// /// 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; - if (Rectangle.Empty.Equals(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; } - 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; @@ -1241,35 +1498,45 @@ 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); } + + // No clipping for the adorners + targetGraphics.ResetClip(); + // Draw adorners last + foreach (var drawableContainer in selectedElements) + { + 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) + { } /// @@ -1277,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; @@ -1318,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); } } @@ -1363,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(); } } @@ -1373,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); } } @@ -1384,15 +1713,19 @@ 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); - foreach (IDrawableContainer dc in selectedDCs){ - if (dc.Equals(_cropContainer)){ + foreach (IDrawableContainer dc in selectedDCs) + { + 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(); @@ -1404,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); 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); } } @@ -1489,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); @@ -1502,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); @@ -1512,80 +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) { - container.HideGrippers(); + public void DeselectElement(IDrawableContainer container, bool generateEvents = true) + { container.Selected = false; selectedElements.Remove(container); 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.Invalidate(); - element.HideGrippers(); - element.Selected = false; - selectedElements.Remove(element); - 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.ShowGrippers(); 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); } @@ -1593,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(); } /// @@ -1604,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); @@ -1651,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); } @@ -1663,8 +2065,10 @@ namespace Greenshot.Drawing { /// /// Property for accessing the elements on the surface /// - public DrawableContainerList Elements { - get { + public IDrawableContainerList Elements + { + get + { return _elements; } } @@ -1672,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 d4c4ec2a0..397a4501e 100644 --- a/Greenshot/Drawing/TextContainer.cs +++ b/Greenshot/Drawing/TextContainer.cs @@ -22,8 +22,8 @@ using Greenshot.Drawing.Fields; using Greenshot.Helpers; using Greenshot.Memento; -using Greenshot.Plugin; using Greenshot.Plugin.Drawing; +using GreenshotPlugin.Interfaces.Drawing; using System; using System.ComponentModel; using System.Drawing; @@ -72,7 +72,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); @@ -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(); } @@ -123,8 +127,10 @@ namespace Greenshot.Drawing { } private void Init() { - _stringFormat = new StringFormat(); - _stringFormat.Trimming = StringTrimming.EllipsisWord; + _stringFormat = new StringFormat + { + Trimming = StringTrimming.EllipsisWord + }; CreateTextBox(); @@ -178,15 +184,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 +205,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 +305,7 @@ namespace Greenshot.Drawing { } } } + _font?.Dispose(); _font = new Font(fam, fontSize, fs, GraphicsUnit.Pixel); _textBox.Font = _font; } @@ -332,8 +344,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) { @@ -390,7 +402,7 @@ namespace Greenshot.Drawing { DrawSelectionBorder(graphics, rect); } - if (text == null || text.Length == 0 ) { + if (string.IsNullOrEmpty(text) ) { return; } @@ -411,11 +423,12 @@ 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 8c11bbf13..05f4dbca1 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 4fa200cb9..566f1cd70 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 a8a5d13de..4891f6124 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(IDrawableContainerList).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 +76,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 +144,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 +190,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 +207,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 +217,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 +231,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 +254,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 +295,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 +311,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 +332,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 +364,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 +389,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 +409,7 @@ namespace Greenshot { public ISurface Surface { get { - return surface; + return _surface; } set { SetSurface(value); @@ -403,7 +421,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 +429,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 +478,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 +495,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 +758,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 +779,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 +871,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 +879,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 +893,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 +907,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 +939,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 +959,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 +975,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 +1003,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); @@ -1028,17 +1047,17 @@ 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 { - hideToolstripItems(); + HideToolstripItems(); } propertiesToolStrip.ResumeLayout(); } - private void hideToolstripItems() { + private void HideToolstripItems() { foreach(ToolStripItem toolStripItem in propertiesToolStrip.Items) { toolStripItem.Visible = false; } @@ -1047,23 +1066,24 @@ 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) { + 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); @@ -1071,25 +1091,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 +1118,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 +1163,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 +1226,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 +1272,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 +1286,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 +1302,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 +1317,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 +1332,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 +1374,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 9c6333668..0963b3d7f 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 17c2f09ea..b8a20ddc6 100644 --- a/Greenshot/Forms/MainForm.cs +++ b/Greenshot/Forms/MainForm.cs @@ -52,7 +52,7 @@ namespace Greenshot { private static ILog LOG; private static ResourceMutex _applicationMutex; private static CoreConfiguration _conf; - public static string LogFileLocation = null; + public static string LogFileLocation; public static void Start(string[] args) { bool isAlreadyRunning = false; @@ -227,7 +227,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(); @@ -550,7 +550,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); } } } @@ -877,7 +877,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/MovableShowColorForm.cs b/Greenshot/Forms/MovableShowColorForm.cs index f2560ba18..325e37e1d 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/PrintOptionsDialog.cs b/Greenshot/Forms/PrintOptionsDialog.cs index fa585a8a9..36793fdc7 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/ResizeSettingsForm.cs b/Greenshot/Forms/ResizeSettingsForm.cs index 0956b62b6..379f7fc55 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 663d8d08c..567185e7b 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; @@ -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; @@ -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 d0089a6cc..388ef2426 100644 --- a/Greenshot/Forms/TornEdgeSettingsForm.cs +++ b/Greenshot/Forms/TornEdgeSettingsForm.cs @@ -22,11 +22,10 @@ using System; using System.Drawing; using System.Windows.Forms; using Greenshot.Core; -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 +59,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/Greenshot.csproj b/Greenshot/Greenshot.csproj index eb756b36a..dd9d31648 100644 --- a/Greenshot/Greenshot.csproj +++ b/Greenshot/Greenshot.csproj @@ -75,7 +75,12 @@ + + + + + @@ -101,16 +106,12 @@ - - Component - - @@ -214,13 +215,14 @@ + + - 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 diff --git a/Greenshot/Helpers/CaptureHelper.cs b/Greenshot/Helpers/CaptureHelper.cs index a1c8f3ae8..e70685a93 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; @@ -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) { + int blackPercentageScreen = blackCountScreen * 100 / screenPixels; + 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/Helpers/CopyData.cs b/Greenshot/Helpers/CopyData.cs index c32ca596e..0237b4744 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 4ddd7d27e..bdb8ad64c 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 2b7e0d4ed..79e3a3bba 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 { @@ -645,6 +639,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 +649,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 @@ -664,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 @@ -722,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 @@ -738,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)); @@ -776,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 { @@ -789,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 { @@ -803,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 { @@ -816,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 { @@ -829,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 ea3c626a9..1487fecf0 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 d1cd44b7e..805afb0f1 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 35c04a960..80f36413d 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 73e8e3bea..79d1c0267 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 802d776fd..0387a18f8 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 29b1e0eed..d84e2fb70 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 ee53a76bb..70ffdd5de 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 fb43662a5..fc01d8ba5 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; @@ -119,15 +116,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 +135,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 +154,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 +168,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 +218,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 +241,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 +252,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 +263,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 +282,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(); @@ -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 f3f34aff8..fe36cbb56 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 2d2692269..afb09df91 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 e2ce53ab2..0df6384c8 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 30b79e745..493539bb7 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,14 +43,8 @@ namespace Greenshot.Memento { protected virtual void Dispose(bool disposing) { //if (disposing) { } - drawableContainer = null; - surface = null; - } - - public LangKey ActionLanguageKey { - get { - return LangKey.none; - } + _drawableContainer = null; + _surface = null; } public bool Merge(IMemento otherMemento) { @@ -59,16 +53,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/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 f64b7762d..7314f097a 100644 --- a/Greenshot/Memento/ChangeFieldHolderMemento.cs +++ b/Greenshot/Memento/ChangeFieldHolderMemento.cs @@ -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 Field fieldToBeChanged; - private 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 b44ddd784..ed7350243 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; @@ -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 2e4241068..123d260f0 100644 --- a/Greenshot/Memento/DrawableContainerBoundsChangeMemento.cs +++ b/Greenshot/Memento/DrawableContainerBoundsChangeMemento.cs @@ -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 { + public class DrawableContainerBoundsChangeMemento : IMemento + { List points = new List(); List sizes = new List(); - List listOfdrawableContainer; - - private void StoreBounds() { - foreach(IDrawableContainer drawableContainer in listOfdrawableContainer) { + 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 0fcacbdb6..13b3da9ea 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 0f954e58c..973f59c94 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; @@ -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/Greenshot/Processors/TitleFixProcessor.cs b/Greenshot/Processors/TitleFixProcessor.cs index bbd3c61be..f75d6c5d7 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/Greenshot/releases/additional_files/readme.txt.template b/Greenshot/releases/additional_files/readme.txt.template index e050d9648..5f93deaf5 100644 --- a/Greenshot/releases/additional_files/readme.txt.template +++ b/Greenshot/releases/additional_files/readme.txt.template @@ -36,6 +36,28 @@ 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 +* 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... + + +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/GreenshotBoxPlugin/BoxCredentials.cs b/GreenshotBoxPlugin/BoxCredentials.cs index bff044e9f..47a221609 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 653f92ffa..2d4492fa9 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 fc2524f60..5cc5b4a3c 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/GreenshotBoxPlugin/Properties/AssemblyInfo.cs b/GreenshotBoxPlugin/Properties/AssemblyInfo.cs index 413f7d5fe..b80f0bc86 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 b6852fcdb..8b4f3958b 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 0f52ceb9b..8765ecba9 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 d216f6028..f7d95c145 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 e98f85aac..8287d7c3b 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 889b5f665..a76402c79 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 1b161d7d9..31c236cf3 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 400d20d42..2f7f59362 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 71ffe073e..214c1f315 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 ea3732328..d9783fc6e 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 16be2bd05..c7437e703 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 0deace234..4fd1dd01c 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 66e0f15b8..f85a5481b 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 62d219a01..4cc3c4e8c 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 e0157343a..489df2fca 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 a7905990f..367a86de3 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 4e64daf5d..3536083de 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 1c4ec1469..526e4759f 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 462722e8b..b6f785e5d 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 39543feca..2b3276214 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 0c95b7a44..2e525f351 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 bd9c7f8db..772a9b4a2 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 4d0c19c07..c8eecb182 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 3a4502353..bc3583f97 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 63951c68b..09c8c5960 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 45dcebbae..eeee6e223 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 47e084756..3ab4d632e 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 5a6c59a0b..2a8ce0956 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 b18a44f8f..cb5e0d929 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 79c3faaca..ca4fd4b9f 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/ImgurConfiguration.cs b/GreenshotImgurPlugin/ImgurConfiguration.cs index 48bba7c4b..db8edf152 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/ImgurDestination.cs b/GreenshotImgurPlugin/ImgurDestination.cs index cd1349fa2..58d5ed38e 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/ImgurInfo.cs b/GreenshotImgurPlugin/ImgurInfo.cs index a39c2326a..40dd8c029 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/ImgurPlugin.cs b/GreenshotImgurPlugin/ImgurPlugin.cs index 65d2c41e7..7655a7a76 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/ImgurUtils.cs b/GreenshotImgurPlugin/ImgurUtils.cs index cb4beaa3b..ad314d05a 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; diff --git a/GreenshotImgurPlugin/Properties/AssemblyInfo.cs b/GreenshotImgurPlugin/Properties/AssemblyInfo.cs index 9e66e2995..2080d0fcb 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 3a35a95de..943b8619a 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 0f9ecdcf0..ed43f199f 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 a08b8fc17..5e6e639da 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 4f03cb9ad..a69a28c93 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 fcf69899b..bbce4e9bc 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 045027cf0..217205e5e 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 4d43d9ace..521b9ef58 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 4bf25d8b6..38a34799f 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 73aa72444..c4d35cc1c 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 5b0405723..8a5004793 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 e2f7a415d..80eb49a54 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 5080678f5..61242866b 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 29663f698..7719a03e8 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 c98d2649d..f33072941 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 dc9cb7052..438f6a1fb 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 f634c1072..ef9637701 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 8d57f7f32..50ed481ba 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 ffbe0be2d..7e65d3758 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 8b911ab86..1cacc070a 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 a2da6e2fd..2c602caed 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 ac4ed4675..64c6a02e5 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 3569c2da2..a2458b13b 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 03919db89..712cdd44b 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 c8e72f2b2..faad20870 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 42a31fa24..92481e605 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 203d02cd8..a9843cee7 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 f45492e53..ffb5209b9 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 5a1976ec1..d822ef44e 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 7e9d53a9c..8e5013b6d 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 ca598ebf8..036555ce1 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 b7003ce97..6eff2da00 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/AnimatingForm.cs b/GreenshotPlugin/Controls/AnimatingForm.cs index ebbf5fda4..394866ec8 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 765ae7e22..499b83518 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 66c7273e2..a864d2974 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 699dcd93f..d0f13a6f0 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 64dc6f127..ad6920c91 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 67d74172f..5d6e7e1dd 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 fe47b59eb..98ccc1f10 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 e304e0f25..565dd53fe 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 36a909462..694f94233 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 6f1ef9f10..e19bce5b9 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 396977c3b..bcc9b168a 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 403f939d0..abeb80e0f 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 03922b1e2..29ebf2908 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 cc599587c..411a595ba 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 addc626d2..a9dd482aa 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 e23d981db..bfd5471a7 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 f543ffe83..1ae92b903 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 8629bc6e1..1dee4013a 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 f61217c72..7bd756fef 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(); @@ -438,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/Controls/IGreenshotConfigBindable.cs b/GreenshotPlugin/Controls/IGreenshotConfigBindable.cs index a83c90fa9..462d4b74b 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 0b7ebaf6e..7a4b0f93f 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 b5cdd8cd1..6e5bdd46d 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 d02d05a8d..17978419d 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 81cef1be8..c636ecbfd 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 ac99facbb..855ff2a04 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 a3cf5de35..846545ba6 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,25 +72,27 @@ 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)); + 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; // 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 64acf4f75..054a01110 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 8613f82f8..978e8f9b2 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 1cdf9547c..401e72d1d 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 c13f7c9dd..3c815fcbd 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); /// @@ -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); + } } /// @@ -168,7 +175,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 280f8d6a4..69130babc 100644 --- a/GreenshotPlugin/Core/ClipboardHelper.cs +++ b/GreenshotPlugin/Core/ClipboardHelper.cs @@ -347,9 +347,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)) { @@ -737,7 +737,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}); } /// @@ -746,7 +746,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 d4a367090..f7361aadb 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 31038e3ae..6d8138963 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. @@ -101,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. @@ -137,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 { @@ -148,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 { @@ -199,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 { @@ -284,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 { @@ -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/Effects.cs b/GreenshotPlugin/Core/Effects.cs index 567dc4f29..8cbf6862f 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 db36fba1e..9c7d03368 100644 --- a/GreenshotPlugin/Core/EventDelay.cs +++ b/GreenshotPlugin/Core/EventDelay.cs @@ -23,10 +23,10 @@ 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; + waitTime = ticks; } public bool Check() { diff --git a/GreenshotPlugin/Core/FastBitmap.cs b/GreenshotPlugin/Core/FastBitmap.cs index 26da6df48..a3432875c 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 6fb51b764..f3c5af085 100644 --- a/GreenshotPlugin/Core/FilenameHelper.cs +++ b/GreenshotPlugin/Core/FilenameHelper.cs @@ -38,10 +38,11 @@ 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; - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); private const string UNSAFE_REPLACEMENT = "_"; /// @@ -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! @@ -159,7 +160,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 +172,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 +192,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]); @@ -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 /// @@ -418,9 +464,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 +501,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 8244775de..5528b788d 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 f5998b0c3..514256986 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 0f98ae73e..e0ee6c801 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 0e3e7044a..2e993a57d 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 44790752a..4a2660c78 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 11172bd92..20a007da5 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 { @@ -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/NetworkHelper.cs b/GreenshotPlugin/Core/NetworkHelper.cs index 30e3ec020..ff0e43fdb 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 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) { @@ -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 Bitmap bitmap; - private SurfaceOutputSettings outputSettings; - private string fileName; + private readonly Bitmap _bitmap; + private readonly SurfaceOutputSettings _outputSettings; + private readonly string _fileName; public BitmapContainer(Bitmap bitmap, SurfaceOutputSettings outputSettings, string filename) { - this.bitmap = bitmap; - this.outputSettings = outputSettings; - fileName = filename; + _bitmap = bitmap; + _outputSettings = outputSettings; + _fileName = filename; } /// @@ -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 ISurface surface; - private SurfaceOutputSettings outputSettings; - private string fileName; + private readonly ISurface _surface; + private readonly SurfaceOutputSettings _outputSettings; + private readonly string _fileName; public SurfaceContainer(ISurface surface, SurfaceOutputSettings outputSettings, string filename) { - this.surface = surface; - this.outputSettings = outputSettings; - fileName = filename; + _surface = surface; + _outputSettings = outputSettings; + _fileName = filename; } /// @@ -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); } diff --git a/GreenshotPlugin/Core/OAuthHelper.cs b/GreenshotPlugin/Core/OAuthHelper.cs index f7adc99fd..4112aae86 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)) { @@ -1033,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/OperatingSystemExtensions.cs b/GreenshotPlugin/Core/OperatingSystemExtensions.cs new file mode 100644 index 000000000..ffe07bc6f --- /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/PluginUtils.cs b/GreenshotPlugin/Core/PluginUtils.cs index 645904e5f..513c93c83 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; @@ -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/QuantizerHelper.cs b/GreenshotPlugin/Core/QuantizerHelper.cs index e7c03c7c1..d29f4412b 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/StringExtensions.cs b/GreenshotPlugin/Core/StringExtensions.cs index 4414e05c0..f2d5097b0 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 df217342e..199eb7333 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;} } @@ -423,6 +423,7 @@ namespace GreenshotPlugin.Core { /// /// [DllImport("gdi32", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DeleteObject(IntPtr hObject); private WindowCapture() { @@ -643,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 71f930686..f6bd71e68 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 /// @@ -47,7 +42,7 @@ namespace GreenshotPlugin.Core { /// public class WindowsEnumerator { #region Member Variables - private List items = null; + private List items; #endregion /// @@ -89,7 +84,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; @@ -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,25 +145,29 @@ 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 /// public class WindowDetails : IEquatable{ - private const string METRO_WINDOWS_CLASS = "Windows.UI.Core.CoreWindow"; + private const string METRO_WINDOWS_CLASS = "Windows.UI.Core.CoreWindow"; // Windows 10 uses ApplicationFrameWindow private const string METRO_APPLAUNCHER_CLASS = "ImmersiveLauncher"; private const string METRO_GUTTER_CLASS = "ImmersiveGutter"; - private static 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 { @@ -180,33 +179,37 @@ 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 = null; - private IntPtr parentHandle = IntPtr.Zero; - private WindowDetails parent = null; - private bool frozen = false; + private List _childWindows; + private IntPtr _parentHandle = IntPtr.Zero; + private WindowDetails _parent; + private bool _frozen; - public bool isApp { + /// + /// This checks if the window is a Windows 8 App + /// For Windows 10 most normal code works, as it's hosted inside "ApplicationFrameWindow" + /// + public bool IsApp { get { 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 +218,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 IntPtr hWnd = IntPtr.Zero; + private readonly IntPtr _hWnd = IntPtr.Zero; /// /// To allow items to be compared, the hash code @@ -257,15 +260,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 +300,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 +324,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 +360,7 @@ namespace GreenshotPlugin.Core { /// /// public static void RegisterIgnoreHandle(IntPtr ignoreHandle) { - ignoreHandles.Add(ignoreHandle); + IgnoreHandles.Add(ignoreHandle); } /// @@ -365,24 +368,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 +434,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 +452,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 +468,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 +479,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 +496,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 +504,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 +546,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 +580,7 @@ namespace GreenshotPlugin.Core { return null; } WindowDetails windowDetails = new WindowDetails(tmphWnd); - windowDetails.parent = this; + windowDetails._parent = this; return windowDetails; } @@ -584,38 +589,38 @@ namespace GreenshotPlugin.Core { /// public IntPtr Handle { get { - return hWnd; + return _hWnd; } } - private string text = null; + 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 = null; + 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 +629,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 +648,8 @@ namespace GreenshotPlugin.Core { /// public bool Maximised { get { - if (isApp) { + if (IsApp) + { if (Visible) { Rectangle windowRectangle = WindowRectangle; foreach (Screen screen in Screen.AllScreens) { @@ -656,13 +662,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 +685,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 +711,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 +757,13 @@ 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 = 0; - private const long CACHE_TIME = TimeSpan.TicksPerSecond * 2; + private Rectangle _previousWindowRectangle = Rectangle.Empty; + private long _lastWindowRectangleRetrieveTime; + private const long CacheTime = TimeSpan.TicksPerSecond * 2; + /// /// Gets the bounding rectangle of the window /// @@ -764,33 +771,59 @@ 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()) { - GetExtendedFrameBounds(out windowRect); + 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) + { + // Somehow DWM doesn't calculate it corectly, there is a 1 pixel border around the capture + // Remove this border, currently it's fixed but TODO: Make it depend on the OS? + windowRect.Inflate(-1, -1); + _previousWindowRectangle = windowRect; + _lastWindowRectangleRetrieveTime = now; + return windowRect; + } } if (windowRect.IsEmpty) { - GetWindowRect(out windowRect); + if (GetWindowRect(out windowRect)) + { + Win32Error error = Win32.GetLastErrorCode(); + LOG.WarnFormat("Couldn't retrieve the windows rectangle: {0}", Win32.GetMessage(error)); + } } // Correction for maximized windows, only if it's not an app - if (!HasParent && !isApp && Maximised) { - 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; } } @@ -819,8 +852,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 for {0}, error: {1}", Text, Win32.GetMessage(error)); + } return clientRect; } } @@ -840,10 +877,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(); @@ -855,10 +892,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)); } } @@ -881,10 +918,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)); } } @@ -893,7 +930,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; @@ -910,15 +947,17 @@ 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; 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); @@ -927,13 +966,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 - Point formLocation; Rectangle windowRectangle = WindowRectangle; + Point formLocation = windowRectangle.Location; Size borderSize = new Size(); bool doesCaptureFit = false; if (!Maximised) { @@ -942,7 +981,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); } } @@ -962,7 +1001,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); @@ -972,32 +1011,38 @@ 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 { + // TODO: Also 8.x? + if (Environment.OSVersion.IsWindows10()) + { + 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; @@ -1024,7 +1069,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(); } @@ -1047,7 +1092,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) @@ -1056,7 +1101,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(); } @@ -1067,9 +1112,9 @@ 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) { + 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"); @@ -1114,8 +1159,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); @@ -1222,7 +1267,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(); @@ -1273,7 +1318,7 @@ namespace GreenshotPlugin.Core { return false; } - foreach (string excludeProcess in excludeProcessesFromFreeze) { + foreach (string excludeProcess in ExcludeProcessesFromFreeze) { if (titleOrProcessname.ToLower().Contains(excludeProcess)) { return false; } @@ -1401,7 +1446,7 @@ namespace GreenshotPlugin.Core { /// /// The Window Handle public WindowDetails(IntPtr hWnd) { - this.hWnd = hWnd; + this._hWnd = hWnd; } /// @@ -1411,7 +1456,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(); } @@ -1431,7 +1476,7 @@ namespace GreenshotPlugin.Core { public bool IsGreenshot { get { try { - if (!isMetroApp) { + if (!IsMetroApp) { using (Process thisWindowProcess = Process) { return "Greenshot".Equals(thisWindowProcess.MainModule.FileVersionInfo.ProductName); } @@ -1462,7 +1507,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; } @@ -1470,7 +1515,6 @@ namespace GreenshotPlugin.Core { /// /// Recursive "find children which" /// - /// Window to look into /// point to check for /// public WindowDetails FindChildUnderPoint(Point point) { @@ -1499,7 +1543,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(); @@ -1515,7 +1559,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; } @@ -1534,7 +1578,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. @@ -1574,7 +1618,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(); @@ -1585,7 +1629,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; } @@ -1652,7 +1696,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/GreenshotPlugin.csproj b/GreenshotPlugin/GreenshotPlugin.csproj index d4da13521..040062bc8 100644 --- a/GreenshotPlugin/GreenshotPlugin.csproj +++ b/GreenshotPlugin/GreenshotPlugin.csproj @@ -42,6 +42,7 @@ + @@ -66,6 +67,10 @@ + + + + diff --git a/GreenshotPlugin/IEInterop/IHTMLBodyElement.cs b/GreenshotPlugin/IEInterop/IHTMLBodyElement.cs index 107027365..6121c851b 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 089b9bb58..d7e631f37 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 ddbcdfe8a..eb6e2f1c4 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 ae7a7c8eb..6712f82ba 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 f164237e3..1b510a80e 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 b84d0d871..76c895dce 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 99c4c26a3..e8e3a3171 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 003f4b034..77deef016 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 e5b5231bc..8b564d09c 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 fdd216e5d..00eb7d376 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 f520a59df..796e37a15 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 75c5c44d6..46cdfb3f4 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 f894fe67b..6d7907850 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 4ebff42f0..2f07c0891 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 4412f5e55..949a5fe03 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 d7fe06570..7de9cc819 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 a604203e9..7bef90a83 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 c198ef772..147a2cde0 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 42f03dc63..a8baece76 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 ab8732654..9247a710f 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 6e06bd75f..fd853646a 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 40eff770b..659a899ba 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 c00b5bae0..027808087 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 fbaea2680..75c683617 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 cf29ab2d7..97982d172 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 70d9b1bb6..0c0f44c3e 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/Drawing/Adorners/IAdorner.cs b/GreenshotPlugin/Interfaces/Drawing/Adorners/IAdorner.cs new file mode 100644 index 000000000..27f825de4 --- /dev/null +++ b/GreenshotPlugin/Interfaces/Drawing/Adorners/IAdorner.cs @@ -0,0 +1,91 @@ +/* + * 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 + { + /// + /// 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 + /// + 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 e2a253a49..02e52cd65 100644 --- a/GreenshotPlugin/Interfaces/Drawing/Container.cs +++ b/GreenshotPlugin/Interfaces/Drawing/Container.cs @@ -24,69 +24,87 @@ using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Windows.Forms; using System.ComponentModel; +using System.Collections.Generic; +using GreenshotPlugin.Interfaces.Drawing; +using Greenshot.Plugin.Drawing.Adorners; -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 { - get; - } - - bool hasFilters { + Rectangle Bounds + { get; } - EditStatus Status { + Rectangle DrawingBounds + { + get; + } + + void ApplyBounds(RectangleF newBounds); + + bool hasFilters + { + get; + } + + EditStatus Status + { get; set; } 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); @@ -94,43 +112,102 @@ namespace Greenshot.Plugin.Drawing { bool HandleMouseMove(int x, int y); bool InitContent(); void MakeBoundsChangeUndoable(bool allowMerge); - EditStatus DefaultEditMode { + EditStatus DefaultEditMode + { get; } + + /// + /// Available adorners for the DrawableContainer + /// + 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/Greenshot/Drawing/Gripper.cs b/GreenshotPlugin/Interfaces/Drawing/IMemento.cs similarity index 55% rename from Greenshot/Drawing/Gripper.cs rename to GreenshotPlugin/Interfaces/Drawing/IMemento.cs index 52ee5adbf..5e3588e20 100644 --- a/Greenshot/Drawing/Gripper.cs +++ b/GreenshotPlugin/Interfaces/Drawing/IMemento.cs @@ -18,39 +18,26 @@ * 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; - -namespace Greenshot.Drawing { +namespace Greenshot.Memento { /// - /// Grippers are the dragable edges of our containers + /// Description of IMemento. /// - public class Gripper : Label { - /// - /// Constants for anchor/gripper position: - /// 0 1 2 - /// 7 3 - /// 6 5 4 + public interface IMemento : IDisposable { + /// + /// Restores target to the state memorized by this memento. /// - 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; - } + /// + /// 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/Forms/ImageEditor.cs b/GreenshotPlugin/Interfaces/Forms/ImageEditor.cs index 1f589e41c..242827792 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 e21141206..ca0ea04b7 100644 --- a/GreenshotPlugin/Interfaces/Generic.cs +++ b/GreenshotPlugin/Interfaces/Generic.cs @@ -18,64 +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.Drawing.Imaging; +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, @@ -94,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; @@ -103,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 @@ -117,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. @@ -155,7 +173,8 @@ namespace Greenshot.Plugin { long SaveElementsToStream(Stream stream); void LoadElementsFromStream(Stream stream); - bool HasSelectedElements { + bool HasSelectedElements + { get; } void RemoveSelectedElements(); @@ -163,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? /// @@ -174,29 +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 diff --git a/GreenshotPlugin/Interfaces/IDestination.cs b/GreenshotPlugin/Interfaces/IDestination.cs index 4da036457..764c337b6 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 131e4ab6b..e74989c9e 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 5416aa294..6d6301d6f 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 98bda9f1c..3cde05cf5 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 31fd60f2e..a3d39a52b 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 97e052037..f06c452d5 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 3fa090e3b..789d9f703 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/DWM.cs b/GreenshotPlugin/UnmanagedHelpers/DWM.cs index 8488ea45d..22b9c4486 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/Enumerations.cs b/GreenshotPlugin/UnmanagedHelpers/Enumerations.cs index 6a3bd273f..a2139906d 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 dd225e914..30ab46857 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); } } @@ -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) { @@ -76,8 +77,14 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// A hbitmap SafeHandle implementation /// public class SafeHBitmapHandle : SafeObjectHandle { + + /// + /// Needed for marshalling return values + /// [SecurityCritical] - private SafeHBitmapHandle() : base(true) { + public SafeHBitmapHandle() : base(true) + { + } [SecurityCritical] @@ -90,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] @@ -104,8 +115,12 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// A dibsection SafeHandle implementation /// public class SafeDibSectionHandle : SafeObjectHandle { + /// + /// Needed for marshalling return values + /// [SecurityCritical] - private SafeDibSectionHandle() : base(true) { + public SafeDibSectionHandle() : base(true) + { } [SecurityCritical] @@ -122,20 +137,23 @@ namespace GreenshotPlugin.UnmanagedHelpers { [DllImport("gdi32", SetLastError = true)] private static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject); - private SafeHandle hdc; - + private readonly SafeHandle _hdc; + /// + /// Needed for marshalling return values + /// [SecurityCritical] - private SafeSelectObjectHandle() : base(true) { + public SafeSelectObjectHandle() : base(true) + { } [SecurityCritical] public SafeSelectObjectHandle(SafeDCHandle hdc, SafeHandle newHandle) : base(true) { - this.hdc = hdc; + _hdc = hdc; SetHandle(SelectObject(hdc.DangerousGetHandle(), newHandle.DangerousGetHandle())); } protected override bool ReleaseHandle() { - SelectObject(hdc.DangerousGetHandle(), handle); + SelectObject(_hdc.DangerousGetHandle(), handle); return true; } } @@ -149,10 +167,15 @@ 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); + /// + /// Needed for marshalling return values + /// [SecurityCritical] - private SafeCompatibleDCHandle() : base(true) { + public SafeCompatibleDCHandle() : base(true) + { } [SecurityCritical] @@ -173,20 +196,24 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// A DeviceContext SafeHandle implementation /// public class SafeDeviceContextHandle : SafeDCHandle { - private Graphics graphics = null; - + private readonly Graphics _graphics; + + /// + /// Needed for marshalling return values + /// [SecurityCritical] - private SafeDeviceContextHandle() : base(true) { + public SafeDeviceContextHandle() : base(true) + { } [SecurityCritical] public SafeDeviceContextHandle(Graphics graphics, IntPtr preexistingHandle) : base(true) { - this.graphics = graphics; + _graphics = graphics; SetHandle(preexistingHandle); } protected override bool ReleaseHandle() { - graphics.ReleaseHdc(handle); + _graphics.ReleaseHdc(handle); return true; } @@ -194,7 +221,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()); } } @@ -219,41 +246,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)] @@ -378,10 +370,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 b4feab39b..171c12f31 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/Kernel32.cs b/GreenshotPlugin/UnmanagedHelpers/Kernel32.cs index e72bf53ba..a0b097a65 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 8d807a4c1..037e3d40e 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)] - private struct BROWSEINFO { - public IntPtr hwndOwner; - public IntPtr pidlRoot; - public IntPtr pszDisplayName; - [MarshalAs(UnmanagedType.LPTStr)] - public string lpszTitle; - public uint ulFlags; - public IntPtr lpfn; - public int lParam; - public IntPtr iImage; - } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] private struct SHFILEINFO { - public IntPtr hIcon; - public int iIcon; - public uint dwAttributes; + public readonly IntPtr hIcon; + public readonly int iIcon; + public readonly uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] - public string szDisplayName; + public readonly string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] - public string szTypeName; + public readonly string szTypeName; }; #endregion @@ -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/Structs.cs b/GreenshotPlugin/UnmanagedHelpers/Structs.cs index 82037faba..3ad858623 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/GreenshotPlugin/UnmanagedHelpers/User32.cs b/GreenshotPlugin/UnmanagedHelpers/User32.cs index a526daf65..ea14a6674 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,12 +98,12 @@ 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); + public static extern bool IsZoomed(IntPtr hwnd); [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] - public extern static int GetClassName (IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); + public static extern int GetClassName (IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); [DllImport("user32", SetLastError = true)] public static extern uint GetClassLong(IntPtr hWnd, int nIndex); [DllImport("user32", SetLastError = true, EntryPoint = "GetClassLongPtr")] @@ -111,15 +111,15 @@ namespace GreenshotPlugin.UnmanagedHelpers { [DllImport("user32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags); - [DllImport("user32", SetLastError=true)] - public extern static IntPtr SendMessage(IntPtr hWnd, uint wMsg, IntPtr wParam, IntPtr lParam); + [DllImport("user32", CharSet=CharSet.Unicode, SetLastError=true)] + public static extern IntPtr SendMessage(IntPtr hWnd, uint wMsg, IntPtr wParam, IntPtr lParam); [DllImport("user32", SetLastError = true)] - public extern static IntPtr SendMessage(IntPtr hWnd, uint wMsg, IntPtr wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam); + public static extern IntPtr SendMessage(IntPtr hWnd, uint wMsg, IntPtr wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam); [DllImport("user32", SetLastError = true, EntryPoint = "GetWindowLong")] - public extern static int GetWindowLong(IntPtr hwnd, int index); + public static extern int GetWindowLong(IntPtr hwnd, int index); [DllImport("user32", SetLastError = true, EntryPoint = "GetWindowLongPtr")] - public extern static IntPtr GetWindowLongPtr(IntPtr hwnd, int nIndex); - [DllImport("user32", SetLastError = true)] + 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")] public static extern IntPtr SetWindowLongPtr(IntPtr hWnd, int index, IntPtr styleFlags); @@ -131,17 +131,17 @@ 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); [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)] @@ -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,16 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// A SafeHandle class implementation for the hIcon /// public class SafeIconHandle : SafeHandleZeroOrMinusOneIsInvalid { - private SafeIconHandle() : base(true) { + + /// + /// Needed for marshalling return values + /// + [SecurityCritical] + public SafeIconHandle() : base(true) + { } + public SafeIconHandle(IntPtr hIcon) : base(true) { SetHandle(hIcon); } @@ -381,24 +388,28 @@ 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; + + /// + /// Needed for marshalling return values + /// + public SafeWindowDCHandle() : base(true) + { } [SecurityCritical] public SafeWindowDCHandle(IntPtr hWnd, IntPtr preexistingHandle) : base(true) { - this.hWnd = hWnd; + _hWnd = hWnd; SetHandle(preexistingHandle); } [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode=true)] protected override bool ReleaseHandle() { - bool returnValue = ReleaseDC(hWnd, handle); + bool returnValue = ReleaseDC(_hWnd, handle); return returnValue; } - public static SafeWindowDCHandle fromDesktop() { + public static SafeWindowDCHandle FromDesktop() { IntPtr hWndDesktop = User32.GetDesktopWindow(); IntPtr hDCDesktop = GetWindowDC(hWndDesktop); return new SafeWindowDCHandle(hWndDesktop, hDCDesktop); diff --git a/appveyor12.yml b/appveyor12.yml index af9116897..25e95b989 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: