Merge remote-tracking branch 'remotes/origin/master' into release/1.2.9

This commit is contained in:
Robin 2016-05-24 13:13:48 +02:00
commit 0323705513
276 changed files with 5382 additions and 3666 deletions

View file

@ -21,7 +21,6 @@
using System.Reflection; using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information // set of attributes. Change these attribute values to modify the information

View file

@ -26,6 +26,7 @@ using Greenshot.Drawing.Fields;
using GreenshotPlugin.UnmanagedHelpers; using GreenshotPlugin.UnmanagedHelpers;
using Greenshot.IniFile; using Greenshot.IniFile;
using Greenshot.Core; using Greenshot.Core;
using GreenshotPlugin.Interfaces.Drawing;
namespace Greenshot.Configuration { namespace Greenshot.Configuration {
/// <summary> /// <summary>
@ -73,9 +74,10 @@ namespace Greenshot.Configuration {
/// <param name="requestingType">Type of the class for which to create the field</param> /// <param name="requestingType">Type of the class for which to create the field</param>
/// <param name="fieldType">FieldType of the field to construct</param> /// <param name="fieldType">FieldType of the field to construct</param>
/// <param name="scope">FieldType of the field to construct</param> /// <param name="preferredDefaultValue"></param>
/// <returns>a new Field of the given fieldType, with the scope of it's value being restricted to the Type scope</returns> /// <returns>a new Field of the given fieldType, with the scope of it's value being restricted to the Type scope</returns>
public Field CreateField(Type requestingType, FieldType fieldType, object preferredDefaultValue) { public IField CreateField(Type requestingType, IFieldType fieldType, object preferredDefaultValue)
{
string requestingTypeName = requestingType.Name; string requestingTypeName = requestingType.Name;
string requestedField = requestingTypeName + "." + fieldType.Name; string requestedField = requestingTypeName + "." + fieldType.Name;
object fieldValue = preferredDefaultValue; object fieldValue = preferredDefaultValue;
@ -101,8 +103,9 @@ namespace Greenshot.Configuration {
returnField.Value = fieldValue; returnField.Value = fieldValue;
return returnField; return returnField;
} }
public void UpdateLastFieldValue(Field field) { public void UpdateLastFieldValue(IField field)
{
string requestedField = field.Scope + "." + field.FieldType.Name; string requestedField = field.Scope + "." + field.FieldType.Name;
// Check if the configuration exists // Check if the configuration exists
if (LastUsedFieldValues == null) { if (LastUsedFieldValues == null) {
@ -110,9 +113,9 @@ namespace Greenshot.Configuration {
} }
// check if settings for the requesting type exist, if not create! // check if settings for the requesting type exist, if not create!
if (LastUsedFieldValues.ContainsKey(requestedField)) { if (LastUsedFieldValues.ContainsKey(requestedField)) {
LastUsedFieldValues[requestedField] = field.myValue; LastUsedFieldValues[requestedField] = field.Value;
} else { } else {
LastUsedFieldValues.Add(requestedField, field.myValue); LastUsedFieldValues.Add(requestedField, field.Value);
} }
} }

View file

@ -36,7 +36,8 @@ namespace Greenshot.Controls {
set; set;
} }
public BindableToolStripButton() :base() { public BindableToolStripButton()
{
CheckedChanged += BindableToolStripButton_CheckedChanged; CheckedChanged += BindableToolStripButton_CheckedChanged;
} }

View file

@ -36,7 +36,8 @@ namespace Greenshot.Controls {
set; set;
} }
public BindableToolStripComboBox() :base() { public BindableToolStripComboBox()
{
SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged; SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged;
} }

View file

@ -38,9 +38,6 @@ namespace Greenshot.Controls {
set; set;
} }
public BindableToolStripDropDownButton() {
}
public object SelectedTag { public object SelectedTag {
get { if(Tag==null && DropDownItems.Count>0) Tag=DropDownItems[0].Tag; return Tag; } get { if(Tag==null && DropDownItems.Count>0) Tag=DropDownItems[0].Tag; return Tag; }
set { AdoptFromTag(value); } set { AdoptFromTag(value); }

View file

@ -22,7 +22,6 @@
using Greenshot.IniFile; using Greenshot.IniFile;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using System.Drawing; using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms; using System.Windows.Forms;
namespace Greenshot.Controls { namespace Greenshot.Controls {
@ -30,7 +29,7 @@ namespace Greenshot.Controls {
/// ToolStripProfessionalRenderer which draws the Check correctly when the icons are larger /// ToolStripProfessionalRenderer which draws the Check correctly when the icons are larger
/// </summary> /// </summary>
public class ContextMenuToolStripProfessionalRenderer : ToolStripProfessionalRenderer { public class ContextMenuToolStripProfessionalRenderer : ToolStripProfessionalRenderer {
private static CoreConfiguration coreConfiguration = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration coreConfiguration = IniConfig.GetIniSection<CoreConfiguration>();
private static Image scaledCheckbox; private static Image scaledCheckbox;
protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) { protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) {

View file

@ -41,12 +41,16 @@ namespace Greenshot.Controls {
} }
} }
public FontFamilyComboBox() : base() { public FontFamilyComboBox()
ComboBox.DataSource = FontFamily.Families; {
ComboBox.DisplayMember = "Name"; if (ComboBox != null)
SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged; {
ComboBox.DrawMode = DrawMode.OwnerDrawFixed; ComboBox.DataSource = FontFamily.Families;
ComboBox.DrawItem += ComboBox_DrawItem; ComboBox.DisplayMember = "Name";
SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged;
ComboBox.DrawMode = DrawMode.OwnerDrawFixed;
ComboBox.DrawItem += ComboBox_DrawItem;
}
} }
void ComboBox_DrawItem(object sender, DrawItemEventArgs e) { void ComboBox_DrawItem(object sender, DrawItemEventArgs e) {
@ -58,7 +62,7 @@ namespace Greenshot.Controls {
if (e.Index > -1) { if (e.Index > -1) {
FontFamily fontFamily = Items[e.Index] as FontFamily; FontFamily fontFamily = Items[e.Index] as FontFamily;
FontStyle fontStyle = FontStyle.Regular; FontStyle fontStyle = FontStyle.Regular;
if (!fontFamily.IsStyleAvailable(FontStyle.Regular)) { if (fontFamily != null && !fontFamily.IsStyleAvailable(FontStyle.Regular)) {
if (fontFamily.IsStyleAvailable(FontStyle.Bold)) { if (fontFamily.IsStyleAvailable(FontStyle.Bold)) {
fontStyle = FontStyle.Bold; fontStyle = FontStyle.Bold;
} else if (fontFamily.IsStyleAvailable(FontStyle.Italic)) { } else if (fontFamily.IsStyleAvailable(FontStyle.Italic)) {
@ -70,10 +74,16 @@ namespace Greenshot.Controls {
} }
} }
try { try {
DrawText(e.Graphics, fontFamily, fontStyle, e.Bounds, fontFamily.Name); if (fontFamily != null)
{
DrawText(e.Graphics, fontFamily, fontStyle, e.Bounds, fontFamily.Name);
}
} catch { } catch {
// If the drawing failed, BUG-1770 seems to have a weird case that causes: Font 'Lucida Sans Typewriter' does not support style 'Regular' // 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 // Uncomment this if you actually like the way the focus rectangle looks
@ -89,7 +99,7 @@ namespace Greenshot.Controls {
/// <param name="bounds"></param> /// <param name="bounds"></param>
/// <param name="text"></param> /// <param name="text"></param>
private void DrawText(Graphics graphics, FontFamily fontFamily, FontStyle fontStyle, Rectangle bounds, string text) { 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 // Make sure the text is visible by centering it in the line
using (StringFormat stringFormat = new StringFormat()) { using (StringFormat stringFormat = new StringFormat()) {
stringFormat.LineAlignment = StringAlignment.Center; stringFormat.LineAlignment = StringAlignment.Center;

View file

@ -32,11 +32,9 @@ namespace Greenshot.Controls {
enum NativeConstants : uint { enum NativeConstants : uint {
MA_ACTIVATE = 1, MA_ACTIVATE = 1,
MA_ACTIVATEANDEAT = 2, MA_ACTIVATEANDEAT = 2,
MA_NOACTIVATE = 3,
MA_NOACTIVATEANDEAT = 4,
} }
private bool clickThrough = false; private bool _clickThrough;
/// <summary> /// <summary>
/// Gets or sets whether the ToolStripEx honors item clicks when its containing form does not have input focus. /// Gets or sets whether the ToolStripEx honors item clicks when its containing form does not have input focus.
/// </summary> /// </summary>
@ -45,17 +43,17 @@ namespace Greenshot.Controls {
/// </remarks> /// </remarks>
public bool ClickThrough { public bool ClickThrough {
get { get {
return clickThrough; return _clickThrough;
} }
set { set {
clickThrough = value; _clickThrough = value;
} }
} }
protected override void WndProc(ref Message m) { protected override void WndProc(ref Message m) {
base.WndProc(ref 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; m.Result = (IntPtr)NativeConstants.MA_ACTIVATE;
} }
} }

View file

@ -19,19 +19,36 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
/// <summary>
/// See: http://nickstips.wordpress.com/2010/03/03/c-panel-resets-scroll-position-after-focus-is-lost-and-regained/
/// </summary>
using System.Drawing; using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
namespace GreenshotPlugin.Controls { namespace GreenshotPlugin.Controls {
/// <summary>
/// See: http://nickstips.wordpress.com/2010/03/03/c-panel-resets-scroll-position-after-focus-is-lost-and-regained/
/// </summary>
public class NonJumpingPanel : Panel { public class NonJumpingPanel : Panel {
protected override Point ScrollToControl(Control activeControl) { protected override Point ScrollToControl(Control activeControl) {
// Returning the current location prevents the panel from // Returning the current location prevents the panel from
// scrolling to the active control when the panel loses and regains focus // scrolling to the active control when the panel loses and regains focus
return DisplayRectangle.Location; return DisplayRectangle.Location;
} }
/// <summary>
/// Add horizontal scrolling to the panel, when using the wheel and the shift key is pressed
/// </summary>
/// <param name="e">MouseEventArgs</param>
protected override void OnMouseWheel(MouseEventArgs e)
{
if (VScroll && (ModifierKeys & Keys.Shift) == Keys.Shift)
{
VScroll = false;
base.OnMouseWheel(e);
VScroll = true;
}
else
{
base.OnMouseWheel(e);
}
}
} }
} }

View file

@ -34,7 +34,7 @@ namespace Greenshot.Controls {
private MovableShowColorForm movableShowColorForm; private MovableShowColorForm movableShowColorForm;
private bool dragging; private bool dragging;
private Cursor _cursor; private Cursor _cursor;
private Bitmap _image; private readonly Bitmap _image;
private const int VK_ESC = 27; private const int VK_ESC = 27;
public event EventHandler<PipetteUsedArgs> PipetteUsed; public event EventHandler<PipetteUsedArgs> PipetteUsed;
@ -111,10 +111,14 @@ namespace Greenshot.Controls {
/// </summary> /// </summary>
/// <param name="e">MouseEventArgs</param> /// <param name="e">MouseEventArgs</param>
protected override void OnMouseUp(MouseEventArgs e) { 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 //Release Capture should consume MouseUp when canceled with the escape key
User32.ReleaseCapture(); User32.ReleaseCapture();
PipetteUsed(this, new PipetteUsedArgs(movableShowColorForm.color)); if (PipetteUsed != null)
{
PipetteUsed(this, new PipetteUsedArgs(movableShowColorForm.color));
}
} }
base.OnMouseUp(e); base.OnMouseUp(e);
} }

View file

@ -32,11 +32,9 @@ namespace Greenshot.Controls {
enum NativeConstants : uint { enum NativeConstants : uint {
MA_ACTIVATE = 1, MA_ACTIVATE = 1,
MA_ACTIVATEANDEAT = 2, MA_ACTIVATEANDEAT = 2,
MA_NOACTIVATE = 3,
MA_NOACTIVATEANDEAT = 4,
} }
private bool clickThrough = false; private bool _clickThrough;
/// <summary> /// <summary>
/// Gets or sets whether the ToolStripEx honors item clicks when its containing form does not have input focus. /// Gets or sets whether the ToolStripEx honors item clicks when its containing form does not have input focus.
/// </summary> /// </summary>
@ -46,17 +44,17 @@ namespace Greenshot.Controls {
public bool ClickThrough { public bool ClickThrough {
get { get {
return clickThrough; return _clickThrough;
} }
set { set {
clickThrough = value; _clickThrough = value;
} }
} }
protected override void WndProc(ref Message m) { protected override void WndProc(ref Message m) {
base.WndProc(ref 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; m.Result = (IntPtr)NativeConstants.MA_ACTIVATE;
} }
} }

View file

@ -25,16 +25,12 @@ using System.Windows.Forms;
using Greenshot.Configuration; using Greenshot.Configuration;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using Greenshot.Plugin; using Greenshot.Plugin;
using Greenshot.IniFile;
using log4net;
namespace Greenshot.Destinations { namespace Greenshot.Destinations {
/// <summary> /// <summary>
/// Description of ClipboardDestination. /// Description of ClipboardDestination.
/// </summary> /// </summary>
public class ClipboardDestination : AbstractDestination { public class ClipboardDestination : AbstractDestination {
private static ILog LOG = LogManager.GetLogger(typeof(ClipboardDestination));
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
public const string DESIGNATION = "Clipboard"; public const string DESIGNATION = "Clipboard";
public override string Designation { public override string Designation {

View file

@ -32,11 +32,11 @@ namespace Greenshot.Destinations {
/// Description of EditorDestination. /// Description of EditorDestination.
/// </summary> /// </summary>
public class EditorDestination : AbstractDestination { public class EditorDestination : AbstractDestination {
private static ILog LOG = LogManager.GetLogger(typeof(EditorDestination)); private static readonly ILog LOG = LogManager.GetLogger(typeof(EditorDestination));
private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>(); private static readonly EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>();
public const string DESIGNATION = "Editor"; public const string DESIGNATION = "Editor";
private IImageEditor editor = null; private readonly IImageEditor editor;
private static Image greenshotIcon = GreenshotResources.getGreenshotIcon().ToBitmap(); private static readonly Image greenshotIcon = GreenshotResources.getGreenshotIcon().ToBitmap();
public EditorDestination() { public EditorDestination() {
} }
@ -79,8 +79,8 @@ namespace Greenshot.Destinations {
} }
public override IEnumerable<IDestination> DynamicDestinations() { public override IEnumerable<IDestination> DynamicDestinations() {
foreach (IImageEditor editor in ImageEditorForm.Editors) { foreach (IImageEditor someEditor in ImageEditorForm.Editors) {
yield return new EditorDestination(editor); yield return new EditorDestination(someEditor);
} }
} }

View file

@ -26,19 +26,15 @@ using Greenshot.Configuration;
using Greenshot.Helpers; using Greenshot.Helpers;
using Greenshot.Plugin; using Greenshot.Plugin;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using Greenshot.IniFile;
using log4net;
namespace Greenshot.Destinations { namespace Greenshot.Destinations {
/// <summary> /// <summary>
/// Description of EmailDestination. /// Description of EmailDestination.
/// </summary> /// </summary>
public class EmailDestination : AbstractDestination { public class EmailDestination : AbstractDestination {
private static ILog LOG = LogManager.GetLogger(typeof(EmailDestination)); private static readonly Image mailIcon = GreenshotResources.getImage("Email.Image");
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>(); private static bool isActiveFlag;
private static Image mailIcon = GreenshotResources.getImage("Email.Image"); private static string mapiClient;
private static bool isActiveFlag = false;
private static string mapiClient = null;
public const string DESIGNATION = "EMail"; public const string DESIGNATION = "EMail";
static EmailDestination() { static EmailDestination() {

View file

@ -35,8 +35,8 @@ namespace Greenshot.Destinations {
/// Description of FileSaveAsDestination. /// Description of FileSaveAsDestination.
/// </summary> /// </summary>
public class FileDestination : AbstractDestination { public class FileDestination : AbstractDestination {
private static ILog LOG = LogManager.GetLogger(typeof(FileDestination)); private static readonly ILog LOG = LogManager.GetLogger(typeof(FileDestination));
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
public const string DESIGNATION = "FileNoDialog"; public const string DESIGNATION = "FileNoDialog";
public override string Designation { public override string Designation {
@ -103,20 +103,23 @@ namespace Greenshot.Destinations {
LOG.InfoFormat("Not overwriting: {0}", ex1.Message); LOG.InfoFormat("Not overwriting: {0}", ex1.Message);
// when we don't allow to overwrite present a new SaveWithDialog // when we don't allow to overwrite present a new SaveWithDialog
fullPath = ImageOutput.SaveWithDialog(surface, captureDetails); fullPath = ImageOutput.SaveWithDialog(surface, captureDetails);
outputMade = (fullPath != null); outputMade = fullPath != null;
} catch (Exception ex2) { } catch (Exception ex2) {
LOG.Error("Error saving screenshot!", ex2); LOG.Error("Error saving screenshot!", ex2);
// Show the problem // Show the problem
MessageBox.Show(Language.GetString(LangKey.error_save), Language.GetString(LangKey.error)); MessageBox.Show(Language.GetString(LangKey.error_save), Language.GetString(LangKey.error));
// when save failed we present a SaveWithDialog // when save failed we present a SaveWithDialog
fullPath = ImageOutput.SaveWithDialog(surface, captureDetails); fullPath = ImageOutput.SaveWithDialog(surface, captureDetails);
outputMade = (fullPath != null); outputMade = fullPath != null;
} }
// Don't overwrite filename if no output is made // Don't overwrite filename if no output is made
if (outputMade) { if (outputMade) {
exportInformation.ExportMade = outputMade; exportInformation.ExportMade = outputMade;
exportInformation.Filepath = fullPath; exportInformation.Filepath = fullPath;
captureDetails.Filename = fullPath; if (captureDetails != null)
{
captureDetails.Filename = fullPath;
}
conf.OutputFileAsFullpath = fullPath; conf.OutputFileAsFullpath = fullPath;
} }

View file

@ -34,7 +34,7 @@ namespace Greenshot.Destinations {
/// </summary> /// </summary>
public class FileWithDialogDestination : AbstractDestination { public class FileWithDialogDestination : AbstractDestination {
private static ILog LOG = LogManager.GetLogger(typeof(FileWithDialogDestination)); private static ILog LOG = LogManager.GetLogger(typeof(FileWithDialogDestination));
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
public const string DESIGNATION = "FileDialog"; public const string DESIGNATION = "FileDialog";
public override string Designation { public override string Designation {

View file

@ -28,18 +28,14 @@ using Greenshot.Configuration;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using Greenshot.Plugin; using Greenshot.Plugin;
using Greenshot.Helpers; using Greenshot.Helpers;
using Greenshot.IniFile;
using log4net;
namespace Greenshot.Destinations { namespace Greenshot.Destinations {
/// <summary> /// <summary>
/// Description of PrinterDestination. /// Description of PrinterDestination.
/// </summary> /// </summary>
public class PrinterDestination : AbstractDestination { public class PrinterDestination : AbstractDestination {
private static ILog LOG = LogManager.GetLogger(typeof(PrinterDestination));
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
public const string DESIGNATION = "Printer"; public const string DESIGNATION = "Printer";
public string printerName = null; public string printerName;
public PrinterDestination() { public PrinterDestination() {
} }

View file

@ -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 <http://www.gnu.org/licenses/>.
*/
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;
}
/// <summary>
/// Returns the cursor for when the mouse is over the adorner
/// </summary>
public virtual Cursor Cursor
{
get
{
return Cursors.SizeAll;
}
}
public virtual IDrawableContainer Owner
{
get;
set;
}
/// <summary>
/// Test if the point is inside the adorner
/// </summary>
/// <param name="point"></param>
/// <returns></returns>
public virtual bool HitTest(Point point)
{
Rectangle hitBounds = Bounds;
hitBounds.Inflate(3, 3);
return hitBounds.Contains(point);
}
/// <summary>
/// Handle the mouse down
/// </summary>
/// <param name="sender"></param>
/// <param name="mouseEventArgs"></param>
public virtual void MouseDown(object sender, MouseEventArgs mouseEventArgs)
{
}
/// <summary>
/// Handle the mouse move
/// </summary>
/// <param name="sender"></param>
/// <param name="mouseEventArgs"></param>
public virtual void MouseMove(object sender, MouseEventArgs mouseEventArgs)
{
}
/// <summary>
/// Handle the mouse up
/// </summary>
/// <param name="sender"></param>
/// <param name="mouseEventArgs"></param>
public virtual void MouseUp(object sender, MouseEventArgs mouseEventArgs)
{
EditStatus = EditStatus.IDLE;
}
/// <summary>
/// Return the location of the adorner
/// </summary>
public virtual Point Location
{
get;
set;
}
/// <summary>
/// Return the bounds of the Adorner
/// </summary>
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);
}
}
/// <summary>
/// The adorner is active if the edit status is not idle or undrawn
/// </summary>
public virtual bool IsActive
{
get
{
return EditStatus != EditStatus.IDLE && EditStatus != EditStatus.UNDRAWN;
}
}
/// <summary>
/// Draw the adorner
/// </summary>
/// <param name="paintEventArgs">PaintEventArgs</param>
public virtual void Paint(PaintEventArgs paintEventArgs)
{
}
/// <summary>
/// We ignore the Transform, as the coordinates are directly bound to those of the owner
/// </summary>
/// <param name="matrix"></param>
public virtual void Transform(Matrix matrix)
{
}
}
}

View file

@ -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 <http://www.gnu.org/licenses/>.
*/
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
{
/// <summary>
/// This is the adorner for the line based containers
/// </summary>
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;
}
/// <summary>
/// Returns the cursor for when the mouse is over the adorner
/// </summary>
public override Cursor Cursor
{
get
{
return Cursors.SizeAll;
}
}
/// <summary>
/// Handle the mouse down
/// </summary>
/// <param name="sender"></param>
/// <param name="mouseEventArgs"></param>
public override void MouseDown(object sender, MouseEventArgs mouseEventArgs)
{
EditStatus = EditStatus.RESIZING;
_boundsBeforeResize = new Rectangle(Owner.Left, Owner.Top, Owner.Width, Owner.Height);
_boundsAfterResize = _boundsBeforeResize;
}
/// <summary>
/// Handle the mouse move
/// </summary>
/// <param name="sender"></param>
/// <param name="mouseEventArgs"></param>
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();
}
/// <summary>
/// Return the location of the adorner
/// </summary>
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);
}
}
/// <summary>
/// Draw the adorner
/// </summary>
/// <param name="paintEventArgs">PaintEventArgs</param>
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);
}
}
}

View file

@ -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 <http://www.gnu.org/licenses/>.
*/
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
{
/// <summary>
/// This is the default "legacy" gripper adorner, not the one used for the tail in the speech-bubble
/// </summary>
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;
}
/// <summary>
/// Returns the cursor for when the mouse is over the adorner
/// </summary>
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;
}
}
}
/// <summary>
/// Handle the mouse down
/// </summary>
/// <param name="sender"></param>
/// <param name="mouseEventArgs"></param>
public override void MouseDown(object sender, MouseEventArgs mouseEventArgs)
{
EditStatus = EditStatus.RESIZING;
_boundsBeforeResize = new Rectangle(Owner.Left, Owner.Top, Owner.Width, Owner.Height);
_boundsAfterResize = _boundsBeforeResize;
}
/// <summary>
/// Handle the mouse move
/// </summary>
/// <param name="sender"></param>
/// <param name="mouseEventArgs"></param>
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();
}
/// <summary>
/// Return the location of the adorner
/// </summary>
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);
}
}
/// <summary>
/// Draw the adorner
/// </summary>
/// <param name="paintEventArgs">PaintEventArgs</param>
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);
}
}
}

View file

@ -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 <http://www.gnu.org/licenses/>.
*/
using Greenshot.Plugin.Drawing;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace Greenshot.Drawing.Adorners
{
/// <summary>
/// This implements the special "gripper" for the Speech-Bubble tail
/// </summary>
public class TargetAdorner : AbstractAdorner
{
public TargetAdorner(IDrawableContainer owner, Point location) : base(owner)
{
Location = location;
}
/// <summary>
/// Handle the mouse down
/// </summary>
/// <param name="sender"></param>
/// <param name="mouseEventArgs"></param>
public override void MouseDown(object sender, MouseEventArgs mouseEventArgs)
{
EditStatus = EditStatus.MOVING;
}
/// <summary>
/// Handle the mouse move
/// </summary>
/// <param name="sender"></param>
/// <param name="mouseEventArgs"></param>
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();
}
/// <summary>
/// Draw the adorner
/// </summary>
/// <param name="paintEventArgs">PaintEventArgs</param>
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);
}
/// <summary>
/// Made sure this adorner is transformed
/// </summary>
/// <param name="matrix">Matrix</param>
public override void Transform(Matrix matrix)
{
if (matrix == null)
{
return;
}
Point[] points = new[] { Location };
matrix.TransformPoints(points);
Location = points[0];
}
}
}

View file

@ -79,7 +79,7 @@ namespace Greenshot.Drawing {
Top + currentStep + Height); Top + currentStep + Height);
currentStep++; currentStep++;
alpha = alpha - (basealpha / steps); alpha = alpha - basealpha / steps;
} }
} }

View file

@ -20,9 +20,11 @@
*/ */
using System.Drawing; using System.Drawing;
using System.Runtime.Serialization;
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using Greenshot.Helpers; using Greenshot.Helpers;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using GreenshotPlugin.Interfaces.Drawing;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
@ -30,13 +32,28 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
public class CropContainer : DrawableContainer { public class CropContainer : DrawableContainer {
public CropContainer(Surface parent) : base(parent) { 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() { protected override void InitializeFields() {
AddField(GetType(), FieldType.FLAGS, FieldType.Flag.CONFIRMABLE); AddField(GetType(), FieldType.FLAGS, FieldFlag.CONFIRMABLE);
} }
public override void Invalidate() { public override void Invalidate() {
if (_parent == null)
{
return;
}
_parent.Invalidate(); _parent.Invalidate();
} }

View file

@ -26,6 +26,7 @@ using System.Windows.Forms;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using log4net; using log4net;
using System.Runtime.Serialization;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
@ -33,14 +34,26 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
[Serializable] [Serializable]
public class CursorContainer : DrawableContainer, ICursorContainer { 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; protected Cursor cursor;
public CursorContainer(Surface parent) : base(parent) { 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); Load(filename);
} }

View file

@ -20,6 +20,7 @@
*/ */
using Greenshot.Configuration; using Greenshot.Configuration;
using Greenshot.Drawing.Adorners;
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using Greenshot.Drawing.Filters; using Greenshot.Drawing.Filters;
using Greenshot.Helpers; using Greenshot.Helpers;
@ -27,15 +28,19 @@ using Greenshot.IniFile;
using Greenshot.Memento; using Greenshot.Memento;
using Greenshot.Plugin; using Greenshot.Plugin;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using Greenshot.Plugin.Drawing.Adorners;
using GreenshotPlugin.Interfaces.Drawing;
using log4net; using log4net;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Drawing; using System.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using System.Runtime.Serialization;
using System.Windows.Forms; using System.Windows.Forms;
namespace Greenshot.Drawing { namespace Greenshot.Drawing
{
/// <summary> /// <summary>
/// represents a rectangle, ellipse, label or whatever. Can contain filters, too. /// represents a rectangle, ellipse, label or whatever. Can contain filters, too.
/// serializable for clipboard support /// serializable for clipboard support
@ -46,12 +51,23 @@ namespace Greenshot.Drawing {
public abstract class DrawableContainer : AbstractFieldHolderWithChildren, IDrawableContainer { public abstract class DrawableContainer : AbstractFieldHolderWithChildren, IDrawableContainer {
private static readonly ILog LOG = LogManager.GetLogger(typeof(DrawableContainer)); private static readonly ILog LOG = LogManager.GetLogger(typeof(DrawableContainer));
protected static readonly EditorConfiguration EditorConfig = IniConfig.GetIniSection<EditorConfiguration>(); protected static readonly EditorConfiguration EditorConfig = IniConfig.GetIniSection<EditorConfiguration>();
private bool isMadeUndoable;
private const int M11 = 0; private const int M11 = 0;
private const int M12 = 1;
private const int M21 = 2;
private const int M22 = 3; private const int M22 = 3;
[OnDeserialized]
private void OnDeserializedInit(StreamingContext context)
{
_adorners = new List<IAdorner>();
OnDeserialized(context);
}
/// <summary>
/// Override to implement your own deserialization logic, like initializing properties which are not serialized
/// </summary>
/// <param name="streamingContext"></param>
protected virtual void OnDeserialized(StreamingContext streamingContext)
{
}
protected EditStatus _defaultEditMode = EditStatus.DRAWING; protected EditStatus _defaultEditMode = EditStatus.DRAWING;
public EditStatus DefaultEditMode { public EditStatus DefaultEditMode {
@ -73,16 +89,6 @@ namespace Greenshot.Drawing {
if (!disposing) { if (!disposing) {
return; 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; FieldAggregator aggProps = _parent.FieldAggregator;
aggProps.UnbindElement(this); aggProps.UnbindElement(this);
@ -99,7 +105,7 @@ namespace Greenshot.Drawing {
remove{ _propertyChanged -= value; } remove{ _propertyChanged -= value; }
} }
public List<IFilter> Filters { public IList<IFilter> Filters {
get { get {
List<IFilter> ret = new List<IFilter>(); List<IFilter> ret = new List<IFilter>();
foreach(IFieldHolder c in Children) { foreach(IFieldHolder c in Children) {
@ -117,16 +123,12 @@ namespace Greenshot.Drawing {
get { return _parent; } get { return _parent; }
set { SwitchParent((Surface)value); } set { SwitchParent((Surface)value); }
} }
[NonSerialized]
protected Gripper[] _grippers;
private bool layoutSuspended;
[NonSerialized] [NonSerialized]
private Gripper _targetGripper; private TargetAdorner _targetAdorner;
public TargetAdorner TargetAdorner {
public Gripper TargetGripper {
get { get {
return _targetGripper; return _targetAdorner;
} }
} }
@ -160,7 +162,6 @@ namespace Greenshot.Drawing {
return; return;
} }
left = value; left = value;
DoLayout();
} }
} }
@ -172,7 +173,6 @@ namespace Greenshot.Drawing {
return; return;
} }
top = value; top = value;
DoLayout();
} }
} }
@ -184,7 +184,6 @@ namespace Greenshot.Drawing {
return; return;
} }
width = value; width = value;
DoLayout();
} }
} }
@ -196,7 +195,6 @@ namespace Greenshot.Drawing {
return; return;
} }
height = value; height = value;
DoLayout();
} }
} }
@ -220,6 +218,19 @@ namespace Greenshot.Drawing {
} }
} }
/// <summary>
/// List of available Adorners
/// </summary>
[NonSerialized]
private IList<IAdorner> _adorners = new List<IAdorner>();
public IList<IAdorner> Adorners
{
get
{
return _adorners;
}
}
[NonSerialized] [NonSerialized]
// will store current bounds of this DrawableContainer before starting a resize // will store current bounds of this DrawableContainer before starting a resize
protected Rectangle _boundsBeforeResize = Rectangle.Empty; protected Rectangle _boundsBeforeResize = Rectangle.Empty;
@ -248,7 +259,6 @@ namespace Greenshot.Drawing {
public DrawableContainer(Surface parent) { public DrawableContainer(Surface parent) {
InitializeFields(); InitializeFields();
_parent = parent; _parent = parent;
InitControls();
} }
public void Add(IFilter filter) { public void Add(IFilter filter) {
@ -296,7 +306,10 @@ namespace Greenshot.Drawing {
} }
public void AlignToParent(HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment) { public void AlignToParent(HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment) {
if (_parent == null)
{
return;
}
int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS); int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS);
if (horizontalAlignment == HorizontalAlignment.Left) { if (horizontalAlignment == HorizontalAlignment.Left) {
Left = lineThickness/2; Left = lineThickness/2;
@ -322,188 +335,35 @@ namespace Greenshot.Drawing {
public virtual bool InitContent() { return true; } public virtual bool InitContent() { return true; }
public virtual void OnDoubleClick() {} public virtual void OnDoubleClick() {}
private void InitControls() {
InitGrippers();
DoLayout();
}
/// <summary>
/// Move the TargetGripper around, confined to the surface to solve BUG-1682
/// </summary>
/// <param name="newX"></param>
/// <param name="newY"></param>
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;
}
/// <summary> /// <summary>
/// Initialize a target gripper /// Initialize a target gripper
/// </summary> /// </summary>
protected void InitTargetGripper(Color gripperColor, Point location) { protected void InitAdorner(Color gripperColor, Point location) {
_targetGripper = new Gripper { _targetAdorner = new TargetAdorner(this, location);
Cursor = Cursors.SizeAll, Adorners.Add(_targetAdorner);
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 InitGrippers() { /// <summary>
/// Create the default adorners for a rectangle based container
_grippers = new Gripper[8]; /// </summary>
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};
_grippers[Gripper.POSITION_TOP_LEFT].Left = xChoords[0]; _grippers[Gripper.POSITION_TOP_LEFT].Top = yChoords[0]; protected void CreateDefaultAdorners() {
_grippers[Gripper.POSITION_TOP_CENTER].Left = xChoords[1]; _grippers[Gripper.POSITION_TOP_CENTER].Top = yChoords[0]; if (Adorners.Count > 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]; LOG.Warn("Adorners are already defined!");
_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;
}
} }
} // Create the GripperAdorners
Adorners.Add(new ResizeAdorner(this, Positions.TopLeft));
private void GripperMouseDown(object sender, MouseEventArgs e) { Adorners.Add(new ResizeAdorner(this, Positions.TopCenter));
Gripper originatingGripper = (Gripper)sender; Adorners.Add(new ResizeAdorner(this, Positions.TopRight));
if (originatingGripper != _targetGripper) { Adorners.Add(new ResizeAdorner(this, Positions.BottomLeft));
Status = EditStatus.RESIZING; Adorners.Add(new ResizeAdorner(this, Positions.BottomCenter));
_boundsBeforeResize = new Rectangle(left, top, width, height); Adorners.Add(new ResizeAdorner(this, Positions.BottomRight));
_boundsAfterResize = new RectangleF(_boundsBeforeResize.Left, _boundsBeforeResize.Top, _boundsBeforeResize.Width, _boundsBeforeResize.Height); Adorners.Add(new ResizeAdorner(this, Positions.MiddleLeft));
} else { Adorners.Add(new ResizeAdorner(this, Positions.MiddleRight));
Status = EditStatus.MOVING;
}
isMadeUndoable = false;
} }
private void GripperMouseUp(object sender, MouseEventArgs e) {
Gripper originatingGripper = (Gripper)sender;
if (originatingGripper != _targetGripper) {
_boundsBeforeResize = Rectangle.Empty;
_boundsAfterResize = RectangleF.Empty;
isMadeUndoable = false;
}
Status = EditStatus.IDLE;
Invalidate();
}
private void GripperMouseMove(object sender, MouseEventArgs e) {
Invalidate();
Gripper originatingGripper = (Gripper)sender;
int absX = originatingGripper.Left + e.X;
int absY = originatingGripper.Top + e.Y;
if (originatingGripper == _targetGripper && Status.Equals(EditStatus.MOVING)) {
TargetGripperMove(absX, absY);
} else if (Status.Equals(EditStatus.RESIZING)) {
// check if we already made this undoable
if (!isMadeUndoable) {
// don't allow another undo until we are finished with this move
isMadeUndoable = true;
// Make undo-able
MakeBoundsChangeUndoable(false);
}
SuspendLayout();
// reset "workbench" rectangle to current bounds
_boundsAfterResize.X = _boundsBeforeResize.X;
_boundsAfterResize.Y = _boundsBeforeResize.Y;
_boundsAfterResize.Width = _boundsBeforeResize.Width;
_boundsAfterResize.Height = _boundsBeforeResize.Height;
// calculate scaled rectangle
ScaleHelper.Scale(ref _boundsAfterResize, originatingGripper.Position, new PointF(absX, absY), ScaleHelper.GetScaleOptions());
// apply scaled bounds to this DrawableContainer
ApplyBounds(_boundsAfterResize);
ResumeLayout();
}
Invalidate();
}
public bool hasFilters { public bool hasFilters {
get { get {
return Filters.Count > 0; 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) { public void ResizeTo(int width, int height, int anchorPosition) {
SuspendLayout();
Width = width; Width = width;
Height = height; Height = height;
ResumeLayout();
} }
/// <summary> /// <summary>
@ -606,10 +433,8 @@ namespace Greenshot.Drawing {
} }
public void MoveBy(int dx, int dy) { public void MoveBy(int dx, int dy) {
SuspendLayout();
Left += dx; Left += dx;
Top += dy; Top += dy;
ResumeLayout();
} }
/// <summary> /// <summary>
@ -632,7 +457,6 @@ namespace Greenshot.Drawing {
/// <returns>true if the event is handled, false if the surface needs to handle it</returns> /// <returns>true if the event is handled, false if the surface needs to handle it</returns>
public virtual bool HandleMouseMove(int x, int y) { public virtual bool HandleMouseMove(int x, int y) {
Invalidate(); Invalidate();
SuspendLayout();
// reset "workrbench" rectangle to current bounds // reset "workrbench" rectangle to current bounds
_boundsAfterResize.X = _boundsBeforeResize.Left; _boundsAfterResize.X = _boundsBeforeResize.Left;
@ -645,7 +469,6 @@ namespace Greenshot.Drawing {
// apply scaled bounds to this DrawableContainer // apply scaled bounds to this DrawableContainer
ApplyBounds(_boundsAfterResize); ApplyBounds(_boundsAfterResize);
ResumeLayout();
Invalidate(); Invalidate();
return true; return true;
} }
@ -659,49 +482,26 @@ namespace Greenshot.Drawing {
} }
protected virtual void SwitchParent(Surface newParent) { protected virtual void SwitchParent(Surface newParent) {
// Target gripper if (newParent == Parent)
if (_parent != null && _targetGripper != null) { {
_parent.Controls.Remove(_targetGripper); return;
} }
// Normal grippers if (_parent != null)
if (_parent != null && _grippers != null) { {
for (int i=0; i<_grippers.Length; i++) { // Remove FieldAggregator
_parent.Controls.Remove(_grippers[i]); 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) { foreach(IFilter filter in Filters) {
filter.Parent = this; 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) { protected void OnPropertyChanged(string propertyName) {
if (_propertyChanged != null) { if (_propertyChanged != null) {
_propertyChanged(this, new PropertyChangedEventArgs(propertyName)); _propertyChanged(this, new PropertyChangedEventArgs(propertyName));
@ -715,7 +515,7 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <param name="fieldToBeChanged">The field to be changed</param> /// <param name="fieldToBeChanged">The field to be changed</param>
/// <param name="newValue">The new value</param> /// <param name="newValue">The new value</param>
public virtual void BeforeFieldChange(Field fieldToBeChanged, object newValue) { public virtual void BeforeFieldChange(IField fieldToBeChanged, object newValue) {
_parent.MakeUndoable(new ChangeFieldHolderMemento(this, fieldToBeChanged), true); _parent.MakeUndoable(new ChangeFieldHolderMemento(this, fieldToBeChanged), true);
Invalidate(); Invalidate();
} }
@ -730,7 +530,6 @@ namespace Greenshot.Drawing {
if (e.Field.FieldType == FieldType.SHADOW) { if (e.Field.FieldType == FieldType.SHADOW) {
accountForShadowChange = true; accountForShadowChange = true;
} }
Invalidate();
} }
/// <summary> /// <summary>
@ -775,26 +574,16 @@ namespace Greenshot.Drawing {
if (matrix == null) { if (matrix == null) {
return; return;
} }
SuspendLayout();
Point topLeft = new Point(Left, Top); Point topLeft = new Point(Left, Top);
Point bottomRight = new Point(Left + Width, Top + Height); Point bottomRight = new Point(Left + Width, Top + Height);
Point[] points; Point[] points = new[] { topLeft, bottomRight };
if (TargetGripper != null) {
points = new[] {topLeft, bottomRight, TargetGripper.Location};
} else {
points = new[] { topLeft, bottomRight };
}
matrix.TransformPoints(points); matrix.TransformPoints(points);
Left = points[0].X; Left = points[0].X;
Top = points[0].Y; Top = points[0].Y;
Width = points[1].X - points[0].X; Width = points[1].X - points[0].X;
Height = points[1].Y - points[0].Y; Height = points[1].Y - points[0].Y;
if (TargetGripper != null) {
TargetGripper.Location = points[points.Length-1];
}
ResumeLayout();
} }
protected virtual ScaleHelper.IDoubleProcessor GetAngleRoundProcessor() { protected virtual ScaleHelper.IDoubleProcessor GetAngleRoundProcessor() {

View file

@ -25,6 +25,7 @@ using Greenshot.Memento;
using Greenshot.Plugin; using Greenshot.Plugin;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using GreenshotPlugin.Interfaces.Drawing;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; 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. /// Dispatches most of a DrawableContainer's public properties and methods to a list of DrawableContainers.
/// </summary> /// </summary>
[Serializable] [Serializable]
public class DrawableContainerList : List<IDrawableContainer> { public class DrawableContainerList : List<IDrawableContainer>, IDrawableContainerList
{
private static readonly ComponentResourceManager editorFormResources = new ComponentResourceManager(typeof(ImageEditorForm)); private static readonly ComponentResourceManager editorFormResources = new ComponentResourceManager(typeof(ImageEditorForm));
public Guid ParentID { public Guid ParentID {
@ -116,14 +118,11 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <param name="allowMerge">true means allow the moves to be merged</param> /// <param name="allowMerge">true means allow the moves to be merged</param>
public void MakeBoundsChangeUndoable(bool allowMerge) { public void MakeBoundsChangeUndoable(bool allowMerge) {
List<IDrawableContainer> movingList = new List<IDrawableContainer>(); if (Count > 0 && Parent != null)
Surface surface = null; {
foreach(DrawableContainer dc in this) { var clone = new DrawableContainerList();
movingList.Add(dc); clone.AddRange(this);
surface = dc._parent; Parent.MakeUndoable(new DrawableContainerBoundsChangeMemento(clone), allowMerge);
}
if (movingList.Count > 0 && surface != null) {
surface.MakeUndoable(new DrawableContainerBoundsChangeMemento(movingList), allowMerge);
} }
} }
@ -171,26 +170,6 @@ namespace Greenshot.Drawing {
} }
} }
/// <summary>
/// Hides the grippers of all elements in the list.
/// </summary>
public void HideGrippers() {
foreach(var dc in this) {
dc.HideGrippers();
dc.Invalidate();
}
}
/// <summary>
/// Shows the grippers of all elements in the list.
/// </summary>
public void ShowGrippers() {
foreach(var dc in this) {
dc.ShowGrippers();
dc.Invalidate();
}
}
/// <summary> /// <summary>
/// Indicates whether on of the elements is clickable at the given location /// Indicates whether on of the elements is clickable at the given location
/// </summary> /// </summary>
@ -266,9 +245,19 @@ namespace Greenshot.Drawing {
/// <param name="renderMode">the rendermode in which the element is to be drawn</param> /// <param name="renderMode">the rendermode in which the element is to be drawn</param>
/// <param name="clipRectangle"></param> /// <param name="clipRectangle"></param>
public void Draw(Graphics g, Bitmap bitmap, RenderMode renderMode, Rectangle clipRectangle) { public void Draw(Graphics g, Bitmap bitmap, RenderMode renderMode, Rectangle clipRectangle) {
foreach(var drawableContainer in this) { if (Parent == null)
var dc = (DrawableContainer) drawableContainer; {
if (dc.DrawingBounds.IntersectsWith(clipRectangle)) { 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); dc.DrawContent(g, bitmap, renderMode, clipRectangle);
} }
} }
@ -290,9 +279,16 @@ namespace Greenshot.Drawing {
/// Invalidate the bounds of all the DC's in this list /// Invalidate the bounds of all the DC's in this list
/// </summary> /// </summary>
public void Invalidate() { public void Invalidate() {
foreach(var dc in this) { if (Parent == null)
dc.Invalidate(); {
return;
} }
Rectangle region = Rectangle.Empty;
foreach (var dc in this)
{
region = Rectangle.Union(region, dc.DrawingBounds);
}
Parent.Invalidate(region);
} }
/// <summary> /// <summary>
/// Indicates whether the given list of elements can be pulled up, /// Indicates whether the given list of elements can be pulled up,
@ -300,7 +296,7 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <param name="elements">list of elements to pull up</param> /// <param name="elements">list of elements to pull up</param>
/// <returns>true if the elements could be pulled up</returns> /// <returns>true if the elements could be pulled up</returns>
public bool CanPullUp(DrawableContainerList elements) { public bool CanPullUp(IDrawableContainerList elements) {
if (elements.Count == 0 || elements.Count == Count) { if (elements.Count == 0 || elements.Count == Count) {
return false; return false;
} }
@ -316,13 +312,13 @@ namespace Greenshot.Drawing {
/// Pulls one or several elements up one level in hierarchy (z-index). /// Pulls one or several elements up one level in hierarchy (z-index).
/// </summary> /// </summary>
/// <param name="elements">list of elements to pull up</param> /// <param name="elements">list of elements to pull up</param>
public void PullElementsUp(DrawableContainerList elements) { public void PullElementsUp(IDrawableContainerList elements) {
for(int i=Count-1; i>=0; i--) { for(int i=Count-1; i>=0; i--) {
var dc = this[i]; var dc = this[i];
if (!elements.Contains(dc)) { if (!elements.Contains(dc)) {
continue; continue;
} }
if (Count > (i+1) && !elements.Contains(this[i+1])) { if (Count > i+1 && !elements.Contains(this[i+1])) {
SwapElements(i,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). /// Pulls one or several elements up to the topmost level(s) in hierarchy (z-index).
/// </summary> /// </summary>
/// <param name="elements">of elements to pull to top</param> /// <param name="elements">of elements to pull to top</param>
public void PullElementsToTop(DrawableContainerList elements) { public void PullElementsToTop(IDrawableContainerList elements) {
var dcs = ToArray(); var dcs = ToArray();
for(int i=0; i<dcs.Length; i++) { for(int i=0; i<dcs.Length; i++) {
var dc = dcs[i]; var dc = dcs[i];
@ -351,7 +347,7 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <param name="elements">list of elements to push down</param> /// <param name="elements">list of elements to push down</param>
/// <returns>true if the elements could be pushed down</returns> /// <returns>true if the elements could be pushed down</returns>
public bool CanPushDown(DrawableContainerList elements) { public bool CanPushDown(IDrawableContainerList elements) {
if (elements.Count == 0 || elements.Count == Count) { if (elements.Count == 0 || elements.Count == Count) {
return false; return false;
} }
@ -367,7 +363,7 @@ namespace Greenshot.Drawing {
/// Pushes one or several elements down one level in hierarchy (z-index). /// Pushes one or several elements down one level in hierarchy (z-index).
/// </summary> /// </summary>
/// <param name="elements">list of elements to push down</param> /// <param name="elements">list of elements to push down</param>
public void PushElementsDown(DrawableContainerList elements) { public void PushElementsDown(IDrawableContainerList elements) {
for(int i=0; i<Count; i++) { for(int i=0; i<Count; i++) {
var dc = this[i]; var dc = this[i];
if (!elements.Contains(dc)) { if (!elements.Contains(dc)) {
@ -383,7 +379,7 @@ namespace Greenshot.Drawing {
/// Pushes one or several elements down to the bottommost level(s) in hierarchy (z-index). /// Pushes one or several elements down to the bottommost level(s) in hierarchy (z-index).
/// </summary> /// </summary>
/// <param name="elements">of elements to push to bottom</param> /// <param name="elements">of elements to push to bottom</param>
public void PushElementsToBottom(DrawableContainerList elements) { public void PushElementsToBottom(IDrawableContainerList elements) {
var dcs = ToArray(); var dcs = ToArray();
for(int i=dcs.Length-1; i>=0; i--) { for(int i=dcs.Length-1; i>=0; i--) {
var dc = dcs[i]; var dc = dcs[i];
@ -417,7 +413,7 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <param name="menu"></param> /// <param name="menu"></param>
/// <param name="surface"></param> /// <param name="surface"></param>
public virtual void AddContextMenuItems(ContextMenuStrip menu, Surface surface) { public virtual void AddContextMenuItems(ContextMenuStrip menu, ISurface surface) {
bool push = surface.Elements.CanPushDown(this); bool push = surface.Elements.CanPushDown(this);
bool pull = surface.Elements.CanPullUp(this); bool pull = surface.Elements.CanPullUp(this);
@ -457,7 +453,7 @@ namespace Greenshot.Drawing {
// Duplicate // Duplicate
item = new ToolStripMenuItem(Language.GetString(LangKey.editor_duplicate)); item = new ToolStripMenuItem(Language.GetString(LangKey.editor_duplicate));
item.Click += delegate { item.Click += delegate {
DrawableContainerList dcs = this.Clone(); IDrawableContainerList dcs = this.Clone();
dcs.Parent = surface; dcs.Parent = surface;
dcs.MoveBy(10, 10); dcs.MoveBy(10, 10);
surface.AddElements(dcs); surface.AddElements(dcs);
@ -470,7 +466,7 @@ namespace Greenshot.Drawing {
item = new ToolStripMenuItem(Language.GetString(LangKey.editor_copytoclipboard)); item = new ToolStripMenuItem(Language.GetString(LangKey.editor_copytoclipboard));
item.Image = ((Image)(editorFormResources.GetObject("copyToolStripMenuItem.Image"))); item.Image = ((Image)(editorFormResources.GetObject("copyToolStripMenuItem.Image")));
item.Click += delegate { item.Click += delegate {
ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), this); ClipboardHelper.SetClipboardData(typeof(IDrawableContainerList), this);
}; };
menu.Items.Add(item); menu.Items.Add(item);
@ -478,15 +474,8 @@ namespace Greenshot.Drawing {
item = new ToolStripMenuItem(Language.GetString(LangKey.editor_cuttoclipboard)); item = new ToolStripMenuItem(Language.GetString(LangKey.editor_cuttoclipboard));
item.Image = ((Image)(editorFormResources.GetObject("btnCut.Image"))); item.Image = ((Image)(editorFormResources.GetObject("btnCut.Image")));
item.Click += delegate { item.Click += delegate {
ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), this); ClipboardHelper.SetClipboardData(typeof(IDrawableContainerList), this);
List<DrawableContainer> containersToDelete = new List<DrawableContainer>(); surface.RemoveElements(this, true);
foreach (var drawableContainer in this) {
var container = (DrawableContainer) drawableContainer;
containersToDelete.Add(container);
}
foreach (var container in containersToDelete) {
surface.RemoveElement(container, true);
}
}; };
menu.Items.Add(item); menu.Items.Add(item);
@ -494,22 +483,17 @@ namespace Greenshot.Drawing {
item = new ToolStripMenuItem(Language.GetString(LangKey.editor_deleteelement)); item = new ToolStripMenuItem(Language.GetString(LangKey.editor_deleteelement));
item.Image = ((Image)(editorFormResources.GetObject("removeObjectToolStripMenuItem.Image"))); item.Image = ((Image)(editorFormResources.GetObject("removeObjectToolStripMenuItem.Image")));
item.Click += delegate { item.Click += delegate {
List<DrawableContainer> containersToDelete = new List<DrawableContainer>(); surface.RemoveElements(this, true);
foreach(var drawableContainer in this) {
var container = (DrawableContainer) drawableContainer;
containersToDelete.Add(container);
}
foreach (DrawableContainer container in containersToDelete) {
surface.RemoveElement(container, true);
}
}; };
menu.Items.Add(item); menu.Items.Add(item);
// Reset // Reset
bool canReset = false; bool canReset = false;
foreach (var drawableContainer in this) { foreach (var drawableContainer in this)
var container = (DrawableContainer) drawableContainer; {
if (container.HasDefaultSize) { var container = (DrawableContainer)drawableContainer;
if (container.HasDefaultSize)
{
canReset = true; canReset = true;
} }
} }
@ -517,24 +501,29 @@ namespace Greenshot.Drawing {
item = new ToolStripMenuItem(Language.GetString(LangKey.editor_resetsize)); item = new ToolStripMenuItem(Language.GetString(LangKey.editor_resetsize));
//item.Image = ((System.Drawing.Image)(editorFormResources.GetObject("removeObjectToolStripMenuItem.Image"))); //item.Image = ((System.Drawing.Image)(editorFormResources.GetObject("removeObjectToolStripMenuItem.Image")));
item.Click += delegate { item.Click += delegate {
MakeBoundsChangeUndoable(false);
foreach (var drawableContainer in this) { foreach (var drawableContainer in this) {
var container = (DrawableContainer) drawableContainer; var container = (DrawableContainer) drawableContainer;
if (!container.HasDefaultSize) { if (!container.HasDefaultSize) {
continue; continue;
} }
Size defaultSize = container.DefaultSize; Size defaultSize = container.DefaultSize;
container.Invalidate();
container.MakeBoundsChangeUndoable(false); container.MakeBoundsChangeUndoable(false);
container.Width = defaultSize.Width; container.Width = defaultSize.Width;
container.Height = defaultSize.Height; container.Height = defaultSize.Height;
container.Invalidate();
} }
surface.Invalidate();
}; };
menu.Items.Add(item); 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; bool hasMenu = false;
foreach (var drawableContainer in this) { foreach (var drawableContainer in this) {
var container = (DrawableContainer) drawableContainer; var container = (DrawableContainer) drawableContainer;
@ -548,7 +537,8 @@ namespace Greenshot.Drawing {
ContextMenuStrip menu = new ContextMenuStrip(); ContextMenuStrip menu = new ContextMenuStrip();
AddContextMenuItems(menu, surface); AddContextMenuItems(menu, surface);
if (menu.Items.Count > 0) { if (menu.Items.Count > 0) {
menu.Show(surface, e.Location); // TODO: cast should be somehow avoided
menu.Show((Surface)surface, e.Location);
while (true) { while (true) {
if (menu.Visible) { if (menu.Visible) {
Application.DoEvents(); 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
} }
} }

View file

@ -33,6 +33,7 @@ namespace Greenshot.Drawing {
[Serializable()] [Serializable()]
public class EllipseContainer : DrawableContainer { public class EllipseContainer : DrawableContainer {
public EllipseContainer(Surface parent) : base(parent) { public EllipseContainer(Surface parent) : base(parent) {
CreateDefaultAdorners();
} }
protected override void InitializeFields() { protected override void InitializeFields() {
@ -59,12 +60,15 @@ namespace Greenshot.Drawing {
/// <summary> /// <summary>
/// This allows another container to draw an ellipse /// This allows another container to draw an ellipse
/// </summary> /// </summary>
/// <param name="caller"></param> /// <param name="rect"></param>
/// <param name="graphics"></param> /// <param name="graphics"></param>
/// <param name="renderMode"></param> /// <param name="renderMode"></param>
/// <param name="lineThickness"></param>
/// <param name="lineColor"></param>
/// <param name="fillColor"></param>
/// <param name="shadow"></param>
public static void DrawEllipse(Rectangle rect, Graphics graphics, RenderMode renderMode, int lineThickness, Color lineColor, Color fillColor, bool shadow) { 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 // draw shadow before anything else
if (shadow && (lineVisible || Colors.IsVisible(fillColor))) { if (shadow && (lineVisible || Colors.IsVisible(fillColor))) {
int basealpha = 100; int basealpha = 100;

View file

@ -26,13 +26,16 @@ using System.Runtime.Serialization;
using Greenshot.Configuration; using Greenshot.Configuration;
using Greenshot.IniFile; using Greenshot.IniFile;
using log4net; using log4net;
using GreenshotPlugin.Interfaces.Drawing;
namespace Greenshot.Drawing.Fields { namespace Greenshot.Drawing.Fields
{
/// <summary> /// <summary>
/// Basic IFieldHolder implementation, providing access to a set of fields /// Basic IFieldHolder implementation, providing access to a set of fields
/// </summary> /// </summary>
[Serializable] [Serializable]
public abstract class AbstractFieldHolder : IFieldHolder { public abstract class AbstractFieldHolder : IFieldHolder
{
private static readonly ILog LOG = LogManager.GetLogger(typeof(AbstractFieldHolder)); private static readonly ILog LOG = LogManager.GetLogger(typeof(AbstractFieldHolder));
private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>(); private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>();
@ -41,26 +44,30 @@ namespace Greenshot.Drawing.Fields {
/// </summary> /// </summary>
[NonSerialized] [NonSerialized]
private FieldChangedEventHandler fieldChanged; private FieldChangedEventHandler fieldChanged;
public event FieldChangedEventHandler FieldChanged { public event FieldChangedEventHandler FieldChanged
{
add { fieldChanged += value; } add { fieldChanged += value; }
remove{ fieldChanged -= value; } remove { fieldChanged -= value; }
} }
// we keep two Collections of our fields, dictionary for quick access, list for serialization // we keep two Collections of our fields, dictionary for quick access, list for serialization
// this allows us to use default serialization // this allows us to use default serialization
[NonSerialized] [NonSerialized]
private Dictionary<FieldType, Field> fieldsByType = new Dictionary<FieldType, Field>(); private IDictionary<IFieldType, IField> fieldsByType = new Dictionary<IFieldType, IField>();
private List<Field> fields = new List<Field>(); private IList<IField> fields = new List<IField>();
public AbstractFieldHolder() {} public AbstractFieldHolder() { }
[OnDeserialized] [OnDeserialized]
private void OnDeserialized(StreamingContext context) { private void OnDeserialized(StreamingContext context)
fieldsByType = new Dictionary<FieldType, Field>(); {
fieldsByType = new Dictionary<IFieldType, IField>();
// listen to changing properties // listen to changing properties
foreach(Field field in fields) { foreach (Field field in fields)
{
field.PropertyChanged += delegate { field.PropertyChanged += delegate {
if (fieldChanged != null) { if (fieldChanged != null)
{
fieldChanged(this, new FieldChangedEventArgs(field)); 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)); AddField(editorConfiguration.CreateField(requestingType, fieldType, fieldValue));
} }
public virtual void AddField(Field field) { public virtual void AddField(IField field)
if (fieldsByType != null && fieldsByType.ContainsKey(field.FieldType)) { {
if (LOG.IsDebugEnabled) { 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()); LOG.DebugFormat("A field with of type '{0}' already exists in this {1}, will overwrite.", field.FieldType, GetType());
} }
} }
fields.Add(field); fields.Add(field);
fieldsByType[field.FieldType] = 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); fields.Remove(field);
fieldsByType.Remove(field.FieldType); fieldsByType.Remove(field.FieldType);
field.PropertyChanged -= delegate { field.PropertyChanged -= delegate {
if (fieldChanged != null) { if (fieldChanged != null)
{
fieldChanged(this, new FieldChangedEventArgs(field)); fieldChanged(this, new FieldChangedEventArgs(field));
} }
}; };
} }
public List<Field> GetFields() { public IList<IField> GetFields()
{
return fields; return fields;
} }
public Field GetField(FieldType fieldType) { public IField GetField(IFieldType fieldType)
try { {
try
{
return fieldsByType[fieldType]; return fieldsByType[fieldType];
} catch(KeyNotFoundException e) { }
catch (KeyNotFoundException e)
{
throw new ArgumentException("Field '" + fieldType + "' does not exist in " + GetType(), 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; return GetField(fieldType).Value;
} }
#region convenience methods to save us some casts outside #region convenience methods to save us some casts outside
public string GetFieldValueAsString(FieldType fieldType) { public string GetFieldValueAsString(IFieldType fieldType)
{
return Convert.ToString(GetFieldValue(fieldType)); return Convert.ToString(GetFieldValue(fieldType));
} }
public int GetFieldValueAsInt(FieldType fieldType) { public int GetFieldValueAsInt(IFieldType fieldType)
{
return Convert.ToInt32(GetFieldValue(fieldType)); return Convert.ToInt32(GetFieldValue(fieldType));
} }
public decimal GetFieldValueAsDecimal(FieldType fieldType) { public decimal GetFieldValueAsDecimal(IFieldType fieldType)
{
return Convert.ToDecimal(GetFieldValue(fieldType)); return Convert.ToDecimal(GetFieldValue(fieldType));
} }
public double GetFieldValueAsDouble(FieldType fieldType) { public double GetFieldValueAsDouble(IFieldType fieldType)
{
return Convert.ToDouble(GetFieldValue(fieldType)); return Convert.ToDouble(GetFieldValue(fieldType));
} }
public float GetFieldValueAsFloat(FieldType fieldType) { public float GetFieldValueAsFloat(IFieldType fieldType)
{
return Convert.ToSingle(GetFieldValue(fieldType)); return Convert.ToSingle(GetFieldValue(fieldType));
} }
public bool GetFieldValueAsBool(FieldType fieldType) { public bool GetFieldValueAsBool(IFieldType fieldType)
{
return Convert.ToBoolean(GetFieldValue(fieldType)); return Convert.ToBoolean(GetFieldValue(fieldType));
} }
public Color GetFieldValueAsColor(FieldType fieldType) { public Color GetFieldValueAsColor(IFieldType fieldType)
{
return (Color)GetFieldValue(fieldType); return (Color)GetFieldValue(fieldType);
} }
#endregion #endregion
public bool HasField(FieldType fieldType) { public bool HasField(IFieldType fieldType)
{
return fieldsByType.ContainsKey(fieldType); return fieldsByType.ContainsKey(fieldType);
} }
public bool HasFieldValue(FieldType fieldType) { public bool HasFieldValue(IFieldType fieldType)
{
return HasField(fieldType) && fieldsByType[fieldType].HasValue; return HasField(fieldType) && fieldsByType[fieldType].HasValue;
} }
public void SetFieldValue(FieldType fieldType, object value) { public void SetFieldValue(IFieldType fieldType, object value)
try { {
try
{
fieldsByType[fieldType].Value = value; 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){ protected void OnFieldChanged(object sender, FieldChangedEventArgs e)
if (fieldChanged != null) { {
if (fieldChanged != null)
{
fieldChanged(sender, e); fieldChanged(sender, e);
} }
} }

View file

@ -18,87 +18,110 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using GreenshotPlugin.Interfaces.Drawing;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.Serialization; using System.Runtime.Serialization;
namespace Greenshot.Drawing.Fields { namespace Greenshot.Drawing.Fields
{
/// <summary> /// <summary>
/// Basic IFieldHolderWithChildren implementation. Similar to IFieldHolder, /// Basic IFieldHolderWithChildren implementation. Similar to IFieldHolder,
/// but has a List<IFieldHolder> of children. /// but has a List<IFieldHolder> of children.
/// Field values are passed to and from children as well. /// Field values are passed to and from children as well.
/// </summary> /// </summary>
[Serializable()] [Serializable()]
public abstract class AbstractFieldHolderWithChildren : AbstractFieldHolder { public abstract class AbstractFieldHolderWithChildren : AbstractFieldHolder
{
FieldChangedEventHandler fieldChangedEventHandler; FieldChangedEventHandler fieldChangedEventHandler;
[NonSerialized] [NonSerialized]
private EventHandler childrenChanged; private EventHandler childrenChanged;
public event EventHandler ChildrenChanged { public event EventHandler ChildrenChanged
{
add { childrenChanged += value; } add { childrenChanged += value; }
remove { childrenChanged -= value; } remove { childrenChanged -= value; }
} }
public List<IFieldHolder> Children = new List<IFieldHolder>(); public List<IFieldHolder> Children = new List<IFieldHolder>();
public AbstractFieldHolderWithChildren() { public AbstractFieldHolderWithChildren()
{
fieldChangedEventHandler = OnFieldChanged; fieldChangedEventHandler = OnFieldChanged;
} }
[OnDeserialized()] [OnDeserialized()]
private void OnDeserialized(StreamingContext context) { private void OnDeserialized(StreamingContext context)
{
// listen to changing properties // listen to changing properties
foreach(IFieldHolder fieldHolder in Children) { foreach (IFieldHolder fieldHolder in Children)
{
fieldHolder.FieldChanged += fieldChangedEventHandler; 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); Children.Add(fieldHolder);
fieldHolder.FieldChanged += fieldChangedEventHandler; 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); Children.Remove(fieldHolder);
fieldHolder.FieldChanged -= fieldChangedEventHandler; fieldHolder.FieldChanged -= fieldChangedEventHandler;
if(childrenChanged != null) childrenChanged(this, EventArgs.Empty); if (childrenChanged != null) childrenChanged(this, EventArgs.Empty);
} }
public new List<Field> GetFields() { public new IList<IField> GetFields()
List<Field> ret = new List<Field>(); {
List<IField> ret = new List<IField>();
ret.AddRange(base.GetFields()); ret.AddRange(base.GetFields());
foreach(IFieldHolder fh in Children) { foreach (IFieldHolder fh in Children)
{
ret.AddRange(fh.GetFields()); ret.AddRange(fh.GetFields());
} }
return ret; return ret;
} }
public new Field GetField(FieldType fieldType) { public new IField GetField(IFieldType fieldType)
Field ret = null; {
if(base.HasField(fieldType)) { IField ret = null;
if (base.HasField(fieldType))
{
ret = base.GetField(fieldType); ret = base.GetField(fieldType);
} else { }
foreach(IFieldHolder fh in Children) { else
if(fh.HasField(fieldType)) { {
foreach (IFieldHolder fh in Children)
{
if (fh.HasField(fieldType))
{
ret = fh.GetField(fieldType); ret = fh.GetField(fieldType);
break; break;
} }
} }
} }
if(ret == null) { if (ret == null)
throw new ArgumentException("Field '"+fieldType+"' does not exist in " + GetType()); {
throw new ArgumentException("Field '" + fieldType + "' does not exist in " + GetType());
} }
return ret; return ret;
} }
public new bool HasField(FieldType fieldType) { public new bool HasField(IFieldType fieldType)
{
bool ret = base.HasField(fieldType); bool ret = base.HasField(fieldType);
if(!ret) { if (!ret)
foreach(IFieldHolder fh in Children) { {
if(fh.HasField(fieldType)) { foreach (IFieldHolder fh in Children)
{
if (fh.HasField(fieldType))
{
ret = true; ret = true;
break; break;
} }
@ -106,16 +129,18 @@ namespace Greenshot.Drawing.Fields {
} }
return ret; return ret;
} }
public new bool HasFieldValue(FieldType fieldType) { public new bool HasFieldValue(IFieldType fieldType)
Field f = GetField(fieldType); {
IField f = GetField(fieldType);
return f != null && f.HasValue; return f != null && f.HasValue;
} }
public new void SetFieldValue(FieldType fieldType, object value) { public new void SetFieldValue(IFieldType fieldType, object value)
Field f = GetField(fieldType); {
if(f != null) f.Value = value; IField f = GetField(fieldType);
if (f != null) f.Value = value;
} }
} }
} }

View file

@ -26,8 +26,6 @@ namespace Greenshot.Drawing.Fields.Binding {
/// </summary> /// </summary>
public abstract class AbstractBindingConverter<T1,T2> : IBindingConverter public abstract class AbstractBindingConverter<T1,T2> : IBindingConverter
{ {
public AbstractBindingConverter() {}
public object convert(object o) { public object convert(object o) {
if(o == null) { if(o == null) {
return null; return null;

View file

@ -29,35 +29,35 @@ namespace Greenshot.Drawing.Fields.Binding {
/// behavior (e.g. when binding to a /// behavior (e.g. when binding to a
/// </summary> /// </summary>
public class BidirectionalBinding { public class BidirectionalBinding {
private INotifyPropertyChanged controlObject; private readonly INotifyPropertyChanged _controlObject;
private INotifyPropertyChanged fieldObject; private readonly INotifyPropertyChanged _fieldObject;
private string controlPropertyName; private readonly string _controlPropertyName;
private string fieldPropertyName; private readonly string _fieldPropertyName;
private bool updatingControl = false; private bool _updatingControl;
private bool updatingField = false; private bool _updatingField;
private IBindingConverter converter; private IBindingConverter _converter;
private IBindingValidator validator; private readonly IBindingValidator _validator;
/// <summary> /// <summary>
/// Whether or not null values are passed on to the other object. /// Whether or not null values are passed on to the other object.
/// </summary> /// </summary>
protected bool AllowSynchronizeNull = true; protected bool AllowSynchronizeNull = true;
/// <summary> /// <summary>
/// Bind properties of two objects bidirectionally /// Bind properties of two objects bidirectionally
/// </summary> /// </summary>
/// <param name="object1">Object containing 1st property to bind</param> /// <param name="controlObject">Object containing 1st property to bind</param>
/// <param name="property1">Property of 1st object to bind</param> /// <param name="controlPropertyName">Property of 1st object to bind</param>
/// <param name="object2">Object containing 2nd property to bind</param> /// <param name="fieldObject">Object containing 2nd property to bind</param>
/// <param name="property2">Property of 2nd object to bind</param> /// <param name="fieldPropertyName">Property of 2nd object to bind</param>
public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName) { public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName) {
this.controlObject = controlObject; _controlObject = controlObject;
this.fieldObject = fieldObject; _fieldObject = fieldObject;
this.controlPropertyName = controlPropertyName; _controlPropertyName = controlPropertyName;
this.fieldPropertyName = fieldPropertyName; _fieldPropertyName = fieldPropertyName;
this.controlObject.PropertyChanged += ControlPropertyChanged; _controlObject.PropertyChanged += ControlPropertyChanged;
this.fieldObject.PropertyChanged += FieldPropertyChanged; _fieldObject.PropertyChanged += FieldPropertyChanged;
} }
/// <summary> /// <summary>
@ -69,7 +69,7 @@ namespace Greenshot.Drawing.Fields.Binding {
/// <param name="fieldPropertyName">Property of 2nd object to bind</param> /// <param name="fieldPropertyName">Property of 2nd object to bind</param>
/// <param name="converter">taking care of converting the synchronized value to the correct target format and back</param> /// <param name="converter">taking care of converting the synchronized value to the correct target format and back</param>
public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingConverter converter) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) { public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingConverter converter) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) {
this.converter = converter; _converter = converter;
} }
/// <summary> /// <summary>
@ -82,7 +82,7 @@ namespace Greenshot.Drawing.Fields.Binding {
/// <param name="fieldPropertyName">Property of 2nd object to bind</param> /// <param name="fieldPropertyName">Property of 2nd object to bind</param>
/// <param name="validator">validator to intercept synchronization if the value does not match certain criteria</param> /// <param name="validator">validator to intercept synchronization if the value does not match certain criteria</param>
public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) { public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) {
this.validator = validator; _validator = validator;
} }
/// <summary> /// <summary>
@ -96,46 +96,46 @@ namespace Greenshot.Drawing.Fields.Binding {
/// <param name="converter">taking care of converting the synchronized value to the correct target format and back</param> /// <param name="converter">taking care of converting the synchronized value to the correct target format and back</param>
/// <param name="validator">validator to intercept synchronization if the value does not match certain criteria</param> /// <param name="validator">validator to intercept synchronization if the value does not match certain criteria</param>
public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingConverter converter, IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName, converter) { 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) { public void ControlPropertyChanged(object sender, PropertyChangedEventArgs e) {
if (!updatingControl && e.PropertyName.Equals(controlPropertyName)) { if (!_updatingControl && e.PropertyName.Equals(_controlPropertyName)) {
updatingField = true; _updatingField = true;
synchronize(controlObject, controlPropertyName, fieldObject, fieldPropertyName); Synchronize(_controlObject, _controlPropertyName, _fieldObject, _fieldPropertyName);
updatingField = false; _updatingField = false;
} }
} }
public void FieldPropertyChanged(object sender, PropertyChangedEventArgs e) { public void FieldPropertyChanged(object sender, PropertyChangedEventArgs e) {
if (!updatingField && e.PropertyName.Equals(fieldPropertyName)) { if (!_updatingField && e.PropertyName.Equals(_fieldPropertyName)) {
updatingControl = true; _updatingControl = true;
synchronize(fieldObject, fieldPropertyName, controlObject, controlPropertyName); Synchronize(_fieldObject, _fieldPropertyName, _controlObject, _controlPropertyName);
updatingControl = false; _updatingControl = false;
} }
} }
private void synchronize(INotifyPropertyChanged sourceObject, string sourceProperty, INotifyPropertyChanged targetObject, string targetProperty) { private void Synchronize(INotifyPropertyChanged sourceObject, string sourceProperty, INotifyPropertyChanged targetObject, string targetProperty) {
PropertyInfo targetPropertyInfo = resolvePropertyInfo(targetObject, targetProperty); PropertyInfo targetPropertyInfo = ResolvePropertyInfo(targetObject, targetProperty);
PropertyInfo sourcePropertyInfo = resolvePropertyInfo(sourceObject, sourceProperty); PropertyInfo sourcePropertyInfo = ResolvePropertyInfo(sourceObject, sourceProperty);
if (sourcePropertyInfo != null && targetPropertyInfo != null && targetPropertyInfo.CanWrite) { if (sourcePropertyInfo != null && targetPropertyInfo != null && targetPropertyInfo.CanWrite) {
object bValue = sourcePropertyInfo.GetValue(sourceObject, null); object bValue = sourcePropertyInfo.GetValue(sourceObject, null);
if (converter != null && bValue != null) { if (_converter != null && bValue != null) {
bValue = converter.convert(bValue); bValue = _converter.convert(bValue);
} }
try { try {
if (validator == null || validator.validate(bValue)) { if (_validator == null || _validator.validate(bValue)) {
targetPropertyInfo.SetValue(targetObject, bValue, null); targetPropertyInfo.SetValue(targetObject, bValue, null);
} }
} catch (Exception e) { } 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; PropertyInfo ret = null;
string[] properties = property.Split(".".ToCharArray()); string[] properties = property.Split(".".ToCharArray());
for(int i=0; i<properties.Length; i++) { for(int i=0; i<properties.Length; i++) {
@ -149,8 +149,8 @@ namespace Greenshot.Drawing.Fields.Binding {
} }
public IBindingConverter Converter { public IBindingConverter Converter {
get { return converter; } get { return _converter; }
set { converter = value; } set { _converter = value; }
} }
} }

View file

@ -18,36 +18,53 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using GreenshotPlugin.Interfaces.Drawing;
using System; using System;
using System.ComponentModel; using System.ComponentModel;
namespace Greenshot.Drawing.Fields { namespace Greenshot.Drawing.Fields
{
/// <summary> /// <summary>
/// Represents a single field of a drawable element, i.e. /// Represents a single field of a drawable element, i.e.
/// line thickness of a rectangle. /// line thickness of a rectangle.
/// </summary> /// </summary>
[Serializable] [Serializable]
public class Field : INotifyPropertyChanged { public class Field : IField
[field:NonSerialized] {
[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangedEventHandler PropertyChanged;
public object myValue; private object _myValue;
public object Value { public object Value
get { {
return myValue; get
{
return _myValue;
} }
set { set
if (!Equals(myValue,value)) { {
myValue = value; if (!Equals(_myValue, value))
if (PropertyChanged!=null) { {
_myValue = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Value")); PropertyChanged(this, new PropertyChangedEventArgs("Value"));
} }
} }
} }
} }
public FieldType FieldType; public IFieldType FieldType
public string Scope; {
get;
set;
}
public string Scope
{
get;
set;
}
/// <summary> /// <summary>
/// Constructs a new Field instance, usually you should be using FieldFactory /// Constructs a new Field instance, usually you should be using FieldFactory
/// to create Fields. /// to create Fields.
@ -59,70 +76,64 @@ namespace Greenshot.Drawing.Fields {
/// When scope is set to a Type (e.g. typeof(RectangleContainer)), its value /// 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)) /// should not be reused for FieldHolders of another Type (e.g. typeof(EllipseContainer))
/// </param> /// </param>
public Field(FieldType fieldType, Type scope) { public Field(IFieldType fieldType, Type scope)
{
FieldType = fieldType; FieldType = fieldType;
Scope = scope.Name; Scope = scope.Name;
} }
public Field(FieldType fieldType, string scope) { public Field(IFieldType fieldType, string scope)
{
FieldType = fieldType; FieldType = fieldType;
Scope = scope; Scope = scope;
} }
public Field(FieldType fieldType) { public Field(IFieldType fieldType)
{
FieldType = fieldType; FieldType = fieldType;
} }
/// <summary> /// <summary>
/// Returns true if this field holds a value other than null. /// Returns true if this field holds a value other than null.
/// </summary> /// </summary>
public bool HasValue { public bool HasValue
get{ return Value != null; } {
get { return Value != null; }
} }
/// <summary> /// <summary>
/// Creates a flat clone of this Field. The fields value itself is not cloned. /// Creates a flat clone of this Field. The fields value itself is not cloned.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public Field Clone() { public Field Clone()
{
Field ret = new Field(FieldType, Scope); Field ret = new Field(FieldType, Scope);
ret.Value = Value; ret.Value = Value;
return ret; return ret;
} }
public override int GetHashCode() { public override int GetHashCode()
{
int hashCode = 0; int hashCode = 0;
unchecked { unchecked
{
hashCode += 1000000009 * FieldType.GetHashCode(); hashCode += 1000000009 * FieldType.GetHashCode();
if (Scope != null) if (Scope != null)
hashCode += 1000000021 * Scope.GetHashCode(); hashCode += 1000000021 * Scope.GetHashCode();
} }
return hashCode; return hashCode;
} }
public override bool Equals(object obj) { public override bool Equals(object obj)
{
Field other = obj as Field; Field other = obj as Field;
if (other == null) { if (other == null)
{
return false; return false;
} }
return FieldType == other.FieldType && Equals(Scope, other.Scope); return FieldType == other.FieldType && Equals(Scope, other.Scope);
} }
public override string ToString() { public override string ToString()
return string.Format("[Field FieldType={1} Value={0} Scope={2}]", myValue, FieldType, Scope); {
} return string.Format("[Field FieldType={1} Value={0} Scope={2}]", _myValue, FieldType, Scope);
}
/// <summary>
/// EventHandler to be used when a field value changes
/// </summary>
public delegate void FieldChangedEventHandler(object sender, FieldChangedEventArgs e);
/// <summary>
/// EventArgs to be used with FieldChangedEventHandler
/// </summary>
public class FieldChangedEventArgs : EventArgs {
public readonly Field Field;
public FieldChangedEventArgs(Field field) {
Field = field;
} }
} }
} }

View file

@ -19,15 +19,18 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
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.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using Greenshot.Configuration; namespace Greenshot.Drawing.Fields
using Greenshot.IniFile; {
using Greenshot.Plugin.Drawing;
using log4net;
namespace Greenshot.Drawing.Fields {
/// <summary> /// <summary>
/// Represents the current set of properties for the editor. /// Represents the current set of properties for the editor.
/// When one of EditorProperties' properties is updated, the change will be promoted /// 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) /// 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. /// If the property values of the selected elements differ, the value of the last bound element wins.
/// </summary> /// </summary>
public class FieldAggregator : AbstractFieldHolder { public class FieldAggregator : AbstractFieldHolder
{
private List<IDrawableContainer> boundContainers;
private IDrawableContainerList boundContainers;
private bool internalUpdateRunning = false; 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 readonly ILog LOG = LogManager.GetLogger(typeof(FieldAggregator));
private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>(); private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>();
public FieldAggregator() { public FieldAggregator(ISurface parent)
foreach(FieldType fieldType in FieldType.Values) { {
foreach (FieldType fieldType in FieldType.Values)
{
Field field = new Field(fieldType, GetType()); Field field = new Field(fieldType, GetType());
AddField(field); AddField(field);
} }
boundContainers = new List<IDrawableContainer>(); boundContainers = new DrawableContainerList();
boundContainers.Parent = parent;
} }
public override void AddField(Field field) { public override void AddField(IField field)
{
base.AddField(field); base.AddField(field);
field.PropertyChanged += OwnPropertyChanged; field.PropertyChanged += OwnPropertyChanged;
} }
public void BindElements(DrawableContainerList dcs) { public void BindElements(IDrawableContainerList dcs)
foreach(DrawableContainer dc in dcs) { {
foreach (DrawableContainer dc in dcs)
{
BindElement(dc); BindElement(dc);
} }
} }
public void BindElement(IDrawableContainer dc) { public void BindElement(IDrawableContainer dc)
{
DrawableContainer container = dc as DrawableContainer; DrawableContainer container = dc as DrawableContainer;
if (container != null && !boundContainers.Contains(container)) { if (container != null && !boundContainers.Contains(container))
{
boundContainers.Add(container); boundContainers.Add(container);
container.ChildrenChanged += delegate { container.ChildrenChanged += delegate {
UpdateFromBoundElements(); UpdateFromBoundElements();
@ -78,101 +90,126 @@ namespace Greenshot.Drawing.Fields {
UpdateFromBoundElements(); UpdateFromBoundElements();
} }
} }
public void BindAndUpdateElement(IDrawableContainer dc) { public void BindAndUpdateElement(IDrawableContainer dc)
{
UpdateElement(dc); UpdateElement(dc);
BindElement(dc); BindElement(dc);
} }
public void UpdateElement(IDrawableContainer dc) { public void UpdateElement(IDrawableContainer dc)
{
DrawableContainer container = dc as DrawableContainer; DrawableContainer container = dc as DrawableContainer;
if (container == null) { if (container == null)
{
return; return;
} }
internalUpdateRunning = true; internalUpdateRunning = true;
foreach(Field field in GetFields()) { foreach (Field field in GetFields())
if (container.HasField(field.FieldType) && field.HasValue) { {
if (container.HasField(field.FieldType) && field.HasValue)
{
//if(LOG.IsDebugEnabled) LOG.Debug(" "+field+ ": "+field.Value); //if(LOG.IsDebugEnabled) LOG.Debug(" "+field+ ": "+field.Value);
container.SetFieldValue(field.FieldType, field.Value); container.SetFieldValue(field.FieldType, field.Value);
} }
} }
internalUpdateRunning = false; internalUpdateRunning = false;
} }
public void UnbindElement(IDrawableContainer dc) { public void UnbindElement(IDrawableContainer dc)
if (boundContainers.Contains(dc)) { {
if (boundContainers.Contains(dc))
{
boundContainers.Remove(dc); boundContainers.Remove(dc);
UpdateFromBoundElements(); UpdateFromBoundElements();
} }
} }
public void Clear() { public void Clear()
{
ClearFields(); ClearFields();
boundContainers.Clear(); boundContainers.Clear();
UpdateFromBoundElements(); UpdateFromBoundElements();
} }
/// <summary> /// <summary>
/// sets all field values to null, however does not remove fields /// sets all field values to null, however does not remove fields
/// </summary> /// </summary>
private void ClearFields() { private void ClearFields()
{
internalUpdateRunning = true; internalUpdateRunning = true;
foreach(Field field in GetFields()) { foreach (Field field in GetFields())
{
field.Value = null; field.Value = null;
} }
internalUpdateRunning = false; internalUpdateRunning = false;
} }
/// <summary> /// <summary>
/// Updates this instance using the respective fields from the bound elements. /// 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. /// 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. /// All other fields will be set to the field value of the least bound element.
/// </summary> /// </summary>
private void UpdateFromBoundElements() { private void UpdateFromBoundElements()
{
ClearFields(); ClearFields();
internalUpdateRunning = true; internalUpdateRunning = true;
foreach(Field field in FindCommonFields()) { foreach (Field field in FindCommonFields())
{
SetFieldValue(field.FieldType, field.Value); SetFieldValue(field.FieldType, field.Value);
} }
internalUpdateRunning = false; internalUpdateRunning = false;
} }
private List<Field> FindCommonFields() { private IList<IField> FindCommonFields()
List<Field> returnFields = null; {
if (boundContainers.Count > 0) { IList<IField> returnFields = null;
if (boundContainers.Count > 0)
{
// take all fields from the least selected container... // take all fields from the least selected container...
DrawableContainer leastSelectedContainer = boundContainers[boundContainers.Count - 1] as DrawableContainer; DrawableContainer leastSelectedContainer = boundContainers[boundContainers.Count - 1] as DrawableContainer;
if (leastSelectedContainer != null) { if (leastSelectedContainer != null)
{
returnFields = leastSelectedContainer.GetFields(); 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; DrawableContainer dc = boundContainers[i] as DrawableContainer;
if (dc != null) { if (dc != null)
List<Field> fieldsToRemove = new List<Field>(); {
foreach (Field f in returnFields) { IList<IField> fieldsToRemove = new List<IField>();
foreach (IField field in returnFields)
{
// ... throw out those that do not apply to one of the other containers // ... throw out those that do not apply to one of the other containers
if (!dc.HasField(f.FieldType)) { if (!dc.HasField(field.FieldType))
fieldsToRemove.Add(f); {
fieldsToRemove.Add(field);
} }
} }
foreach (Field f in fieldsToRemove) { foreach (IField field in fieldsToRemove)
returnFields.Remove(f); {
returnFields.Remove(field);
} }
} }
} }
} }
} }
if (returnFields == null) { if (returnFields == null)
returnFields = new List<Field>(); {
returnFields = new List<IField>();
} }
return returnFields; return returnFields;
} }
public void OwnPropertyChanged(object sender, PropertyChangedEventArgs ea) { public void OwnPropertyChanged(object sender, PropertyChangedEventArgs ea)
Field field = (Field) sender; {
if (!internalUpdateRunning && field.Value != null) { IField field = (IField)sender;
foreach(DrawableContainer drawableContainer in boundContainers) { if (!internalUpdateRunning && field.Value != null)
if (drawableContainer.HasField(field.FieldType)) { {
Field drawableContainerField = drawableContainer.GetField(field.FieldType); 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 // Notify before change, so we can e.g. invalidate the area
drawableContainer.BeforeFieldChange(drawableContainerField, field.Value); drawableContainer.BeforeFieldChange(drawableContainerField, field.Value);
@ -184,5 +221,5 @@ namespace Greenshot.Drawing.Fields {
} }
} }
} }
} }

View file

@ -18,38 +18,41 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using GreenshotPlugin.Interfaces.Drawing;
using System; using System;
namespace Greenshot.Drawing.Fields { namespace Greenshot.Drawing.Fields
{
/// <summary> /// <summary>
/// Defines all FieldTypes + their default value. /// Defines all FieldTypes + their default value.
/// (The additional value is why this is not an enum) /// (The additional value is why this is not an enum)
/// </summary> /// </summary>
[Serializable] [Serializable]
public class FieldType { public class FieldType : IFieldType
{
public static readonly FieldType ARROWHEADS = new FieldType("ARROWHEADS");
public static readonly FieldType BLUR_RADIUS = new FieldType("BLUR_RADIUS"); public static readonly IFieldType ARROWHEADS = new FieldType("ARROWHEADS");
public static readonly FieldType BRIGHTNESS = new FieldType("BRIGHTNESS"); public static readonly IFieldType BLUR_RADIUS = new FieldType("BLUR_RADIUS");
public static readonly FieldType FILL_COLOR = new FieldType("FILL_COLOR"); public static readonly IFieldType BRIGHTNESS = new FieldType("BRIGHTNESS");
public static readonly FieldType FONT_BOLD = new FieldType("FONT_BOLD"); public static readonly IFieldType FILL_COLOR = new FieldType("FILL_COLOR");
public static readonly FieldType FONT_FAMILY = new FieldType("FONT_FAMILY"); public static readonly IFieldType FONT_BOLD = new FieldType("FONT_BOLD");
public static readonly FieldType FONT_ITALIC = new FieldType("FONT_ITALIC"); public static readonly IFieldType FONT_FAMILY = new FieldType("FONT_FAMILY");
public static readonly FieldType FONT_SIZE = new FieldType("FONT_SIZE"); public static readonly IFieldType FONT_ITALIC = new FieldType("FONT_ITALIC");
public static readonly FieldType TEXT_HORIZONTAL_ALIGNMENT = new FieldType("TEXT_HORIZONTAL_ALIGNMENT"); public static readonly IFieldType FONT_SIZE = new FieldType("FONT_SIZE");
public static readonly FieldType TEXT_VERTICAL_ALIGNMENT = new FieldType("TEXT_VERTICAL_ALIGNMENT"); public static readonly IFieldType TEXT_HORIZONTAL_ALIGNMENT = new FieldType("TEXT_HORIZONTAL_ALIGNMENT");
public static readonly FieldType HIGHLIGHT_COLOR = new FieldType("HIGHLIGHT_COLOR"); public static readonly IFieldType TEXT_VERTICAL_ALIGNMENT = new FieldType("TEXT_VERTICAL_ALIGNMENT");
public static readonly FieldType LINE_COLOR = new FieldType("LINE_COLOR"); public static readonly IFieldType HIGHLIGHT_COLOR = new FieldType("HIGHLIGHT_COLOR");
public static readonly FieldType LINE_THICKNESS = new FieldType("LINE_THICKNESS"); public static readonly IFieldType LINE_COLOR = new FieldType("LINE_COLOR");
public static readonly FieldType MAGNIFICATION_FACTOR = new FieldType("MAGNIFICATION_FACTOR"); public static readonly IFieldType LINE_THICKNESS = new FieldType("LINE_THICKNESS");
public static readonly FieldType PIXEL_SIZE = new FieldType("PIXEL_SIZE"); public static readonly IFieldType MAGNIFICATION_FACTOR = new FieldType("MAGNIFICATION_FACTOR");
public static readonly FieldType PREVIEW_QUALITY = new FieldType("PREVIEW_QUALITY"); public static readonly IFieldType PIXEL_SIZE = new FieldType("PIXEL_SIZE");
public static readonly FieldType SHADOW = new FieldType("SHADOW"); public static readonly IFieldType PREVIEW_QUALITY = new FieldType("PREVIEW_QUALITY");
public static readonly FieldType PREPARED_FILTER_OBFUSCATE = new FieldType("PREPARED_FILTER_OBFUSCATE"); public static readonly IFieldType SHADOW = new FieldType("SHADOW");
public static readonly FieldType PREPARED_FILTER_HIGHLIGHT = new FieldType("PREPARED_FILTER_HIGHLIGHT"); public static readonly IFieldType PREPARED_FILTER_OBFUSCATE = new FieldType("PREPARED_FILTER_OBFUSCATE");
public static readonly FieldType FLAGS = new FieldType("FLAGS"); public static readonly IFieldType PREPARED_FILTER_HIGHLIGHT = new FieldType("PREPARED_FILTER_HIGHLIGHT");
public static readonly IFieldType FLAGS = new FieldType("FLAGS");
public static FieldType[] Values = new FieldType[]{
public static IFieldType[] Values = new IFieldType[]{
ARROWHEADS, ARROWHEADS,
BLUR_RADIUS, BLUR_RADIUS,
BRIGHTNESS, BRIGHTNESS,
@ -66,53 +69,55 @@ namespace Greenshot.Drawing.Fields {
MAGNIFICATION_FACTOR, MAGNIFICATION_FACTOR,
PIXEL_SIZE, PIXEL_SIZE,
PREVIEW_QUALITY, PREVIEW_QUALITY,
SHADOW, SHADOW,
PREPARED_FILTER_OBFUSCATE, PREPARED_FILTER_OBFUSCATE,
PREPARED_FILTER_HIGHLIGHT, PREPARED_FILTER_HIGHLIGHT,
FLAGS FLAGS
}; };
[Flags] public string Name
public enum Flag { {
NONE = 0, get;
CONFIRMABLE = 1 set;
} }
private FieldType(string name)
public string Name; {
private FieldType(string name) {
Name = name; Name = name;
} }
public override string ToString() { public override string ToString()
{
return Name; return Name;
} }
public override int GetHashCode() public override int GetHashCode()
{ {
int hashCode = 0; int hashCode = 0;
unchecked { unchecked
{
if (Name != null) if (Name != null)
hashCode += 1000000009 * Name.GetHashCode(); hashCode += 1000000009 * Name.GetHashCode();
} }
return hashCode; return hashCode;
} }
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
FieldType other = obj as FieldType; FieldType other = obj as FieldType;
if (other == null) if (other == null)
{
return false; return false;
return Equals(Name,other.Name); }
return Equals(Name, other.Name);
} }
public static bool operator ==(FieldType a, FieldType b) { public static bool operator ==(FieldType a, FieldType b)
return Equals(a,b); {
return Equals(a, b);
} }
public static bool operator !=(FieldType a, FieldType b) { public static bool operator !=(FieldType a, FieldType b)
return !Equals(a,b); {
return !Equals(a, b);
} }
} }
} }

View file

@ -24,6 +24,7 @@ using Greenshot.Drawing.Fields;
using Greenshot.Helpers; using Greenshot.Helpers;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using System.Runtime.Serialization;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
@ -40,6 +41,18 @@ namespace Greenshot.Drawing {
} }
public FilterContainer(Surface parent) : base(parent) { 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() { protected override void InitializeFields() {
@ -52,7 +65,7 @@ namespace Greenshot.Drawing {
int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS); int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS);
Color lineColor = GetFieldValueAsColor(FieldType.LINE_COLOR); Color lineColor = GetFieldValueAsColor(FieldType.LINE_COLOR);
bool shadow = GetFieldValueAsBool(FieldType.SHADOW); bool shadow = GetFieldValueAsBool(FieldType.SHADOW);
bool lineVisible = (lineThickness > 0 && Colors.IsVisible(lineColor)); bool lineVisible = lineThickness > 0 && Colors.IsVisible(lineColor);
if (lineVisible) { if (lineVisible) {
graphics.SmoothingMode = SmoothingMode.HighSpeed; graphics.SmoothingMode = SmoothingMode.HighSpeed;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
@ -69,7 +82,7 @@ namespace Greenshot.Drawing {
Rectangle shadowRect = GuiRectangle.GetGuiRectangle(Left + currentStep, Top + currentStep, Width, Height); Rectangle shadowRect = GuiRectangle.GetGuiRectangle(Left + currentStep, Top + currentStep, Width, Height);
graphics.DrawRectangle(shadowPen, shadowRect); graphics.DrawRectangle(shadowPen, shadowRect);
currentStep++; currentStep++;
alpha = alpha - (basealpha / steps); alpha = alpha - basealpha / steps;
} }
} }
} }

View file

@ -41,7 +41,7 @@ namespace Greenshot.Drawing.Filters {
remove{ propertyChanged -= value; } remove{ propertyChanged -= value; }
} }
private bool invert = false; private bool invert;
public bool Invert { public bool Invert {
get { get {
return invert; return invert;

View file

@ -18,6 +18,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using System; using System;
using System.Drawing; using System.Drawing;
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
@ -25,13 +26,10 @@ using Greenshot.Plugin.Drawing;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using GreenshotPlugin.UnmanagedHelpers; using GreenshotPlugin.UnmanagedHelpers;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using log4net;
namespace Greenshot.Drawing.Filters { namespace Greenshot.Drawing.Filters {
[Serializable()] [Serializable()]
public class BlurFilter : AbstractFilter { public class BlurFilter : AbstractFilter {
private static ILog LOG = LogManager.GetLogger(typeof(BlurFilter));
public double previewQuality; public double previewQuality;
public double PreviewQuality { public double PreviewQuality {
get { return previewQuality; } get { return previewQuality; }
@ -43,7 +41,7 @@ namespace Greenshot.Drawing.Filters {
AddField(GetType(), FieldType.PREVIEW_QUALITY, 1.0d); 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); int blurRadius = GetFieldValueAsInt(FieldType.BLUR_RADIUS);
Rectangle applyRect = ImageHelper.CreateIntersectRectangle(applyBitmap.Size, rect, Invert); Rectangle applyRect = ImageHelper.CreateIntersectRectangle(applyBitmap.Size, rect, Invert);
if (applyRect.Width == 0 || applyRect.Height == 0) { if (applyRect.Width == 0 || applyRect.Height == 0) {
@ -54,7 +52,7 @@ namespace Greenshot.Drawing.Filters {
graphics.SetClip(applyRect); graphics.SetClip(applyRect);
graphics.ExcludeClip(rect); graphics.ExcludeClip(rect);
} }
if (GDIplus.isBlurPossible(blurRadius)) { if (GDIplus.IsBlurPossible(blurRadius)) {
GDIplus.DrawWithBlur(graphics, applyBitmap, applyRect, null, null, blurRadius, false); GDIplus.DrawWithBlur(graphics, applyBitmap, applyRect, null, null, blurRadius, false);
} else { } else {
using (IFastBitmap fastBitmap = FastBitmap.CreateCloneOf(applyBitmap, applyRect)) { using (IFastBitmap fastBitmap = FastBitmap.CreateCloneOf(applyBitmap, applyRect)) {
@ -63,7 +61,6 @@ namespace Greenshot.Drawing.Filters {
} }
} }
graphics.Restore(state); graphics.Restore(state);
return;
} }
} }
} }

View file

@ -21,11 +21,11 @@
using System.ComponentModel; using System.ComponentModel;
using System.Drawing; using System.Drawing;
using Greenshot.Drawing.Fields;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using GreenshotPlugin.Interfaces.Drawing;
namespace Greenshot.Drawing.Filters { namespace Greenshot.Drawing.Filters
{
public interface IFilter : INotifyPropertyChanged, IFieldHolder { public interface IFilter : INotifyPropertyChanged, IFieldHolder {
DrawableContainer Parent {get; set; } DrawableContainer Parent {get; set; }
void Apply(Graphics graphics, Bitmap bmp, Rectangle rect, RenderMode renderMode); void Apply(Graphics graphics, Bitmap bmp, Rectangle rect, RenderMode renderMode);

View file

@ -53,7 +53,7 @@ namespace Greenshot.Drawing.Filters {
int halfHeight = rect.Height / 2; int halfHeight = rect.Height / 2;
int newWidth = rect.Width / magnificationFactor; int newWidth = rect.Width / magnificationFactor;
int newHeight = rect.Height / 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.DrawImage(applyBitmap, rect, source, GraphicsUnit.Pixel);
graphics.Restore(state); graphics.Restore(state);
} }

View file

@ -37,7 +37,7 @@ namespace Greenshot.Drawing.Filters {
public override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode) { public override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode) {
int pixelSize = GetFieldValueAsInt(FieldType.PIXEL_SIZE); 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) { if (pixelSize <= 1 || rect.Width == 0 || rect.Height == 0) {
// Nothing to do // Nothing to do
return; return;

View file

@ -22,7 +22,6 @@
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using Greenshot.Helpers; using Greenshot.Helpers;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using log4net;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing; using System.Drawing;
@ -35,21 +34,19 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
[Serializable] [Serializable]
public class FreehandContainer : DrawableContainer { 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}; private static readonly float [] POINT_OFFSET = new float[]{0.5f, 0.25f, 0.75f};
[NonSerialized] [NonSerialized]
private GraphicsPath freehandPath = new GraphicsPath(); private GraphicsPath freehandPath = new GraphicsPath();
private Rectangle myBounds = Rectangle.Empty; private Rectangle myBounds = Rectangle.Empty;
private Point lastMouse = Point.Empty; private Point lastMouse = Point.Empty;
private List<Point> capturePoints = new List<Point>(); private readonly List<Point> capturePoints = new List<Point>();
private bool isRecalculated = false; private bool isRecalculated;
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
public FreehandContainer(Surface parent) : base(parent) { public FreehandContainer(Surface parent) : base(parent) {
Init();
Width = parent.Width; Width = parent.Width;
Height = parent.Height; Height = parent.Height;
Top = 0; Top = 0;
@ -61,16 +58,6 @@ namespace Greenshot.Drawing {
AddField(GetType(), FieldType.LINE_COLOR, Color.Red); 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) { public override void Transform(Matrix matrix) {
Point[] points = capturePoints.ToArray(); Point[] points = capturePoints.ToArray();
@ -80,11 +67,7 @@ namespace Greenshot.Drawing {
RecalculatePath(); RecalculatePath();
} }
[OnDeserialized] protected override void OnDeserialized(StreamingContext context) {
private void OnDeserialized(StreamingContext context) {
InitGrippers();
DoLayout();
Init();
RecalculatePath(); RecalculatePath();
} }
@ -119,7 +102,7 @@ namespace Greenshot.Drawing {
public override bool HandleMouseMove(int mouseX, int mouseY) { public override bool HandleMouseMove(int mouseX, int mouseY) {
Point previousPoint = capturePoints[capturePoints.Count-1]; 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)); capturePoints.Add(new Point(mouseX, mouseY));
} }
if (GeometryHelper.Distance2D(lastMouse.X, lastMouse.Y, mouseX, mouseY) >= EditorConfig.FreehandSensitivity) { if (GeometryHelper.Distance2D(lastMouse.X, lastMouse.Y, mouseX, mouseY) >= EditorConfig.FreehandSensitivity) {
@ -232,7 +215,7 @@ namespace Greenshot.Drawing {
if (!myBounds.IsEmpty) { if (!myBounds.IsEmpty) {
int lineThickness = Math.Max(10, GetFieldValueAsInt(FieldType.LINE_THICKNESS)); int lineThickness = Math.Max(10, GetFieldValueAsInt(FieldType.LINE_THICKNESS));
int safetymargin = 10; 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); return new Rectangle(0, 0, _parent.Width, _parent.Height);
} }
@ -258,17 +241,6 @@ namespace Greenshot.Drawing {
return freehandPath.GetHashCode(); return freehandPath.GetHashCode();
} }
/// <summary>
/// This is overriden to prevent the grippers to be modified.
/// Might not be the best way...
/// </summary>
protected override void DoLayout() {
}
public override void ShowGrippers() {
ResumeLayout();
}
public override bool ClickableAt(int x, int y) { public override bool ClickableAt(int x, int y) {
bool returnValue = base.ClickableAt(x, y); bool returnValue = base.ClickableAt(x, y);
if (returnValue) { if (returnValue) {

View file

@ -19,11 +19,11 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using System; using System;
using System.Drawing;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using Greenshot.Drawing.Filters; using Greenshot.Drawing.Filters;
using GreenshotPlugin.Interfaces.Drawing;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
@ -43,8 +43,8 @@ namespace Greenshot.Drawing {
AddField(GetType(), FieldType.PREPARED_FILTER_HIGHLIGHT, PreparedFilter.TEXT_HIGHTLIGHT); AddField(GetType(), FieldType.PREPARED_FILTER_HIGHLIGHT, PreparedFilter.TEXT_HIGHTLIGHT);
} }
[OnDeserialized] protected override void OnDeserialized(StreamingContext context)
private void OnDeserialized(StreamingContext context) { {
Init(); Init();
} }

View file

@ -24,6 +24,7 @@ using System.IO;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using log4net; using log4net;
using System.Runtime.Serialization;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
@ -31,11 +32,23 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
[Serializable] [Serializable]
public class IconContainer : DrawableContainer, IIconContainer { 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; protected Icon icon;
public IconContainer(Surface parent) : base(parent) { 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) { public IconContainer(Surface parent, string filename) : base(parent) {

View file

@ -27,6 +27,8 @@ using GreenshotPlugin.Core;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using Greenshot.Core; using Greenshot.Core;
using log4net; using log4net;
using System.Runtime.Serialization;
using GreenshotPlugin.Interfaces.Drawing;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
@ -34,7 +36,7 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
[Serializable] [Serializable]
public class ImageContainer : DrawableContainer, IImageContainer { 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; private Image image;
@ -58,6 +60,18 @@ namespace Greenshot.Drawing {
public ImageContainer(Surface parent) : base(parent) { public ImageContainer(Surface parent) : base(parent) {
FieldChanged += BitmapContainer_OnFieldChanged; FieldChanged += BitmapContainer_OnFieldChanged;
Init();
}
protected override void OnDeserialized(StreamingContext streamingContext)
{
base.OnDeserialized(streamingContext);
Init();
}
private void Init()
{
CreateDefaultAdorners();
} }
protected override void InitializeFields() { protected override void InitializeFields() {

View file

@ -26,6 +26,7 @@ using System.Runtime.Serialization;
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using Greenshot.Helpers; using Greenshot.Helpers;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using Greenshot.Drawing.Adorners;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
@ -45,19 +46,14 @@ namespace Greenshot.Drawing {
AddField(GetType(), FieldType.SHADOW, true); AddField(GetType(), FieldType.SHADOW, true);
} }
[OnDeserialized()] protected override void OnDeserialized(StreamingContext context)
private void OnDeserialized(StreamingContext context) { {
InitGrippers();
DoLayout();
Init(); Init();
} }
protected void Init() { protected void Init() {
if (_grippers != null) { Adorners.Add(new MoveAdorner(this, Positions.TopLeft));
foreach (int index in new[] { 1, 2, 3, 5, 6, 7 }) { Adorners.Add(new MoveAdorner(this, Positions.BottomRight));
_grippers[index].Enabled = false;
}
}
} }
public override void Draw(Graphics graphics, RenderMode rm) { public override void Draw(Graphics graphics, RenderMode rm) {
@ -86,7 +82,7 @@ namespace Greenshot.Drawing {
Top + currentStep + Height); Top + currentStep + Height);
currentStep++; currentStep++;
alpha = alpha - (basealpha / steps); alpha = alpha - basealpha / steps;
} }
} }
} }
@ -113,8 +109,6 @@ namespace Greenshot.Drawing {
protected override ScaleHelper.IDoubleProcessor GetAngleRoundProcessor() { protected override ScaleHelper.IDoubleProcessor GetAngleRoundProcessor() {
return ScaleHelper.LineAngleRoundBehavior.Instance; return ScaleHelper.LineAngleRoundBehavior.Instance;
} }
} }
} }

View file

@ -22,6 +22,7 @@ using System;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using Greenshot.Drawing.Filters; using Greenshot.Drawing.Filters;
using GreenshotPlugin.Interfaces.Drawing;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
@ -37,15 +38,16 @@ namespace Greenshot.Drawing {
base.InitializeFields(); base.InitializeFields();
AddField(GetType(), FieldType.PREPARED_FILTER_OBFUSCATE, PreparedFilter.PIXELIZE); AddField(GetType(), FieldType.PREPARED_FILTER_OBFUSCATE, PreparedFilter.PIXELIZE);
} }
[OnDeserialized] protected override void OnDeserialized(StreamingContext context)
private void OnDeserialized(StreamingContext context) { {
Init(); Init();
} }
private void Init() { private void Init() {
FieldChanged += ObfuscateContainer_OnFieldChanged; FieldChanged += ObfuscateContainer_OnFieldChanged;
ConfigurePreparedFilters(); ConfigurePreparedFilters();
CreateDefaultAdorners();
} }
protected void ObfuscateContainer_OnFieldChanged(object sender, FieldChangedEventArgs e) { protected void ObfuscateContainer_OnFieldChanged(object sender, FieldChangedEventArgs e) {

View file

@ -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 <http://www.gnu.org/licenses/>.
*/
namespace Greenshot.Drawing
{
/// <summary>
/// Position
/// </summary>
public enum Positions : int
{
TopLeft = 0,
TopCenter = 1,
TopRight = 2,
MiddleRight = 3,
BottomRight = 4,
BottomCenter = 5,
BottomLeft = 6,
MiddleLeft = 7
}
}

View file

@ -25,6 +25,7 @@ using System.Drawing.Drawing2D;
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using Greenshot.Helpers; using Greenshot.Helpers;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using System.Runtime.Serialization;
namespace Greenshot.Drawing { namespace Greenshot.Drawing {
/// <summary> /// <summary>
@ -34,6 +35,22 @@ namespace Greenshot.Drawing {
public class RectangleContainer : DrawableContainer { public class RectangleContainer : DrawableContainer {
public RectangleContainer(Surface parent) : base(parent) { public RectangleContainer(Surface parent) : base(parent) {
Init();
}
/// <summary>
/// Do some logic to make sure all field are initiated correctly
/// </summary>
/// <param name="streamingContext">StreamingContext</param>
protected override void OnDeserialized(StreamingContext streamingContext)
{
base.OnDeserialized(streamingContext);
Init();
}
private void Init()
{
CreateDefaultAdorners();
} }
protected override void InitializeFields() { protected override void InitializeFields() {
@ -69,7 +86,7 @@ namespace Greenshot.Drawing {
graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.None; graphics.PixelOffsetMode = PixelOffsetMode.None;
bool lineVisible = (lineThickness > 0 && Colors.IsVisible(lineColor)); bool lineVisible = lineThickness > 0 && Colors.IsVisible(lineColor);
if (shadow && (lineVisible || Colors.IsVisible(fillColor))) { if (shadow && (lineVisible || Colors.IsVisible(fillColor))) {
//draw shadow first //draw shadow first
int basealpha = 100; int basealpha = 100;
@ -86,7 +103,7 @@ namespace Greenshot.Drawing {
rect.Height); rect.Height);
graphics.DrawRectangle(shadowPen, shadowRect); graphics.DrawRectangle(shadowPen, shadowRect);
currentStep++; currentStep++;
alpha = alpha - (basealpha / steps); alpha = alpha - basealpha / steps;
} }
} }
} }

View file

@ -35,13 +35,13 @@ namespace Greenshot.Drawing {
public static GraphicsPath Create2(int x, int y, int width, int height, int radius) { public static GraphicsPath Create2(int x, int y, int width, int height, int radius) {
GraphicsPath gp = new GraphicsPath(); GraphicsPath gp = new GraphicsPath();
gp.AddLine(x + radius, y, x + width - (radius * 2), y); // 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.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.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.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.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.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, y + height - radius * 2, x, y + radius); // Line
gp.AddArc(x, y, radius * 2, radius * 2, 180, 90); // Corner gp.AddArc(x, y, radius * 2, radius * 2, 180, 90); // Corner
gp.CloseFigure(); gp.CloseFigure();

View file

@ -21,17 +21,15 @@
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using Greenshot.Helpers; using Greenshot.Helpers;
using Greenshot.Plugin;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using System; using System;
using System.Drawing; using System.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using System.Drawing.Text; using System.Drawing.Text;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using System.Windows.Forms;
using log4net;
namespace Greenshot.Drawing { namespace Greenshot.Drawing
{
/// <summary> /// <summary>
/// Description of SpeechbubbleContainer. /// Description of SpeechbubbleContainer.
/// </summary> /// </summary>
@ -50,8 +48,8 @@ namespace Greenshot.Drawing {
/// <param name="context"></param> /// <param name="context"></param>
[OnSerializing] [OnSerializing]
private void SetValuesOnSerializing(StreamingContext context) { private void SetValuesOnSerializing(StreamingContext context) {
if (TargetGripper != null) { if (TargetAdorner != null) {
_storedTargetGripperLocation = TargetGripper.Location; _storedTargetGripperLocation = TargetAdorner.Location;
} }
} }
@ -59,9 +57,9 @@ namespace Greenshot.Drawing {
/// Restore the target gripper /// Restore the target gripper
/// </summary> /// </summary>
/// <param name="context"></param> /// <param name="context"></param>
[OnDeserialized] protected override void OnDeserialized(StreamingContext context)
private void SetValuesOnDeserialized(StreamingContext context) { {
InitTargetGripper(Color.Green, _storedTargetGripperLocation); InitAdorner(Color.Green, _storedTargetGripperLocation);
} }
#endregion #endregion
@ -90,9 +88,9 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <returns>true if the surface doesn't need to handle the event</returns> /// <returns>true if the surface doesn't need to handle the event</returns>
public override bool HandleMouseDown(int mouseX, int mouseY) { public override bool HandleMouseDown(int mouseX, int mouseY) {
if (TargetGripper == null) { if (TargetAdorner == null) {
_initialGripperPoint = new Point(mouseX, mouseY); _initialGripperPoint = new Point(mouseX, mouseY);
InitTargetGripper(Color.Green, new Point(mouseX, mouseY)); InitAdorner(Color.Green, new Point(mouseX, mouseY));
} }
return base.HandleMouseDown(mouseX, mouseY); return base.HandleMouseDown(mouseX, mouseY);
} }
@ -116,9 +114,9 @@ namespace Greenshot.Drawing {
Point newGripperLocation = _initialGripperPoint; Point newGripperLocation = _initialGripperPoint;
newGripperLocation.Offset(xOffset, yOffset); newGripperLocation.Offset(xOffset, yOffset);
if (TargetGripper.Location != newGripperLocation) { if (TargetAdorner.Location != newGripperLocation) {
Invalidate(); Invalidate();
TargetGripperMove(newGripperLocation.X, newGripperLocation.Y); TargetAdorner.Location = newGripperLocation;
Invalidate(); Invalidate();
} }
return returnValue; return returnValue;
@ -180,7 +178,7 @@ namespace Greenshot.Drawing {
private GraphicsPath CreateTail() { private GraphicsPath CreateTail() {
Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height); 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; int tailWidth = (Math.Abs(rect.Width) + Math.Abs(rect.Height)) / 20;
// This should fix a problem with the tail being to wide // 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.AddLine(tailWidth, 0, 0, -tailLength);
tail.CloseFigure(); 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()) { 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); tailMatrix.Rotate(tailAngle);
tail.Transform(tailMatrix); tail.Transform(tailMatrix);
} }
@ -209,7 +207,7 @@ namespace Greenshot.Drawing {
/// <param name="graphics"></param> /// <param name="graphics"></param>
/// <param name="renderMode"></param> /// <param name="renderMode"></param>
public override void Draw(Graphics graphics, RenderMode renderMode) { public override void Draw(Graphics graphics, RenderMode renderMode) {
if (TargetGripper == null) { if (TargetAdorner == null) {
return; return;
} }
graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.SmoothingMode = SmoothingMode.HighQuality;
@ -223,7 +221,7 @@ namespace Greenshot.Drawing {
bool shadow = GetFieldValueAsBool(FieldType.SHADOW); bool shadow = GetFieldValueAsBool(FieldType.SHADOW);
int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS); 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); Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height);
if (Selected && renderMode == RenderMode.EDIT) { if (Selected && renderMode == RenderMode.EDIT) {
@ -253,7 +251,7 @@ namespace Greenshot.Drawing {
graphics.DrawPath(shadowPen, bubbleClone); graphics.DrawPath(shadowPen, bubbleClone);
} }
currentStep++; currentStep++;
alpha = alpha - (basealpha / steps); alpha = alpha - basealpha / steps;
} }
} }
} }

View file

@ -45,6 +45,12 @@ namespace Greenshot.Drawing {
public StepLabelContainer(Surface parent) : base(parent) { public StepLabelContainer(Surface parent) : base(parent) {
parent.AddStepLabel(this); parent.AddStepLabel(this);
InitContent(); InitContent();
Init();
}
private void Init()
{
CreateDefaultAdorners();
} }
#region Number serializing #region Number serializing
@ -75,8 +81,9 @@ namespace Greenshot.Drawing {
/// Restore values that don't serialize /// Restore values that don't serialize
/// </summary> /// </summary>
/// <param name="context"></param> /// <param name="context"></param>
[OnDeserialized] protected override void OnDeserialized(StreamingContext context)
private void SetValuesOnDeserialized(StreamingContext context) { {
Init();
_stringFormat = new StringFormat(); _stringFormat = new StringFormat();
_stringFormat.Alignment = StringAlignment.Center; _stringFormat.Alignment = StringAlignment.Center;
_stringFormat.LineAlignment = StringAlignment.Center; _stringFormat.LineAlignment = StringAlignment.Center;
@ -87,6 +94,10 @@ namespace Greenshot.Drawing {
/// </summary> /// </summary>
/// <param name="newParent"></param> /// <param name="newParent"></param>
protected override void SwitchParent(Surface newParent) { protected override void SwitchParent(Surface newParent) {
if (newParent == Parent)
{
return;
}
if (Parent != null) { if (Parent != null) {
((Surface)Parent).RemoveStepLabel(this); ((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. /// This makes it possible for the label to be placed exactly in the middle of the pointer.
/// </summary> /// </summary>
public override bool HandleMouseDown(int mouseX, int mouseY) { 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);
} }
/// <summary> /// <summary>
@ -146,8 +157,8 @@ namespace Greenshot.Drawing {
public override bool HandleMouseMove(int x, int y) { public override bool HandleMouseMove(int x, int y) {
Invalidate(); Invalidate();
Left = x - (Width / 2); Left = x - Width / 2;
Top = y - (Height / 2); Top = y - Height / 2;
Invalidate(); Invalidate();
return true; return true;
} }
@ -167,7 +178,7 @@ namespace Greenshot.Drawing {
int widthAfter = rect.Width; int widthAfter = rect.Width;
int heightAfter = rect.Height; int heightAfter = rect.Height;
float factor = (((float)widthAfter / widthBefore) + ((float)heightAfter / heightBefore)) / 2; float factor = ((float)widthAfter / widthBefore + (float)heightAfter / heightBefore) / 2;
fontSize *= factor; fontSize *= factor;
} }

File diff suppressed because it is too large Load diff

View file

@ -22,8 +22,8 @@
using Greenshot.Drawing.Fields; using Greenshot.Drawing.Fields;
using Greenshot.Helpers; using Greenshot.Helpers;
using Greenshot.Memento; using Greenshot.Memento;
using Greenshot.Plugin;
using Greenshot.Plugin.Drawing; using Greenshot.Plugin.Drawing;
using GreenshotPlugin.Interfaces.Drawing;
using System; using System;
using System.ComponentModel; using System.ComponentModel;
using System.Drawing; using System.Drawing;
@ -72,7 +72,7 @@ namespace Greenshot.Drawing {
} }
internal void ChangeText(string newText, bool allowUndoable) { 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) { if (makeUndoable && allowUndoable) {
makeUndoable = false; makeUndoable = false;
_parent.MakeUndoable(new TextChangeMemento(this), 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_HORIZONTAL_ALIGNMENT, StringAlignment.Center);
AddField(GetType(), FieldType.TEXT_VERTICAL_ALIGNMENT, StringAlignment.Center); AddField(GetType(), FieldType.TEXT_VERTICAL_ALIGNMENT, StringAlignment.Center);
} }
[OnDeserialized] /// <summary>
private void OnDeserialized(StreamingContext context) { /// Do some logic to make sure all field are initiated correctly
/// </summary>
/// <param name="streamingContext">StreamingContext</param>
protected override void OnDeserialized(StreamingContext streamingContext) {
base.OnDeserialized(streamingContext);
Init(); Init();
} }
@ -123,8 +127,10 @@ namespace Greenshot.Drawing {
} }
private void Init() { private void Init() {
_stringFormat = new StringFormat(); _stringFormat = new StringFormat
_stringFormat.Trimming = StringTrimming.EllipsisWord; {
Trimming = StringTrimming.EllipsisWord
};
CreateTextBox(); CreateTextBox();
@ -178,15 +184,18 @@ namespace Greenshot.Drawing {
} }
// Only dispose the font, and re-create it, when a font field has changed. // Only dispose the font, and re-create it, when a font field has changed.
if (e.Field.FieldType.Name.StartsWith("FONT")) { if (e.Field.FieldType.Name.StartsWith("FONT")) {
_font.Dispose(); if (_font != null)
_font = null; {
_font.Dispose();
_font = null;
}
UpdateFormat(); UpdateFormat();
} else { } else {
UpdateAlignment(); UpdateAlignment();
} }
UpdateTextBoxFormat(); UpdateTextBoxFormat();
if (_textBox.Visible) { if (_textBox != null && _textBox.Visible) {
_textBox.Invalidate(); _textBox.Invalidate();
} }
} }
@ -196,17 +205,19 @@ namespace Greenshot.Drawing {
} }
private void CreateTextBox() { 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.DataBindings.Add("Text", this, "Text", false, DataSourceUpdateMode.OnPropertyChanged);
_textBox.LostFocus += textBox_LostFocus; _textBox.LostFocus += textBox_LostFocus;
_textBox.KeyDown += textBox_KeyDown; _textBox.KeyDown += textBox_KeyDown;
_textBox.BorderStyle = BorderStyle.None;
_textBox.Visible = false;
} }
private void ShowTextBox() { private void ShowTextBox() {
@ -294,6 +305,7 @@ namespace Greenshot.Drawing {
} }
} }
} }
_font?.Dispose();
_font = new Font(fam, fontSize, fs, GraphicsUnit.Pixel); _font = new Font(fam, fontSize, fs, GraphicsUnit.Pixel);
_textBox.Font = _font; _textBox.Font = _font;
} }
@ -332,8 +344,8 @@ namespace Greenshot.Drawing {
if (lineThickness <= 1) { if (lineThickness <= 1) {
lineWidth = 0; lineWidth = 0;
} }
_textBox.Width = absRectangle.Width - (2 * lineWidth) + correction; _textBox.Width = absRectangle.Width - 2 * lineWidth + correction;
_textBox.Height = absRectangle.Height - (2 * lineWidth) + correction; _textBox.Height = absRectangle.Height - 2 * lineWidth + correction;
} }
public override void ApplyBounds(RectangleF newBounds) { public override void ApplyBounds(RectangleF newBounds) {
@ -390,7 +402,7 @@ namespace Greenshot.Drawing {
DrawSelectionBorder(graphics, rect); DrawSelectionBorder(graphics, rect);
} }
if (text == null || text.Length == 0 ) { if (string.IsNullOrEmpty(text) ) {
return; return;
} }
@ -411,11 +423,12 @@ namespace Greenshot.Drawing {
/// <param name="drawingRectange"></param> /// <param name="drawingRectange"></param>
/// <param name="lineThickness"></param> /// <param name="lineThickness"></param>
/// <param name="fontColor"></param> /// <param name="fontColor"></param>
/// <param name="drawShadow"></param>
/// <param name="stringFormat"></param> /// <param name="stringFormat"></param>
/// <param name="text"></param> /// <param name="text"></param>
/// <param name="font"></param> /// <param name="font"></param>
public static void DrawText(Graphics graphics, Rectangle drawingRectange, int lineThickness, Color fontColor, bool drawShadow, StringFormat stringFormat, string text, Font font) { 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 // draw shadow before anything else
if (drawShadow) { if (drawShadow) {
int basealpha = 100; int basealpha = 100;

View file

@ -41,21 +41,21 @@ namespace Greenshot {
/// The about form /// The about form
/// </summary> /// </summary>
public partial class AboutForm : AnimatingBaseForm { public partial class AboutForm : AnimatingBaseForm {
private static ILog LOG = LogManager.GetLogger(typeof(AboutForm)); private static readonly ILog LOG = LogManager.GetLogger(typeof(AboutForm));
private Bitmap gBitmap; private Bitmap _bitmap;
private ColorAnimator backgroundAnimation; private readonly ColorAnimator _backgroundAnimation;
private List<RectangleAnimator> pixels = new List<RectangleAnimator>(); private readonly IList<RectangleAnimator> _pixels = new List<RectangleAnimator>();
private List<Color> colorFlow = new List<Color>(); private readonly IList<Color> _colorFlow = new List<Color>();
private List<Color> pixelColors = new List<Color>(); private readonly IList<Color> _pixelColors = new List<Color>();
private Random rand = new Random(); private readonly Random _rand = new Random();
private readonly Color backColor = Color.FromArgb(61, 61, 61); private readonly Color _backColor = Color.FromArgb(61, 61, 61);
private readonly Color pixelColor = Color.FromArgb(138, 255, 0); private readonly Color _pixelColor = Color.FromArgb(138, 255, 0);
// Variables used for the color-cycle // Variables used for the color-cycle
private int waitFrames = 0; private int _waitFrames;
private int colorIndex = 0; private int _colorIndex;
private int scrollCount = 0; private int _scrollCount;
private bool hasAnimationsLeft; private bool _hasAnimationsLeft;
// Variables are used to define the location of the dots // Variables are used to define the location of the dots
private const int w = 13; private const int w = 13;
@ -70,7 +70,7 @@ namespace Greenshot {
/// <summary> /// <summary>
/// The location of every dot in the "G" /// The location of every dot in the "G"
/// </summary> /// </summary>
private List<Point> gSpots = new List<Point>() { private readonly List<Point> gSpots = new List<Point>() {
// Top row // Top row
new Point(p2, p1), // 0 new Point(p2, p1), // 0
new Point(p3, p1), // 1 new Point(p3, p1), // 1
@ -116,15 +116,15 @@ namespace Greenshot {
// 18 19 20 21 22 23 // 18 19 20 21 22 23
// The order in which we draw the dots & flow the collors. // The order in which we draw the dots & flow the collors.
List<int> flowOrder = new List<int>() { 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<int> flowOrder = new List<int>() { 4, 3, 2, 1, 0, 5, 6, 7, 8, 9, 10, 14, 15, 18, 19, 20, 21, 22, 23, 16, 17, 13, 12, 11 };
/// <summary> /// <summary>
/// Cleanup all the allocated resources /// Cleanup all the allocated resources
/// </summary> /// </summary>
private void Cleanup(object sender, EventArgs e) { private void Cleanup(object sender, EventArgs e) {
if (gBitmap != null) { if (_bitmap != null) {
gBitmap.Dispose(); _bitmap.Dispose();
gBitmap = null; _bitmap = null;
} }
} }
@ -144,22 +144,22 @@ namespace Greenshot {
InitializeComponent(); InitializeComponent();
// Only use double-buffering when we are NOT in a Terminal Server session // 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) // 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); _bitmap = ImageHelper.CreateEmpty(90, 90, PixelFormat.Format24bppRgb, BackColor, 96, 96);
pictureBox1.Image = gBitmap; pictureBox1.Image = _bitmap;
Version v = Assembly.GetExecutingAssembly().GetName().Version; Version v = Assembly.GetExecutingAssembly().GetName().Version;
// Format is like this: AssemblyVersion("Major.Minor.Build.Revision")] // 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(); //Random rand = new Random();
// Number of frames the pixel animation takes // Number of frames the pixel animation takes
int frames = FramesForMillis(2000); int frames = FramesForMillis(2000);
// The number of frames the color-cycle waits before it starts // 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. // Every pixel is created after pixelWaitFrames frames, which is increased in the loop.
int pixelWaitFrames = FramesForMillis(2000); int pixelWaitFrames = FramesForMillis(2000);
@ -174,7 +174,7 @@ namespace Greenshot {
int offset = (w - 2) / 2; int offset = (w - 2) / 2;
// If the optimize for Terminal Server is set we make the animation without much ado // If the optimize for Terminal Server is set we make the animation without much ado
if (isTerminalServerSession) { if (IsTerminalServerSession) {
// No animation // 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); 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 { } else {
@ -187,23 +187,23 @@ namespace Greenshot {
// Increase the wait frames // Increase the wait frames
pixelWaitFrames += FramesForMillis(100); pixelWaitFrames += FramesForMillis(100);
// Add to the list of to be animated pixels // Add to the list of to be animated pixels
pixels.Add(pixelAnimation); _pixels.Add(pixelAnimation);
// Add a color to the list for this pixel. // 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 // 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. // 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); ColorAnimator pixelColorAnimator = new ColorAnimator(_pixelColor, Color.FromArgb(255, 255, 255), 6, EasingType.Quadratic, EasingMode.EaseIn);
pixelColorAnimator.QueueDestinationLeg(pixelColor, 6, EasingType.Quadratic, EasingMode.EaseOut); pixelColorAnimator.QueueDestinationLeg(_pixelColor, 6, EasingType.Quadratic, EasingMode.EaseOut);
do { do {
colorFlow.Add(pixelColorAnimator.Current); _colorFlow.Add(pixelColorAnimator.Current);
pixelColorAnimator.Next(); pixelColorAnimator.Next();
} while (pixelColorAnimator.hasNext); } while (pixelColorAnimator.HasNext);
// color animation for the background // 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);
} }
/// <summary> /// <summary>
@ -227,63 +227,63 @@ namespace Greenshot {
/// Called from the AnimatingForm, for every frame /// Called from the AnimatingForm, for every frame
/// </summary> /// </summary>
protected override void Animate() { protected override void Animate() {
if (gBitmap == null) { if (_bitmap == null) {
return; return;
} }
if (!isTerminalServerSession) { if (!IsTerminalServerSession) {
// Color cycle // Color cycle
if (waitFrames != 0) { if (_waitFrames != 0) {
waitFrames--; _waitFrames--;
// Check if there is something else to do, if not we return so we don't occupy the CPU // Check if there is something else to do, if not we return so we don't occupy the CPU
if (!hasAnimationsLeft) { if (!_hasAnimationsLeft) {
return; 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. // Scroll colors, the scrollCount is the amount of pixels + the amount of colors to cycle.
for (int index = pixelColors.Count - 1; index > 0; index--) { for (int index = _pixelColors.Count - 1; index > 0; index--) {
pixelColors[index] = pixelColors[index - 1]; _pixelColors[index] = _pixelColors[index - 1];
} }
// Keep adding from the colors to cycle until there is nothing left // Keep adding from the colors to cycle until there is nothing left
if (colorIndex < colorFlow.Count) { if (_colorIndex < _colorFlow.Count) {
pixelColors[0] = colorFlow[colorIndex++]; _pixelColors[0] = _colorFlow[_colorIndex++];
} }
scrollCount++; _scrollCount++;
} else { } else {
// Reset values, wait X time for the next one // Reset values, wait X time for the next one
waitFrames = FramesForMillis(3000 + rand.Next(35000)); _waitFrames = FramesForMillis(3000 + _rand.Next(35000));
colorIndex = 0; _colorIndex = 0;
scrollCount = 0; _scrollCount = 0;
// Check if there is something else to do, if not we return so we don't occupy the CPU // Check if there is something else to do, if not we return so we don't occupy the CPU
if (!hasAnimationsLeft) { if (!_hasAnimationsLeft) {
return; return;
} }
} }
} else if (!hasAnimationsLeft) { } else if (!_hasAnimationsLeft) {
return; return;
} }
// Draw the "G" // Draw the "G"
using (Graphics graphics = Graphics.FromImage(gBitmap)) { using (Graphics graphics = Graphics.FromImage(_bitmap)) {
graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBilinear; graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.Clear(backgroundAnimation.Next()); graphics.Clear(_backgroundAnimation.Next());
graphics.TranslateTransform(2, -2); graphics.TranslateTransform(2, -2);
graphics.RotateTransform(20); graphics.RotateTransform(20);
using (SolidBrush brush = new SolidBrush(pixelColor)) { using (SolidBrush brush = new SolidBrush(_pixelColor)) {
int index = 0; int index = 0;
// We asume there is nothing to animate in the next Animate loop // We asume there is nothing to animate in the next Animate loop
hasAnimationsLeft = false; _hasAnimationsLeft = false;
// Pixels of the G // Pixels of the G
foreach (RectangleAnimator pixel in pixels) { foreach (RectangleAnimator pixel in _pixels) {
brush.Color = pixelColors[index++]; brush.Color = _pixelColors[index++];
graphics.FillEllipse(brush, pixel.Current); graphics.FillEllipse(brush, pixel.Current);
// If a pixel still has frames left, the hasAnimationsLeft will be true // If a pixel still has frames left, the hasAnimationsLeft will be true
hasAnimationsLeft = hasAnimationsLeft | pixel.hasNext; _hasAnimationsLeft = _hasAnimationsLeft | pixel.HasNext;
pixel.Next(); pixel.Next();
} }
} }

View file

@ -61,9 +61,9 @@ namespace Greenshot.Forms {
private int _mX; private int _mX;
private int _mY; private int _mY;
private Point _mouseMovePos = Point.Empty; private Point _mouseMovePos = Point.Empty;
private Point _cursorPos = Point.Empty; private Point _cursorPos;
private CaptureMode _captureMode = CaptureMode.None; private CaptureMode _captureMode;
private readonly List<WindowDetails> _windows = new List<WindowDetails>(); private readonly List<WindowDetails> _windows;
private WindowDetails _selectedCaptureWindow; private WindowDetails _selectedCaptureWindow;
private bool _mouseDown; private bool _mouseDown;
private Rectangle _captureRect = Rectangle.Empty; private Rectangle _captureRect = Rectangle.Empty;
@ -73,7 +73,7 @@ namespace Greenshot.Forms {
private RectangleAnimator _windowAnimator; private RectangleAnimator _windowAnimator;
private RectangleAnimator _zoomAnimator; private RectangleAnimator _zoomAnimator;
private readonly bool _isZoomerTransparent = Conf.ZoomerOpacity < 1; private readonly bool _isZoomerTransparent = Conf.ZoomerOpacity < 1;
private bool _isCtrlPressed = false; private bool _isCtrlPressed;
/// <summary> /// <summary>
/// Property to access the selected capture rectangle /// Property to access the selected capture rectangle
@ -153,7 +153,7 @@ namespace Greenshot.Forms {
// //
InitializeComponent(); InitializeComponent();
// Only double-buffer when we are not in a TerminalServerSession // Only double-buffer when we are not in a TerminalServerSession
DoubleBuffered = !isTerminalServerSession; DoubleBuffered = !IsTerminalServerSession;
Text = "Greenshot capture form"; Text = "Greenshot capture form";
// Make sure we never capture the captureform // Make sure we never capture the captureform
@ -398,7 +398,7 @@ namespace Greenshot.Forms {
if (animator == null) { if (animator == null) {
return false; return false;
} }
return animator.hasNext; return animator.HasNext;
} }
/// <summary> /// <summary>
@ -486,7 +486,7 @@ namespace Greenshot.Forms {
invalidateRectangle = new Rectangle(x1,y1, x2-x1, y2-y1); invalidateRectangle = new Rectangle(x1,y1, x2-x1, y2-y1);
Invalidate(invalidateRectangle); Invalidate(invalidateRectangle);
} else if (_captureMode != CaptureMode.Window) { } else if (_captureMode != CaptureMode.Window) {
if (!isTerminalServerSession) { if (!IsTerminalServerSession) {
Rectangle allScreenBounds = WindowCapture.GetScreenBounds(); Rectangle allScreenBounds = WindowCapture.GetScreenBounds();
allScreenBounds.Location = WindowCapture.GetLocationRelativeToScreenBounds(allScreenBounds.Location); allScreenBounds.Location = WindowCapture.GetLocationRelativeToScreenBounds(allScreenBounds.Location);
if (verticalMove) { if (verticalMove) {
@ -570,7 +570,7 @@ namespace Greenshot.Forms {
screenBounds.Location = WindowCapture.GetLocationRelativeToScreenBounds(screenBounds.Location); screenBounds.Location = WindowCapture.GetLocationRelativeToScreenBounds(screenBounds.Location);
int relativeZoomSize = Math.Min(screenBounds.Width, screenBounds.Height) / 5; int relativeZoomSize = Math.Min(screenBounds.Width, screenBounds.Height) / 5;
// Make sure the final size is a plural of 4, this makes it look better // 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); Size zoomSize = new Size(relativeZoomSize, relativeZoomSize);
Point zoomOffset = new Point(20, 20); Point zoomOffset = new Point(20, 20);
@ -652,9 +652,9 @@ namespace Greenshot.Forms {
// Calculate some values // Calculate some values
int pixelThickness = destinationRectangle.Width / sourceRectangle.Width; int pixelThickness = destinationRectangle.Width / sourceRectangle.Width;
int halfWidth = destinationRectangle.Width / 2; 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 halfHeight = destinationRectangle.Height / 2;
int halfHeightEnd = (destinationRectangle.Height / 2) - (pixelThickness / 2); int halfHeightEnd = destinationRectangle.Height / 2 - pixelThickness / 2;
int drawAtHeight = destinationRectangle.Y + halfHeight; int drawAtHeight = destinationRectangle.Y + halfHeight;
int drawAtWidth = destinationRectangle.X + halfWidth; 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); 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 // Fix offset for drawing the white rectangle around the crosshair-lines
drawAtHeight -= (pixelThickness / 2); drawAtHeight -= pixelThickness / 2;
drawAtWidth -= (pixelThickness / 2); drawAtWidth -= pixelThickness / 2;
// Fix off by one error with the DrawRectangle // Fix off by one error with the DrawRectangle
pixelThickness -= 1; pixelThickness -= 1;
// Change the color and the pen width // Change the color and the pen width
@ -762,7 +762,7 @@ namespace Greenshot.Forms {
graphics.DrawPath(rulerPen, p); graphics.DrawPath(rulerPen, p);
graphics.DrawString(captureWidth, rulerFont, rulerPen.Brush, fixedRect.X + (fixedRect.Width / 2 - hSpace / 2) + 3, fixedRect.Y - dist - 7); 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.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.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); 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.DrawPath(rulerPen, p);
graphics.DrawString(captureHeight, rulerFont, rulerPen.Brush, fixedRect.X - measureHeight.Width + 1, fixedRect.Y + (fixedRect.Height / 2 - vSpace / 2) + 2); 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.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.X - dist + 3, fixedRect.Y);
graphics.DrawLine(rulerPen, fixedRect.X - dist - 3, fixedRect.Y + fixedRect.Height, fixedRect.X - dist + 3, fixedRect.Y + fixedRect.Height); 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; string sizeText;
if (_captureMode == CaptureMode.Region) { if (_captureMode == CaptureMode.Region) {
// correct the GUI width to real width for the shown size // 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 { } else {
sizeText = _captureRect.Width + " x " + _captureRect.Height; sizeText = _captureRect.Width + " x " + _captureRect.Height;
} }
@ -806,7 +806,7 @@ namespace Greenshot.Forms {
SizeF extent = graphics.MeasureString( sizeText, sizeFont ); SizeF extent = graphics.MeasureString( sizeText, sizeFont );
float hRatio = _captureRect.Height / (extent.Height * 2); float hRatio = _captureRect.Height / (extent.Height * 2);
float wRatio = _captureRect.Width / (extent.Width * 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; float newSize = sizeFont.Size * ratio;
if ( newSize >= 4 ) { if ( newSize >= 4 ) {
@ -816,13 +816,13 @@ namespace Greenshot.Forms {
} }
// Draw the size. // Draw the size.
using (Font newSizeFont = new Font(FontFamily.GenericSansSerif, newSize, FontStyle.Bold)) { 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); graphics.DrawString(sizeText, newSizeFont, Brushes.LightSeaGreen, sizeLocation);
} }
} }
} }
} else { } else {
if (!isTerminalServerSession) { if (!IsTerminalServerSession) {
using (Pen pen = new Pen(Color.LightSeaGreen)) { using (Pen pen = new Pen(Color.LightSeaGreen)) {
pen.DashStyle = DashStyle.Dot; pen.DashStyle = DashStyle.Dot;
Rectangle screenBounds = _capture.ScreenBounds; Rectangle screenBounds = _capture.ScreenBounds;
@ -852,7 +852,7 @@ namespace Greenshot.Forms {
const int zoomSourceWidth = 25; const int zoomSourceWidth = 25;
const int zoomSourceHeight = 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; Rectangle destinationRectangle = _zoomAnimator.Current;
destinationRectangle.Offset(_cursorPos); destinationRectangle.Offset(_cursorPos);

View file

@ -35,7 +35,7 @@ namespace Greenshot {
/// </summary> /// </summary>
public partial class ColorDialog : BaseForm { public partial class ColorDialog : BaseForm {
private static ColorDialog uniqueInstance; private static ColorDialog uniqueInstance;
private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>(); private static readonly EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>();
private ColorDialog() { private ColorDialog() {
SuspendLayout(); SuspendLayout();
@ -57,7 +57,7 @@ namespace Greenshot {
private readonly List<Button> _colorButtons = new List<Button>(); private readonly List<Button> _colorButtons = new List<Button>();
private readonly List<Button> _recentColorButtons = new List<Button>(); private readonly List<Button> _recentColorButtons = new List<Button>();
private readonly ToolTip _toolTip = new ToolTip(); private readonly ToolTip _toolTip = new ToolTip();
private bool _updateInProgress = false; private bool _updateInProgress;
public Color Color { public Color Color {
get { return colorPanel.BackColor; } get { return colorPanel.BackColor; }

View file

@ -22,11 +22,10 @@ using System;
using System.Drawing; using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
using Greenshot.Core; using Greenshot.Core;
using GreenshotPlugin.Core;
namespace Greenshot.Forms { namespace Greenshot.Forms {
public partial class DropShadowSettingsForm : BaseForm { public partial class DropShadowSettingsForm : BaseForm {
private DropShadowEffect effect; private readonly DropShadowEffect effect;
public DropShadowSettingsForm(DropShadowEffect effect) { public DropShadowSettingsForm(DropShadowEffect effect) {
this.effect = effect; this.effect = effect;
@ -50,10 +49,5 @@ namespace Greenshot.Forms {
effect.ShadowSize = (int)thickness.Value; effect.ShadowSize = (int)thickness.Value;
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;
} }
private void ButtonReset_Click(object sender, EventArgs e) {
effect.Reset();
ShowSettings();
}
} }
} }

View file

@ -1022,7 +1022,7 @@ namespace Greenshot {
this.propertiesToolStrip.Renderer = new CustomToolStripProfessionalRenderer(); this.propertiesToolStrip.Renderer = new CustomToolStripProfessionalRenderer();
this.propertiesToolStrip.BackColor = System.Drawing.SystemColors.Control; this.propertiesToolStrip.BackColor = System.Drawing.SystemColors.Control;
this.propertiesToolStrip.OverflowButton.DropDown.BackColor = System.Drawing.SystemColors.Control; this.propertiesToolStrip.OverflowButton.DropDown.BackColor = System.Drawing.SystemColors.Control;
this.propertiesToolStrip.Paint += propertiesToolStrip_Paint; this.propertiesToolStrip.Paint += PropertiesToolStrip_Paint;
this.propertiesToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.propertiesToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.obfuscateModeButton, this.obfuscateModeButton,
this.highlightModeButton, this.highlightModeButton,

File diff suppressed because it is too large Load diff

View file

@ -29,9 +29,9 @@ namespace Greenshot.Forms {
/// Description of LanguageDialog. /// Description of LanguageDialog.
/// </summary> /// </summary>
public partial class LanguageDialog : Form { 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 static LanguageDialog uniqueInstance;
private bool properOkPressed = false; private bool properOkPressed;
private LanguageDialog() { private LanguageDialog() {
// //

View file

@ -52,7 +52,7 @@ namespace Greenshot {
private static ILog LOG; private static ILog LOG;
private static ResourceMutex _applicationMutex; private static ResourceMutex _applicationMutex;
private static CoreConfiguration _conf; private static CoreConfiguration _conf;
public static string LogFileLocation = null; public static string LogFileLocation;
public static void Start(string[] args) { public static void Start(string[] args) {
bool isAlreadyRunning = false; bool isAlreadyRunning = false;
@ -227,7 +227,7 @@ namespace Greenshot {
using (Form dummyForm = new Form()) { using (Form dummyForm = new Form()) {
dummyForm.Icon = GreenshotResources.getGreenshotIcon(); dummyForm.Icon = GreenshotResources.getGreenshotIcon();
dummyForm.ShowInTaskbar = true; dummyForm.ShowInTaskbar = true;
dummyForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; dummyForm.FormBorderStyle = FormBorderStyle.None;
dummyForm.Location = new Point(int.MinValue, int.MinValue); dummyForm.Location = new Point(int.MinValue, int.MinValue);
dummyForm.Load += delegate { dummyForm.Size = Size.Empty; }; dummyForm.Load += delegate { dummyForm.Size = Size.Empty; };
dummyForm.Show(); dummyForm.Show();
@ -550,7 +550,7 @@ namespace Greenshot {
contextMenu.ImageScalingSize = coreConfiguration.IconSize; contextMenu.ImageScalingSize = coreConfiguration.IconSize;
string ieExePath = PluginUtils.GetExePath("iexplore.exe"); string ieExePath = PluginUtils.GetExePath("iexplore.exe");
if (!string.IsNullOrEmpty(ieExePath)) { 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) { public void AddCaptureWindowMenuItems(ToolStripMenuItem menuItem, EventHandler eventHandler) {
menuItem.DropDownItems.Clear(); menuItem.DropDownItems.Clear();
// check if thumbnailPreview is enabled and DWM is enabled // check if thumbnailPreview is enabled and DWM is enabled
bool thumbnailPreview = _conf.ThumnailPreview && DWM.isDWMEnabled(); bool thumbnailPreview = _conf.ThumnailPreview && DWM.IsDwmEnabled();
List<WindowDetails> windows = WindowDetails.GetTopLevelWindows(); List<WindowDetails> windows = WindowDetails.GetTopLevelWindows();
foreach(WindowDetails window in windows) { foreach(WindowDetails window in windows) {

View file

@ -85,8 +85,8 @@ namespace Greenshot.Forms {
/// </summary> /// </summary>
/// <param name="screenCoordinates">Point with the coordinates</param> /// <param name="screenCoordinates">Point with the coordinates</param>
/// <returns>Color at the specified screenCoordinates</returns> /// <returns>Color at the specified screenCoordinates</returns>
static private Color GetPixelColor(Point screenCoordinates) { private static Color GetPixelColor(Point screenCoordinates) {
using (SafeWindowDCHandle screenDC = SafeWindowDCHandle.fromDesktop()) { using (SafeWindowDCHandle screenDC = SafeWindowDCHandle.FromDesktop()) {
try { try {
uint pixel = GDI32.GetPixel(screenDC, screenCoordinates.X, screenCoordinates.Y); 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); Color color = Color.FromArgb(255, (int)(pixel & 0xFF), (int)(pixel & 0xFF00) >> 8, (int)(pixel & 0xFF0000) >> 16);

View file

@ -21,7 +21,6 @@
using System; using System;
using System.Windows.Forms; using System.Windows.Forms;
using Greenshot.IniFile; using Greenshot.IniFile;
using GreenshotPlugin.Core;
namespace Greenshot.Forms { namespace Greenshot.Forms {
/// <summary> /// <summary>

View file

@ -29,9 +29,9 @@ namespace Greenshot.Forms {
/// A form to set the resize settings /// A form to set the resize settings
/// </summary> /// </summary>
public partial class ResizeSettingsForm : BaseForm { public partial class ResizeSettingsForm : BaseForm {
private ResizeEffect effect; private readonly ResizeEffect effect;
private string value_pixel; private readonly string value_pixel;
private string value_percent; private readonly string value_percent;
private double newWidth, newHeight; private double newWidth, newHeight;
public ResizeSettingsForm(ResizeEffect effect) { public ResizeSettingsForm(ResizeEffect effect) {
@ -50,8 +50,8 @@ namespace Greenshot.Forms {
textbox_height.Text = effect.Height.ToString(); textbox_height.Text = effect.Height.ToString();
newWidth = effect.Width; newWidth = effect.Width;
newHeight = effect.Height; newHeight = effect.Height;
combobox_width.SelectedIndexChanged += new System.EventHandler(this.combobox_SelectedIndexChanged); combobox_width.SelectedIndexChanged += new EventHandler(combobox_SelectedIndexChanged);
combobox_height.SelectedIndexChanged += new System.EventHandler(this.combobox_SelectedIndexChanged); combobox_height.SelectedIndexChanged += new EventHandler(combobox_SelectedIndexChanged);
checkbox_aspectratio.Checked = effect.MaintainAspectRatio; checkbox_aspectratio.Checked = effect.MaintainAspectRatio;
} }
@ -82,7 +82,7 @@ namespace Greenshot.Forms {
private void displayWidth() { private void displayWidth() {
double displayValue; double displayValue;
if (value_percent.Equals(combobox_width.SelectedItem)) { if (value_percent.Equals(combobox_width.SelectedItem)) {
displayValue = ((double)newWidth / (double)effect.Width) * 100d; displayValue = (double)newWidth / (double)effect.Width * 100d;
} else { } else {
displayValue = newWidth; displayValue = newWidth;
} }
@ -92,7 +92,7 @@ namespace Greenshot.Forms {
private void displayHeight() { private void displayHeight() {
double displayValue; double displayValue;
if (value_percent.Equals(combobox_height.SelectedItem)) { if (value_percent.Equals(combobox_height.SelectedItem)) {
displayValue = ((double)newHeight / (double)effect.Height) * 100d; displayValue = (double)newHeight / (double)effect.Height * 100d;
} else { } else {
displayValue = newHeight; displayValue = newHeight;
} }
@ -126,25 +126,25 @@ namespace Greenshot.Forms {
if (isWidth) { if (isWidth) {
if (isPercent) { if (isPercent) {
percent = double.Parse(textbox_width.Text); percent = double.Parse(textbox_width.Text);
newWidth = ((double)effect.Width / 100d) * percent; newWidth = (double)effect.Width / 100d * percent;
} else { } else {
newWidth = double.Parse(textbox_width.Text); 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) { if (checkbox_aspectratio.Checked) {
newHeight = ((double)effect.Height / 100d) * percent; newHeight = (double)effect.Height / 100d * percent;
displayHeight(); displayHeight();
} }
} else { } else {
if (isPercent) { if (isPercent) {
percent = double.Parse(textbox_height.Text); percent = double.Parse(textbox_height.Text);
newHeight = ((double)effect.Height / 100d) * percent; newHeight = (double)effect.Height / 100d * percent;
} else { } else {
newHeight = double.Parse(textbox_height.Text); 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) { if (checkbox_aspectratio.Checked) {
newWidth = ((double)effect.Width / 100d) * percent; newWidth = (double)effect.Width / 100d * percent;
displayWidth(); displayWidth();
} }
} }

View file

@ -43,7 +43,7 @@ namespace Greenshot {
/// Description of SettingsForm. /// Description of SettingsForm.
/// </summary> /// </summary>
public partial class SettingsForm : BaseForm { 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<EditorConfiguration>(); private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>();
private readonly ToolTip _toolTip = new ToolTip(); private readonly ToolTip _toolTip = new ToolTip();
private bool _inHotkey; private bool _inHotkey;
@ -146,7 +146,7 @@ namespace Greenshot {
private void SetWindowCaptureMode(WindowCaptureMode selectedWindowCaptureMode) { private void SetWindowCaptureMode(WindowCaptureMode selectedWindowCaptureMode) {
WindowCaptureMode[] availableModes; WindowCaptureMode[] availableModes;
if (!DWM.isDWMEnabled()) { if (!DWM.IsDwmEnabled()) {
// Remove DWM from configuration, as DWM is disabled! // Remove DWM from configuration, as DWM is disabled!
if (coreConfiguration.WindowCaptureMode == WindowCaptureMode.Aero || coreConfiguration.WindowCaptureMode == WindowCaptureMode.AeroTransparent) { if (coreConfiguration.WindowCaptureMode == WindowCaptureMode.Aero || coreConfiguration.WindowCaptureMode == WindowCaptureMode.AeroTransparent) {
coreConfiguration.WindowCaptureMode = WindowCaptureMode.GDI; coreConfiguration.WindowCaptureMode = WindowCaptureMode.GDI;
@ -237,7 +237,7 @@ namespace Greenshot {
string filenamePart = pathParts[pathParts.Length-1]; string filenamePart = pathParts[pathParts.Length-1];
settingsOk = FilenameHelper.IsFilenameValid(filenamePart); settingsOk = FilenameHelper.IsFilenameValid(filenamePart);
for (int i = 0; (settingsOk && i<pathParts.Length-1); i++) { for (int i = 0; settingsOk && i<pathParts.Length-1; i++) {
settingsOk = FilenameHelper.IsDirectoryNameValid(pathParts[i]); settingsOk = FilenameHelper.IsDirectoryNameValid(pathParts[i]);
} }
@ -399,7 +399,7 @@ namespace Greenshot {
numericUpDown_daysbetweencheck.Value = coreConfiguration.UpdateCheckInterval; numericUpDown_daysbetweencheck.Value = coreConfiguration.UpdateCheckInterval;
numericUpDown_daysbetweencheck.Enabled = !coreConfiguration.Values["UpdateCheckInterval"].IsFixed; numericUpDown_daysbetweencheck.Enabled = !coreConfiguration.Values["UpdateCheckInterval"].IsFixed;
numericUpdownIconSize.Value = (coreConfiguration.IconSize.Width /16) * 16; numericUpdownIconSize.Value = coreConfiguration.IconSize.Width /16 * 16;
CheckDestinationSettings(); CheckDestinationSettings();
} }
@ -444,7 +444,6 @@ namespace Greenshot {
coreConfiguration.DWMBackgroundColor = colorButton_window_background.SelectedColor; coreConfiguration.DWMBackgroundColor = colorButton_window_background.SelectedColor;
coreConfiguration.UpdateCheckInterval = (int)numericUpDown_daysbetweencheck.Value; coreConfiguration.UpdateCheckInterval = (int)numericUpDown_daysbetweencheck.Value;
Size previousValue = coreConfiguration.IconSize;
coreConfiguration.IconSize = new Size((int)numericUpdownIconSize.Value, (int)numericUpdownIconSize.Value); coreConfiguration.IconSize = new Size((int)numericUpdownIconSize.Value, (int)numericUpdownIconSize.Value);
try { try {

View file

@ -32,9 +32,9 @@ namespace Greenshot.Forms {
/// the ToolStripMenuSelectList makes it possible to have a single or multi-check menu /// the ToolStripMenuSelectList makes it possible to have a single or multi-check menu
/// </summary> /// </summary>
public class ToolStripMenuSelectList : ToolStripMenuItem { public class ToolStripMenuSelectList : ToolStripMenuItem {
private static CoreConfiguration coreConfiguration = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration coreConfiguration = IniConfig.GetIniSection<CoreConfiguration>();
private bool multiCheckAllowed = false; private readonly bool multiCheckAllowed;
private bool updateInProgress = false; private bool updateInProgress;
private static Image defaultImage; private static Image defaultImage;
/// <summary> /// <summary>

View file

@ -22,11 +22,10 @@ using System;
using System.Drawing; using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
using Greenshot.Core; using Greenshot.Core;
using GreenshotPlugin.Core;
namespace Greenshot.Forms { namespace Greenshot.Forms {
public partial class TornEdgeSettingsForm : BaseForm { public partial class TornEdgeSettingsForm : BaseForm {
private TornEdgeEffect effect; private readonly TornEdgeEffect effect;
public TornEdgeSettingsForm(TornEdgeEffect effect) { public TornEdgeSettingsForm(TornEdgeEffect effect) {
this.effect = effect; this.effect = effect;
InitializeComponent(); InitializeComponent();
@ -60,11 +59,6 @@ namespace Greenshot.Forms {
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;
} }
private void ButtonReset_Click(object sender, EventArgs e) {
effect.Reset();
ShowSettings();
}
private void ShadowCheckbox_CheckedChanged(object sender, EventArgs e) { private void ShadowCheckbox_CheckedChanged(object sender, EventArgs e) {
thickness.Enabled = shadowCheckbox.Checked; thickness.Enabled = shadowCheckbox.Checked;
offsetX.Enabled = shadowCheckbox.Checked; offsetX.Enabled = shadowCheckbox.Checked;

View file

@ -75,7 +75,12 @@
<Compile Include="Destinations\FileWithDialogDestination.cs" /> <Compile Include="Destinations\FileWithDialogDestination.cs" />
<Compile Include="Destinations\PickerDestination.cs" /> <Compile Include="Destinations\PickerDestination.cs" />
<Compile Include="Destinations\PrinterDestination.cs" /> <Compile Include="Destinations\PrinterDestination.cs" />
<Compile Include="Drawing\Adorners\AbstractAdorner.cs" />
<Compile Include="Drawing\Adorners\MoveAdorner.cs" />
<Compile Include="Drawing\Adorners\ResizeAdorner.cs" />
<Compile Include="Drawing\Adorners\TargetAdorner.cs" />
<Compile Include="Drawing\ArrowContainer.cs" /> <Compile Include="Drawing\ArrowContainer.cs" />
<Compile Include="Drawing\Positions.cs" />
<Compile Include="Drawing\StepLabelContainer.cs" /> <Compile Include="Drawing\StepLabelContainer.cs" />
<Compile Include="Drawing\ImageContainer.cs" /> <Compile Include="Drawing\ImageContainer.cs" />
<Compile Include="Drawing\CropContainer.cs" /> <Compile Include="Drawing\CropContainer.cs" />
@ -101,16 +106,12 @@
<Compile Include="Drawing\Filters\MagnifierFilter.cs" /> <Compile Include="Drawing\Filters\MagnifierFilter.cs" />
<Compile Include="Drawing\Filters\PixelizationFilter.cs" /> <Compile Include="Drawing\Filters\PixelizationFilter.cs" />
<Compile Include="Drawing\Filters\BlurFilter.cs" /> <Compile Include="Drawing\Filters\BlurFilter.cs" />
<Compile Include="Drawing\Gripper.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="Drawing\HighlightContainer.cs" /> <Compile Include="Drawing\HighlightContainer.cs" />
<Compile Include="Drawing\IconContainer.cs" /> <Compile Include="Drawing\IconContainer.cs" />
<Compile Include="Drawing\LineContainer.cs" /> <Compile Include="Drawing\LineContainer.cs" />
<Compile Include="Drawing\Fields\AbstractFieldHolder.cs" /> <Compile Include="Drawing\Fields\AbstractFieldHolder.cs" />
<Compile Include="Drawing\Fields\Field.cs" /> <Compile Include="Drawing\Fields\Field.cs" />
<Compile Include="Drawing\Fields\FieldType.cs" /> <Compile Include="Drawing\Fields\FieldType.cs" />
<Compile Include="Drawing\Fields\IFieldHolder.cs" />
<Compile Include="Drawing\Fields\FieldAggregator.cs" /> <Compile Include="Drawing\Fields\FieldAggregator.cs" />
<Compile Include="Drawing\ObfuscateContainer.cs" /> <Compile Include="Drawing\ObfuscateContainer.cs" />
<Compile Include="Drawing\FreehandContainer.cs" /> <Compile Include="Drawing\FreehandContainer.cs" />
@ -214,13 +215,14 @@
<Compile Include="Helpers\ProcessorHelper.cs" /> <Compile Include="Helpers\ProcessorHelper.cs" />
<Compile Include="Helpers\ResourceMutex.cs" /> <Compile Include="Helpers\ResourceMutex.cs" />
<Compile Include="Help\HelpFileLoader.cs" /> <Compile Include="Help\HelpFileLoader.cs" />
<Compile Include="Memento\AddElementsMemento.cs" />
<Compile Include="Memento\DeleteElementsMemento.cs" />
<Compile Include="Processors\TitleFixProcessor.cs" /> <Compile Include="Processors\TitleFixProcessor.cs" />
<Compile Include="Helpers\WindowWrapper.cs" /> <Compile Include="Helpers\WindowWrapper.cs" />
<Compile Include="Memento\AddElementMemento.cs" /> <Compile Include="Memento\AddElementMemento.cs" />
<Compile Include="Memento\ChangeFieldHolderMemento.cs" /> <Compile Include="Memento\ChangeFieldHolderMemento.cs" />
<Compile Include="Memento\DeleteElementMemento.cs" /> <Compile Include="Memento\DeleteElementMemento.cs" />
<Compile Include="Memento\TextChangeMemento.cs" /> <Compile Include="Memento\TextChangeMemento.cs" />
<Compile Include="Memento\IMemento.cs" />
<Compile Include="Memento\DrawableContainerBoundsChangeMemento.cs" /> <Compile Include="Memento\DrawableContainerBoundsChangeMemento.cs" />
<Compile Include="Memento\SurfaceBackgroundChangeMemento.cs" /> <Compile Include="Memento\SurfaceBackgroundChangeMemento.cs" />
<Compile Include="Helpers\UpdateHelper.cs" /> <Compile Include="Helpers\UpdateHelper.cs" />

View file

@ -1,7 +1,8 @@
 
Microsoft Visual Studio Solution File, Format Version 11.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2010 # Visual Studio 14
# SharpDevelop 4.2.2.8818 VisualStudioVersion = 14.0.25123.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Greenshot", "Greenshot.csproj", "{CD642BF4-D815-4D67-A0B5-C69F0B8231AF}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Greenshot", "Greenshot.csproj", "{CD642BF4-D815-4D67-A0B5-C69F0B8231AF}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GreenshotPlugin", "..\GreenshotPlugin\GreenshotPlugin.csproj", "{5B924697-4DCD-4F98-85F1-105CB84B7341}" 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|Mixed Platforms.ActiveCfg = Release|Any CPU
{C6988EE8-2FEE-4349-9F09-F9628A0D8965}.Release|x86.ActiveCfg = Release|x86 {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.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|Mixed Platforms.ActiveCfg = Debug|x86
{D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|x86.ActiveCfg = Debug|x86 {D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|x86.ActiveCfg = Debug|x86
{D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|x86.Build.0 = Debug|x86 {D61E6ECE-E0B6-4467-B492-F08A06BA8F02}.Debug|x86.Build.0 = Debug|x86

View file

@ -42,7 +42,7 @@ namespace Greenshot.Helpers {
/// </summary> /// </summary>
public class CaptureHelper : IDisposable { public class CaptureHelper : IDisposable {
private static readonly ILog LOG = LogManager.GetLogger(typeof(CaptureHelper)); private static readonly ILog LOG = LogManager.GetLogger(typeof(CaptureHelper));
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
// TODO: when we get the screen capture code working correctly, this needs to be enabled // TODO: when we get the screen capture code working correctly, this needs to be enabled
//private static ScreenCaptureHelper screenCapture = null; //private static ScreenCaptureHelper screenCapture = null;
private List<WindowDetails> _windows = new List<WindowDetails>(); private List<WindowDetails> _windows = new List<WindowDetails>();
@ -404,7 +404,7 @@ namespace Greenshot.Helpers {
// Set capture title, fixing bug #3569703 // Set capture title, fixing bug #3569703
foreach (WindowDetails window in WindowDetails.GetVisibleWindows()) { 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)) { if (window.Contains(estimatedLocation)) {
_selectedCaptureWindow = window; _selectedCaptureWindow = window;
_capture.CaptureDetails.Title = _selectedCaptureWindow.Text; _capture.CaptureDetails.Title = _selectedCaptureWindow.Text;
@ -693,7 +693,10 @@ namespace Greenshot.Helpers {
} else { } else {
_selectedCaptureWindow = WindowDetails.GetActiveWindow(); _selectedCaptureWindow = WindowDetails.GetActiveWindow();
if (_selectedCaptureWindow != null) { 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)) { 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 // Trying workaround, the size 0 arrises with e.g. Toad.exe, has a different Window when minimized
WindowDetails linkedWindow = WindowDetails.GetLinkedWindow(windowToCapture); WindowDetails linkedWindow = WindowDetails.GetLinkedWindow(windowToCapture);
if (linkedWindow != null) { if (linkedWindow != null) {
windowRectangle = linkedWindow.WindowRectangle;
windowToCapture = linkedWindow; windowToCapture = linkedWindow;
} else { } else {
return null; return null;
@ -777,7 +779,7 @@ namespace Greenshot.Helpers {
Rectangle windowRectangle = windowToCapture.WindowRectangle; Rectangle windowRectangle = windowToCapture.WindowRectangle;
// When Vista & DWM (Aero) enabled // 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 // get process name to be able to exclude certain processes from certain capture modes
using (Process process = windowToCapture.Process) { using (Process process = windowToCapture.Process) {
bool isAutoMode = windowCaptureMode == WindowCaptureMode.Auto; bool isAutoMode = windowCaptureMode == WindowCaptureMode.Auto;
@ -801,7 +803,7 @@ namespace Greenshot.Helpers {
windowCaptureMode = WindowCaptureMode.Screen; windowCaptureMode = WindowCaptureMode.Screen;
// Change to GDI, if allowed // Change to GDI, if allowed
if (!windowToCapture.isMetroApp && WindowCapture.IsGdiAllowed(process)) { if (!windowToCapture.IsMetroApp && WindowCapture.IsGdiAllowed(process)) {
if (!dwmEnabled && isWPF(process)) { if (!dwmEnabled && isWPF(process)) {
// do not use GDI, as DWM is not enabled and the application uses PresentationFramework.dll -> isWPF // 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); 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 // Change to DWM, if enabled and allowed
if (dwmEnabled) { if (dwmEnabled) {
if (windowToCapture.isMetroApp || WindowCapture.IsDwmAllowed(process)) { if (windowToCapture.IsMetroApp || WindowCapture.IsDwmAllowed(process)) {
windowCaptureMode = WindowCaptureMode.Aero; windowCaptureMode = WindowCaptureMode.Aero;
} }
} }
} else if (windowCaptureMode == WindowCaptureMode.Aero || windowCaptureMode == WindowCaptureMode.AeroTransparent) { } 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 // Take default screen
windowCaptureMode = WindowCaptureMode.Screen; windowCaptureMode = WindowCaptureMode.Screen;
// Change to GDI, if allowed // Change to GDI, if allowed
@ -845,32 +847,32 @@ namespace Greenshot.Helpers {
} else { } else {
windowToCapture.ToForeground(); windowToCapture.ToForeground();
} }
tmpCapture = windowToCapture.CaptureGDIWindow(captureForWindow); tmpCapture = windowToCapture.CaptureGdiWindow(captureForWindow);
if (tmpCapture != null) { if (tmpCapture != null) {
// check if GDI capture any good, by comparing it with the screen content // check if GDI capture any good, by comparing it with the screen content
int blackCountGDI = ImageHelper.CountColor(tmpCapture.Image, Color.Black, false); int blackCountGdi = ImageHelper.CountColor(tmpCapture.Image, Color.Black, false);
int GDIPixels = tmpCapture.Image.Width * tmpCapture.Image.Height; int gdiPixels = tmpCapture.Image.Width * tmpCapture.Image.Height;
int blackPercentageGDI = (blackCountGDI * 100) / GDIPixels; int blackPercentageGdi = blackCountGdi * 100 / gdiPixels;
if (blackPercentageGDI >= 1) { if (blackPercentageGdi >= 1) {
int screenPixels = windowRectangle.Width * windowRectangle.Height; int screenPixels = windowRectangle.Width * windowRectangle.Height;
using (ICapture screenCapture = new Capture()) { using (ICapture screenCapture = new Capture()) {
screenCapture.CaptureDetails = captureForWindow.CaptureDetails; screenCapture.CaptureDetails = captureForWindow.CaptureDetails;
if (WindowCapture.CaptureRectangleFromDesktopScreen(screenCapture, windowRectangle) != null) { if (WindowCapture.CaptureRectangleFromDesktopScreen(screenCapture, windowRectangle) != null) {
int blackCountScreen = ImageHelper.CountColor(screenCapture.Image, Color.Black, false); int blackCountScreen = ImageHelper.CountColor(screenCapture.Image, Color.Black, false);
int blackPercentageScreen = (blackCountScreen * 100) / screenPixels; int blackPercentageScreen = blackCountScreen * 100 / screenPixels;
if (screenPixels == GDIPixels) { if (screenPixels == gdiPixels) {
// "easy compare", both have the same size // "easy compare", both have the same size
// If GDI has more black, use the screen capture. // 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."); LOG.Debug("Using screen capture, as GDI had additional black.");
// changeing the image will automatically dispose the previous // changeing the image will automatically dispose the previous
tmpCapture.Image = screenCapture.Image; tmpCapture.Image = screenCapture.Image;
// Make sure it's not disposed, else the picture is gone! // Make sure it's not disposed, else the picture is gone!
screenCapture.NullImage(); screenCapture.NullImage();
} }
} else if (screenPixels < GDIPixels) { } else if (screenPixels < gdiPixels) {
// Screen capture is cropped, window is outside of screen // 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."); LOG.Debug("Using screen capture, as GDI had additional black.");
// changeing the image will automatically dispose the previous // changeing the image will automatically dispose the previous
tmpCapture.Image = screenCapture.Image; tmpCapture.Image = screenCapture.Image;
@ -896,8 +898,8 @@ namespace Greenshot.Helpers {
break; break;
case WindowCaptureMode.Aero: case WindowCaptureMode.Aero:
case WindowCaptureMode.AeroTransparent: case WindowCaptureMode.AeroTransparent:
if (windowToCapture.isMetroApp || WindowCapture.IsDwmAllowed(process)) { if (windowToCapture.IsMetroApp || WindowCapture.IsDwmAllowed(process)) {
tmpCapture = windowToCapture.CaptureDWMWindow(captureForWindow, windowCaptureMode, isAutoMode); tmpCapture = windowToCapture.CaptureDwmWindow(captureForWindow, windowCaptureMode, isAutoMode);
} }
if (tmpCapture != null) { if (tmpCapture != null) {
captureForWindow = tmpCapture; captureForWindow = tmpCapture;

View file

@ -18,6 +18,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
@ -28,21 +29,21 @@ using System.Windows.Forms;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
/// <summary>
/// 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
/// </summary>
namespace Greenshot.Helpers { namespace Greenshot.Helpers {
public enum CommandEnum { OpenFile, Exit, FirstLaunch, ReloadConfig }; public enum CommandEnum { OpenFile, Exit, FirstLaunch, ReloadConfig };
/// <summary>
/// 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
/// </summary>
[Serializable()] [Serializable()]
public class CopyDataTransport { public class CopyDataTransport {
List<KeyValuePair<CommandEnum, string>> commands; private readonly List<KeyValuePair<CommandEnum, string>> _commands;
public List<KeyValuePair<CommandEnum, string>> Commands { public List<KeyValuePair<CommandEnum, string>> Commands {
get {return commands;} get {return _commands;}
} }
public CopyDataTransport() { public CopyDataTransport() {
commands = new List<KeyValuePair<CommandEnum, string>>(); _commands = new List<KeyValuePair<CommandEnum, string>>();
} }
public CopyDataTransport(CommandEnum command) : this() { public CopyDataTransport(CommandEnum command) : this() {
@ -53,10 +54,10 @@ namespace Greenshot.Helpers {
AddCommand(command, commandData); AddCommand(command, commandData);
} }
public void AddCommand(CommandEnum command) { public void AddCommand(CommandEnum command) {
commands.Add(new KeyValuePair<CommandEnum, string>(command, null)); _commands.Add(new KeyValuePair<CommandEnum, string>(command, null));
} }
public void AddCommand(CommandEnum command, string commandData) { public void AddCommand(CommandEnum command, string commandData) {
commands.Add(new KeyValuePair<CommandEnum, string>(command, commandData)); _commands.Add(new KeyValuePair<CommandEnum, string>(command, commandData));
} }
} }
@ -81,16 +82,16 @@ namespace Greenshot.Helpers {
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
private struct COPYDATASTRUCT { private struct COPYDATASTRUCT {
public IntPtr dwData; public readonly IntPtr dwData;
public int cbData; public readonly int cbData;
public IntPtr lpData; public readonly IntPtr lpData;
} }
private const int WM_COPYDATA = 0x4A; private const int WM_COPYDATA = 0x4A;
private const int WM_DESTROY = 0x2; private const int WM_DESTROY = 0x2;
#region Member Variables #region Member Variables
private CopyDataChannels channels = null; private CopyDataChannels _channels;
#endregion #endregion
/// <summary> /// <summary>
@ -109,7 +110,7 @@ namespace Greenshot.Helpers {
BinaryFormatter b = new BinaryFormatter(); BinaryFormatter b = new BinaryFormatter();
CopyDataObjectData cdo = (CopyDataObjectData) b.Deserialize(stream); 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); CopyDataReceivedEventArgs d = new CopyDataReceivedEventArgs(cdo.Channel, cdo.Data, cdo.Sent);
OnCopyDataReceived(d); OnCopyDataReceived(d);
m.Result = (IntPtr) 1; m.Result = (IntPtr) 1;
@ -119,8 +120,8 @@ namespace Greenshot.Helpers {
// WM_DESTROY fires before OnHandleChanged and is // WM_DESTROY fires before OnHandleChanged and is
// a better place to ensure that we've cleared // a better place to ensure that we've cleared
// everything up. // everything up.
if (channels != null) { if (_channels != null) {
channels.OnHandleChange(); _channels.OnHandleChange();
} }
base.OnHandleChange(); base.OnHandleChange();
} }
@ -131,8 +132,12 @@ namespace Greenshot.Helpers {
/// Raises the DataReceived event from this class. /// Raises the DataReceived event from this class.
/// </summary> /// </summary>
/// <param name="e">The data which has been received.</param> /// <param name="e">The data which has been received.</param>
protected void OnCopyDataReceived(CopyDataReceivedEventArgs e) { protected void OnCopyDataReceived(CopyDataReceivedEventArgs e)
CopyDataReceived(this, e); {
if (CopyDataReceived != null)
{
CopyDataReceived(this, e);
}
} }
/// <summary> /// <summary>
@ -144,8 +149,8 @@ namespace Greenshot.Helpers {
/// </summary> /// </summary>
protected override void OnHandleChange () { protected override void OnHandleChange () {
// need to clear up everything we had set. // need to clear up everything we had set.
if (channels != null) { if (_channels != null) {
channels.OnHandleChange(); _channels.OnHandleChange();
} }
base.OnHandleChange(); base.OnHandleChange();
} }
@ -155,7 +160,7 @@ namespace Greenshot.Helpers {
/// </summary> /// </summary>
public CopyDataChannels Channels { public CopyDataChannels Channels {
get { get {
return channels; return _channels;
} }
} }
@ -168,9 +173,9 @@ namespace Greenshot.Helpers {
/// Clears up any resources associated with this object. /// Clears up any resources associated with this object.
/// </summary> /// </summary>
protected virtual void Dispose(bool disposing) { protected virtual void Dispose(bool disposing) {
if (disposing && channels != null) { if (disposing && _channels != null) {
channels.Clear(); _channels.Clear();
channels = null; _channels = null;
} }
} }
@ -178,7 +183,7 @@ namespace Greenshot.Helpers {
/// Constructs a new instance of the CopyData class /// Constructs a new instance of the CopyData class
/// </summary> /// </summary>
public CopyData() { public CopyData() {
channels = new CopyDataChannels(this); _channels = new CopyDataChannels(this);
} }
/// <summary> /// <summary>
@ -196,45 +201,28 @@ namespace Greenshot.Helpers {
/// which has been sent from another application. /// which has been sent from another application.
/// </summary> /// </summary>
public class CopyDataReceivedEventArgs : EventArgs { public class CopyDataReceivedEventArgs : EventArgs {
private string channelName = "";
private object data = null;
private DateTime sent;
private DateTime received;
/// <summary> /// <summary>
/// Gets the channel name that this data was sent on. /// Gets the channel name that this data was sent on.
/// </summary> /// </summary>
public string ChannelName { public string ChannelName { get; } = "";
get {
return channelName;
}
}
/// <summary> /// <summary>
/// Gets the data object which was sent. /// Gets the data object which was sent.
/// </summary> /// </summary>
public Object Data { public object Data { get; }
get {
return data;
}
}
/// <summary> /// <summary>
/// Gets the date and time which at the data was sent /// Gets the date and time which at the data was sent
/// by the sending application. /// by the sending application.
/// </summary> /// </summary>
public DateTime Sent { public DateTime Sent { get; }
get {
return sent;
}
}
/// <summary> /// <summary>
/// Gets the date and time which this data item as /// Gets the date and time which this data item as
/// received. /// received.
/// </summary> /// </summary>
public DateTime Received { public DateTime Received { get; }
get {
return received;
}
}
/// <summary> /// <summary>
/// Constructs an instance of this class. /// Constructs an instance of this class.
/// </summary> /// </summary>
@ -242,10 +230,10 @@ namespace Greenshot.Helpers {
/// <param name="data">The data which was sent</param> /// <param name="data">The data which was sent</param>
/// <param name="sent">The date and time the data was sent</param> /// <param name="sent">The date and time the data was sent</param>
internal CopyDataReceivedEventArgs(string channelName, object data, DateTime sent) { internal CopyDataReceivedEventArgs(string channelName, object data, DateTime sent) {
this.channelName = channelName; ChannelName = channelName;
this.data = data; Data = data;
this.sent = sent; Sent = sent;
received = DateTime.Now; Received = DateTime.Now;
} }
} }
@ -254,7 +242,7 @@ namespace Greenshot.Helpers {
/// class. /// class.
/// </summary> /// </summary>
public class CopyDataChannels : DictionaryBase { public class CopyDataChannels : DictionaryBase {
private NativeWindow owner = null; private readonly NativeWindow _owner;
/// <summary> /// <summary>
/// Returns an enumerator for each of the CopyDataChannel objects /// Returns an enumerator for each of the CopyDataChannel objects
@ -296,7 +284,7 @@ namespace Greenshot.Helpers {
/// receive messages. /// receive messages.
/// </summary> /// </summary>
public void Add(string channelName) { public void Add(string channelName) {
CopyDataChannel cdc = new CopyDataChannel(owner, channelName); CopyDataChannel cdc = new CopyDataChannel(_owner, channelName);
Dictionary.Add(channelName , cdc); Dictionary.Add(channelName , cdc);
} }
/// <summary> /// <summary>
@ -334,7 +322,7 @@ namespace Greenshot.Helpers {
/// just been removed</param> /// just been removed</param>
protected override void OnRemoveComplete ( Object key , Object data ) { protected override void OnRemoveComplete ( Object key , Object data ) {
( (CopyDataChannel) data).Dispose(); ( (CopyDataChannel) data).Dispose();
base.OnRemove(key, data); OnRemove(key, data);
} }
/// <summary> /// <summary>
@ -357,7 +345,7 @@ namespace Greenshot.Helpers {
/// <param name="owner">The NativeWindow this collection /// <param name="owner">The NativeWindow this collection
/// will be associated with</param> /// will be associated with</param>
internal CopyDataChannels(NativeWindow owner) { internal CopyDataChannels(NativeWindow owner) {
this.owner = owner; _owner = owner;
} }
} }
@ -367,14 +355,14 @@ namespace Greenshot.Helpers {
public class CopyDataChannel : IDisposable { public class CopyDataChannel : IDisposable {
#region Unmanaged Code #region Unmanaged Code
[DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)] [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)] [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)] [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)] [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)] [StructLayout(LayoutKind.Sequential)]
private struct COPYDATASTRUCT { private struct COPYDATASTRUCT {
@ -387,19 +375,15 @@ namespace Greenshot.Helpers {
#endregion #endregion
#region Member Variables #region Member Variables
private string channelName = "";
private NativeWindow owner = null; private readonly NativeWindow _owner;
private bool recreateChannel = false; private bool _recreateChannel;
#endregion #endregion
/// <summary> /// <summary>
/// Gets the name associated with this channel. /// Gets the name associated with this channel.
/// </summary> /// </summary>
public string ChannelName { public string ChannelName { get; private set; }
get {
return channelName;
}
}
/// <summary> /// <summary>
/// Sends the specified object on this channel to any other /// Sends the specified object on this channel to any other
@ -411,12 +395,12 @@ namespace Greenshot.Helpers {
public int Send(object obj) { public int Send(object obj) {
int recipients = 0; int recipients = 0;
if (recreateChannel) { if (_recreateChannel) {
// handle has changed // 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. // Try to do a binary serialization on obj.
@ -446,14 +430,16 @@ namespace Greenshot.Helpers {
// Send the data to each window identified on // Send the data to each window identified on
// the channel: // the channel:
foreach(WindowDetails window in WindowDetails.GetAllWindows()) { foreach(WindowDetails window in WindowDetails.GetAllWindows()) {
if (!window.Handle.Equals(owner.Handle)) { if (!window.Handle.Equals(_owner.Handle)) {
if (GetProp(window.Handle, channelName) != IntPtr.Zero) { if (GetProp(window.Handle, ChannelName) != IntPtr.Zero) {
COPYDATASTRUCT cds = new COPYDATASTRUCT(); COPYDATASTRUCT cds = new COPYDATASTRUCT
cds.cbData = dataSize; {
cds.dwData = IntPtr.Zero; cbData = dataSize,
cds.lpData = ptrData; dwData = IntPtr.Zero,
SendMessage(window.Handle, WM_COPYDATA, owner.Handle, ref cds); lpData = ptrData
recipients += (Marshal.GetLastWin32Error() == 0 ? 1 : 0); };
SendMessage(window.Handle, WM_COPYDATA, _owner.Handle, ref cds);
recipients += Marshal.GetLastWin32Error() == 0 ? 1 : 0;
} }
} }
} }
@ -466,14 +452,14 @@ namespace Greenshot.Helpers {
return recipients; return recipients;
} }
private void addChannel() { private void AddChannel() {
// Tag this window with property "channelName" // 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 // Remove the "channelName" property from this window
RemoveProp(owner.Handle, channelName); RemoveProp(_owner.Handle, ChannelName);
} }
/// <summary> /// <summary>
@ -484,8 +470,8 @@ namespace Greenshot.Helpers {
/// the new handle has been assigned. /// the new handle has been assigned.
/// </summary> /// </summary>
public void OnHandleChange() { public void OnHandleChange() {
removeChannel(); RemoveChannel();
recreateChannel = true; _recreateChannel = true;
} }
public void Dispose() { public void Dispose() {
@ -498,10 +484,10 @@ namespace Greenshot.Helpers {
/// </summary> /// </summary>
protected virtual void Dispose(bool disposing) { protected virtual void Dispose(bool disposing) {
if (disposing) { if (disposing) {
if (channelName.Length > 0) { if (ChannelName.Length > 0) {
removeChannel(); RemoveChannel();
} }
channelName = ""; ChannelName = "";
} }
} }
@ -513,9 +499,9 @@ namespace Greenshot.Helpers {
/// <param name="channelName">The name of the channel to /// <param name="channelName">The name of the channel to
/// send messages on</param> /// send messages on</param>
internal CopyDataChannel(NativeWindow owner, string channelName) { internal CopyDataChannel(NativeWindow owner, string channelName) {
this.owner = owner; _owner = owner;
this.channelName = channelName; ChannelName = channelName;
addChannel(); AddChannel();
} }
~CopyDataChannel() { ~CopyDataChannel() {
@ -552,7 +538,7 @@ namespace Greenshot.Helpers {
Data = data; Data = data;
if (!data.GetType().IsSerializable) { if (!data.GetType().IsSerializable) {
throw new ArgumentException("Data object must be serializable.", throw new ArgumentException("Data object must be serializable.",
"data"); nameof(data));
} }
Channel = channel; Channel = channel;
Sent = DateTime.Now; Sent = DateTime.Now;

View file

@ -31,9 +31,9 @@ namespace Greenshot.Helpers {
/// Description of DestinationHelper. /// Description of DestinationHelper.
/// </summary> /// </summary>
public static class DestinationHelper { public static class DestinationHelper {
private static ILog LOG = LogManager.GetLogger(typeof(DestinationHelper)); private static readonly ILog LOG = LogManager.GetLogger(typeof(DestinationHelper));
private static Dictionary<string, IDestination> RegisteredDestinations = new Dictionary<string, IDestination>(); private static readonly Dictionary<string, IDestination> RegisteredDestinations = new Dictionary<string, IDestination>();
private static CoreConfiguration coreConfig = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration coreConfig = IniConfig.GetIniSection<CoreConfiguration>();
/// Initialize the destinations /// Initialize the destinations
static DestinationHelper() { static DestinationHelper() {

View file

@ -20,14 +20,12 @@
*/ */
using System; using System;
using System.IO;
using System.Reflection; using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
using Greenshot.IniFile; using Greenshot.IniFile;
using GreenshotPlugin.UnmanagedHelpers; using GreenshotPlugin.UnmanagedHelpers;
using log4net;
namespace Greenshot.Helpers namespace Greenshot.Helpers
{ {
@ -36,19 +34,18 @@ namespace Greenshot.Helpers
/// </summary> /// </summary>
public static class EnvironmentInfo public static class EnvironmentInfo
{ {
private static readonly ILog LOG = LogManager.GetLogger(typeof(EnvironmentInfo)); private static bool? _isWindows;
private static bool? isWindows = null;
public static bool IsWindows public static bool IsWindows
{ {
get get
{ {
if (isWindows.HasValue) if (_isWindows.HasValue)
{ {
return isWindows.Value; return _isWindows.Value;
} }
isWindows = Environment.OSVersion.Platform.ToString().StartsWith("Win"); _isWindows = Environment.OSVersion.Platform.ToString().StartsWith("Win");
return isWindows.Value; return _isWindows.Value;
} }
} }
@ -101,7 +98,7 @@ namespace Greenshot.Helpers
{ {
environment.Append(", "); 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) if (newline)
{ {
environment.AppendLine(); environment.AppendLine();
@ -201,11 +198,6 @@ namespace Greenshot.Helpers
exceptionText.AppendLine(EnvironmentToString(true)); exceptionText.AppendLine(EnvironmentToString(true));
exceptionText.AppendLine(ExceptionToString(exception)); exceptionText.AppendLine(ExceptionToString(exception));
exceptionText.AppendLine("Configuration dump:"); exceptionText.AppendLine("Configuration dump:");
using (TextWriter writer = new StringWriter(exceptionText))
{
// TODO: Create summary of properties
//var iniConfig = IniConfig.Current.WriteToStreamAsync();
}
return exceptionText.ToString(); return exceptionText.ToString();
} }
@ -215,13 +207,13 @@ namespace Greenshot.Helpers
/// Provides detailed information about the host operating system. /// Provides detailed information about the host operating system.
/// Code is available at: http://www.csharp411.com/determine-windows-version-and-edition-with-c/ /// Code is available at: http://www.csharp411.com/determine-windows-version-and-edition-with-c/
/// </summary> /// </summary>
static public class OSInfo public static class OSInfo
{ {
#region BITS #region BITS
/// <summary> /// <summary>
/// Determines if the current application is 32 or 64-bit. /// Determines if the current application is 32 or 64-bit.
/// </summary> /// </summary>
static public int Bits public static int Bits
{ {
get get
{ {
@ -231,24 +223,26 @@ namespace Greenshot.Helpers
#endregion BITS #endregion BITS
#region EDITION #region EDITION
static private string s_Edition; private static string _sEdition;
/// <summary> /// <summary>
/// Gets the edition of the operating system running on this computer. /// Gets the edition of the operating system running on this computer.
/// </summary> /// </summary>
static public string Edition public static string Edition
{ {
get 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; OperatingSystem osVersion = Environment.OSVersion;
OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX(); OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX
osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf(typeof(OSVERSIONINFOEX)); {
dwOSVersionInfoSize = Marshal.SizeOf(typeof (OSVERSIONINFOEX))
};
if (GetVersionEx(ref osVersionInfo)) if (GetVersionEx(ref osVersionInfo))
{ {
@ -469,18 +463,18 @@ namespace Greenshot.Helpers
#endregion VERSION 6 #endregion VERSION 6
} }
s_Edition = edition; _sEdition = edition;
return edition; return edition;
} }
} }
#endregion EDITION #endregion EDITION
#region NAME #region NAME
static private string s_Name; private static string s_Name;
/// <summary> /// <summary>
/// Gets the name of the operating system running on this computer. /// Gets the name of the operating system running on this computer.
/// </summary> /// </summary>
static public string Name public static string Name
{ {
get get
{ {
@ -645,6 +639,7 @@ namespace Greenshot.Helpers
#region GET #region GET
#region PRODUCT INFO #region PRODUCT INFO
[DllImport("Kernel32.dll")] [DllImport("Kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetProductInfo( internal static extern bool GetProductInfo(
int osMajorVersion, int osMajorVersion,
int osMinorVersion, int osMinorVersion,
@ -654,7 +649,8 @@ namespace Greenshot.Helpers
#endregion PRODUCT INFO #endregion PRODUCT INFO
#region VERSION #region VERSION
[DllImport("kernel32.dll")] [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetVersionEx(ref OSVERSIONINFOEX osVersionInfo); private static extern bool GetVersionEx(ref OSVERSIONINFOEX osVersionInfo);
#endregion VERSION #endregion VERSION
#endregion GET #endregion GET
@ -664,17 +660,17 @@ namespace Greenshot.Helpers
private struct OSVERSIONINFOEX private struct OSVERSIONINFOEX
{ {
public int dwOSVersionInfoSize; public int dwOSVersionInfoSize;
public int dwMajorVersion; public readonly int dwMajorVersion;
public int dwMinorVersion; public readonly int dwMinorVersion;
public int dwBuildNumber; public readonly int dwBuildNumber;
public int dwPlatformId; public readonly int dwPlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string szCSDVersion; public readonly string szCSDVersion;
public short wServicePackMajor; public readonly short wServicePackMajor;
public short wServicePackMinor; public readonly short wServicePackMinor;
public short wSuiteMask; public readonly short wSuiteMask;
public byte wProductType; public readonly byte wProductType;
public byte wReserved; public readonly byte wReserved;
} }
#endregion OSVERSIONINFOEX #endregion OSVERSIONINFOEX
@ -722,13 +718,9 @@ namespace Greenshot.Helpers
#region VERSIONS #region VERSIONS
private const int VER_NT_WORKSTATION = 1; 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_NT_SERVER = 3;
private const int VER_SUITE_SMALLBUSINESS = 1;
private const int VER_SUITE_ENTERPRISE = 2; 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_DATACENTER = 128;
private const int VER_SUITE_SINGLEUSERTS = 256;
private const int VER_SUITE_PERSONAL = 512; private const int VER_SUITE_PERSONAL = 512;
private const int VER_SUITE_BLADE = 1024; private const int VER_SUITE_BLADE = 1024;
#endregion VERSIONS #endregion VERSIONS
@ -738,11 +730,11 @@ namespace Greenshot.Helpers
/// <summary> /// <summary>
/// Gets the service pack information of the operating system running on this computer. /// Gets the service pack information of the operating system running on this computer.
/// </summary> /// </summary>
static public string ServicePack public static string ServicePack
{ {
get get
{ {
string servicePack = String.Empty; string servicePack = string.Empty;
OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX(); OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX();
osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf(typeof(OSVERSIONINFOEX)); osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf(typeof(OSVERSIONINFOEX));
@ -776,7 +768,7 @@ namespace Greenshot.Helpers
/// <summary> /// <summary>
/// Gets the full version string of the operating system running on this computer. /// Gets the full version string of the operating system running on this computer.
/// </summary> /// </summary>
static public string VersionString public static string VersionString
{ {
get get
{ {
@ -789,7 +781,7 @@ namespace Greenshot.Helpers
/// <summary> /// <summary>
/// Gets the full version of the operating system running on this computer. /// Gets the full version of the operating system running on this computer.
/// </summary> /// </summary>
static public Version Version public static Version Version
{ {
get get
{ {
@ -803,7 +795,7 @@ namespace Greenshot.Helpers
/// <summary> /// <summary>
/// Gets the major version number of the operating system running on this computer. /// Gets the major version number of the operating system running on this computer.
/// </summary> /// </summary>
static public int MajorVersion public static int MajorVersion
{ {
get get
{ {
@ -816,7 +808,7 @@ namespace Greenshot.Helpers
/// <summary> /// <summary>
/// Gets the minor version number of the operating system running on this computer. /// Gets the minor version number of the operating system running on this computer.
/// </summary> /// </summary>
static public int MinorVersion public static int MinorVersion
{ {
get get
{ {
@ -829,7 +821,7 @@ namespace Greenshot.Helpers
/// <summary> /// <summary>
/// Gets the revision version number of the operating system running on this computer. /// Gets the revision version number of the operating system running on this computer.
/// </summary> /// </summary>
static public int RevisionVersion public static int RevisionVersion
{ {
get get
{ {

View file

@ -37,9 +37,9 @@ namespace Greenshot.Helpers {
//Our end result //Our end result
int result = 0; int result = 0;
//Take x2-x1, then square it //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 //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 //Add both of the parts together
double underRadical = part1 + part2; double underRadical = part1 + part2;
//Get the square root of the parts //Get the square root of the parts

View file

@ -42,7 +42,7 @@ namespace Greenshot.Helpers {
/// Many thanks to all the people who contributed here! /// Many thanks to all the people who contributed here!
/// </summary> /// </summary>
public static class IECaptureHelper { 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<CoreConfiguration>(); private static readonly CoreConfiguration configuration = IniConfig.GetIniSection<CoreConfiguration>();
// Helper method to activate a certain IE Tab // Helper method to activate a certain IE Tab
@ -69,7 +69,7 @@ namespace Greenshot.Helpers {
if (ieWindow != null) { if (ieWindow != null) {
Rectangle wholeClient = someWindow.ClientRectangle; Rectangle wholeClient = someWindow.ClientRectangle;
Rectangle partClient = ieWindow.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); LOG.InfoFormat("Window {0}, ie part {1}, percentage {2}", wholeClient, partClient, percentage);
if (percentage > minimumPercentage) { if (percentage > minimumPercentage) {
return true; return true;
@ -143,7 +143,7 @@ namespace Greenshot.Helpers {
} else if (configuration.WindowClassesToCheckForIE != null && configuration.WindowClassesToCheckForIE.Contains(ieWindow.ClassName)) { } else if (configuration.WindowClassesToCheckForIE != null && configuration.WindowClassesToCheckForIE.Contains(ieWindow.ClassName)) {
List<string> singleWindowText = new List<string>(); List<string> singleWindowText = new List<string>();
try { try {
IHTMLDocument2 document2 = getHTMLDocument(ieWindow); IHTMLDocument2 document2 = GetHtmlDocument(ieWindow);
string title = document2.title; string title = document2.title;
Marshal.ReleaseComObject(document2); Marshal.ReleaseComObject(document2);
if (string.IsNullOrEmpty(title)) { if (string.IsNullOrEmpty(title)) {
@ -177,7 +177,7 @@ namespace Greenshot.Helpers {
/// </summary> /// </summary>
/// <param name="mainWindow"></param> /// <param name="mainWindow"></param>
/// <returns></returns> /// <returns></returns>
private static IHTMLDocument2 getHTMLDocument(WindowDetails mainWindow) { private static IHTMLDocument2 GetHtmlDocument(WindowDetails mainWindow) {
WindowDetails ieServer; WindowDetails ieServer;
if ("Internet Explorer_Server".Equals(mainWindow.ClassName)) { if ("Internet Explorer_Server".Equals(mainWindow.ClassName)) {
ieServer = mainWindow; ieServer = mainWindow;
@ -249,7 +249,7 @@ namespace Greenshot.Helpers {
try { try {
// Get the Document // Get the Document
IHTMLDocument2 document2 = getHTMLDocument(ieWindow); IHTMLDocument2 document2 = GetHtmlDocument(ieWindow);
if (document2 == null) { if (document2 == null) {
continue; continue;
} }
@ -371,7 +371,7 @@ namespace Greenshot.Helpers {
Bitmap returnBitmap = null; Bitmap returnBitmap = null;
try { try {
Size pageSize = PrepareCapture(documentContainer, capture); Size pageSize = PrepareCapture(documentContainer, capture);
returnBitmap = capturePage(documentContainer, capture, pageSize); returnBitmap = CapturePage(documentContainer, pageSize);
} catch (Exception captureException) { } catch (Exception captureException) {
LOG.Error("Exception found, ignoring and returning nothing! Error was: ", captureException); LOG.Error("Exception found, ignoring and returning nothing! Error was: ", captureException);
} }
@ -554,8 +554,9 @@ namespace Greenshot.Helpers {
/// Capture the actual page (document) /// Capture the actual page (document)
/// </summary> /// </summary>
/// <param name="documentContainer">The document wrapped in a container</param> /// <param name="documentContainer">The document wrapped in a container</param>
/// <param name="pageSize"></param>
/// <returns>Bitmap with the page content as an image</returns> /// <returns>Bitmap with the page content as an image</returns>
private static Bitmap capturePage(DocumentContainer documentContainer, ICapture capture, Size pageSize) { private static Bitmap CapturePage(DocumentContainer documentContainer, Size pageSize) {
WindowDetails contentWindowDetails = documentContainer.ContentWindow; WindowDetails contentWindowDetails = documentContainer.ContentWindow;
//Create a target bitmap to draw into with the calculated page size //Create a target bitmap to draw into with the calculated page size
@ -567,7 +568,7 @@ namespace Greenshot.Helpers {
graphicsTarget.Clear(clearColor); graphicsTarget.Clear(clearColor);
// Get the base document & draw it // 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 // Loop over the frames and clear their source area so we don't see any artefacts
foreach(DocumentContainer frameDocument in documentContainer.Frames) { foreach(DocumentContainer frameDocument in documentContainer.Frames) {
@ -577,7 +578,7 @@ namespace Greenshot.Helpers {
} }
// Loop over the frames and capture their content // Loop over the frames and capture their content
foreach(DocumentContainer frameDocument in documentContainer.Frames) { foreach(DocumentContainer frameDocument in documentContainer.Frames) {
drawDocument(frameDocument, contentWindowDetails, graphicsTarget); DrawDocument(frameDocument, contentWindowDetails, graphicsTarget);
} }
} }
return returnBitmap; return returnBitmap;
@ -586,11 +587,11 @@ namespace Greenshot.Helpers {
/// <summary> /// <summary>
/// This method takes the actual capture of the document (frame) /// This method takes the actual capture of the document (frame)
/// </summary> /// </summary>
/// <param name="frameDocument"></param> /// <param name="documentContainer"></param>
/// <param name="contentWindowDetails">Needed for referencing the location of the frame</param> /// <param name="contentWindowDetails">Needed for referencing the location of the frame</param>
/// <returns>Bitmap with the capture</returns> /// <returns>Bitmap with the capture</returns>
private static void drawDocument(DocumentContainer documentContainer, WindowDetails contentWindowDetails, Graphics graphicsTarget) { private static void DrawDocument(DocumentContainer documentContainer, WindowDetails contentWindowDetails, Graphics graphicsTarget) {
documentContainer.setAttribute("scroll", 1); documentContainer.SetAttribute("scroll", 1);
//Get Browser Window Width & Height //Get Browser Window Width & Height
int pageWidth = documentContainer.ScrollWidth; int pageWidth = documentContainer.ScrollWidth;
@ -621,14 +622,14 @@ namespace Greenshot.Helpers {
Point targetOffset = new Point(); Point targetOffset = new Point();
// Loop of the pages and make a copy of the visible viewport // Loop of the pages and make a copy of the visible viewport
while ((horizontalPage * viewportWidth) < pageWidth) { while (horizontalPage * viewportWidth < pageWidth) {
// Scroll to location // Scroll to location
documentContainer.ScrollLeft = viewportWidth * horizontalPage; documentContainer.ScrollLeft = viewportWidth * horizontalPage;
targetOffset.X = documentContainer.ScrollLeft; targetOffset.X = documentContainer.ScrollLeft;
// Variable used for looping vertically // Variable used for looping vertically
int verticalPage = 0; int verticalPage = 0;
while ((verticalPage * viewportHeight) < pageHeight) { while (verticalPage * viewportHeight < pageHeight) {
// Scroll to location // Scroll to location
documentContainer.ScrollTop = viewportHeight * verticalPage; documentContainer.ScrollTop = viewportHeight * verticalPage;
//Shoot visible window //Shoot visible window

View file

@ -26,33 +26,31 @@ using System.Runtime.InteropServices;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using Greenshot.Interop.IE; using Greenshot.Interop.IE;
using Greenshot.IniFile;
using log4net; using log4net;
using IServiceProvider = Greenshot.Interop.IServiceProvider; using IServiceProvider = Greenshot.Interop.IServiceProvider;
namespace Greenshot.Helpers.IEInterop { namespace Greenshot.Helpers.IEInterop {
public class DocumentContainer { public class DocumentContainer {
private static ILog LOG = LogManager.GetLogger(typeof(DocumentContainer)); private static readonly ILog LOG = LogManager.GetLogger(typeof(DocumentContainer));
private static CoreConfiguration configuration = IniConfig.GetIniSection<CoreConfiguration>();
private const int E_ACCESSDENIED = unchecked((int)0x80070005L); 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_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");
private static readonly Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E"); private static readonly Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E");
private static int counter = 0; private static int _counter;
private int id = counter++; private readonly int _id = _counter++;
private IHTMLDocument2 document2; private IHTMLDocument2 _document2;
private IHTMLDocument3 document3; private IHTMLDocument3 _document3;
private Point sourceLocation; private Point _sourceLocation;
private Point destinationLocation; private Point _destinationLocation;
private Point startLocation = Point.Empty; private Point _startLocation = Point.Empty;
private Rectangle viewportRectangle = Rectangle.Empty; private Rectangle _viewportRectangle = Rectangle.Empty;
private string name = null; private string _name;
private string url; private string _url;
private bool isDTD; private bool _isDtd;
private DocumentContainer parent; private DocumentContainer _parent;
private WindowDetails contentWindow; private WindowDetails _contentWindow;
private double zoomLevelX = 1; private double _zoomLevelX = 1;
private double zoomLevelY = 1; private double _zoomLevelY = 1;
private List<DocumentContainer> frames = new List<DocumentContainer>(); private readonly IList<DocumentContainer> _frames = new List<DocumentContainer>();
private DocumentContainer(IHTMLWindow2 frameWindow, WindowDetails contentWindow, DocumentContainer parent) { private DocumentContainer(IHTMLWindow2 frameWindow, WindowDetails contentWindow, DocumentContainer parent) {
//IWebBrowser2 webBrowser2 = frame as IWebBrowser2; //IWebBrowser2 webBrowser2 = frame as IWebBrowser2;
@ -60,22 +58,22 @@ namespace Greenshot.Helpers.IEInterop {
IHTMLDocument2 document2 = GetDocumentFromWindow(frameWindow); IHTMLDocument2 document2 = GetDocumentFromWindow(frameWindow);
try { try {
LOG.DebugFormat("frameWindow.name {0}", frameWindow.name); LOG.DebugFormat("frameWindow.name {0}", frameWindow.name);
name = frameWindow.name; _name = frameWindow.name;
} catch { } catch {
// Ignore
} }
try { try {
LOG.DebugFormat("document2.url {0}",document2.url); LOG.DebugFormat("document2.url {0}",document2.url);
} catch { } catch {
// Ignore
} }
try { try {
LOG.DebugFormat("document2.title {0}", document2.title); LOG.DebugFormat("document2.title {0}", document2.title);
} catch { } catch {
// Ignore
} }
this.parent = parent; _parent = parent;
// Calculate startLocation for the frames // Calculate startLocation for the frames
IHTMLWindow2 window2 = document2.parentWindow; IHTMLWindow2 window2 = document2.parentWindow;
IHTMLWindow3 window3 = (IHTMLWindow3)window2; IHTMLWindow3 window3 = (IHTMLWindow3)window2;
@ -87,13 +85,13 @@ namespace Greenshot.Helpers.IEInterop {
releaseCom(window2); releaseCom(window2);
releaseCom(window3); releaseCom(window3);
startLocation = new Point(x, y); _startLocation = new Point(x, y);
Init(document2, contentWindow); Init(document2, contentWindow);
} }
public DocumentContainer(IHTMLDocument2 document2, WindowDetails contentWindow) { public DocumentContainer(IHTMLDocument2 document2, WindowDetails contentWindow) {
Init(document2, 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);
} }
/// <summary> /// <summary>
@ -112,17 +110,17 @@ namespace Greenshot.Helpers.IEInterop {
/// <param name="document2">IHTMLDocument2</param> /// <param name="document2">IHTMLDocument2</param>
/// <param name="contentWindow">WindowDetails</param> /// <param name="contentWindow">WindowDetails</param>
private void Init(IHTMLDocument2 document2, WindowDetails contentWindow) { private void Init(IHTMLDocument2 document2, WindowDetails contentWindow) {
this.document2 = document2; _document2 = document2;
this.contentWindow = contentWindow; _contentWindow = contentWindow;
document3 = document2 as IHTMLDocument3; _document3 = document2 as IHTMLDocument3;
// Check what access method is needed for the document // Check what access method is needed for the document
IHTMLDocument5 document5 = (IHTMLDocument5)document2; IHTMLDocument5 document5 = (IHTMLDocument5)document2;
//compatibility mode affects how height is computed //compatibility mode affects how height is computed
isDTD = false; _isDtd = false;
try { try {
if ((document3.documentElement != null) && (!document5.compatMode.Equals("BackCompat"))) { if (_document3 != null && (_document3.documentElement != null) && !document5.compatMode.Equals("BackCompat")) {
isDTD = true; _isDtd = true;
} }
} catch (Exception ex) { } catch (Exception ex) {
LOG.Error("Error checking the compatibility mode:"); LOG.Error("Error checking the compatibility mode:");
@ -133,21 +131,21 @@ namespace Greenshot.Helpers.IEInterop {
Rectangle clientRectangle = contentWindow.WindowRectangle; Rectangle clientRectangle = contentWindow.WindowRectangle;
try { try {
IHTMLWindow2 window2 = (IHTMLWindow2)document2.parentWindow; IHTMLWindow2 window2 = document2.parentWindow;
//IHTMLWindow3 window3 = (IHTMLWindow3)document2.parentWindow; //IHTMLWindow3 window3 = (IHTMLWindow3)document2.parentWindow;
IHTMLScreen screen = window2.screen; IHTMLScreen screen = window2.screen;
IHTMLScreen2 screen2 = (IHTMLScreen2)screen; IHTMLScreen2 screen2 = (IHTMLScreen2)screen;
if (parent != null) { if (_parent != null) {
// Copy parent values // Copy parent values
zoomLevelX = parent.zoomLevelX; _zoomLevelX = _parent._zoomLevelX;
zoomLevelY = parent.zoomLevelY; _zoomLevelY = _parent._zoomLevelY;
viewportRectangle = parent.viewportRectangle; _viewportRectangle = _parent._viewportRectangle;
} else { } else {
//DisableScrollbars(document2); //DisableScrollbars(document2);
// Calculate zoom level // Calculate zoom level
zoomLevelX = (double)screen2.deviceXDPI/(double)screen2.logicalXDPI; _zoomLevelX = screen2.deviceXDPI/(double)screen2.logicalXDPI;
zoomLevelY = (double)screen2.deviceYDPI/(double)screen2.logicalYDPI; _zoomLevelY = screen2.deviceYDPI/(double)screen2.logicalYDPI;
// Calculate the viewport rectangle, needed if there is a frame around the html window // 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)) { if ((diffX == 4 || diffX >= 20) && (diffY == 4 || diffY >= 20)) {
Point viewportOffset = new Point(2, 2); Point viewportOffset = new Point(2, 2);
Size viewportSize = new Size(ClientWidth, ClientHeight); Size viewportSize = new Size(ClientWidth, ClientHeight);
viewportRectangle = new Rectangle(viewportOffset, viewportSize); _viewportRectangle = new Rectangle(viewportOffset, viewportSize);
LOG.DebugFormat("viewportRect {0}", viewportRectangle); LOG.DebugFormat("viewportRect {0}", _viewportRectangle);
} }
} }
LOG.DebugFormat("Zoomlevel {0}, {1}", zoomLevelX, zoomLevelY); LOG.DebugFormat("Zoomlevel {0}, {1}", _zoomLevelX, _zoomLevelY);
// Release com objects // Release com objects
releaseCom(window2); releaseCom(window2);
releaseCom(screen); releaseCom(screen);
@ -177,23 +175,23 @@ namespace Greenshot.Helpers.IEInterop {
try { try {
LOG.DebugFormat("Calculated location {0} for {1}", startLocation, document2.title); LOG.DebugFormat("Calculated location {0} for {1}", _startLocation, document2.title);
if (name == null) { if (_name == null) {
name = document2.title; _name = document2.title;
} }
} catch (Exception e) { } catch (Exception e) {
LOG.Warn("Problem while trying to get document title!", e); LOG.Warn("Problem while trying to get document title!", e);
} }
try { try {
url = document2.url; _url = document2.url;
} catch (Exception e) { } catch (Exception e) {
LOG.Warn("Problem while trying to get document url!", e); LOG.Warn("Problem while trying to get document url!", e);
} }
sourceLocation = new Point(ScaleX((int)startLocation.X), ScaleY((int)startLocation.Y)); _sourceLocation = new Point(ScaleX(_startLocation.X), ScaleY(_startLocation.Y));
destinationLocation = new Point(ScaleX((int)startLocation.X), ScaleY((int)startLocation.Y)); _destinationLocation = new Point(ScaleX(_startLocation.X), ScaleY(_startLocation.Y));
if (parent != null) { if (_parent != null) {
return; return;
} }
try { try {
@ -203,9 +201,9 @@ namespace Greenshot.Helpers.IEInterop {
IHTMLWindow2 frameWindow = frameCollection.item(frame); IHTMLWindow2 frameWindow = frameCollection.item(frame);
DocumentContainer frameData = new DocumentContainer(frameWindow, contentWindow, this); DocumentContainer frameData = new DocumentContainer(frameWindow, contentWindow, this);
// check if frame is hidden // check if frame is hidden
if (!frameData.isHidden) { if (!frameData.IsHidden) {
LOG.DebugFormat("Creating DocumentContainer for Frame {0} found in window with rectangle {1}", frameData.name, frameData.SourceRectangle); LOG.DebugFormat("Creating DocumentContainer for Frame {0} found in window with rectangle {1}", frameData._name, frameData.SourceRectangle);
frames.Add(frameData); _frames.Add(frameData);
} else { } else {
LOG.DebugFormat("Skipping frame {0}", frameData.Name); LOG.DebugFormat("Skipping frame {0}", frameData.Name);
} }
@ -223,7 +221,7 @@ namespace Greenshot.Helpers.IEInterop {
try { try {
// Correct iframe locations // Correct iframe locations
foreach (IHTMLElement frameElement in document3.getElementsByTagName("IFRAME")) { foreach (IHTMLElement frameElement in _document3.getElementsByTagName("IFRAME")) {
try { try {
CorrectFrameLocations(frameElement); CorrectFrameLocations(frameElement);
// Clean up frameElement // Clean up frameElement
@ -264,7 +262,7 @@ namespace Greenshot.Helpers.IEInterop {
// Release IHTMLRect // Release IHTMLRect
releaseCom(rec); releaseCom(rec);
LOG.DebugFormat("Looking for iframe to correct at {0}", elementBoundingLocation); LOG.DebugFormat("Looking for iframe to correct at {0}", elementBoundingLocation);
foreach(DocumentContainer foundFrame in frames) { foreach(DocumentContainer foundFrame in _frames) {
Point frameLocation = foundFrame.SourceLocation; Point frameLocation = foundFrame.SourceLocation;
if (frameLocation.Equals(elementBoundingLocation)) { if (frameLocation.Equals(elementBoundingLocation)) {
// Match found, correcting location // Match found, correcting location
@ -313,13 +311,13 @@ namespace Greenshot.Helpers.IEInterop {
IServiceProvider sp = (IServiceProvider)htmlWindow; IServiceProvider sp = (IServiceProvider)htmlWindow;
// Use IServiceProvider.QueryService to get IWebBrowser2 object. // Use IServiceProvider.QueryService to get IWebBrowser2 object.
Object brws = null; object brws;
Guid webBrowserApp = IID_IWebBrowserApp; Guid webBrowserApp = IID_IWebBrowserApp;
Guid webBrowser2 = IID_IWebBrowser2; Guid webBrowser2 = IID_IWebBrowser2;
sp.QueryService(ref webBrowserApp, ref webBrowser2, out brws); sp.QueryService(ref webBrowserApp, ref webBrowser2, out brws);
// Get the document from IWebBrowser2. // Get the document from IWebBrowser2.
IWebBrowser2 browser = (IWebBrowser2)(brws); IWebBrowser2 browser = (IWebBrowser2)brws;
return (IHTMLDocument2)browser.Document; return (IHTMLDocument2)browser.Document;
} catch (Exception ex2) { } catch (Exception ex2) {
@ -331,9 +329,9 @@ namespace Greenshot.Helpers.IEInterop {
public Color BackgroundColor { public Color BackgroundColor {
get { get {
try { try {
string bgColor = (string)document2.bgColor; string bgColor = (string)_document2.bgColor;
if (bgColor != null) { 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); return Color.FromArgb(rgbInt >> 16, (rgbInt >> 8) & 255, rgbInt & 255);
} }
} catch (Exception ex) { } catch (Exception ex) {
@ -345,46 +343,46 @@ namespace Greenshot.Helpers.IEInterop {
public Rectangle ViewportRectangle { public Rectangle ViewportRectangle {
get { get {
return viewportRectangle; return _viewportRectangle;
} }
} }
public WindowDetails ContentWindow { public WindowDetails ContentWindow {
get { get {
return contentWindow; return _contentWindow;
} }
} }
public DocumentContainer Parent { public DocumentContainer Parent {
get { get {
return parent; return _parent;
} }
set { set {
parent = value; _parent = value;
} }
} }
private int ScaleX(int physicalValue) { 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) { 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) { 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) { private int UnscaleY(int physicalValue) {
return (int)Math.Round(physicalValue / zoomLevelY, MidpointRounding.AwayFromZero); return (int)Math.Round(physicalValue / _zoomLevelY, MidpointRounding.AwayFromZero);
} }
/// <summary> /// <summary>
/// Set/change an int attribute on a document /// Set/change an int attribute on a document
/// </summary> /// </summary>
public void setAttribute(string attribute, int value) { public void SetAttribute(string attribute, int value) {
setAttribute(attribute, value.ToString()); SetAttribute(attribute, value.ToString());
} }
/// <summary> /// <summary>
@ -392,14 +390,12 @@ namespace Greenshot.Helpers.IEInterop {
/// </summary> /// </summary>
/// <param name="attribute">Attribute to set</param> /// <param name="attribute">Attribute to set</param>
/// <param name="value">Value to set</param> /// <param name="value">Value to set</param>
/// <param name="document2">The IHTMLDocument2</param> public void SetAttribute(string attribute, string value) {
/// <param name="document3">The IHTMLDocument3</param>
public void setAttribute(string attribute, string value) {
IHTMLElement element = null; IHTMLElement element = null;
if (!isDTD) { if (!_isDtd) {
element = document2.body; element = _document2.body;
} else { } else {
element = document3.documentElement; element = _document3.documentElement;
} }
element.setAttribute(attribute, value, 1); element.setAttribute(attribute, value, 1);
// Release IHTMLElement com object // Release IHTMLElement com object
@ -410,18 +406,15 @@ namespace Greenshot.Helpers.IEInterop {
/// Get the attribute from a document /// Get the attribute from a document
/// </summary> /// </summary>
/// <param name="attribute">Attribute to get</param> /// <param name="attribute">Attribute to get</param>
/// <param name="document2">The IHTMLDocument2</param>
/// <param name="document3">The IHTMLDocument3</param>
/// <returns>object with the attribute value</returns> /// <returns>object with the attribute value</returns>
public object getAttribute(string attribute) { public object GetAttribute(string attribute) {
IHTMLElement element = null; IHTMLElement element;
object retVal = 0; if (!_isDtd) {
if (!isDTD) { element = _document2.body;
element = document2.body;
} else { } else {
element = document3.documentElement; element = _document3.documentElement;
} }
retVal = element.getAttribute(attribute, 1); var retVal = element.getAttribute(attribute, 1);
// Release IHTMLElement com object // Release IHTMLElement com object
releaseCom(element); releaseCom(element);
return retVal; return retVal;
@ -430,30 +423,30 @@ namespace Greenshot.Helpers.IEInterop {
/// <summary> /// <summary>
/// Get the attribute as int from a document /// Get the attribute as int from a document
/// </summary> /// </summary>
public int getAttributeAsInt(string attribute) { public int GetAttributeAsInt(string attribute) {
int retVal = (int)getAttribute(attribute); int retVal = (int)GetAttribute(attribute);
return retVal; return retVal;
} }
public int ID { public int ID {
get { get {
return id; return _id;
} }
} }
public string Name { public string Name {
get { get {
return name; return _name;
} }
} }
public string Url { public string Url {
get { get {
return url; return _url;
} }
} }
public bool isHidden { public bool IsHidden {
get { get {
return ClientWidth == 0 || ClientHeight == 0; return ClientWidth == 0 || ClientHeight == 0;
} }
@ -461,34 +454,34 @@ namespace Greenshot.Helpers.IEInterop {
public int ClientWidth { public int ClientWidth {
get { get {
return ScaleX(getAttributeAsInt("clientWidth")); return ScaleX(GetAttributeAsInt("clientWidth"));
} }
} }
public int ClientHeight { public int ClientHeight {
get { get {
return ScaleY(getAttributeAsInt("clientHeight")); return ScaleY(GetAttributeAsInt("clientHeight"));
} }
} }
public int ScrollWidth { public int ScrollWidth {
get { get {
return ScaleX(getAttributeAsInt("scrollWidth")); return ScaleX(GetAttributeAsInt("scrollWidth"));
} }
} }
public int ScrollHeight { public int ScrollHeight {
get { get {
return ScaleY(getAttributeAsInt("scrollHeight")); return ScaleY(GetAttributeAsInt("scrollHeight"));
} }
} }
public Point SourceLocation { public Point SourceLocation {
get { get {
return sourceLocation; return _sourceLocation;
} }
set { set {
sourceLocation = value; _sourceLocation = value;
} }
} }
@ -506,34 +499,34 @@ namespace Greenshot.Helpers.IEInterop {
public int SourceLeft { public int SourceLeft {
get { get {
return sourceLocation.X; return _sourceLocation.X;
} }
} }
public int SourceTop { public int SourceTop {
get { get {
return sourceLocation.Y; return _sourceLocation.Y;
} }
} }
public int SourceRight { public int SourceRight {
get { get {
return sourceLocation.X + ClientWidth; return _sourceLocation.X + ClientWidth;
} }
} }
public int SourceBottom { public int SourceBottom {
get { get {
return sourceLocation.Y + ClientHeight; return _sourceLocation.Y + ClientHeight;
} }
} }
public Point DestinationLocation { public Point DestinationLocation {
get { get {
return destinationLocation; return _destinationLocation;
} }
set { set {
destinationLocation = value; _destinationLocation = value;
} }
} }
@ -552,55 +545,55 @@ namespace Greenshot.Helpers.IEInterop {
public int DestinationLeft { public int DestinationLeft {
get { get {
return destinationLocation.X; return _destinationLocation.X;
} }
set { set {
destinationLocation.X = value; _destinationLocation.X = value;
} }
} }
public int DestinationTop { public int DestinationTop {
get { get {
return destinationLocation.Y; return _destinationLocation.Y;
} }
set { set {
destinationLocation.Y = value; _destinationLocation.Y = value;
} }
} }
public int DestinationRight { public int DestinationRight {
get { get {
return destinationLocation.X + ScrollWidth; return _destinationLocation.X + ScrollWidth;
} }
} }
public int DestinationBottom { public int DestinationBottom {
get { get {
return destinationLocation.Y + ScrollHeight; return _destinationLocation.Y + ScrollHeight;
} }
} }
public int ScrollLeft { public int ScrollLeft {
get{ get{
return ScaleX(getAttributeAsInt("scrollLeft")); return ScaleX(GetAttributeAsInt("scrollLeft"));
} }
set { set {
setAttribute("scrollLeft", UnscaleX(value)); SetAttribute("scrollLeft", UnscaleX(value));
} }
} }
public int ScrollTop { public int ScrollTop {
get{ get{
return ScaleY(getAttributeAsInt("scrollTop")); return ScaleY(GetAttributeAsInt("scrollTop"));
} }
set { set {
setAttribute("scrollTop", UnscaleY(value)); SetAttribute("scrollTop", UnscaleY(value));
} }
} }
public List<DocumentContainer> Frames { public IList<DocumentContainer> Frames {
get { get {
return frames; return _frames;
} }
} }
} }

View file

@ -97,9 +97,9 @@ namespace Greenshot.Helpers {
private class MapiFileDescriptor { private class MapiFileDescriptor {
public int reserved = 0; public int reserved = 0;
public int flags = 0; public int flags = 0;
public int position = 0; public int position;
public string path = null; public string path;
public string name = null; public string name;
public IntPtr type = IntPtr.Zero; public IntPtr type = IntPtr.Zero;
} }
@ -110,7 +110,8 @@ namespace Greenshot.Helpers {
/// <summary> /// <summary>
/// Specifies the valid RecipientTypes for a Recipient. /// Specifies the valid RecipientTypes for a Recipient.
/// </summary> /// </summary>
public enum RecipientType : int { public enum RecipientType
{
/// <summary> /// <summary>
/// Recipient will be in the TO list. /// Recipient will be in the TO list.
/// </summary> /// </summary>
@ -497,25 +498,25 @@ namespace Greenshot.Helpers {
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiMessage { public class MapiMessage {
public int Reserved = 0; public int Reserved = 0;
public string Subject = null; public string Subject;
public string NoteText = null; public string NoteText;
public string MessageType = null; public string MessageType = null;
public string DateReceived = null; public string DateReceived = null;
public string ConversationID = null; public string ConversationID = null;
public int Flags = 0; public int Flags = 0;
public IntPtr Originator = IntPtr.Zero; public IntPtr Originator = IntPtr.Zero;
public int RecipientCount = 0; public int RecipientCount;
public IntPtr Recipients = IntPtr.Zero; public IntPtr Recipients = IntPtr.Zero;
public int FileCount = 0; public int FileCount;
public IntPtr Files = IntPtr.Zero; public IntPtr Files = IntPtr.Zero;
} }
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiRecipDesc { public class MapiRecipDesc {
public int Reserved = 0; public int Reserved = 0;
public int RecipientClass = 0; public int RecipientClass;
public string Name = null; public string Name;
public string Address = null; public string Address;
public int eIDSize = 0; public int eIDSize = 0;
public IntPtr EntryID = IntPtr.Zero; public IntPtr EntryID = IntPtr.Zero;
} }
@ -542,12 +543,12 @@ namespace Greenshot.Helpers {
/// <summary> /// <summary>
/// The email address of this recipient. /// The email address of this recipient.
/// </summary> /// </summary>
public string Address = null; public string Address;
/// <summary> /// <summary>
/// The display name of this recipient. /// The display name of this recipient.
/// </summary> /// </summary>
public string DisplayName = null; public string DisplayName;
/// <summary> /// <summary>
/// How the recipient will receive this message (To, CC, BCC). /// How the recipient will receive this message (To, CC, BCC).

View file

@ -36,12 +36,12 @@ namespace Greenshot.Helpers {
[Serializable] [Serializable]
public class PluginHelper : IGreenshotHost { public class PluginHelper : IGreenshotHost {
private static readonly ILog LOG = LogManager.GetLogger(typeof(PluginHelper)); private static readonly ILog LOG = LogManager.GetLogger(typeof(PluginHelper));
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
private static string pluginPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),Application.ProductName); private static readonly string pluginPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),Application.ProductName);
private static string applicationPath = Path.GetDirectoryName(Application.ExecutablePath); private static readonly string applicationPath = Path.GetDirectoryName(Application.ExecutablePath);
private static string pafPath = Path.Combine(Application.StartupPath, @"App\Greenshot"); private static readonly string pafPath = Path.Combine(Application.StartupPath, @"App\Greenshot");
private static IDictionary<PluginAttribute, IGreenshotPlugin> plugins = new SortedDictionary<PluginAttribute, IGreenshotPlugin>(); private static readonly IDictionary<PluginAttribute, IGreenshotPlugin> plugins = new SortedDictionary<PluginAttribute, IGreenshotPlugin>();
private static readonly PluginHelper instance = new PluginHelper(); private static readonly PluginHelper instance = new PluginHelper();
public static PluginHelper Instance { public static PluginHelper Instance {
get { get {
@ -66,7 +66,7 @@ namespace Greenshot.Helpers {
} }
public bool HasPlugins() { public bool HasPlugins() {
return (plugins != null && plugins.Count > 0); return plugins != null && plugins.Count > 0;
} }
public void Shutdown() { public void Shutdown() {

View file

@ -37,10 +37,10 @@ namespace Greenshot.Helpers {
/// </summary> /// </summary>
public class PrintHelper : IDisposable { public class PrintHelper : IDisposable {
private static readonly ILog LOG = LogManager.GetLogger(typeof(PrintHelper)); private static readonly ILog LOG = LogManager.GetLogger(typeof(PrintHelper));
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
private ISurface surface; private ISurface surface;
private ICaptureDetails captureDetails; private readonly ICaptureDetails captureDetails;
private PrintDocument printDocument = new PrintDocument(); private PrintDocument printDocument = new PrintDocument();
private PrintDialog printDialog = new PrintDialog(); private PrintDialog printDialog = new PrintDialog();
@ -218,7 +218,7 @@ namespace Greenshot.Helpers {
if (conf.OutputPrintFooter) { if (conf.OutputPrintFooter) {
//printRect = new RectangleF(0, 0, printRect.Width, printRect.Height - (dateStringHeight * 2)); //printRect = new RectangleF(0, 0, printRect.Width, printRect.Height - (dateStringHeight * 2));
using (Font f = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular)) { 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); e.Graphics.DrawImage(image, printRect, imageRect, GraphicsUnit.Pixel);

View file

@ -30,8 +30,8 @@ namespace Greenshot.Helpers {
/// Description of ProcessorHelper. /// Description of ProcessorHelper.
/// </summary> /// </summary>
public static class ProcessorHelper { public static class ProcessorHelper {
private static ILog LOG = LogManager.GetLogger(typeof(ProcessorHelper)); private static readonly ILog LOG = LogManager.GetLogger(typeof(ProcessorHelper));
private static Dictionary<string, IProcessor> RegisteredProcessors = new Dictionary<string, IProcessor>(); private static readonly Dictionary<string, IProcessor> RegisteredProcessors = new Dictionary<string, IProcessor>();
/// Initialize the Processors /// Initialize the Processors
static ProcessorHelper() { static ProcessorHelper() {

View file

@ -22,7 +22,6 @@ using System;
using System.Drawing; using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
using Greenshot.Drawing; using Greenshot.Drawing;
using log4net;
namespace Greenshot.Helpers { namespace Greenshot.Helpers {
/// <summary> /// <summary>
@ -45,9 +44,7 @@ namespace Greenshot.Helpers {
/// </summary> /// </summary>
Rational = 0x02 Rational = 0x02
} }
private static readonly ILog LOG = LogManager.GetLogger(typeof(ScaleHelper));
/// <summary> /// <summary>
/// calculates the Size an element must be resized to, in order to fit another element, keeping aspect ratio /// calculates the Size an element must be resized to, in order to fit another element, keeping aspect ratio
/// </summary> /// </summary>
@ -77,7 +74,7 @@ namespace Greenshot.Helpers {
newRect.X = (targetRect.Width - currentRect.Width) / 2; newRect.X = (targetRect.Width - currentRect.Width) / 2;
break; break;
case ContentAlignment.TopRight: case ContentAlignment.TopRight:
newRect.X = (targetRect.Width - currentRect.Width); newRect.X = targetRect.Width - currentRect.Width;
break; break;
case ContentAlignment.MiddleLeft: case ContentAlignment.MiddleLeft:
newRect.Y = (targetRect.Height - currentRect.Height) / 2; newRect.Y = (targetRect.Height - currentRect.Height) / 2;
@ -88,18 +85,18 @@ namespace Greenshot.Helpers {
break; break;
case ContentAlignment.MiddleRight: case ContentAlignment.MiddleRight:
newRect.Y = (targetRect.Height - currentRect.Height) / 2; newRect.Y = (targetRect.Height - currentRect.Height) / 2;
newRect.X = (targetRect.Width - currentRect.Width); newRect.X = targetRect.Width - currentRect.Width;
break; break;
case ContentAlignment.BottomLeft: case ContentAlignment.BottomLeft:
newRect.Y = (targetRect.Height - currentRect.Height); newRect.Y = targetRect.Height - currentRect.Height;
break; break;
case ContentAlignment.BottomCenter: case ContentAlignment.BottomCenter:
newRect.Y = (targetRect.Height - currentRect.Height); newRect.Y = targetRect.Height - currentRect.Height;
newRect.X = (targetRect.Width - currentRect.Width) / 2; newRect.X = (targetRect.Width - currentRect.Width) / 2;
break; break;
case ContentAlignment.BottomRight: case ContentAlignment.BottomRight:
newRect.Y = (targetRect.Height - currentRect.Height); newRect.Y = targetRect.Height - currentRect.Height;
newRect.X = (targetRect.Width - currentRect.Width); newRect.X = targetRect.Width - currentRect.Width;
break; break;
} }
return newRect; return newRect;
@ -119,15 +116,15 @@ namespace Greenshot.Helpers {
return GetAlignedRectangle(newRect, targetRect, alignment); 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); 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); 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); Scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords, null);
} }
@ -138,7 +135,7 @@ namespace Greenshot.Helpers {
/// <param name="resizeHandlePosition">position of the handle/gripper being used for resized, see constants in Gripper.cs, e.g. Gripper.POSITION_TOP_LEFT</param> /// <param name="resizeHandlePosition">position of the handle/gripper being used for resized, see constants in Gripper.cs, e.g. Gripper.POSITION_TOP_LEFT</param>
/// <param name="resizeHandleCoords">coordinates of the used handle/gripper</param> /// <param name="resizeHandleCoords">coordinates of the used handle/gripper</param>
/// <param name="options">ScaleOptions to use when scaling</param> /// <param name="options">ScaleOptions to use when scaling</param>
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) { if(options == null) {
options = GetScaleOptions(); options = GetScaleOptions();
} }
@ -157,7 +154,7 @@ namespace Greenshot.Helpers {
resizeHandleCoords.X -= 2 * (resizeHandleCoords.X - rectCenterX); resizeHandleCoords.X -= 2 * (resizeHandleCoords.X - rectCenterX);
resizeHandleCoords.Y -= 2 * (resizeHandleCoords.Y - rectCenterY); resizeHandleCoords.Y -= 2 * (resizeHandleCoords.Y - rectCenterY);
// scale again with opposing handle and mirrored coordinates // scale again with opposing handle and mirrored coordinates
resizeHandlePosition = (resizeHandlePosition + 4) % 8; resizeHandlePosition = (Positions)((((int)resizeHandlePosition) + 4) % 8);
scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords); scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords);
} else { } else {
scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords); scale(ref originalRectangle, resizeHandlePosition, resizeHandleCoords);
@ -171,47 +168,47 @@ namespace Greenshot.Helpers {
/// <param name="originalRectangle">bounds of the current rectangle, scaled values will be written to this reference</param> /// <param name="originalRectangle">bounds of the current rectangle, scaled values will be written to this reference</param>
/// <param name="resizeHandlePosition">position of the handle/gripper being used for resized, see constants in Gripper.cs, e.g. Gripper.POSITION_TOP_LEFT</param> /// <param name="resizeHandlePosition">position of the handle/gripper being used for resized, see constants in Gripper.cs, e.g. Gripper.POSITION_TOP_LEFT</param>
/// <param name="resizeHandleCoords">coordinates of the used handle/gripper</param> /// <param name="resizeHandleCoords">coordinates of the used handle/gripper</param>
private static void scale(ref RectangleF originalRectangle, int resizeHandlePosition, PointF resizeHandleCoords) { private static void scale(ref RectangleF originalRectangle, Positions resizeHandlePosition, PointF resizeHandleCoords) {
switch(resizeHandlePosition) { switch(resizeHandlePosition) {
case Gripper.POSITION_TOP_LEFT: case Positions.TopLeft:
originalRectangle.Width = originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X; originalRectangle.Width = originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X;
originalRectangle.Height = originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y; originalRectangle.Height = originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y;
originalRectangle.X = resizeHandleCoords.X; originalRectangle.X = resizeHandleCoords.X;
originalRectangle.Y = resizeHandleCoords.Y; originalRectangle.Y = resizeHandleCoords.Y;
break; break;
case Gripper.POSITION_TOP_CENTER: case Positions.TopCenter:
originalRectangle.Height = originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y; originalRectangle.Height = originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y;
originalRectangle.Y = resizeHandleCoords.Y; originalRectangle.Y = resizeHandleCoords.Y;
break; break;
case Gripper.POSITION_TOP_RIGHT: case Positions.TopRight:
originalRectangle.Width = resizeHandleCoords.X - originalRectangle.Left; originalRectangle.Width = resizeHandleCoords.X - originalRectangle.Left;
originalRectangle.Height = originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y; originalRectangle.Height = originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y;
originalRectangle.Y = resizeHandleCoords.Y; originalRectangle.Y = resizeHandleCoords.Y;
break; break;
case Gripper.POSITION_MIDDLE_LEFT: case Positions.MiddleLeft:
originalRectangle.Width = originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X; originalRectangle.Width = originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X;
originalRectangle.X = resizeHandleCoords.X; originalRectangle.X = resizeHandleCoords.X;
break; break;
case Gripper.POSITION_MIDDLE_RIGHT: case Positions.MiddleRight:
originalRectangle.Width = resizeHandleCoords.X - originalRectangle.Left; originalRectangle.Width = resizeHandleCoords.X - originalRectangle.Left;
break; break;
case Gripper.POSITION_BOTTOM_LEFT: case Positions.BottomLeft:
originalRectangle.Width = originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X; originalRectangle.Width = originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X;
originalRectangle.Height = resizeHandleCoords.Y - originalRectangle.Top; originalRectangle.Height = resizeHandleCoords.Y - originalRectangle.Top;
originalRectangle.X = resizeHandleCoords.X; originalRectangle.X = resizeHandleCoords.X;
break; break;
case Gripper.POSITION_BOTTOM_CENTER: case Positions.BottomCenter:
originalRectangle.Height = resizeHandleCoords.Y - originalRectangle.Top; originalRectangle.Height = resizeHandleCoords.Y - originalRectangle.Top;
break; break;
case Gripper.POSITION_BOTTOM_RIGHT: case Positions.BottomRight:
originalRectangle.Width = resizeHandleCoords.X - originalRectangle.Left; originalRectangle.Width = resizeHandleCoords.X - originalRectangle.Left;
originalRectangle.Height = resizeHandleCoords.Y - originalRectangle.Top; originalRectangle.Height = resizeHandleCoords.Y - originalRectangle.Top;
break; break;
@ -221,19 +218,19 @@ namespace Greenshot.Helpers {
} }
} }
/// <summary> /// <summary>
/// Adjusts resizeHandleCoords so that aspect ratio is kept after resizing a given rectangle with provided arguments /// Adjusts resizeHandleCoords so that aspect ratio is kept after resizing a given rectangle with provided arguments
/// </summary> /// </summary>
/// <param name="originalRectangle">bounds of the current rectangle</param> /// <param name="originalRectangle">bounds of the current rectangle</param>
/// <param name="resizeHandlePosition">position of the handle/gripper being used for resized, see constants in Gripper.cs, e.g. Gripper.POSITION_TOP_LEFT</param> /// <param name="resizeHandlePosition">position of the handle/gripper being used for resized, see Position</param>
/// <param name="resizeHandleCoords">coordinates of the used handle/gripper, adjusted coordinates will be written to this reference</param> /// <param name="resizeHandleCoords">coordinates of the used handle/gripper, adjusted coordinates will be written to this reference</param>
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 originalRatio = originalRectangle.Width / originalRectangle.Height;
float newWidth, newHeight, newRatio; float newWidth, newHeight, newRatio;
switch(resizeHandlePosition) { switch(resizeHandlePosition) {
case Gripper.POSITION_TOP_LEFT: case Positions.TopLeft:
newWidth = originalRectangle.Right - resizeHandleCoords.X; newWidth = originalRectangle.Right - resizeHandleCoords.X;
newHeight = originalRectangle.Bottom - resizeHandleCoords.Y; newHeight = originalRectangle.Bottom - resizeHandleCoords.Y;
newRatio = newWidth / newHeight; newRatio = newWidth / newHeight;
@ -244,7 +241,7 @@ namespace Greenshot.Helpers {
} }
break; break;
case Gripper.POSITION_TOP_RIGHT: case Positions.TopRight:
newWidth = resizeHandleCoords.X - originalRectangle.Left; newWidth = resizeHandleCoords.X - originalRectangle.Left;
newHeight = originalRectangle.Bottom - resizeHandleCoords.Y; newHeight = originalRectangle.Bottom - resizeHandleCoords.Y;
newRatio = newWidth / newHeight; newRatio = newWidth / newHeight;
@ -255,7 +252,7 @@ namespace Greenshot.Helpers {
} }
break; break;
case Gripper.POSITION_BOTTOM_LEFT: case Positions.BottomLeft:
newWidth = originalRectangle.Right - resizeHandleCoords.X; newWidth = originalRectangle.Right - resizeHandleCoords.X;
newHeight = resizeHandleCoords.Y - originalRectangle.Top; newHeight = resizeHandleCoords.Y - originalRectangle.Top;
newRatio = newWidth / newHeight; newRatio = newWidth / newHeight;
@ -266,7 +263,7 @@ namespace Greenshot.Helpers {
} }
break; break;
case Gripper.POSITION_BOTTOM_RIGHT: case Positions.BottomRight:
newWidth = resizeHandleCoords.X - originalRectangle.Left; newWidth = resizeHandleCoords.X - originalRectangle.Left;
newHeight = resizeHandleCoords.Y - originalRectangle.Top; newHeight = resizeHandleCoords.Y - originalRectangle.Top;
newRatio = newWidth / newHeight; 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) { 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(); ScaleOptions opts = GetScaleOptions();
@ -323,7 +320,7 @@ namespace Greenshot.Helpers {
/// <returns>the current ScaleOptions depending on modifier keys held down</returns> /// <returns>the current ScaleOptions depending on modifier keys held down</returns>
public static ScaleOptions GetScaleOptions() { public static ScaleOptions GetScaleOptions() {
bool anchorAtCenter = (Control.ModifierKeys & Keys.Control) != 0; 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; ScaleOptions opts = ScaleOptions.Default;
if(anchorAtCenter) opts |= ScaleOptions.Centered; if(anchorAtCenter) opts |= ScaleOptions.Centered;
if(maintainAspectRatio) opts |= ScaleOptions.Rational; if(maintainAspectRatio) opts |= ScaleOptions.Rational;
@ -349,7 +346,7 @@ namespace Greenshot.Helpers {
} }
} }
public class FixedAngleRoundBehavior : IDoubleProcessor { public class FixedAngleRoundBehavior : IDoubleProcessor {
private double fixedAngle; private readonly double fixedAngle;
public FixedAngleRoundBehavior(double fixedAngle) { public FixedAngleRoundBehavior(double fixedAngle) {
this.fixedAngle = fixedAngle; this.fixedAngle = fixedAngle;
} }

View file

@ -39,27 +39,27 @@ namespace Greenshot.Helpers {
/// </summary> /// </summary>
public static class SoundHelper { public static class SoundHelper {
private static readonly ILog LOG = LogManager.GetLogger(typeof(SoundHelper)); private static readonly ILog LOG = LogManager.GetLogger(typeof(SoundHelper));
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
private static GCHandle? gcHandle = null; private static GCHandle? _gcHandle;
private static byte[] soundBuffer = null; private static byte[] _soundBuffer;
public static void Initialize() { public static void Initialize() {
if (gcHandle == null) { if (_gcHandle == null) {
try { try {
ResourceManager resources = new ResourceManager("Greenshot.Sounds", Assembly.GetExecutingAssembly()); 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")) { if (conf.NotificationSound != null && conf.NotificationSound.EndsWith(".wav")) {
try { try {
if (File.Exists(conf.NotificationSound)) { if (File.Exists(conf.NotificationSound)) {
soundBuffer = File.ReadAllBytes(conf.NotificationSound); _soundBuffer = File.ReadAllBytes(conf.NotificationSound);
} }
} catch (Exception ex) { } catch (Exception ex) {
LOG.WarnFormat("couldn't load {0}: {1}", conf.NotificationSound, ex.Message); 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 // 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) { } catch (Exception e) {
LOG.Error("Error initializing.", e); LOG.Error("Error initializing.", e);
} }
@ -67,11 +67,11 @@ namespace Greenshot.Helpers {
} }
public static void Play() { public static void Play() {
if (soundBuffer != null) { if (_soundBuffer != null) {
//Thread playSoundThread = new Thread(delegate() { //Thread playSoundThread = new Thread(delegate() {
SoundFlags flags = SoundFlags.SND_ASYNC | SoundFlags.SND_MEMORY | SoundFlags.SND_NOWAIT | SoundFlags.SND_NOSTOP; SoundFlags flags = SoundFlags.SND_ASYNC | SoundFlags.SND_MEMORY | SoundFlags.SND_NOWAIT | SoundFlags.SND_NOSTOP;
try { try {
WinMM.PlaySound(gcHandle.Value.AddrOfPinnedObject(), (UIntPtr)0, (uint)flags); WinMM.PlaySound(_gcHandle.Value.AddrOfPinnedObject(), (UIntPtr)0, (uint)flags);
} catch (Exception e) { } catch (Exception e) {
LOG.Error("Error in play.", e); LOG.Error("Error in play.", e);
} }
@ -84,10 +84,10 @@ namespace Greenshot.Helpers {
public static void Deinitialize() { public static void Deinitialize() {
try { try {
if (gcHandle != null) { if (_gcHandle != null) {
WinMM.PlaySound((byte[])null, (UIntPtr)0, (uint)0); WinMM.PlaySound((byte[])null, (UIntPtr)0, (uint)0);
gcHandle.Value.Free(); _gcHandle.Value.Free();
gcHandle = null; _gcHandle = null;
} }
} catch (Exception e) { } catch (Exception e) {
LOG.Error("Error in deinitialize.", e); LOG.Error("Error in deinitialize.", e);

View file

@ -35,7 +35,7 @@ namespace Greenshot.Experimental {
/// </summary> /// </summary>
public static class UpdateHelper { public static class UpdateHelper {
private static readonly ILog LOG = LogManager.GetLogger(typeof(UpdateHelper)); private static readonly ILog LOG = LogManager.GetLogger(typeof(UpdateHelper));
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
private const string STABLE_DOWNLOAD_LINK = "http://getgreenshot.org/downloads/"; private const string STABLE_DOWNLOAD_LINK = "http://getgreenshot.org/downloads/";
private const string VERSION_HISTORY_LINK = "http://getgreenshot.org/version-history/"; private const string VERSION_HISTORY_LINK = "http://getgreenshot.org/version-history/";
private static readonly object LockObject = new object(); private static readonly object LockObject = new object();

View file

@ -31,6 +31,6 @@ namespace Greenshot.Helpers {
get { return _hwnd; } get { return _hwnd; }
} }
private IntPtr _hwnd; private readonly IntPtr _hwnd;
} }
} }

View file

@ -28,12 +28,12 @@ namespace Greenshot.Memento {
/// The AddElementMemento makes it possible to undo adding an element /// The AddElementMemento makes it possible to undo adding an element
/// </summary> /// </summary>
public class AddElementMemento : IMemento { public class AddElementMemento : IMemento {
private IDrawableContainer drawableContainer; private IDrawableContainer _drawableContainer;
private Surface surface; private Surface _surface;
public AddElementMemento(Surface surface, IDrawableContainer drawableContainer) { public AddElementMemento(Surface surface, IDrawableContainer drawableContainer) {
this.surface = surface; _surface = surface;
this.drawableContainer = drawableContainer; _drawableContainer = drawableContainer;
} }
public void Dispose() { public void Dispose() {
@ -43,14 +43,8 @@ namespace Greenshot.Memento {
protected virtual void Dispose(bool disposing) { protected virtual void Dispose(bool disposing) {
//if (disposing) { } //if (disposing) { }
drawableContainer = null; _drawableContainer = null;
surface = null; _surface = null;
}
public LangKey ActionLanguageKey {
get {
return LangKey.none;
}
} }
public bool Merge(IMemento otherMemento) { public bool Merge(IMemento otherMemento) {
@ -59,16 +53,15 @@ namespace Greenshot.Memento {
public IMemento Restore() { public IMemento Restore() {
// Before // Before
drawableContainer.Invalidate(); _drawableContainer.Invalidate();
// Store the selected state, as it's overwritten by the RemoveElement // Store the selected state, as it's overwritten by the RemoveElement
bool selected = drawableContainer.Selected;
DeleteElementMemento oldState = new DeleteElementMemento(surface, drawableContainer); DeleteElementMemento oldState = new DeleteElementMemento(_surface, _drawableContainer);
surface.RemoveElement(drawableContainer, false); _surface.RemoveElement(_drawableContainer, false);
drawableContainer.Selected = true; _drawableContainer.Selected = true;
// After // After
drawableContainer.Invalidate(); _drawableContainer.Invalidate();
return oldState; return oldState;
} }
} }

View file

@ -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 <http://www.gnu.org/licenses/>.
*/
using Greenshot.Drawing;
using Greenshot.Plugin.Drawing;
namespace Greenshot.Memento
{
/// <summary>
/// The AddElementMemento makes it possible to undo adding an element
/// </summary>
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;
}
}
}

View file

@ -18,47 +18,54 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
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
{
/// <summary> /// <summary>
/// The ChangeFieldHolderMemento makes it possible to undo-redo an IDrawableContainer move /// The ChangeFieldHolderMemento makes it possible to undo-redo an IDrawableContainer move
/// </summary> /// </summary>
public class ChangeFieldHolderMemento : IMemento { public class ChangeFieldHolderMemento : IMemento
private IDrawableContainer drawableContainer; {
private Field fieldToBeChanged; private IDrawableContainer _drawableContainer;
private object oldValue; private IField _fieldToBeChanged;
private object _oldValue;
public ChangeFieldHolderMemento(IDrawableContainer drawableContainer, Field fieldToBeChanged) {
this.drawableContainer = drawableContainer; public ChangeFieldHolderMemento(IDrawableContainer drawableContainer, IField fieldToBeChanged)
this.fieldToBeChanged = fieldToBeChanged; {
oldValue = fieldToBeChanged.Value; _drawableContainer = drawableContainer;
_fieldToBeChanged = fieldToBeChanged;
_oldValue = fieldToBeChanged.Value;
} }
public void Dispose() { public void Dispose()
{
Dispose(true); Dispose(true);
GC.SuppressFinalize(this);
} }
protected virtual void Dispose(bool disposing) { protected virtual void Dispose(bool disposing)
//if (disposing) { } {
drawableContainer = null; if (disposing)
} {
if (_drawableContainer != null)
public LangKey ActionLanguageKey { {
get { _drawableContainer.Dispose();
return LangKey.none; }
} }
_drawableContainer = null;
} }
public bool Merge(IMemento otherMemento) { public bool Merge(IMemento otherMemento)
{
ChangeFieldHolderMemento other = otherMemento as ChangeFieldHolderMemento; ChangeFieldHolderMemento other = otherMemento as ChangeFieldHolderMemento;
if (other != null) { if (other != null)
if (other.drawableContainer.Equals(drawableContainer)) { {
if (other.fieldToBeChanged.Equals(fieldToBeChanged)) { if (other._drawableContainer.Equals(_drawableContainer))
{
if (other._fieldToBeChanged.Equals(_fieldToBeChanged))
{
// Match, do not store anything as the initial state is what we want. // Match, do not store anything as the initial state is what we want.
return true; return true;
} }
@ -67,13 +74,14 @@ namespace Greenshot.Memento {
return false; return false;
} }
public IMemento Restore() { public IMemento Restore()
{
// Before // Before
drawableContainer.Invalidate(); _drawableContainer.Invalidate();
ChangeFieldHolderMemento oldState = new ChangeFieldHolderMemento(drawableContainer, fieldToBeChanged); ChangeFieldHolderMemento oldState = new ChangeFieldHolderMemento(_drawableContainer, _fieldToBeChanged);
fieldToBeChanged.Value = oldValue; _fieldToBeChanged.Value = _oldValue;
// After // After
drawableContainer.Invalidate(); _drawableContainer.Invalidate();
return oldState; return oldState;
} }
} }

View file

@ -29,7 +29,7 @@ namespace Greenshot.Memento {
/// </summary> /// </summary>
public class DeleteElementMemento : IMemento { public class DeleteElementMemento : IMemento {
private IDrawableContainer drawableContainer; private IDrawableContainer drawableContainer;
private Surface surface; private readonly Surface surface;
public DeleteElementMemento(Surface surface, IDrawableContainer drawableContainer) { public DeleteElementMemento(Surface surface, IDrawableContainer drawableContainer) {
this.surface = surface; 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) { public bool Merge(IMemento otherMemento) {
return false; return false;
} }

View file

@ -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 <http://www.gnu.org/licenses/>.
*/
using Greenshot.Drawing;
using Greenshot.Plugin.Drawing;
namespace Greenshot.Memento
{
/// <summary>
/// The DeleteElementMemento makes it possible to undo deleting an element
/// </summary>
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;
}
}
}

View file

@ -18,61 +18,70 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using System; using Greenshot.Drawing;
using Greenshot.Plugin.Drawing;
using GreenshotPlugin.Core;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using Greenshot.Configuration; namespace Greenshot.Memento
using Greenshot.Plugin.Drawing; {
using GreenshotPlugin.Core;
namespace Greenshot.Memento {
/// <summary> /// <summary>
/// The DrawableContainerBoundsChangeMemento makes it possible to undo-redo an IDrawableContainer resize & move /// The DrawableContainerBoundsChangeMemento makes it possible to undo-redo an IDrawableContainer resize & move
/// </summary> /// </summary>
public class DrawableContainerBoundsChangeMemento : IMemento { public class DrawableContainerBoundsChangeMemento : IMemento
{
List<Point> points = new List<Point>(); List<Point> points = new List<Point>();
List<Size> sizes = new List<Size>(); List<Size> sizes = new List<Size>();
List<IDrawableContainer> listOfdrawableContainer; IDrawableContainerList listOfdrawableContainer;
private void StoreBounds() { private void StoreBounds()
foreach(IDrawableContainer drawableContainer in listOfdrawableContainer) { {
foreach (IDrawableContainer drawableContainer in listOfdrawableContainer)
{
points.Add(drawableContainer.Location); points.Add(drawableContainer.Location);
sizes.Add(drawableContainer.Size); sizes.Add(drawableContainer.Size);
} }
} }
public DrawableContainerBoundsChangeMemento(List<IDrawableContainer> listOfdrawableContainer) { public DrawableContainerBoundsChangeMemento(IDrawableContainerList listOfdrawableContainer)
{
this.listOfdrawableContainer = listOfdrawableContainer; this.listOfdrawableContainer = listOfdrawableContainer;
StoreBounds(); StoreBounds();
} }
public DrawableContainerBoundsChangeMemento(IDrawableContainer drawableContainer) { public DrawableContainerBoundsChangeMemento(IDrawableContainer drawableContainer)
listOfdrawableContainer = new List<IDrawableContainer>(); {
listOfdrawableContainer = new DrawableContainerList();
listOfdrawableContainer.Add(drawableContainer); listOfdrawableContainer.Add(drawableContainer);
listOfdrawableContainer.Parent = drawableContainer.Parent;
StoreBounds(); StoreBounds();
} }
public void Dispose() { public void Dispose()
{
Dispose(true); Dispose(true);
GC.SuppressFinalize(this);
} }
protected virtual void Dispose(bool disposing) { protected virtual void Dispose(bool disposing)
// if (disposing) { } {
if (disposing)
{
if (listOfdrawableContainer != null)
{
listOfdrawableContainer.Dispose();
}
}
listOfdrawableContainer = null; listOfdrawableContainer = null;
} }
public LangKey ActionLanguageKey { public bool Merge(IMemento otherMemento)
get { {
return LangKey.none; var other = otherMemento as DrawableContainerBoundsChangeMemento;
} if (other != null)
} {
if (Objects.CompareLists<IDrawableContainer>(listOfdrawableContainer, other.listOfdrawableContainer))
public bool Merge(IMemento otherMemento) { {
DrawableContainerBoundsChangeMemento other = otherMemento as DrawableContainerBoundsChangeMemento;
if (other != null) {
if (Objects.CompareLists<IDrawableContainer>(listOfdrawableContainer, other.listOfdrawableContainer)) {
// Lists are equal, as we have the state already we can ignore the new memento // Lists are equal, as we have the state already we can ignore the new memento
return true; return true;
} }
@ -80,9 +89,11 @@ namespace Greenshot.Memento {
return false; return false;
} }
public IMemento Restore() { public IMemento Restore()
DrawableContainerBoundsChangeMemento oldState = new DrawableContainerBoundsChangeMemento(listOfdrawableContainer); {
for(int index = 0; index < listOfdrawableContainer.Count; index++) { var oldState = new DrawableContainerBoundsChangeMemento(listOfdrawableContainer);
for (int index = 0; index < listOfdrawableContainer.Count; index++)
{
IDrawableContainer drawableContainer = listOfdrawableContainer[index]; IDrawableContainer drawableContainer = listOfdrawableContainer[index];
// Before // Before
drawableContainer.Invalidate(); drawableContainer.Invalidate();

View file

@ -44,7 +44,6 @@ namespace Greenshot.Memento {
public void Dispose() { public void Dispose() {
Dispose(true); Dispose(true);
GC.SuppressFinalize(this);
} }
protected virtual void Dispose(bool disposing) { protected virtual void Dispose(bool disposing) {
@ -64,13 +63,6 @@ namespace Greenshot.Memento {
public bool Merge(IMemento otherMemento) { public bool Merge(IMemento otherMemento) {
return false; return false;
} }
public LangKey ActionLanguageKey {
get {
//return LangKey.editor_crop;
return LangKey.none;
}
}
public IMemento Restore() { public IMemento Restore() {
SurfaceBackgroundChangeMemento oldState = new SurfaceBackgroundChangeMemento(_surface, _matrix); SurfaceBackgroundChangeMemento oldState = new SurfaceBackgroundChangeMemento(_surface, _matrix);

View file

@ -28,7 +28,7 @@ namespace Greenshot.Memento {
/// </summary> /// </summary>
public class TextChangeMemento : IMemento { public class TextChangeMemento : IMemento {
private TextContainer textContainer; private TextContainer textContainer;
private string oldText; private readonly string oldText;
public TextChangeMemento(TextContainer textContainer) { public TextChangeMemento(TextContainer textContainer) {
this.textContainer = textContainer; this.textContainer = textContainer;
@ -37,7 +37,6 @@ namespace Greenshot.Memento {
public void Dispose() { public void Dispose() {
Dispose(true); Dispose(true);
GC.SuppressFinalize(this);
} }
protected virtual void Dispose(bool disposing) { 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) { public bool Merge(IMemento otherMemento) {
TextChangeMemento other = otherMemento as TextChangeMemento; TextChangeMemento other = otherMemento as TextChangeMemento;
if (other != null) { if (other != null) {

View file

@ -32,8 +32,8 @@ namespace Greenshot.Processors {
/// Description of TitleFixProcessor. /// Description of TitleFixProcessor.
/// </summary> /// </summary>
public class TitleFixProcessor : AbstractProcessor { public class TitleFixProcessor : AbstractProcessor {
private static ILog LOG = LogManager.GetLogger(typeof(TitleFixProcessor)); private static readonly ILog LOG = LogManager.GetLogger(typeof(TitleFixProcessor));
private static CoreConfiguration config = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration config = IniConfig.GetIniSection<CoreConfiguration>();
public TitleFixProcessor() { public TitleFixProcessor() {
List<string> corruptKeys = new List<string>(); List<string> corruptKeys = new List<string>();

View file

@ -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: 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: Bugs Resolved:
BUG-1527 / BUG-1848 / BUG-1850 / BUG-1851 / BUG-1859 : Greenshot stops responding, hangs or crashes BUG-1527 / BUG-1848 / BUG-1850 / BUG-1851 / BUG-1859 : Greenshot stops responding, hangs or crashes

View file

@ -18,7 +18,6 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using System;
namespace GreenshotBoxPlugin { namespace GreenshotBoxPlugin {
/// <summary> /// <summary>

View file

@ -22,12 +22,9 @@ using System.ComponentModel;
using System.Drawing; using System.Drawing;
using Greenshot.Plugin; using Greenshot.Plugin;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using log4net;
namespace GreenshotBoxPlugin { namespace GreenshotBoxPlugin {
public class BoxDestination : AbstractDestination { public class BoxDestination : AbstractDestination {
private static ILog LOG = LogManager.GetLogger(typeof(BoxDestination));
private readonly BoxPlugin _plugin; private readonly BoxPlugin _plugin;
public BoxDestination(BoxPlugin plugin) { public BoxDestination(BoxPlugin plugin) {
_plugin = plugin; _plugin = plugin;

View file

@ -18,20 +18,14 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
using System;
using System.Drawing;
using System.Windows.Forms;
using GreenshotBoxPlugin.Forms; using GreenshotBoxPlugin.Forms;
using GreenshotPlugin.Core;
namespace GreenshotBoxPlugin { namespace GreenshotBoxPlugin {
/// <summary> /// <summary>
/// Description of PasswordRequestForm. /// Description of PasswordRequestForm.
/// </summary> /// </summary>
public partial class SettingsForm : BoxForm { public partial class SettingsForm : BoxForm {
string boxTicket = string.Empty;
public SettingsForm(BoxConfiguration config) { public SettingsForm(BoxConfiguration config) {
// //
// The InitializeComponent() call is required for Windows Forms designer support. // The InitializeComponent() call is required for Windows Forms designer support.

View file

@ -22,7 +22,6 @@
using Greenshot.Plugin; using Greenshot.Plugin;
using System.Reflection; using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Security;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information // set of attributes. Change these attribute values to modify the information

View file

@ -95,14 +95,14 @@ namespace Confluence {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ConfluenceConnector)); 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 AUTH_FAILED_EXCEPTION_NAME = "com.atlassian.confluence.rpc.AuthenticationFailedException";
private const string V2_FAILED = "AXIS"; private const string V2_FAILED = "AXIS";
private static ConfluenceConfiguration config = IniConfig.GetIniSection<ConfluenceConfiguration>(); private static readonly ConfluenceConfiguration config = IniConfig.GetIniSection<ConfluenceConfiguration>();
private string credentials = null; private string credentials = null;
private DateTime loggedInTime = DateTime.Now; private DateTime loggedInTime = DateTime.Now;
private bool loggedIn = false; private bool loggedIn = false;
private ConfluenceSoapServiceService confluence; private ConfluenceSoapServiceService confluence;
private int timeout; private readonly int timeout;
private string url; private string url;
private Cache<string, RemotePage> pageCache = new Cache<string, RemotePage>(60 * config.Timeout); private readonly Cache<string, RemotePage> pageCache = new Cache<string, RemotePage>(60 * config.Timeout);
public void Dispose() { public void Dispose() {
Dispose(true); Dispose(true);
@ -143,9 +143,9 @@ namespace Confluence {
/// <returns>true if login was done sucessfully</returns> /// <returns>true if login was done sucessfully</returns>
private bool doLogin(string user, string password) { private bool doLogin(string user, string password) {
try { try {
this.credentials = confluence.login(user, password); credentials = confluence.login(user, password);
this.loggedInTime = DateTime.Now; loggedInTime = DateTime.Now;
this.loggedIn = true; loggedIn = true;
} catch (Exception e) { } catch (Exception e) {
// Check if confluence-v2 caused an error, use v1 instead // Check if confluence-v2 caused an error, use v1 instead
if (e.Message.Contains(V2_FAILED) && url.Contains("v2")) { if (e.Message.Contains(V2_FAILED) && url.Contains("v2")) {
@ -157,8 +157,8 @@ namespace Confluence {
return false; return false;
} }
// Not an authentication issue // Not an authentication issue
this.loggedIn = false; loggedIn = false;
this.credentials = null; credentials = null;
e.Data.Add("user", user); e.Data.Add("user", user);
e.Data.Add("url", url); e.Data.Add("url", url);
throw; throw;

View file

@ -36,11 +36,11 @@ namespace GreenshotConfluencePlugin {
/// Description of ConfluenceDestination. /// Description of ConfluenceDestination.
/// </summary> /// </summary>
public class ConfluenceDestination : AbstractDestination { 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<ConfluenceConfiguration>(); private static readonly ConfluenceConfiguration config = IniConfig.GetIniSection<ConfluenceConfiguration>();
private static readonly CoreConfiguration coreConfig = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration coreConfig = IniConfig.GetIniSection<CoreConfiguration>();
private static Image confluenceIcon = null; private static readonly Image confluenceIcon = null;
private Confluence.Page page; private readonly Page page;
public static bool IsInitialized { public static bool IsInitialized {
get; get;
private set; private set;
@ -63,7 +63,7 @@ namespace GreenshotConfluencePlugin {
public ConfluenceDestination() { public ConfluenceDestination() {
} }
public ConfluenceDestination(Confluence.Page page) { public ConfluenceDestination(Page page) {
this.page = page; this.page = page;
} }
@ -105,17 +105,17 @@ namespace GreenshotConfluencePlugin {
if (ConfluencePlugin.ConfluenceConnectorNoLogin == null || !ConfluencePlugin.ConfluenceConnectorNoLogin.isLoggedIn) { if (ConfluencePlugin.ConfluenceConnectorNoLogin == null || !ConfluencePlugin.ConfluenceConnectorNoLogin.isLoggedIn) {
yield break; yield break;
} }
List<Confluence.Page> currentPages = ConfluenceUtils.GetCurrentPages(); List<Page> currentPages = ConfluenceUtils.GetCurrentPages();
if (currentPages == null || currentPages.Count == 0) { if (currentPages == null || currentPages.Count == 0) {
yield break; yield break;
} }
foreach(Confluence.Page currentPage in currentPages) { foreach(Page currentPage in currentPages) {
yield return new ConfluenceDestination(currentPage); yield return new ConfluenceDestination(currentPage);
} }
} }
public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { 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 // force password check to take place before the pages load
if (!ConfluencePlugin.ConfluenceConnector.isLoggedIn) { if (!ConfluencePlugin.ConfluenceConnector.isLoggedIn) {
return exportInformation; return exportInformation;

Some files were not shown because too many files have changed in this diff Show more