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.Runtime.InteropServices;
using System.Security;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information

View file

@ -26,6 +26,7 @@ using Greenshot.Drawing.Fields;
using GreenshotPlugin.UnmanagedHelpers;
using Greenshot.IniFile;
using Greenshot.Core;
using GreenshotPlugin.Interfaces.Drawing;
namespace Greenshot.Configuration {
/// <summary>
@ -73,9 +74,10 @@ namespace Greenshot.Configuration {
/// <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="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>
public Field CreateField(Type requestingType, FieldType fieldType, object preferredDefaultValue) {
public IField CreateField(Type requestingType, IFieldType fieldType, object preferredDefaultValue)
{
string requestingTypeName = requestingType.Name;
string requestedField = requestingTypeName + "." + fieldType.Name;
object fieldValue = preferredDefaultValue;
@ -102,7 +104,8 @@ namespace Greenshot.Configuration {
return returnField;
}
public void UpdateLastFieldValue(Field field) {
public void UpdateLastFieldValue(IField field)
{
string requestedField = field.Scope + "." + field.FieldType.Name;
// Check if the configuration exists
if (LastUsedFieldValues == null) {
@ -110,9 +113,9 @@ namespace Greenshot.Configuration {
}
// check if settings for the requesting type exist, if not create!
if (LastUsedFieldValues.ContainsKey(requestedField)) {
LastUsedFieldValues[requestedField] = field.myValue;
LastUsedFieldValues[requestedField] = field.Value;
} else {
LastUsedFieldValues.Add(requestedField, field.myValue);
LastUsedFieldValues.Add(requestedField, field.Value);
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -19,19 +19,36 @@
* 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.Windows.Forms;
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 {
protected override Point ScrollToControl(Control activeControl) {
// Returning the current location prevents the panel from
// scrolling to the active control when the panel loses and regains focus
return DisplayRectangle.Location;
}
/// <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 bool dragging;
private Cursor _cursor;
private Bitmap _image;
private readonly Bitmap _image;
private const int VK_ESC = 27;
public event EventHandler<PipetteUsedArgs> PipetteUsed;
@ -111,11 +111,15 @@ namespace Greenshot.Controls {
/// </summary>
/// <param name="e">MouseEventArgs</param>
protected override void OnMouseUp(MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
if (e.Button == MouseButtons.Left)
{
//Release Capture should consume MouseUp when canceled with the escape key
User32.ReleaseCapture();
if (PipetteUsed != null)
{
PipetteUsed(this, new PipetteUsedArgs(movableShowColorForm.color));
}
}
base.OnMouseUp(e);
}

View file

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

View file

@ -25,16 +25,12 @@ using System.Windows.Forms;
using Greenshot.Configuration;
using GreenshotPlugin.Core;
using Greenshot.Plugin;
using Greenshot.IniFile;
using log4net;
namespace Greenshot.Destinations {
/// <summary>
/// Description of ClipboardDestination.
/// </summary>
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 override string Designation {

View file

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

View file

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

View file

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

View file

@ -34,7 +34,7 @@ namespace Greenshot.Destinations {
/// </summary>
public class FileWithDialogDestination : AbstractDestination {
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 override string Designation {

View file

@ -28,18 +28,14 @@ using Greenshot.Configuration;
using GreenshotPlugin.Core;
using Greenshot.Plugin;
using Greenshot.Helpers;
using Greenshot.IniFile;
using log4net;
namespace Greenshot.Destinations {
/// <summary>
/// Description of PrinterDestination.
/// </summary>
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 string printerName = null;
public string printerName;
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);
currentStep++;
alpha = alpha - (basealpha / steps);
alpha = alpha - basealpha / steps;
}
}

View file

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

View file

@ -26,6 +26,7 @@ using System.Windows.Forms;
using Greenshot.Plugin.Drawing;
using System.Drawing.Drawing2D;
using log4net;
using System.Runtime.Serialization;
namespace Greenshot.Drawing {
/// <summary>
@ -33,14 +34,26 @@ namespace Greenshot.Drawing {
/// </summary>
[Serializable]
public class CursorContainer : DrawableContainer, ICursorContainer {
private static ILog LOG = LogManager.GetLogger(typeof(CursorContainer));
private static readonly ILog LOG = LogManager.GetLogger(typeof(CursorContainer));
protected Cursor cursor;
public CursorContainer(Surface parent) : base(parent) {
Init();
}
public CursorContainer(Surface parent, string filename) : base(parent) {
protected override void OnDeserialized(StreamingContext streamingContext)
{
base.OnDeserialized(streamingContext);
Init();
}
private void Init()
{
CreateDefaultAdorners();
}
public CursorContainer(Surface parent, string filename) : this(parent) {
Load(filename);
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -29,14 +29,14 @@ namespace Greenshot.Drawing.Fields.Binding {
/// behavior (e.g. when binding to a
/// </summary>
public class BidirectionalBinding {
private INotifyPropertyChanged controlObject;
private INotifyPropertyChanged fieldObject;
private string controlPropertyName;
private string fieldPropertyName;
private bool updatingControl = false;
private bool updatingField = false;
private IBindingConverter converter;
private IBindingValidator validator;
private readonly INotifyPropertyChanged _controlObject;
private readonly INotifyPropertyChanged _fieldObject;
private readonly string _controlPropertyName;
private readonly string _fieldPropertyName;
private bool _updatingControl;
private bool _updatingField;
private IBindingConverter _converter;
private readonly IBindingValidator _validator;
/// <summary>
/// Whether or not null values are passed on to the other object.
@ -46,18 +46,18 @@ namespace Greenshot.Drawing.Fields.Binding {
/// <summary>
/// Bind properties of two objects bidirectionally
/// </summary>
/// <param name="object1">Object containing 1st property to bind</param>
/// <param name="property1">Property of 1st object to bind</param>
/// <param name="object2">Object containing 2nd property to bind</param>
/// <param name="property2">Property of 2nd object to bind</param>
/// <param name="controlObject">Object containing 1st property to bind</param>
/// <param name="controlPropertyName">Property of 1st object to bind</param>
/// <param name="fieldObject">Object containing 2nd property to bind</param>
/// <param name="fieldPropertyName">Property of 2nd object to bind</param>
public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName) {
this.controlObject = controlObject;
this.fieldObject = fieldObject;
this.controlPropertyName = controlPropertyName;
this.fieldPropertyName = fieldPropertyName;
_controlObject = controlObject;
_fieldObject = fieldObject;
_controlPropertyName = controlPropertyName;
_fieldPropertyName = fieldPropertyName;
this.controlObject.PropertyChanged += ControlPropertyChanged;
this.fieldObject.PropertyChanged += FieldPropertyChanged;
_controlObject.PropertyChanged += ControlPropertyChanged;
_fieldObject.PropertyChanged += FieldPropertyChanged;
}
/// <summary>
@ -69,7 +69,7 @@ namespace Greenshot.Drawing.Fields.Binding {
/// <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>
public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingConverter converter) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) {
this.converter = converter;
_converter = converter;
}
/// <summary>
@ -82,7 +82,7 @@ namespace Greenshot.Drawing.Fields.Binding {
/// <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>
public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) {
this.validator = validator;
_validator = validator;
}
/// <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="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) {
this.validator = validator;
_validator = validator;
}
public void ControlPropertyChanged(object sender, PropertyChangedEventArgs e) {
if (!updatingControl && e.PropertyName.Equals(controlPropertyName)) {
updatingField = true;
synchronize(controlObject, controlPropertyName, fieldObject, fieldPropertyName);
updatingField = false;
if (!_updatingControl && e.PropertyName.Equals(_controlPropertyName)) {
_updatingField = true;
Synchronize(_controlObject, _controlPropertyName, _fieldObject, _fieldPropertyName);
_updatingField = false;
}
}
public void FieldPropertyChanged(object sender, PropertyChangedEventArgs e) {
if (!updatingField && e.PropertyName.Equals(fieldPropertyName)) {
updatingControl = true;
synchronize(fieldObject, fieldPropertyName, controlObject, controlPropertyName);
updatingControl = false;
if (!_updatingField && e.PropertyName.Equals(_fieldPropertyName)) {
_updatingControl = true;
Synchronize(_fieldObject, _fieldPropertyName, _controlObject, _controlPropertyName);
_updatingControl = false;
}
}
private void synchronize(INotifyPropertyChanged sourceObject, string sourceProperty, INotifyPropertyChanged targetObject, string targetProperty) {
PropertyInfo targetPropertyInfo = resolvePropertyInfo(targetObject, targetProperty);
PropertyInfo sourcePropertyInfo = resolvePropertyInfo(sourceObject, sourceProperty);
private void Synchronize(INotifyPropertyChanged sourceObject, string sourceProperty, INotifyPropertyChanged targetObject, string targetProperty) {
PropertyInfo targetPropertyInfo = ResolvePropertyInfo(targetObject, targetProperty);
PropertyInfo sourcePropertyInfo = ResolvePropertyInfo(sourceObject, sourceProperty);
if (sourcePropertyInfo != null && targetPropertyInfo != null && targetPropertyInfo.CanWrite) {
object bValue = sourcePropertyInfo.GetValue(sourceObject, null);
if (converter != null && bValue != null) {
bValue = converter.convert(bValue);
if (_converter != null && bValue != null) {
bValue = _converter.convert(bValue);
}
try {
if (validator == null || validator.validate(bValue)) {
if (_validator == null || _validator.validate(bValue)) {
targetPropertyInfo.SetValue(targetObject, bValue, null);
}
} catch (Exception e) {
throw new MemberAccessException("Could not set property '"+targetProperty+"' to '"+bValue+"' ["+((bValue!=null)?bValue.GetType().Name:"")+"] on "+targetObject+". Probably other type than expected, IBindingCoverter to the rescue.", e);
throw new MemberAccessException("Could not set property '"+targetProperty+"' to '"+bValue+"' ["+(bValue!=null?bValue.GetType().Name:"")+"] on "+targetObject+". Probably other type than expected, IBindingCoverter to the rescue.", e);
}
}
}
private PropertyInfo resolvePropertyInfo(object obj, string property) {
private static PropertyInfo ResolvePropertyInfo(object obj, string property) {
PropertyInfo ret = null;
string[] properties = property.Split(".".ToCharArray());
for(int i=0; i<properties.Length; i++) {
@ -149,8 +149,8 @@ namespace Greenshot.Drawing.Fields.Binding {
}
public IBindingConverter Converter {
get { return converter; }
set { converter = value; }
get { return _converter; }
set { _converter = value; }
}
}

View file

@ -18,35 +18,52 @@
* 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 GreenshotPlugin.Interfaces.Drawing;
using System;
using System.ComponentModel;
namespace Greenshot.Drawing.Fields {
namespace Greenshot.Drawing.Fields
{
/// <summary>
/// Represents a single field of a drawable element, i.e.
/// line thickness of a rectangle.
/// </summary>
[Serializable]
public class Field : INotifyPropertyChanged {
public class Field : IField
{
[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
public object myValue;
public object Value {
get {
return myValue;
private object _myValue;
public object Value
{
get
{
return _myValue;
}
set {
if (!Equals(myValue,value)) {
myValue = value;
if (PropertyChanged!=null) {
set
{
if (!Equals(_myValue, value))
{
_myValue = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Value"));
}
}
}
}
public FieldType FieldType;
public string Scope;
public IFieldType FieldType
{
get;
set;
}
public string Scope
{
get;
set;
}
/// <summary>
/// Constructs a new Field instance, usually you should be using FieldFactory
@ -59,21 +76,25 @@ namespace Greenshot.Drawing.Fields {
/// When scope is set to a Type (e.g. typeof(RectangleContainer)), its value
/// should not be reused for FieldHolders of another Type (e.g. typeof(EllipseContainer))
/// </param>
public Field(FieldType fieldType, Type scope) {
public Field(IFieldType fieldType, Type scope)
{
FieldType = fieldType;
Scope = scope.Name;
}
public Field(FieldType fieldType, string scope) {
public Field(IFieldType fieldType, string scope)
{
FieldType = fieldType;
Scope = scope;
}
public Field(FieldType fieldType) {
public Field(IFieldType fieldType)
{
FieldType = fieldType;
}
/// <summary>
/// Returns true if this field holds a value other than null.
/// </summary>
public bool HasValue {
public bool HasValue
{
get { return Value != null; }
}
@ -81,15 +102,18 @@ namespace Greenshot.Drawing.Fields {
/// Creates a flat clone of this Field. The fields value itself is not cloned.
/// </summary>
/// <returns></returns>
public Field Clone() {
public Field Clone()
{
Field ret = new Field(FieldType, Scope);
ret.Value = Value;
return ret;
}
public override int GetHashCode() {
public override int GetHashCode()
{
int hashCode = 0;
unchecked {
unchecked
{
hashCode += 1000000009 * FieldType.GetHashCode();
if (Scope != null)
hashCode += 1000000021 * Scope.GetHashCode();
@ -97,32 +121,19 @@ namespace Greenshot.Drawing.Fields {
return hashCode;
}
public override bool Equals(object obj) {
public override bool Equals(object obj)
{
Field other = obj as Field;
if (other == null) {
if (other == null)
{
return false;
}
return FieldType == other.FieldType && Equals(Scope, other.Scope);
}
public override string ToString() {
return string.Format("[Field FieldType={1} Value={0} Scope={2}]", myValue, FieldType, Scope);
}
}
/// <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;
public override string ToString()
{
return string.Format("[Field FieldType={1} Value={0} Scope={2}]", _myValue, FieldType, Scope);
}
}
}

View file

@ -19,15 +19,18 @@
* 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.ComponentModel;
using Greenshot.Configuration;
using Greenshot.IniFile;
using Greenshot.Plugin.Drawing;
using log4net;
namespace Greenshot.Drawing.Fields {
namespace Greenshot.Drawing.Fields
{
/// <summary>
/// Represents the current set of properties for the editor.
/// When one of EditorProperties' properties is updated, the change will be promoted
@ -39,9 +42,10 @@ namespace Greenshot.Drawing.Fields {
/// Properties that do not apply for ALL selected elements are null (or 0 respectively)
/// If the property values of the selected elements differ, the value of the last bound element wins.
/// </summary>
public class FieldAggregator : AbstractFieldHolder {
public class FieldAggregator : AbstractFieldHolder
{
private List<IDrawableContainer> boundContainers;
private IDrawableContainerList boundContainers;
private bool internalUpdateRunning = false;
enum Status { IDLE, BINDING, UPDATING };
@ -49,28 +53,36 @@ namespace Greenshot.Drawing.Fields {
private static readonly ILog LOG = LogManager.GetLogger(typeof(FieldAggregator));
private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>();
public FieldAggregator() {
foreach(FieldType fieldType in FieldType.Values) {
public FieldAggregator(ISurface parent)
{
foreach (FieldType fieldType in FieldType.Values)
{
Field field = new Field(fieldType, GetType());
AddField(field);
}
boundContainers = new List<IDrawableContainer>();
boundContainers = new DrawableContainerList();
boundContainers.Parent = parent;
}
public override void AddField(Field field) {
public override void AddField(IField field)
{
base.AddField(field);
field.PropertyChanged += OwnPropertyChanged;
}
public void BindElements(DrawableContainerList dcs) {
foreach(DrawableContainer dc in dcs) {
public void BindElements(IDrawableContainerList dcs)
{
foreach (DrawableContainer dc in dcs)
{
BindElement(dc);
}
}
public void BindElement(IDrawableContainer dc) {
public void BindElement(IDrawableContainer dc)
{
DrawableContainer container = dc as DrawableContainer;
if (container != null && !boundContainers.Contains(container)) {
if (container != null && !boundContainers.Contains(container))
{
boundContainers.Add(container);
container.ChildrenChanged += delegate {
UpdateFromBoundElements();
@ -79,19 +91,24 @@ namespace Greenshot.Drawing.Fields {
}
}
public void BindAndUpdateElement(IDrawableContainer dc) {
public void BindAndUpdateElement(IDrawableContainer dc)
{
UpdateElement(dc);
BindElement(dc);
}
public void UpdateElement(IDrawableContainer dc) {
public void UpdateElement(IDrawableContainer dc)
{
DrawableContainer container = dc as DrawableContainer;
if (container == null) {
if (container == null)
{
return;
}
internalUpdateRunning = true;
foreach(Field field in GetFields()) {
if (container.HasField(field.FieldType) && field.HasValue) {
foreach (Field field in GetFields())
{
if (container.HasField(field.FieldType) && field.HasValue)
{
//if(LOG.IsDebugEnabled) LOG.Debug(" "+field+ ": "+field.Value);
container.SetFieldValue(field.FieldType, field.Value);
}
@ -99,14 +116,17 @@ namespace Greenshot.Drawing.Fields {
internalUpdateRunning = false;
}
public void UnbindElement(IDrawableContainer dc) {
if (boundContainers.Contains(dc)) {
public void UnbindElement(IDrawableContainer dc)
{
if (boundContainers.Contains(dc))
{
boundContainers.Remove(dc);
UpdateFromBoundElements();
}
}
public void Clear() {
public void Clear()
{
ClearFields();
boundContainers.Clear();
UpdateFromBoundElements();
@ -115,9 +135,11 @@ namespace Greenshot.Drawing.Fields {
/// <summary>
/// sets all field values to null, however does not remove fields
/// </summary>
private void ClearFields() {
private void ClearFields()
{
internalUpdateRunning = true;
foreach(Field field in GetFields()) {
foreach (Field field in GetFields())
{
field.Value = null;
}
internalUpdateRunning = false;
@ -128,51 +150,66 @@ namespace Greenshot.Drawing.Fields {
/// 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.
/// </summary>
private void UpdateFromBoundElements() {
private void UpdateFromBoundElements()
{
ClearFields();
internalUpdateRunning = true;
foreach(Field field in FindCommonFields()) {
foreach (Field field in FindCommonFields())
{
SetFieldValue(field.FieldType, field.Value);
}
internalUpdateRunning = false;
}
private List<Field> FindCommonFields() {
List<Field> returnFields = null;
if (boundContainers.Count > 0) {
private IList<IField> FindCommonFields()
{
IList<IField> returnFields = null;
if (boundContainers.Count > 0)
{
// take all fields from the least selected container...
DrawableContainer leastSelectedContainer = boundContainers[boundContainers.Count - 1] as DrawableContainer;
if (leastSelectedContainer != null) {
if (leastSelectedContainer != null)
{
returnFields = leastSelectedContainer.GetFields();
for (int i = 0; i < boundContainers.Count - 1; i++) {
for (int i = 0; i < boundContainers.Count - 1; i++)
{
DrawableContainer dc = boundContainers[i] as DrawableContainer;
if (dc != null) {
List<Field> fieldsToRemove = new List<Field>();
foreach (Field f in returnFields) {
if (dc != null)
{
IList<IField> fieldsToRemove = new List<IField>();
foreach (IField field in returnFields)
{
// ... throw out those that do not apply to one of the other containers
if (!dc.HasField(f.FieldType)) {
fieldsToRemove.Add(f);
if (!dc.HasField(field.FieldType))
{
fieldsToRemove.Add(field);
}
}
foreach (Field f in fieldsToRemove) {
returnFields.Remove(f);
foreach (IField field in fieldsToRemove)
{
returnFields.Remove(field);
}
}
}
}
}
if (returnFields == null) {
returnFields = new List<Field>();
if (returnFields == null)
{
returnFields = new List<IField>();
}
return returnFields;
}
public void OwnPropertyChanged(object sender, PropertyChangedEventArgs ea) {
Field field = (Field) sender;
if (!internalUpdateRunning && field.Value != null) {
foreach(DrawableContainer drawableContainer in boundContainers) {
if (drawableContainer.HasField(field.FieldType)) {
Field drawableContainerField = drawableContainer.GetField(field.FieldType);
public void OwnPropertyChanged(object sender, PropertyChangedEventArgs ea)
{
IField field = (IField)sender;
if (!internalUpdateRunning && field.Value != null)
{
foreach (DrawableContainer drawableContainer in boundContainers)
{
if (drawableContainer.HasField(field.FieldType))
{
IField drawableContainerField = drawableContainer.GetField(field.FieldType);
// Notify before change, so we can e.g. invalidate the area
drawableContainer.BeforeFieldChange(drawableContainerField, field.Value);

View file

@ -18,38 +18,41 @@
* 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 GreenshotPlugin.Interfaces.Drawing;
using System;
namespace Greenshot.Drawing.Fields {
namespace Greenshot.Drawing.Fields
{
/// <summary>
/// Defines all FieldTypes + their default value.
/// (The additional value is why this is not an enum)
/// </summary>
[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 FieldType BRIGHTNESS = new FieldType("BRIGHTNESS");
public static readonly FieldType FILL_COLOR = new FieldType("FILL_COLOR");
public static readonly FieldType FONT_BOLD = new FieldType("FONT_BOLD");
public static readonly FieldType FONT_FAMILY = new FieldType("FONT_FAMILY");
public static readonly FieldType FONT_ITALIC = new FieldType("FONT_ITALIC");
public static readonly FieldType FONT_SIZE = new FieldType("FONT_SIZE");
public static readonly FieldType TEXT_HORIZONTAL_ALIGNMENT = new FieldType("TEXT_HORIZONTAL_ALIGNMENT");
public static readonly FieldType TEXT_VERTICAL_ALIGNMENT = new FieldType("TEXT_VERTICAL_ALIGNMENT");
public static readonly FieldType HIGHLIGHT_COLOR = new FieldType("HIGHLIGHT_COLOR");
public static readonly FieldType LINE_COLOR = new FieldType("LINE_COLOR");
public static readonly FieldType LINE_THICKNESS = new FieldType("LINE_THICKNESS");
public static readonly FieldType MAGNIFICATION_FACTOR = new FieldType("MAGNIFICATION_FACTOR");
public static readonly FieldType PIXEL_SIZE = new FieldType("PIXEL_SIZE");
public static readonly FieldType PREVIEW_QUALITY = new FieldType("PREVIEW_QUALITY");
public static readonly FieldType SHADOW = new FieldType("SHADOW");
public static readonly FieldType PREPARED_FILTER_OBFUSCATE = new FieldType("PREPARED_FILTER_OBFUSCATE");
public static readonly FieldType PREPARED_FILTER_HIGHLIGHT = new FieldType("PREPARED_FILTER_HIGHLIGHT");
public static readonly FieldType FLAGS = new FieldType("FLAGS");
public static readonly IFieldType ARROWHEADS = new FieldType("ARROWHEADS");
public static readonly IFieldType BLUR_RADIUS = new FieldType("BLUR_RADIUS");
public static readonly IFieldType BRIGHTNESS = new FieldType("BRIGHTNESS");
public static readonly IFieldType FILL_COLOR = new FieldType("FILL_COLOR");
public static readonly IFieldType FONT_BOLD = new FieldType("FONT_BOLD");
public static readonly IFieldType FONT_FAMILY = new FieldType("FONT_FAMILY");
public static readonly IFieldType FONT_ITALIC = new FieldType("FONT_ITALIC");
public static readonly IFieldType FONT_SIZE = new FieldType("FONT_SIZE");
public static readonly IFieldType TEXT_HORIZONTAL_ALIGNMENT = new FieldType("TEXT_HORIZONTAL_ALIGNMENT");
public static readonly IFieldType TEXT_VERTICAL_ALIGNMENT = new FieldType("TEXT_VERTICAL_ALIGNMENT");
public static readonly IFieldType HIGHLIGHT_COLOR = new FieldType("HIGHLIGHT_COLOR");
public static readonly IFieldType LINE_COLOR = new FieldType("LINE_COLOR");
public static readonly IFieldType LINE_THICKNESS = new FieldType("LINE_THICKNESS");
public static readonly IFieldType MAGNIFICATION_FACTOR = new FieldType("MAGNIFICATION_FACTOR");
public static readonly IFieldType PIXEL_SIZE = new FieldType("PIXEL_SIZE");
public static readonly IFieldType PREVIEW_QUALITY = new FieldType("PREVIEW_QUALITY");
public static readonly IFieldType SHADOW = new FieldType("SHADOW");
public static readonly IFieldType PREPARED_FILTER_OBFUSCATE = new FieldType("PREPARED_FILTER_OBFUSCATE");
public static readonly IFieldType PREPARED_FILTER_HIGHLIGHT = new FieldType("PREPARED_FILTER_HIGHLIGHT");
public static readonly IFieldType FLAGS = new FieldType("FLAGS");
public static FieldType[] Values = new FieldType[]{
public static IFieldType[] Values = new IFieldType[]{
ARROWHEADS,
BLUR_RADIUS,
BRIGHTNESS,
@ -72,24 +75,25 @@ namespace Greenshot.Drawing.Fields {
FLAGS
};
[Flags]
public enum Flag {
NONE = 0,
CONFIRMABLE = 1
public string Name
{
get;
set;
}
public string Name;
private FieldType(string name) {
private FieldType(string name)
{
Name = name;
}
public override string ToString() {
public override string ToString()
{
return Name;
}
public override int GetHashCode()
{
int hashCode = 0;
unchecked {
unchecked
{
if (Name != null)
hashCode += 1000000009 * Name.GetHashCode();
}
@ -100,19 +104,20 @@ namespace Greenshot.Drawing.Fields {
{
FieldType other = obj as FieldType;
if (other == null)
{
return false;
}
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);
}
public static bool operator !=(FieldType a, FieldType b) {
public static bool operator !=(FieldType a, FieldType b)
{
return !Equals(a, b);
}
}
}

View file

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

View file

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

View file

@ -18,6 +18,7 @@
* 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 System;
using System.Drawing;
using Greenshot.Drawing.Fields;
@ -25,13 +26,10 @@ using Greenshot.Plugin.Drawing;
using GreenshotPlugin.Core;
using GreenshotPlugin.UnmanagedHelpers;
using System.Drawing.Drawing2D;
using log4net;
namespace Greenshot.Drawing.Filters {
[Serializable()]
public class BlurFilter : AbstractFilter {
private static ILog LOG = LogManager.GetLogger(typeof(BlurFilter));
public double previewQuality;
public double PreviewQuality {
get { return previewQuality; }
@ -43,7 +41,7 @@ namespace Greenshot.Drawing.Filters {
AddField(GetType(), FieldType.PREVIEW_QUALITY, 1.0d);
}
public unsafe override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode) {
public override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode) {
int blurRadius = GetFieldValueAsInt(FieldType.BLUR_RADIUS);
Rectangle applyRect = ImageHelper.CreateIntersectRectangle(applyBitmap.Size, rect, Invert);
if (applyRect.Width == 0 || applyRect.Height == 0) {
@ -54,7 +52,7 @@ namespace Greenshot.Drawing.Filters {
graphics.SetClip(applyRect);
graphics.ExcludeClip(rect);
}
if (GDIplus.isBlurPossible(blurRadius)) {
if (GDIplus.IsBlurPossible(blurRadius)) {
GDIplus.DrawWithBlur(graphics, applyBitmap, applyRect, null, null, blurRadius, false);
} else {
using (IFastBitmap fastBitmap = FastBitmap.CreateCloneOf(applyBitmap, applyRect)) {
@ -63,7 +61,6 @@ namespace Greenshot.Drawing.Filters {
}
}
graphics.Restore(state);
return;
}
}
}

View file

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

View file

@ -53,7 +53,7 @@ namespace Greenshot.Drawing.Filters {
int halfHeight = rect.Height / 2;
int newWidth = rect.Width / magnificationFactor;
int newHeight = rect.Height / magnificationFactor;
Rectangle source = new Rectangle(rect.X + halfWidth - (newWidth / 2), rect.Y + halfHeight - (newHeight / 2), newWidth, newHeight);
Rectangle source = new Rectangle(rect.X + halfWidth - newWidth / 2, rect.Y + halfHeight - newHeight / 2, newWidth, newHeight);
graphics.DrawImage(applyBitmap, rect, source, GraphicsUnit.Pixel);
graphics.Restore(state);
}

View file

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

View file

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

View file

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

View file

@ -24,6 +24,7 @@ using System.IO;
using Greenshot.Plugin.Drawing;
using System.Drawing.Drawing2D;
using log4net;
using System.Runtime.Serialization;
namespace Greenshot.Drawing {
/// <summary>
@ -31,11 +32,23 @@ namespace Greenshot.Drawing {
/// </summary>
[Serializable]
public class IconContainer : DrawableContainer, IIconContainer {
private static ILog LOG = LogManager.GetLogger(typeof(IconContainer));
private static readonly ILog LOG = LogManager.GetLogger(typeof(IconContainer));
protected Icon icon;
public IconContainer(Surface parent) : base(parent) {
Init();
}
protected override void OnDeserialized(StreamingContext streamingContext)
{
base.OnDeserialized(streamingContext);
Init();
}
private void Init()
{
CreateDefaultAdorners();
}
public IconContainer(Surface parent, string filename) : base(parent) {

View file

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

View file

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

View file

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

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.Helpers;
using Greenshot.Plugin.Drawing;
using System.Runtime.Serialization;
namespace Greenshot.Drawing {
/// <summary>
@ -34,6 +35,22 @@ namespace Greenshot.Drawing {
public class RectangleContainer : DrawableContainer {
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() {
@ -69,7 +86,7 @@ namespace Greenshot.Drawing {
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.None;
bool lineVisible = (lineThickness > 0 && Colors.IsVisible(lineColor));
bool lineVisible = lineThickness > 0 && Colors.IsVisible(lineColor);
if (shadow && (lineVisible || Colors.IsVisible(fillColor))) {
//draw shadow first
int basealpha = 100;
@ -86,7 +103,7 @@ namespace Greenshot.Drawing {
rect.Height);
graphics.DrawRectangle(shadowPen, shadowRect);
currentStep++;
alpha = alpha - (basealpha / steps);
alpha = alpha - basealpha / steps;
}
}
}

View file

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

View file

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

View file

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

File diff suppressed because it is too large Load diff

View file

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

View file

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

View file

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

View file

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

View file

@ -22,11 +22,10 @@ using System;
using System.Drawing;
using System.Windows.Forms;
using Greenshot.Core;
using GreenshotPlugin.Core;
namespace Greenshot.Forms {
public partial class DropShadowSettingsForm : BaseForm {
private DropShadowEffect effect;
private readonly DropShadowEffect effect;
public DropShadowSettingsForm(DropShadowEffect effect) {
this.effect = effect;
@ -50,10 +49,5 @@ namespace Greenshot.Forms {
effect.ShadowSize = (int)thickness.Value;
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.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.obfuscateModeButton,
this.highlightModeButton,

File diff suppressed because it is too large Load diff

View file

@ -29,9 +29,9 @@ namespace Greenshot.Forms {
/// Description of LanguageDialog.
/// </summary>
public partial class LanguageDialog : Form {
private static ILog LOG = LogManager.GetLogger(typeof(LanguageDialog));
private static readonly ILog LOG = LogManager.GetLogger(typeof(LanguageDialog));
private static LanguageDialog uniqueInstance;
private bool properOkPressed = false;
private bool properOkPressed;
private LanguageDialog() {
//

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,7 +1,8 @@

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

View file

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

View file

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

View file

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

View file

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

View file

@ -37,9 +37,9 @@ namespace Greenshot.Helpers {
//Our end result
int result = 0;
//Take x2-x1, then square it
double part1 = Math.Pow((x2 - x1), 2);
double part1 = Math.Pow(x2 - x1, 2);
//Take y2-y1, then square it
double part2 = Math.Pow((y2 - y1), 2);
double part2 = Math.Pow(y2 - y1, 2);
//Add both of the parts together
double underRadical = part1 + part2;
//Get the square root of the parts

View file

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

View file

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

View file

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

View file

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

View file

@ -37,10 +37,10 @@ namespace Greenshot.Helpers {
/// </summary>
public class PrintHelper : IDisposable {
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 ICaptureDetails captureDetails;
private readonly ICaptureDetails captureDetails;
private PrintDocument printDocument = new PrintDocument();
private PrintDialog printDialog = new PrintDialog();
@ -218,7 +218,7 @@ namespace Greenshot.Helpers {
if (conf.OutputPrintFooter) {
//printRect = new RectangleF(0, 0, printRect.Width, printRect.Height - (dateStringHeight * 2));
using (Font f = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular)) {
e.Graphics.DrawString(footerString, f, Brushes.Black, pageRect.Width / 2 - (footerStringWidth / 2), pageRect.Height);
e.Graphics.DrawString(footerString, f, Brushes.Black, pageRect.Width / 2 - footerStringWidth / 2, pageRect.Height);
}
}
e.Graphics.DrawImage(image, printRect, imageRect, GraphicsUnit.Pixel);

View file

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

View file

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

View file

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

View file

@ -35,7 +35,7 @@ namespace Greenshot.Experimental {
/// </summary>
public static class 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 VERSION_HISTORY_LINK = "http://getgreenshot.org/version-history/";
private static readonly object LockObject = new object();

View file

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

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

View file

@ -29,7 +29,7 @@ namespace Greenshot.Memento {
/// </summary>
public class DeleteElementMemento : IMemento {
private IDrawableContainer drawableContainer;
private Surface surface;
private readonly Surface surface;
public DeleteElementMemento(Surface surface, IDrawableContainer drawableContainer) {
this.surface = surface;
@ -50,13 +50,6 @@ namespace Greenshot.Memento {
}
}
public LangKey ActionLanguageKey {
get {
//return LangKey.editor_deleteelement;
return LangKey.none;
}
}
public bool Merge(IMemento otherMemento) {
return false;
}

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
* 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.Drawing;
using Greenshot.Configuration;
using Greenshot.Plugin.Drawing;
using GreenshotPlugin.Core;
namespace Greenshot.Memento {
namespace Greenshot.Memento
{
/// <summary>
/// The DrawableContainerBoundsChangeMemento makes it possible to undo-redo an IDrawableContainer resize & move
/// </summary>
public class DrawableContainerBoundsChangeMemento : IMemento {
public class DrawableContainerBoundsChangeMemento : IMemento
{
List<Point> points = new List<Point>();
List<Size> sizes = new List<Size>();
List<IDrawableContainer> listOfdrawableContainer;
IDrawableContainerList listOfdrawableContainer;
private void StoreBounds() {
foreach(IDrawableContainer drawableContainer in listOfdrawableContainer) {
private void StoreBounds()
{
foreach (IDrawableContainer drawableContainer in listOfdrawableContainer)
{
points.Add(drawableContainer.Location);
sizes.Add(drawableContainer.Size);
}
}
public DrawableContainerBoundsChangeMemento(List<IDrawableContainer> listOfdrawableContainer) {
public DrawableContainerBoundsChangeMemento(IDrawableContainerList listOfdrawableContainer)
{
this.listOfdrawableContainer = listOfdrawableContainer;
StoreBounds();
}
public DrawableContainerBoundsChangeMemento(IDrawableContainer drawableContainer) {
listOfdrawableContainer = new List<IDrawableContainer>();
public DrawableContainerBoundsChangeMemento(IDrawableContainer drawableContainer)
{
listOfdrawableContainer = new DrawableContainerList();
listOfdrawableContainer.Add(drawableContainer);
listOfdrawableContainer.Parent = drawableContainer.Parent;
StoreBounds();
}
public void Dispose() {
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) {
// if (disposing) { }
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (listOfdrawableContainer != null)
{
listOfdrawableContainer.Dispose();
}
}
listOfdrawableContainer = null;
}
public LangKey ActionLanguageKey {
get {
return LangKey.none;
}
}
public bool Merge(IMemento otherMemento) {
DrawableContainerBoundsChangeMemento other = otherMemento as DrawableContainerBoundsChangeMemento;
if (other != null) {
if (Objects.CompareLists<IDrawableContainer>(listOfdrawableContainer, other.listOfdrawableContainer)) {
public bool Merge(IMemento otherMemento)
{
var 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
return true;
}
@ -80,9 +89,11 @@ namespace Greenshot.Memento {
return false;
}
public IMemento Restore() {
DrawableContainerBoundsChangeMemento oldState = new DrawableContainerBoundsChangeMemento(listOfdrawableContainer);
for(int index = 0; index < listOfdrawableContainer.Count; index++) {
public IMemento Restore()
{
var oldState = new DrawableContainerBoundsChangeMemento(listOfdrawableContainer);
for (int index = 0; index < listOfdrawableContainer.Count; index++)
{
IDrawableContainer drawableContainer = listOfdrawableContainer[index];
// Before
drawableContainer.Invalidate();

View file

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

View file

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

View file

@ -32,8 +32,8 @@ namespace Greenshot.Processors {
/// Description of TitleFixProcessor.
/// </summary>
public class TitleFixProcessor : AbstractProcessor {
private static ILog LOG = LogManager.GetLogger(typeof(TitleFixProcessor));
private static CoreConfiguration config = IniConfig.GetIniSection<CoreConfiguration>();
private static readonly ILog LOG = LogManager.GetLogger(typeof(TitleFixProcessor));
private static readonly CoreConfiguration config = IniConfig.GetIniSection<CoreConfiguration>();
public TitleFixProcessor() {
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:
This is a pre-release for the comming bug-fix release of Greenshot.
This version has changes, compared to 1.2.8.12, for the following reported tickets:
* BUG-1884: OCR has trailing blank spaces|
* BUG-1890: Slight cropping around window on Windows 10|
* BUG-1892: Greenshot saves blank JPG file with reduce colors|
* BUG-1898: Specify GPLv3 in the license text|
* BUG-1918: Speechbubble issue: Artifacts appeared when shadow is on and transparency is used|
* BUG-1933: Greenshot Installer sets bad registry key permission|
* BUG-1935: Delay when pasting and ShapeShifter from FlameFusion is running|
* BUG-1941: Error when creating speech bubble|
* BUG-1945: Failure starting Greenshot at system startup|
* BUG-1949: Can't delete Imgur upload
* BUG-1965: Activation border around window is visible in the capture
* FEATURE-945: Added environment variables to the external command
Testing is not finished, use at your own risk...
1.2.8.12 Release
Bugs Resolved:
BUG-1527 / BUG-1848 / BUG-1850 / BUG-1851 / BUG-1859 : Greenshot stops responding, hangs or crashes

View file

@ -18,7 +18,6 @@
* 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 System;
namespace GreenshotBoxPlugin {
/// <summary>

View file

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

View file

@ -18,20 +18,14 @@
* 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 System;
using System.Drawing;
using System.Windows.Forms;
using GreenshotBoxPlugin.Forms;
using GreenshotPlugin.Core;
namespace GreenshotBoxPlugin {
/// <summary>
/// Description of PasswordRequestForm.
/// </summary>
public partial class SettingsForm : BoxForm {
string boxTicket = string.Empty;
public SettingsForm(BoxConfiguration config) {
//
// The InitializeComponent() call is required for Windows Forms designer support.

View file

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

View file

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

View file

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

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