Code quality changes

This commit is contained in:
Robin 2016-09-22 20:40:13 +02:00
commit 610f45d082
189 changed files with 4609 additions and 5203 deletions

View file

@ -45,13 +45,7 @@ namespace Greenshot.Drawing.Adorners
/// <summary>
/// Returns the cursor for when the mouse is over the adorner
/// </summary>
public override Cursor Cursor
{
get
{
return Cursors.SizeAll;
}
}
public override Cursor Cursor => Cursors.SizeAll;
/// <summary>
/// Handle the mouse down
@ -147,7 +141,6 @@ namespace Greenshot.Drawing.Adorners
public override void Paint(PaintEventArgs paintEventArgs)
{
Graphics targetGraphics = paintEventArgs.Graphics;
Rectangle clipRectangle = paintEventArgs.ClipRectangle;
var bounds = Bounds;
GraphicsState state = targetGraphics.Save();

View file

@ -168,7 +168,6 @@ namespace Greenshot.Drawing.Adorners
public override void Paint(PaintEventArgs paintEventArgs)
{
Graphics targetGraphics = paintEventArgs.Graphics;
Rectangle clipRectangle = paintEventArgs.ClipRectangle;
var bounds = Bounds;
GraphicsState state = targetGraphics.Save();

View file

@ -95,7 +95,6 @@ namespace Greenshot.Drawing.Adorners
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);

View file

@ -383,12 +383,12 @@ namespace Greenshot.Drawing
Rectangle drawingRect = new Rectangle(Bounds.Location, Bounds.Size);
drawingRect.Intersect(clipRectangle);
if(filter is MagnifierFilter) {
// quick&dirty bugfix, because MagnifierFilter behaves differently when drawn only partially
// what we should actually do to resolve this is add a better magnifier which is not that special
filter.Apply(graphics, bmp, Bounds, renderMode);
} else {
filter.Apply(graphics, bmp, drawingRect, renderMode);
}
// quick&dirty bugfix, because MagnifierFilter behaves differently when drawn only partially
// what we should actually do to resolve this is add a better magnifier which is not that special
filter.Apply(graphics, bmp, Bounds, renderMode);
} else {
filter.Apply(graphics, bmp, drawingRect, renderMode);
}
}
}
}
@ -517,7 +517,7 @@ namespace Greenshot.Drawing
/// <param name="e"></param>
public void HandleFieldChanged(object sender, FieldChangedEventArgs e) {
LOG.DebugFormat("Field {0} changed", e.Field.FieldType);
if (e.Field.FieldType == FieldType.SHADOW) {
if (Equals(e.Field.FieldType, FieldType.SHADOW)) {
accountForShadowChange = true;
}
}

View file

@ -20,6 +20,7 @@
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.Serialization;
@ -37,52 +38,55 @@ namespace Greenshot.Drawing.Fields
public abstract class AbstractFieldHolder : IFieldHolder
{
private static readonly ILog LOG = LogManager.GetLogger(typeof(AbstractFieldHolder));
private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>();
private static readonly EditorConfiguration EditorConfig = IniConfig.GetIniSection<EditorConfiguration>();
private readonly IDictionary<IField, PropertyChangedEventHandler> _handlers = new Dictionary<IField, PropertyChangedEventHandler>();
/// <summary>
/// called when a field's value has changed
/// </summary>
[NonSerialized]
private FieldChangedEventHandler fieldChanged;
private FieldChangedEventHandler _fieldChanged;
public event FieldChangedEventHandler FieldChanged
{
add { fieldChanged += value; }
remove { fieldChanged -= value; }
add { _fieldChanged += value; }
remove { _fieldChanged -= value; }
}
// we keep two Collections of our fields, dictionary for quick access, list for serialization
// this allows us to use default serialization
[NonSerialized]
private IDictionary<IFieldType, IField> fieldsByType = new Dictionary<IFieldType, IField>();
private IList<IField> fields = new List<IField>();
public AbstractFieldHolder() { }
private IDictionary<IFieldType, IField> _fieldsByType = new Dictionary<IFieldType, IField>();
private readonly IList<IField> fields = new List<IField>();
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
fieldsByType = new Dictionary<IFieldType, IField>();
_fieldsByType = new Dictionary<IFieldType, IField>();
// listen to changing properties
foreach (Field field in fields)
foreach (var field in fields)
{
field.PropertyChanged += delegate {
if (fieldChanged != null)
{
fieldChanged(this, new FieldChangedEventArgs(field));
}
_fieldChanged?.Invoke(this, new FieldChangedEventArgs(field));
};
fieldsByType[field.FieldType] = field;
_fieldsByType[field.FieldType] = field;
}
}
public void AddField(Type requestingType, IFieldType fieldType, object fieldValue)
{
AddField(editorConfiguration.CreateField(requestingType, fieldType, fieldValue));
AddField(EditorConfig.CreateField(requestingType, fieldType, fieldValue));
}
public virtual void AddField(IField field)
{
if (fieldsByType != null && fieldsByType.ContainsKey(field.FieldType))
fields.Add(field);
if (_fieldsByType == null)
{
return;
}
if (_fieldsByType.ContainsKey(field.FieldType))
{
if (LOG.IsDebugEnabled)
{
@ -90,21 +94,21 @@ namespace Greenshot.Drawing.Fields
}
}
fields.Add(field);
fieldsByType[field.FieldType] = field;
field.PropertyChanged += delegate { if (fieldChanged != null) fieldChanged(this, new FieldChangedEventArgs(field)); };
_fieldsByType[field.FieldType] = field;
_handlers[field] = (sender, args) =>
{
_fieldChanged?.Invoke(this, new FieldChangedEventArgs(field));
};
field.PropertyChanged += _handlers[field];
}
public void RemoveField(IField field)
{
fields.Remove(field);
fieldsByType.Remove(field.FieldType);
field.PropertyChanged -= delegate {
if (fieldChanged != null)
{
fieldChanged(this, new FieldChangedEventArgs(field));
}
};
_fieldsByType.Remove(field.FieldType);
field.PropertyChanged -= _handlers[field];
_handlers.Remove(field);
}
public IList<IField> GetFields()
@ -117,7 +121,7 @@ namespace Greenshot.Drawing.Fields
{
try
{
return fieldsByType[fieldType];
return _fieldsByType[fieldType];
}
catch (KeyNotFoundException e)
{
@ -169,19 +173,19 @@ namespace Greenshot.Drawing.Fields
public bool HasField(IFieldType fieldType)
{
return fieldsByType.ContainsKey(fieldType);
return _fieldsByType.ContainsKey(fieldType);
}
public bool HasFieldValue(IFieldType fieldType)
{
return HasField(fieldType) && fieldsByType[fieldType].HasValue;
return HasField(fieldType) && _fieldsByType[fieldType].HasValue;
}
public void SetFieldValue(IFieldType fieldType, object value)
{
try
{
fieldsByType[fieldType].Value = value;
_fieldsByType[fieldType].Value = value;
}
catch (KeyNotFoundException e)
{
@ -191,10 +195,7 @@ namespace Greenshot.Drawing.Fields
protected void OnFieldChanged(object sender, FieldChangedEventArgs e)
{
if (fieldChanged != null)
{
fieldChanged(sender, e);
}
_fieldChanged?.Invoke(sender, e);
}
}
}

View file

@ -34,7 +34,7 @@ namespace Greenshot.Drawing.Fields
[Serializable()]
public abstract class AbstractFieldHolderWithChildren : AbstractFieldHolder
{
private FieldChangedEventHandler fieldChangedEventHandler;
private readonly FieldChangedEventHandler _fieldChangedEventHandler;
[NonSerialized]
private EventHandler childrenChanged;
@ -48,7 +48,7 @@ namespace Greenshot.Drawing.Fields
public AbstractFieldHolderWithChildren()
{
fieldChangedEventHandler = OnFieldChanged;
_fieldChangedEventHandler = OnFieldChanged;
}
[OnDeserialized()]
@ -57,28 +57,28 @@ namespace Greenshot.Drawing.Fields
// listen to changing properties
foreach (IFieldHolder fieldHolder in Children)
{
fieldHolder.FieldChanged += fieldChangedEventHandler;
fieldHolder.FieldChanged += _fieldChangedEventHandler;
}
if (childrenChanged != null) childrenChanged(this, EventArgs.Empty);
childrenChanged?.Invoke(this, EventArgs.Empty);
}
public void AddChild(IFieldHolder fieldHolder)
{
Children.Add(fieldHolder);
fieldHolder.FieldChanged += fieldChangedEventHandler;
if (childrenChanged != null) childrenChanged(this, EventArgs.Empty);
fieldHolder.FieldChanged += _fieldChangedEventHandler;
childrenChanged?.Invoke(this, EventArgs.Empty);
}
public void RemoveChild(IFieldHolder fieldHolder)
{
Children.Remove(fieldHolder);
fieldHolder.FieldChanged -= fieldChangedEventHandler;
if (childrenChanged != null) childrenChanged(this, EventArgs.Empty);
fieldHolder.FieldChanged -= _fieldChangedEventHandler;
childrenChanged?.Invoke(this, EventArgs.Empty);
}
public new IList<IField> GetFields()
{
List<IField> ret = new List<IField>();
var ret = new List<IField>();
ret.AddRange(base.GetFields());
foreach (IFieldHolder fh in Children)
{

View file

@ -129,7 +129,7 @@ namespace Greenshot.Drawing.Fields.Binding {
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?.GetType().Name ?? "")+"] on "+targetObject+". Probably other type than expected, IBindingCoverter to the rescue.", e);
}
}

View file

@ -47,10 +47,7 @@ namespace Greenshot.Drawing.Fields
if (!Equals(_myValue, value))
{
_myValue = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Value"));
}
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value"));
}
}
}
@ -93,10 +90,7 @@ namespace Greenshot.Drawing.Fields
/// <summary>
/// Returns true if this field holds a value other than null.
/// </summary>
public bool HasValue
{
get { return Value != null; }
}
public bool HasValue => Value != null;
/// <summary>
/// Creates a flat clone of this Field. The fields value itself is not cloned.
@ -104,9 +98,7 @@ namespace Greenshot.Drawing.Fields
/// <returns></returns>
public Field Clone()
{
Field ret = new Field(FieldType, Scope);
ret.Value = Value;
return ret;
return new Field(FieldType, Scope) {Value = Value};
}
public override int GetHashCode()
@ -123,7 +115,7 @@ namespace Greenshot.Drawing.Fields
public override bool Equals(object obj)
{
Field other = obj as Field;
var other = obj as Field;
if (other == null)
{
return false;

View file

@ -24,7 +24,6 @@ using Greenshot.IniFile;
using Greenshot.Plugin;
using Greenshot.Plugin.Drawing;
using GreenshotPlugin.Interfaces.Drawing;
using log4net;
using System.Collections.Generic;
using System.ComponentModel;
@ -41,26 +40,25 @@ 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 sealed class FieldAggregator : AbstractFieldHolder
{
private IDrawableContainerList boundContainers;
private bool internalUpdateRunning = false;
private readonly IDrawableContainerList _boundContainers;
private bool _internalUpdateRunning;
private enum Status { IDLE, BINDING, UPDATING };
private static readonly ILog LOG = LogManager.GetLogger(typeof(FieldAggregator));
private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>();
private static readonly EditorConfiguration EditorConfig = IniConfig.GetIniSection<EditorConfiguration>();
public FieldAggregator(ISurface parent)
{
foreach (FieldType fieldType in FieldType.Values)
foreach (var fieldType in FieldType.Values)
{
Field field = new Field(fieldType, GetType());
var field = new Field(fieldType, GetType());
AddField(field);
}
boundContainers = new DrawableContainerList();
boundContainers.Parent = parent;
_boundContainers = new DrawableContainerList
{
Parent = parent
};
}
public override void AddField(IField field)
@ -71,7 +69,7 @@ namespace Greenshot.Drawing.Fields
public void BindElements(IDrawableContainerList dcs)
{
foreach (DrawableContainer dc in dcs)
foreach (var dc in dcs)
{
BindElement(dc);
}
@ -80,14 +78,15 @@ namespace Greenshot.Drawing.Fields
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();
};
UpdateFromBoundElements();
return;
}
_boundContainers.Add(container);
container.ChildrenChanged += delegate {
UpdateFromBoundElements();
};
UpdateFromBoundElements();
}
public void BindAndUpdateElement(IDrawableContainer dc)
@ -103,8 +102,8 @@ namespace Greenshot.Drawing.Fields
{
return;
}
internalUpdateRunning = true;
foreach (Field field in GetFields())
_internalUpdateRunning = true;
foreach (var field in GetFields())
{
if (container.HasField(field.FieldType) && field.HasValue)
{
@ -112,14 +111,14 @@ namespace Greenshot.Drawing.Fields
container.SetFieldValue(field.FieldType, field.Value);
}
}
internalUpdateRunning = false;
_internalUpdateRunning = false;
}
public void UnbindElement(IDrawableContainer dc)
{
if (boundContainers.Contains(dc))
if (_boundContainers.Contains(dc))
{
boundContainers.Remove(dc);
_boundContainers.Remove(dc);
UpdateFromBoundElements();
}
}
@ -127,7 +126,7 @@ namespace Greenshot.Drawing.Fields
public void Clear()
{
ClearFields();
boundContainers.Clear();
_boundContainers.Clear();
UpdateFromBoundElements();
}
@ -136,12 +135,12 @@ namespace Greenshot.Drawing.Fields
/// </summary>
private void ClearFields()
{
internalUpdateRunning = true;
foreach (Field field in GetFields())
_internalUpdateRunning = true;
foreach (var field in GetFields())
{
field.Value = null;
}
internalUpdateRunning = false;
_internalUpdateRunning = false;
}
/// <summary>
@ -152,27 +151,27 @@ namespace Greenshot.Drawing.Fields
private void UpdateFromBoundElements()
{
ClearFields();
internalUpdateRunning = true;
_internalUpdateRunning = true;
foreach (var field in FindCommonFields())
{
SetFieldValue(field.FieldType, field.Value);
}
internalUpdateRunning = false;
_internalUpdateRunning = false;
}
private IList<IField> FindCommonFields()
{
IList<IField> returnFields = null;
if (boundContainers.Count > 0)
if (_boundContainers.Count > 0)
{
// take all fields from the least selected container...
DrawableContainer leastSelectedContainer = boundContainers[boundContainers.Count - 1] as DrawableContainer;
DrawableContainer leastSelectedContainer = _boundContainers[_boundContainers.Count - 1] as DrawableContainer;
if (leastSelectedContainer != null)
{
returnFields = leastSelectedContainer.GetFields();
for (int i = 0; i < boundContainers.Count - 1; i++)
for (int i = 0; i < _boundContainers.Count - 1; i++)
{
DrawableContainer dc = boundContainers[i] as DrawableContainer;
DrawableContainer dc = _boundContainers[i] as DrawableContainer;
if (dc != null)
{
IList<IField> fieldsToRemove = new List<IField>();
@ -184,7 +183,7 @@ namespace Greenshot.Drawing.Fields
fieldsToRemove.Add(field);
}
}
foreach (IField field in fieldsToRemove)
foreach (var field in fieldsToRemove)
{
returnFields.Remove(field);
}
@ -192,31 +191,30 @@ namespace Greenshot.Drawing.Fields
}
}
}
if (returnFields == null)
{
returnFields = new List<IField>();
}
return returnFields;
return returnFields ?? new List<IField>();
}
public void OwnPropertyChanged(object sender, PropertyChangedEventArgs ea)
{
IField field = (IField)sender;
if (!internalUpdateRunning && field.Value != null)
if (_internalUpdateRunning || field.Value == null)
{
foreach (DrawableContainer drawableContainer in boundContainers)
return;
}
foreach (var drawableContainer1 in _boundContainers)
{
var drawableContainer = (DrawableContainer) drawableContainer1;
if (!drawableContainer.HasField(field.FieldType))
{
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);
drawableContainerField.Value = field.Value;
// update last used from DC field, so that scope is honored
editorConfiguration.UpdateLastFieldValue(drawableContainerField);
}
continue;
}
IField drawableContainerField = drawableContainer.GetField(field.FieldType);
// Notify before change, so we can e.g. invalidate the area
drawableContainer.BeforeFieldChange(drawableContainerField, field.Value);
drawableContainerField.Value = field.Value;
// update last used from DC field, so that scope is honored
EditorConfig.UpdateLastFieldValue(drawableContainerField);
}
}

View file

@ -72,10 +72,9 @@ namespace Greenshot.Drawing.Filters {
public abstract void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode);
protected void OnPropertyChanged(string propertyName) {
if (propertyChanged != null) {
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
protected void OnPropertyChanged(string propertyName)
{
propertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}

View file

@ -34,7 +34,7 @@ namespace Greenshot.Drawing {
/// </summary>
[Serializable]
public class FreehandContainer : DrawableContainer {
private static readonly float [] POINT_OFFSET = new float[]{0.5f, 0.25f, 0.75f};
private static readonly float [] PointOffset = {0.5f, 0.25f, 0.75f};
[NonSerialized]
private GraphicsPath freehandPath = new GraphicsPath();
@ -77,10 +77,9 @@ namespace Greenshot.Drawing {
/// <param name="disposing">When disposing==true all non-managed resources should be freed too!</param>
protected override void Dispose(bool disposing) {
base.Dispose(disposing);
if (disposing) {
if (freehandPath != null) {
freehandPath.Dispose();
}
if (disposing)
{
freehandPath?.Dispose();
}
freehandPath = null;
}
@ -133,9 +132,7 @@ namespace Greenshot.Drawing {
private void RecalculatePath() {
isRecalculated = true;
// Dispose the previous path, if we have one
if (freehandPath != null) {
freehandPath.Dispose();
}
freehandPath?.Dispose();
freehandPath = new GraphicsPath();
// Here we can put some cleanup... like losing all the uninteresting points.
@ -143,7 +140,7 @@ namespace Greenshot.Drawing {
int index = 0;
while ((capturePoints.Count - 1) % 3 != 0) {
// duplicate points, first at 50% than 25% than 75%
capturePoints.Insert((int)(capturePoints.Count*POINT_OFFSET[index]), capturePoints[(int)(capturePoints.Count*POINT_OFFSET[index++])]);
capturePoints.Insert((int)(capturePoints.Count*PointOffset[index]), capturePoints[(int)(capturePoints.Count*PointOffset[index++])]);
}
freehandPath.AddBeziers(capturePoints.ToArray());
} else if (capturePoints.Count == 2) {
@ -228,9 +225,9 @@ namespace Greenshot.Drawing {
/// <returns></returns>
public override bool Equals(object obj) {
bool ret = false;
if(obj != null && GetType().Equals(obj.GetType())) {
if(obj != null && GetType() == obj.GetType()) {
FreehandContainer other = obj as FreehandContainer;
if(freehandPath.Equals(other.freehandPath)) {
if(other != null && freehandPath.Equals(other.freehandPath)) {
ret = true;
}
}

View file

@ -57,7 +57,7 @@ namespace Greenshot.Drawing {
if (!sender.Equals(this)) {
return;
}
if (e.Field.FieldType == FieldType.PREPARED_FILTER_HIGHLIGHT) {
if (Equals(e.Field.FieldType, FieldType.PREPARED_FILTER_HIGHLIGHT)) {
ConfigurePreparedFilters();
}
}
@ -72,12 +72,16 @@ namespace Greenshot.Drawing {
Add(new HighlightFilter(this));
break;
case PreparedFilter.AREA_HIGHLIGHT:
AbstractFilter bf = new BrightnessFilter(this);
bf.Invert = true;
Add(bf);
bf = new BlurFilter(this);
bf.Invert = true;
Add(bf);
var brightnessFilter = new BrightnessFilter(this)
{
Invert = true
};
Add(brightnessFilter);
var blurFilter = new BlurFilter(this)
{
Invert = true
};
Add(blurFilter);
break;
case PreparedFilter.GRAYSCALE:
AbstractFilter f = new GrayscaleFilter(this);

View file

@ -32,7 +32,7 @@ namespace Greenshot.Drawing {
/// </summary>
[Serializable]
public class IconContainer : DrawableContainer, IIconContainer {
private static readonly ILog LOG = LogManager.GetLogger(typeof(IconContainer));
private static readonly ILog Log = LogManager.GetLogger(typeof(IconContainer));
protected Icon icon;
@ -57,9 +57,7 @@ namespace Greenshot.Drawing {
public Icon Icon {
set {
if (icon != null) {
icon.Dispose();
}
icon?.Dispose();
icon = (Icon)value.Clone();
Width = value.Width;
Height = value.Height;
@ -72,10 +70,9 @@ namespace Greenshot.Drawing {
* When disposing==true all non-managed resources should be freed too!
*/
protected override void Dispose(bool disposing) {
if (disposing) {
if (icon != null) {
icon.Dispose();
}
if (disposing)
{
icon?.Dispose();
}
icon = null;
base.Dispose(disposing);
@ -85,7 +82,7 @@ namespace Greenshot.Drawing {
if (File.Exists(filename)) {
using (Icon fileIcon = new Icon(filename)) {
Icon = fileIcon;
LOG.Debug("Loaded file: " + filename + " with resolution: " + Height + "," + Width);
Log.Debug("Loaded file: " + filename + " with resolution: " + Height + "," + Width);
}
}
}
@ -100,16 +97,8 @@ namespace Greenshot.Drawing {
}
}
public override bool HasDefaultSize {
get {
return true;
}
}
public override bool HasDefaultSize => true;
public override Size DefaultSize {
get {
return icon.Size;
}
}
public override Size DefaultSize => icon.Size;
}
}

View file

@ -28,6 +28,7 @@ using System.Drawing.Drawing2D;
using Greenshot.Core;
using log4net;
using System.Runtime.Serialization;
using GreenshotPlugin.Effects;
using GreenshotPlugin.Interfaces.Drawing;
namespace Greenshot.Drawing {

View file

@ -52,7 +52,7 @@ namespace Greenshot.Drawing {
protected void ObfuscateContainer_OnFieldChanged(object sender, FieldChangedEventArgs e) {
if(sender.Equals(this)) {
if(e.Field.FieldType == FieldType.PREPARED_FILTER_OBFUSCATE) {
if(Equals(e.Field.FieldType, FieldType.PREPARED_FILTER_OBFUSCATE)) {
ConfigurePreparedFilters();
}
}

View file

@ -19,6 +19,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
@ -27,6 +28,7 @@ namespace Greenshot.Drawing {
/// TODO: currently this is only used in the capture form, we might move this code directly to there!
/// </summary>
public abstract class RoundedRectangle {
[Flags]
public enum RectangleCorners {
None = 0, TopLeft = 1, TopRight = 2,
BottomLeft = 4, BottomRight = 8,

View file

@ -84,9 +84,11 @@ namespace Greenshot.Drawing {
protected override void OnDeserialized(StreamingContext context)
{
Init();
_stringFormat = new StringFormat();
_stringFormat.Alignment = StringAlignment.Center;
_stringFormat.LineAlignment = StringAlignment.Center;
_stringFormat = new StringFormat
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
}
/// <summary>
@ -98,20 +100,14 @@ namespace Greenshot.Drawing {
{
return;
}
if (Parent != null) {
((Surface)Parent).RemoveStepLabel(this);
}
((Surface) Parent)?.RemoveStepLabel(this);
base.SwitchParent(newParent);
if (newParent != null) {
((Surface)Parent)?.AddStepLabel(this);
}
}
public override Size DefaultSize {
get {
return new Size(30, 30);
}
}
public override Size DefaultSize => new Size(30, 30);
public override bool InitContent() {
_defaultEditMode = EditStatus.IDLE;
@ -148,14 +144,13 @@ namespace Greenshot.Drawing {
if (!disposing) {
return;
}
if (Parent != null)
((Surface) Parent)?.RemoveStepLabel(this);
if (_stringFormat == null)
{
((Surface)Parent).RemoveStepLabel(this);
}
if (_stringFormat != null) {
_stringFormat.Dispose();
_stringFormat = null;
return;
}
_stringFormat.Dispose();
_stringFormat = null;
}
public override bool HandleMouseMove(int x, int y) {

View file

@ -40,6 +40,7 @@ using System.Drawing.Imaging;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
using GreenshotPlugin.Effects;
namespace Greenshot.Drawing
{
@ -48,9 +49,9 @@ namespace Greenshot.Drawing
/// </summary>
public sealed class Surface : Control, ISurface
{
private static ILog LOG = LogManager.GetLogger(typeof(Surface));
public static int Count = 0;
private static CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
private static readonly ILog LOG = LogManager.GetLogger(typeof(Surface));
public static int Count;
private static readonly CoreConfiguration conf = IniConfig.GetIniSection<CoreConfiguration>();
// Property to identify the Surface ID
private Guid _uniqueId = Guid.NewGuid();
@ -276,11 +277,6 @@ namespace Greenshot.Drawing
/// </summary>
private IDrawableContainer _cursorContainer;
/// <summary>
/// the capture details, needed with serialization
/// </summary>
private ICaptureDetails _captureDetails;
/// <summary>
/// the modified flag specifies if the surface has had modifications after the last export.
/// Initial state is modified, as "it's not saved"
@ -325,31 +321,19 @@ namespace Greenshot.Drawing
/// <summary>
/// The cursor container has it's own accessor so we can find and remove this (when needed)
/// </summary>
public IDrawableContainer CursorContainer
{
get
{
return _cursorContainer;
}
}
public IDrawableContainer CursorContainer => _cursorContainer;
/// <summary>
/// A simple getter to ask if this surface has a cursor
/// </summary>
public bool HasCursor
{
get
{
return _cursorContainer != null;
}
}
public bool HasCursor => _cursorContainer != null;
/// <summary>
/// A simple helper method to remove the cursor from the surface
/// </summary>
public void RemoveCursor()
{
RemoveElement(_cursorContainer, true);
RemoveElement(_cursorContainer);
_cursorContainer = null;
}
@ -409,8 +393,10 @@ namespace Greenshot.Drawing
_drawingMode = value;
if (_drawingModeChanged != null)
{
SurfaceDrawingModeEventArgs eventArgs = new SurfaceDrawingModeEventArgs();
eventArgs.DrawingMode = _drawingMode;
SurfaceDrawingModeEventArgs eventArgs = new SurfaceDrawingModeEventArgs
{
DrawingMode = _drawingMode
};
_drawingModeChanged.Invoke(this, eventArgs);
}
DeselectAllElements();
@ -445,22 +431,12 @@ namespace Greenshot.Drawing
/// <summary>
/// Property for accessing the capture details
/// </summary>
public ICaptureDetails CaptureDetails
{
get
{
return _captureDetails;
}
set
{
_captureDetails = value;
}
}
public ICaptureDetails CaptureDetails { get; set; }
/// <summary>
/// Base Surface constructor
/// </summary>
public Surface() : base()
public Surface()
{
_fieldAggregator = new FieldAggregator(this);
Count++;
@ -537,7 +513,7 @@ namespace Greenshot.Drawing
// Make sure the image is NOT disposed, we took the reference directly into ourselves
((Capture)capture).NullImage();
_captureDetails = capture.CaptureDetails;
CaptureDetails = capture.CaptureDetails;
}
protected override void Dispose(bool disposing)
@ -615,46 +591,22 @@ namespace Greenshot.Drawing
/// <summary>
/// Returns if the surface can do a undo
/// </summary>
public bool CanUndo
{
get
{
return _undoStack.Count > 0;
}
}
public bool CanUndo => _undoStack.Count > 0;
/// <summary>
/// Returns if the surface can do a redo
/// </summary>
public bool CanRedo
{
get
{
return _redoStack.Count > 0;
}
}
public bool CanRedo => _redoStack.Count > 0;
/// <summary>
/// Get the language key for the undo action
/// </summary>
public LangKey UndoActionLanguageKey
{
get
{
return LangKey.none;
}
}
public LangKey UndoActionLanguageKey => LangKey.none;
/// <summary>
/// Get the language key for redo action
/// </summary>
public LangKey RedoActionLanguageKey
{
get
{
return LangKey.none;
}
}
public LangKey RedoActionLanguageKey => LangKey.none;
/// <summary>
/// Make an action undo-able
@ -722,9 +674,7 @@ namespace Greenshot.Drawing
IDrawableContainerList loadedElements = (IDrawableContainerList)binaryRead.Deserialize(streamRead);
loadedElements.Parent = this;
// Make sure the steplabels are sorted accoring to their number
_stepLabels.Sort(delegate (StepLabelContainer p1, StepLabelContainer p2) {
return p1.Number.CompareTo(p2.Number);
});
_stepLabels.Sort((p1, p2) => p1.Number.CompareTo(p2.Number));
DeselectAllElements();
AddElements(loadedElements);
SelectElements(loadedElements);
@ -799,10 +749,12 @@ namespace Greenshot.Drawing
#region Plugin interface implementations
public IImageContainer AddImageContainer(Image image, int x, int y)
{
ImageContainer bitmapContainer = new ImageContainer(this);
bitmapContainer.Image = image;
bitmapContainer.Left = x;
bitmapContainer.Top = y;
ImageContainer bitmapContainer = new ImageContainer(this)
{
Image = image,
Left = x,
Top = y
};
AddElement(bitmapContainer);
return bitmapContainer;
}
@ -818,10 +770,12 @@ namespace Greenshot.Drawing
}
public IIconContainer AddIconContainer(Icon icon, int x, int y)
{
IconContainer iconContainer = new IconContainer(this);
iconContainer.Icon = icon;
iconContainer.Left = x;
iconContainer.Top = y;
IconContainer iconContainer = new IconContainer(this)
{
Icon = icon,
Left = x,
Top = y
};
AddElement(iconContainer);
return iconContainer;
}
@ -836,10 +790,12 @@ namespace Greenshot.Drawing
}
public ICursorContainer AddCursorContainer(Cursor cursor, int x, int y)
{
CursorContainer cursorContainer = new CursorContainer(this);
cursorContainer.Cursor = cursor;
cursorContainer.Left = x;
cursorContainer.Top = y;
CursorContainer cursorContainer = new CursorContainer(this)
{
Cursor = cursor,
Left = x,
Top = y
};
AddElement(cursorContainer);
return cursorContainer;
}
@ -855,8 +811,7 @@ namespace Greenshot.Drawing
public ITextContainer AddTextContainer(string text, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment, FontFamily family, float size, bool italic, bool bold, bool shadow, int borderSize, Color color, Color fillColor)
{
TextContainer textContainer = new TextContainer(this);
textContainer.Text = text;
TextContainer textContainer = new TextContainer(this) {Text = text};
textContainer.SetFieldValue(FieldType.FONT_FAMILY, family.Name);
textContainer.SetFieldValue(FieldType.FONT_BOLD, bold);
textContainer.SetFieldValue(FieldType.FONT_ITALIC, italic);
@ -1069,10 +1024,12 @@ namespace Greenshot.Drawing
{
if (_surfaceMessage != null)
{
SurfaceMessageEventArgs eventArgs = new SurfaceMessageEventArgs();
eventArgs.Message = message;
eventArgs.MessageType = messageType;
eventArgs.Surface = this;
var eventArgs = new SurfaceMessageEventArgs
{
Message = message,
MessageType = messageType,
Surface = this
};
_surfaceMessage(source, eventArgs);
}
}
@ -1133,10 +1090,7 @@ namespace Greenshot.Drawing
{
_elements.Transform(matrix);
}
if (_surfaceSizeChanged != null)
{
_surfaceSizeChanged(this, null);
}
_surfaceSizeChanged?.Invoke(this, null);
Invalidate();
}
/// <summary>
@ -1196,8 +1150,7 @@ namespace Greenshot.Drawing
IDrawableContainer rightClickedContainer = _elements.ClickableElementAt(_mouseStart.X, _mouseStart.Y);
if (rightClickedContainer != null)
{
selectedList = new DrawableContainerList(ID);
selectedList.Add(rightClickedContainer);
selectedList = new DrawableContainerList(ID) {rightClickedContainer};
}
}
if (selectedList != null && selectedList.Count > 0)
@ -1231,7 +1184,10 @@ namespace Greenshot.Drawing
// if a new element has been drawn, set location and register it
if (_drawingElement != null)
{
_drawingElement.Status = _undrawnElement.DefaultEditMode;
if (_undrawnElement != null)
{
_drawingElement.Status = _undrawnElement.DefaultEditMode;
}
if (!_drawingElement.HandleMouseDown(_mouseStart.X, _mouseStart.Y))
{
_drawingElement.Left = _mouseStart.X;
@ -1362,14 +1318,7 @@ namespace Greenshot.Drawing
Point currentMouse = e.Location;
if (DrawingMode != DrawingModes.None)
{
Cursor = Cursors.Cross;
}
else
{
Cursor = Cursors.Default;
}
Cursor = DrawingMode != DrawingModes.None ? Cursors.Cross : Cursors.Default;
if (_mouseDown)
{
@ -1597,8 +1546,7 @@ namespace Greenshot.Drawing
Invalidate();
if (_movingElementChanged != null)
{
SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs();
eventArgs.Elements = cloned;
SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs {Elements = cloned};
_movingElementChanged(this, eventArgs);
}
}
@ -1663,13 +1611,7 @@ namespace Greenshot.Drawing
/// Returns if this surface has selected elements
/// </summary>
/// <returns></returns>
public bool HasSelectedElements
{
get
{
return (selectedElements != null && selectedElements.Count > 0);
}
}
public bool HasSelectedElements => (selectedElements != null && selectedElements.Count > 0);
/// <summary>
/// Remove all the selected elements
@ -1764,29 +1706,14 @@ namespace Greenshot.Drawing
if (dcs != null)
{
// Make element(s) only move 10,10 if the surface is the same
Point moveOffset;
bool isSameSurface = (dcs.ParentID == _uniqueId);
dcs.Parent = this;
if (isSameSurface)
{
moveOffset = new Point(10, 10);
}
else
{
moveOffset = Point.Empty;
}
var moveOffset = isSameSurface ? new Point(10, 10) : Point.Empty;
// Here a fix for bug #1475, first calculate the bounds of the complete IDrawableContainerList
Rectangle drawableContainerListBounds = Rectangle.Empty;
foreach (IDrawableContainer element in dcs)
foreach (var element in dcs)
{
if (drawableContainerListBounds == Rectangle.Empty)
{
drawableContainerListBounds = element.DrawingBounds;
}
else
{
drawableContainerListBounds = Rectangle.Union(drawableContainerListBounds, element.DrawingBounds);
}
drawableContainerListBounds = drawableContainerListBounds == Rectangle.Empty ? element.DrawingBounds : Rectangle.Union(drawableContainerListBounds, element.DrawingBounds);
}
// And find a location inside the target surface to paste to
bool containersCanFit = drawableContainerListBounds.Width < Bounds.Width && drawableContainerListBounds.Height < Bounds.Height;
@ -1797,15 +1724,7 @@ namespace Greenshot.Drawing
if (!Bounds.Contains(containersLocation))
{
// Easy fix for same surface
if (isSameSurface)
{
moveOffset = new Point(-10, -10);
}
else
{
// For different surface, which is most likely smaller, we move to "10,10"
moveOffset = new Point(-drawableContainerListBounds.Location.X + 10, -drawableContainerListBounds.Location.Y + 10);
}
moveOffset = isSameSurface ? new Point(-10, -10) : new Point(-drawableContainerListBounds.Location.X + 10, -drawableContainerListBounds.Location.Y + 10);
}
}
else
@ -1932,8 +1851,10 @@ namespace Greenshot.Drawing
}
if (_movingElementChanged != null)
{
SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs();
eventArgs.Elements = selectedElements;
SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs
{
Elements = selectedElements
};
_movingElementChanged(this, eventArgs);
}
Invalidate();
@ -1962,8 +1883,10 @@ namespace Greenshot.Drawing
FieldAggregator.BindElement(container);
if (generateEvents && _movingElementChanged != null)
{
SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs();
eventArgs.Elements = selectedElements;
SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs
{
Elements = selectedElements
};
_movingElementChanged(this, eventArgs);
}
if (invalidate)
@ -1988,14 +1911,14 @@ namespace Greenshot.Drawing
public void SelectElements(IDrawableContainerList elements)
{
SuspendLayout();
foreach (DrawableContainer element in elements)
foreach (var drawableContainer in elements)
{
var element = (DrawableContainer) drawableContainer;
SelectElement(element, false, false);
}
if (_movingElementChanged != null)
{
SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs();
eventArgs.Elements = selectedElements;
SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs {Elements = selectedElements};
_movingElementChanged(this, eventArgs);
}
ResumeLayout();
@ -2070,13 +1993,7 @@ namespace Greenshot.Drawing
/// <summary>
/// Property for accessing the elements on the surface
/// </summary>
public IDrawableContainerList Elements
{
get
{
return _elements;
}
}
public IDrawableContainerList Elements => _elements;
/// <summary>
/// pulls selected elements up one level in hierarchy

View file

@ -26,6 +26,7 @@ using Greenshot.Plugin.Drawing;
using GreenshotPlugin.Interfaces.Drawing;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
@ -321,47 +322,47 @@ namespace Greenshot.Drawing
UpdateFormat();
}
private Font CreateFont(string fontFamily, bool fontBold, bool fontItalic, float fontSize)
private Font CreateFont(string fontFamilyName, bool fontBold, bool fontItalic, float fontSize)
{
FontStyle fs = FontStyle.Regular;
FontStyle fontStyle = FontStyle.Regular;
bool hasStyle = false;
using (FontFamily fam = new FontFamily(fontFamily))
using (var fontFamily = new FontFamily(fontFamilyName))
{
bool boldAvailable = fam.IsStyleAvailable(FontStyle.Bold);
bool boldAvailable = fontFamily.IsStyleAvailable(FontStyle.Bold);
if (fontBold && boldAvailable)
{
fs |= FontStyle.Bold;
fontStyle |= FontStyle.Bold;
hasStyle = true;
}
bool italicAvailable = fam.IsStyleAvailable(FontStyle.Italic);
bool italicAvailable = fontFamily.IsStyleAvailable(FontStyle.Italic);
if (fontItalic && italicAvailable)
{
fs |= FontStyle.Italic;
fontStyle |= FontStyle.Italic;
hasStyle = true;
}
if (!hasStyle)
{
bool regularAvailable = fam.IsStyleAvailable(FontStyle.Regular);
bool regularAvailable = fontFamily.IsStyleAvailable(FontStyle.Regular);
if (regularAvailable)
{
fs = FontStyle.Regular;
fontStyle = FontStyle.Regular;
}
else
{
if (boldAvailable)
{
fs = FontStyle.Bold;
fontStyle = FontStyle.Bold;
}
else if (italicAvailable)
{
fs = FontStyle.Italic;
fontStyle = FontStyle.Italic;
}
}
}
return new Font(fam, fontSize, fs, GraphicsUnit.Pixel);
return new Font(fontFamily, fontSize, fontStyle, GraphicsUnit.Pixel);
}
}
@ -400,7 +401,7 @@ namespace Greenshot.Drawing
catch (Exception)
{
// When this happens... the PC is broken
ex.Data.Add("fontFamily", fontFamily);
ex.Data.Add("fontFamilyName", fontFamily);
ex.Data.Add("fontBold", fontBold);
ex.Data.Add("fontItalic", fontItalic);
ex.Data.Add("fontSize", fontSize);
@ -534,6 +535,14 @@ namespace Greenshot.Drawing
/// <param name="font"></param>
public static void DrawText(Graphics graphics, Rectangle drawingRectange, int lineThickness, Color fontColor, bool drawShadow, StringFormat stringFormat, string text, Font font)
{
#if DEBUG
Debug.Assert(font != null);
#else
if (font == null)
{
return;
}
#endif
int textOffset = lineThickness > 0 ? (int)Math.Ceiling(lineThickness / 2d) : 0;
// draw shadow before anything else
if (drawShadow)