Small cleanups [skip ci]

This commit is contained in:
Robin 2016-04-17 23:32:22 +02:00
parent 02a06a12b0
commit 98e6be5eb6
171 changed files with 1607 additions and 1769 deletions

View file

@ -73,7 +73,7 @@ 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) {
string requestingTypeName = requestingType.Name;

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

@ -30,7 +30,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,14 +19,13 @@
* 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

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

@ -36,9 +36,9 @@ namespace Greenshot.Destinations {
public class EmailDestination : AbstractDestination {
private static ILog LOG = LogManager.GetLogger(typeof(EmailDestination));
private static CoreConfiguration conf = IniConfig.GetIniSection<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

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

View file

@ -33,7 +33,7 @@ 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;

View file

@ -46,10 +46,8 @@ namespace Greenshot.Drawing {
public abstract class DrawableContainer : AbstractFieldHolderWithChildren, IDrawableContainer {
private static readonly ILog LOG = LogManager.GetLogger(typeof(DrawableContainer));
protected static readonly EditorConfiguration EditorConfig = IniConfig.GetIniSection<EditorConfiguration>();
private bool isMadeUndoable;
private bool _isMadeUndoable;
private const int M11 = 0;
private const int M12 = 1;
private const int M21 = 2;
private const int M22 = 3;
@ -305,7 +303,7 @@ namespace Greenshot.Drawing {
Left = _parent.Width - Width - lineThickness/2;
}
if (horizontalAlignment == HorizontalAlignment.Center) {
Left = (_parent.Width / 2) - (Width / 2) - lineThickness/2;
Left = _parent.Width / 2 - Width / 2 - lineThickness/2;
}
if (verticalAlignment == VerticalAlignment.TOP) {
@ -315,7 +313,7 @@ namespace Greenshot.Drawing {
Top = _parent.Height - Height - lineThickness/2;
}
if (verticalAlignment == VerticalAlignment.CENTER) {
Top = (_parent.Height / 2) - (Height / 2) - lineThickness/2;
Top = _parent.Height / 2 - Height / 2 - lineThickness/2;
}
}
@ -455,7 +453,7 @@ namespace Greenshot.Drawing {
} else {
Status = EditStatus.MOVING;
}
isMadeUndoable = false;
_isMadeUndoable = false;
}
private void GripperMouseUp(object sender, MouseEventArgs e) {
@ -463,7 +461,7 @@ namespace Greenshot.Drawing {
if (originatingGripper != _targetGripper) {
_boundsBeforeResize = Rectangle.Empty;
_boundsAfterResize = RectangleF.Empty;
isMadeUndoable = false;
_isMadeUndoable = false;
}
Status = EditStatus.IDLE;
Invalidate();
@ -478,9 +476,9 @@ namespace Greenshot.Drawing {
TargetGripperMove(absX, absY);
} else if (Status.Equals(EditStatus.RESIZING)) {
// check if we already made this undoable
if (!isMadeUndoable) {
if (!_isMadeUndoable) {
// don't allow another undo until we are finished with this move
isMadeUndoable = true;
_isMadeUndoable = true;
// Make undo-able
MakeBoundsChangeUndoable(false);
}
@ -699,6 +697,8 @@ namespace Greenshot.Drawing {
}
public override int GetHashCode() {
// TODO: This actually doesn't make sense...
// Place the container in a list, and you can't find it :)
return left.GetHashCode() ^ top.GetHashCode() ^ width.GetHashCode() ^ height.GetHashCode() ^ GetFields().GetHashCode();
}

View file

@ -322,7 +322,7 @@ namespace Greenshot.Drawing {
if (!elements.Contains(dc)) {
continue;
}
if (Count > (i+1) && !elements.Contains(this[i+1])) {
if (Count > i+1 && !elements.Contains(this[i+1])) {
SwapElements(i,i+1);
}
}
@ -468,7 +468,7 @@ namespace Greenshot.Drawing {
// Copy
item = new ToolStripMenuItem(Language.GetString(LangKey.editor_copytoclipboard));
item.Image = ((Image)(editorFormResources.GetObject("copyToolStripMenuItem.Image")));
item.Image = (Image)editorFormResources.GetObject("copyToolStripMenuItem.Image");
item.Click += delegate {
ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), this);
};
@ -476,7 +476,7 @@ namespace Greenshot.Drawing {
// Cut
item = new ToolStripMenuItem(Language.GetString(LangKey.editor_cuttoclipboard));
item.Image = ((Image)(editorFormResources.GetObject("btnCut.Image")));
item.Image = (Image)editorFormResources.GetObject("btnCut.Image");
item.Click += delegate {
ClipboardHelper.SetClipboardData(typeof(DrawableContainerList), this);
List<DrawableContainer> containersToDelete = new List<DrawableContainer>();
@ -492,7 +492,7 @@ namespace Greenshot.Drawing {
// Delete
item = new ToolStripMenuItem(Language.GetString(LangKey.editor_deleteelement));
item.Image = ((Image)(editorFormResources.GetObject("removeObjectToolStripMenuItem.Image")));
item.Image = (Image)editorFormResources.GetObject("removeObjectToolStripMenuItem.Image");
item.Click += delegate {
List<DrawableContainer> containersToDelete = new List<DrawableContainer>();
foreach(var drawableContainer in this) {

View file

@ -59,12 +59,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

@ -34,7 +34,7 @@ namespace Greenshot.Drawing.Fields {
[Serializable]
public abstract class AbstractFieldHolder : IFieldHolder {
private static readonly ILog LOG = LogManager.GetLogger(typeof(AbstractFieldHolder));
private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>();
private static readonly EditorConfiguration editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>();
/// <summary>
/// called when a field's value has changed
@ -50,9 +50,7 @@ namespace Greenshot.Drawing.Fields {
// this allows us to use default serialization
[NonSerialized]
private Dictionary<FieldType, Field> fieldsByType = new Dictionary<FieldType, Field>();
private List<Field> fields = new List<Field>();
public AbstractFieldHolder() {}
private readonly List<Field> fields = new List<Field>();
[OnDeserialized]
private void OnDeserialized(StreamingContext context) {

View file

@ -30,8 +30,7 @@ namespace Greenshot.Drawing.Fields {
/// </summary>
[Serializable()]
public abstract class AbstractFieldHolderWithChildren : AbstractFieldHolder {
FieldChangedEventHandler fieldChangedEventHandler;
readonly FieldChangedEventHandler fieldChangedEventHandler;
[NonSerialized]
private EventHandler childrenChanged;

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

@ -25,7 +25,6 @@ using System.ComponentModel;
using Greenshot.Configuration;
using Greenshot.IniFile;
using Greenshot.Plugin.Drawing;
using log4net;
namespace Greenshot.Drawing.Fields {
/// <summary>
@ -41,13 +40,10 @@ namespace Greenshot.Drawing.Fields {
/// </summary>
public class FieldAggregator : AbstractFieldHolder {
private List<IDrawableContainer> boundContainers;
private bool internalUpdateRunning = false;
private readonly List<IDrawableContainer> boundContainers;
private bool internalUpdateRunning;
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 editorConfiguration = IniConfig.GetIniSection<EditorConfiguration>();
public FieldAggregator() {
foreach(FieldType fieldType in FieldType.Values) {

View file

@ -52,7 +52,7 @@ namespace Greenshot.Drawing {
int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS);
Color lineColor = GetFieldValueAsColor(FieldType.LINE_COLOR);
bool shadow = GetFieldValueAsBool(FieldType.SHADOW);
bool lineVisible = (lineThickness > 0 && Colors.IsVisible(lineColor));
bool lineVisible = lineThickness > 0 && Colors.IsVisible(lineColor);
if (lineVisible) {
graphics.SmoothingMode = SmoothingMode.HighSpeed;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
@ -69,7 +69,7 @@ namespace Greenshot.Drawing {
Rectangle shadowRect = GuiRectangle.GetGuiRectangle(Left + currentStep, Top + currentStep, Width, Height);
graphics.DrawRectangle(shadowPen, shadowRect);
currentStep++;
alpha = alpha - (basealpha / steps);
alpha = alpha - basealpha / steps;
}
}
}

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

@ -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,15 +34,14 @@ 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
@ -119,7 +117,7 @@ namespace Greenshot.Drawing {
public override bool HandleMouseMove(int mouseX, int mouseY) {
Point previousPoint = capturePoints[capturePoints.Count-1];
if (GeometryHelper.Distance2D(previousPoint.X, previousPoint.Y, mouseX, mouseY) >= (2*EditorConfig.FreehandSensitivity)) {
if (GeometryHelper.Distance2D(previousPoint.X, previousPoint.Y, mouseX, mouseY) >= 2*EditorConfig.FreehandSensitivity) {
capturePoints.Add(new Point(mouseX, mouseY));
}
if (GeometryHelper.Distance2D(lastMouse.X, lastMouse.Y, mouseX, mouseY) >= EditorConfig.FreehandSensitivity) {
@ -232,7 +230,7 @@ namespace Greenshot.Drawing {
if (!myBounds.IsEmpty) {
int lineThickness = Math.Max(10, GetFieldValueAsInt(FieldType.LINE_THICKNESS));
int safetymargin = 10;
return new Rectangle((myBounds.Left + Left) - (safetymargin+lineThickness), (myBounds.Top + Top) - (safetymargin+lineThickness), myBounds.Width + (2*(lineThickness+safetymargin)), myBounds.Height + (2*(lineThickness+safetymargin)));
return new Rectangle(myBounds.Left + Left - (safetymargin+lineThickness), myBounds.Top + Top - (safetymargin+lineThickness), myBounds.Width + 2*(lineThickness+safetymargin), myBounds.Height + 2*(lineThickness+safetymargin));
}
return new Rectangle(0, 0, _parent.Width, _parent.Height);
}

View file

@ -31,7 +31,7 @@ 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;

View file

@ -34,7 +34,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;

View file

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

View file

@ -69,7 +69,7 @@ namespace Greenshot.Drawing {
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.None;
bool lineVisible = (lineThickness > 0 && Colors.IsVisible(lineColor));
bool lineVisible = lineThickness > 0 && Colors.IsVisible(lineColor);
if (shadow && (lineVisible || Colors.IsVisible(fillColor))) {
//draw shadow first
int basealpha = 100;
@ -86,7 +86,7 @@ namespace Greenshot.Drawing {
rect.Height);
graphics.DrawRectangle(shadowPen, shadowRect);
currentStep++;
alpha = alpha - (basealpha / steps);
alpha = alpha - basealpha / steps;
}
}
}

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

@ -180,7 +180,7 @@ namespace Greenshot.Drawing {
private GraphicsPath CreateTail() {
Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height);
int tailLength = GeometryHelper.Distance2D(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2), TargetGripper.Left, TargetGripper.Top);
int tailLength = GeometryHelper.Distance2D(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2, TargetGripper.Left, TargetGripper.Top);
int tailWidth = (Math.Abs(rect.Width) + Math.Abs(rect.Height)) / 20;
// This should fix a problem with the tail being to wide
@ -192,10 +192,10 @@ namespace Greenshot.Drawing {
tail.AddLine(tailWidth, 0, 0, -tailLength);
tail.CloseFigure();
int tailAngle = 90 + (int)GeometryHelper.Angle2D(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2), TargetGripper.Left, TargetGripper.Top);
int tailAngle = 90 + (int)GeometryHelper.Angle2D(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2, TargetGripper.Left, TargetGripper.Top);
using (Matrix tailMatrix = new Matrix()) {
tailMatrix.Translate(rect.Left + (rect.Width / 2), rect.Top + (rect.Height / 2));
tailMatrix.Translate(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2);
tailMatrix.Rotate(tailAngle);
tail.Transform(tailMatrix);
}
@ -223,7 +223,7 @@ namespace Greenshot.Drawing {
bool shadow = GetFieldValueAsBool(FieldType.SHADOW);
int lineThickness = GetFieldValueAsInt(FieldType.LINE_THICKNESS);
bool lineVisible = (lineThickness > 0 && Colors.IsVisible(lineColor));
bool lineVisible = lineThickness > 0 && Colors.IsVisible(lineColor);
Rectangle rect = GuiRectangle.GetGuiRectangle(Left, Top, Width, Height);
if (Selected && renderMode == RenderMode.EDIT) {
@ -253,7 +253,7 @@ namespace Greenshot.Drawing {
graphics.DrawPath(shadowPen, bubbleClone);
}
currentStep++;
alpha = alpha - (basealpha / steps);
alpha = alpha - basealpha / steps;
}
}
}

View file

@ -118,7 +118,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 +146,8 @@ namespace Greenshot.Drawing {
public override bool HandleMouseMove(int x, int y) {
Invalidate();
Left = x - (Width / 2);
Top = y - (Height / 2);
Left = x - Width / 2;
Top = y - Height / 2;
Invalidate();
return true;
}
@ -167,7 +167,7 @@ namespace Greenshot.Drawing {
int widthAfter = rect.Width;
int heightAfter = rect.Height;
float factor = (((float)widthAfter / widthBefore) + ((float)heightAfter / heightBefore)) / 2;
float factor = ((float)widthAfter / widthBefore + (float)heightAfter / heightBefore) / 2;
fontSize *= factor;
}

View file

@ -46,9 +46,9 @@ namespace Greenshot.Drawing {
/// Description of Surface.
/// </summary>
public 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();
@ -169,7 +169,7 @@ namespace Greenshot.Drawing {
/// all selected elements, do not serialize
/// </summary>
[NonSerialized]
private DrawableContainerList selectedElements;
private readonly DrawableContainerList selectedElements;
/// <summary>
/// the element we are drawing with, do not serialize
@ -208,7 +208,7 @@ namespace Greenshot.Drawing {
/// <summary>
/// all stepLabels for the surface, needed with serialization
/// </summary>
private List<StepLabelContainer> _stepLabels = new List<StepLabelContainer>();
private readonly List<StepLabelContainer> _stepLabels = new List<StepLabelContainer>();
public void AddStepLabel(StepLabelContainer stepLabel) {
_stepLabels.Add(stepLabel);
@ -225,7 +225,7 @@ namespace Greenshot.Drawing {
public int CountStepLabels(IDrawableContainer stopAtContainer) {
int number = 1;
foreach (var possibleThis in _stepLabels) {
if (possibleThis == stopAtContainer) {
if (possibleThis.Equals(stopAtContainer)) {
break;
}
if (IsOnSurface(possibleThis)) {
@ -1037,7 +1037,10 @@ namespace Greenshot.Drawing {
_drawingElement = _undrawnElement;
// if a new element has been drawn, set location and register it
if (_drawingElement != null) {
if (_undrawnElement != null)
{
_drawingElement.Status = _undrawnElement.DefaultEditMode;
}
_drawingElement.PropertyChanged += ElementPropertyChanged;
if (!_drawingElement.HandleMouseDown(_mouseStart.X, _mouseStart.Y)) {
_drawingElement.Left = _mouseStart.X;
@ -1331,7 +1334,7 @@ namespace Greenshot.Drawing {
/// <returns></returns>
public bool HasSelectedElements {
get {
return (selectedElements != null && selectedElements.Count > 0);
return selectedElements != null && selectedElements.Count > 0;
}
}
@ -1387,6 +1390,10 @@ namespace Greenshot.Drawing {
public void ConfirmSelectedConfirmableElements(bool confirm){
// create new collection so that we can iterate safely (selectedElements might change due with confirm/cancel)
List<IDrawableContainer> selectedDCs = new List<IDrawableContainer>(selectedElements);
if (_cropContainer == null)
{
return;
}
foreach (IDrawableContainer dc in selectedDCs){
if (dc.Equals(_cropContainer)){
DrawingMode = DrawingModes.None;
@ -1397,6 +1404,7 @@ namespace Greenshot.Drawing {
}
_cropContainer.Dispose();
_cropContainer = null;
break;
}
}
}
@ -1423,7 +1431,7 @@ namespace Greenshot.Drawing {
if (dcs != null) {
// Make element(s) only move 10,10 if the surface is the same
Point moveOffset;
bool isSameSurface = (dcs.ParentID == _uniqueId);
bool isSameSurface = dcs.ParentID == _uniqueId;
dcs.Parent = this;
if (isSameSurface) {
moveOffset = new Point(10, 10);

View file

@ -332,8 +332,8 @@ namespace Greenshot.Drawing {
if (lineThickness <= 1) {
lineWidth = 0;
}
_textBox.Width = absRectangle.Width - (2 * lineWidth) + correction;
_textBox.Height = absRectangle.Height - (2 * lineWidth) + correction;
_textBox.Width = absRectangle.Width - 2 * lineWidth + correction;
_textBox.Height = absRectangle.Height - 2 * lineWidth + correction;
}
public override void ApplyBounds(RectangleF newBounds) {
@ -415,7 +415,7 @@ namespace Greenshot.Drawing {
/// <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

@ -26,7 +26,7 @@ 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 +50,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

@ -54,7 +54,7 @@ namespace Greenshot {
private static ILog LOG;
private static Mutex _applicationMutex;
private static CoreConfiguration _conf;
public static string LogFileLocation = null;
public static string LogFileLocation;
public static void Start(string[] args) {
bool isAlreadyRunning = false;
@ -258,7 +258,7 @@ namespace Greenshot {
using (Form dummyForm = new Form()) {
dummyForm.Icon = GreenshotResources.getGreenshotIcon();
dummyForm.ShowInTaskbar = true;
dummyForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
dummyForm.FormBorderStyle = FormBorderStyle.None;
dummyForm.Location = new Point(int.MinValue, int.MinValue);
dummyForm.Load += delegate { dummyForm.Size = Size.Empty; };
dummyForm.Show();
@ -581,7 +581,7 @@ namespace Greenshot {
contextMenu.ImageScalingSize = coreConfiguration.IconSize;
string ieExePath = PluginUtils.GetExePath("iexplore.exe");
if (!string.IsNullOrEmpty(ieExePath)) {
this.contextmenu_captureie.Image = PluginUtils.GetCachedExeIcon(ieExePath, 0);
contextmenu_captureie.Image = PluginUtils.GetCachedExeIcon(ieExePath, 0);
}
}
}

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

@ -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;
@ -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

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

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;
@ -850,14 +850,14 @@ namespace Greenshot.Helpers {
// check if GDI capture any good, by comparing it with the screen content
int blackCountGDI = ImageHelper.CountColor(tmpCapture.Image, Color.Black, false);
int GDIPixels = tmpCapture.Image.Width * tmpCapture.Image.Height;
int blackPercentageGDI = (blackCountGDI * 100) / GDIPixels;
int blackPercentageGDI = blackCountGDI * 100 / GDIPixels;
if (blackPercentageGDI >= 1) {
int screenPixels = windowRectangle.Width * windowRectangle.Height;
using (ICapture screenCapture = new Capture()) {
screenCapture.CaptureDetails = captureForWindow.CaptureDetails;
if (WindowCapture.CaptureRectangleFromDesktopScreen(screenCapture, windowRectangle) != null) {
int blackCountScreen = ImageHelper.CountColor(screenCapture.Image, Color.Black, false);
int blackPercentageScreen = (blackCountScreen * 100) / screenPixels;
int blackPercentageScreen = blackCountScreen * 100 / screenPixels;
if (screenPixels == GDIPixels) {
// "easy compare", both have the same size
// If GDI has more black, use the screen capture.

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;
/// <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 };
/// <summary>
/// Code from vbAccelerator, location:
/// http://www.vbaccelerator.com/home/NET/Code/Libraries/Windows_Messages/Simple_Interprocess_Communication/WM_COPYDATA_Demo_zip_SimpleInterprocessCommunicationsCS_CopyData_cs.asp
/// </summary>
[Serializable()]
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
{
@ -666,17 +660,17 @@ namespace Greenshot.Helpers
private struct OSVERSIONINFOEX
{
public int dwOSVersionInfoSize;
public int dwMajorVersion;
public int dwMinorVersion;
public int dwBuildNumber;
public int dwPlatformId;
public readonly int dwMajorVersion;
public readonly int dwMinorVersion;
public readonly int dwBuildNumber;
public readonly int dwPlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string szCSDVersion;
public short wServicePackMajor;
public short wServicePackMinor;
public short wSuiteMask;
public byte wProductType;
public byte wReserved;
public readonly string szCSDVersion;
public readonly short wServicePackMajor;
public readonly short wServicePackMinor;
public readonly short wSuiteMask;
public readonly byte wProductType;
public readonly byte wReserved;
}
#endregion OSVERSIONINFOEX
@ -724,13 +718,9 @@ namespace Greenshot.Helpers
#region VERSIONS
private const int VER_NT_WORKSTATION = 1;
private const int VER_NT_DOMAIN_CONTROLLER = 2;
private const int VER_NT_SERVER = 3;
private const int VER_SUITE_SMALLBUSINESS = 1;
private const int VER_SUITE_ENTERPRISE = 2;
private const int VER_SUITE_TERMINAL = 16;
private const int VER_SUITE_DATACENTER = 128;
private const int VER_SUITE_SINGLEUSERTS = 256;
private const int VER_SUITE_PERSONAL = 512;
private const int VER_SUITE_BLADE = 1024;
#endregion VERSIONS
@ -740,11 +730,11 @@ namespace Greenshot.Helpers
/// <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));
@ -778,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
{
@ -791,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
{
@ -805,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
{
@ -818,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
{
@ -831,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;
@ -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,8 +43,8 @@ namespace Greenshot.Memento {
protected virtual void Dispose(bool disposing) {
//if (disposing) { }
drawableContainer = null;
surface = null;
_drawableContainer = null;
_surface = null;
}
public LangKey ActionLanguageKey {
@ -59,16 +59,15 @@ namespace Greenshot.Memento {
public IMemento Restore() {
// Before
drawableContainer.Invalidate();
_drawableContainer.Invalidate();
// Store the selected state, as it's overwritten by the RemoveElement
bool selected = drawableContainer.Selected;
DeleteElementMemento oldState = new DeleteElementMemento(surface, drawableContainer);
surface.RemoveElement(drawableContainer, false);
drawableContainer.Selected = true;
DeleteElementMemento oldState = new DeleteElementMemento(_surface, _drawableContainer);
_surface.RemoveElement(_drawableContainer, false);
_drawableContainer.Selected = true;
// After
drawableContainer.Invalidate();
_drawableContainer.Invalidate();
return oldState;
}
}

View file

@ -29,8 +29,8 @@ namespace Greenshot.Memento {
/// </summary>
public class ChangeFieldHolderMemento : IMemento {
private IDrawableContainer drawableContainer;
private Field fieldToBeChanged;
private object oldValue;
private readonly Field fieldToBeChanged;
private readonly object oldValue;
public ChangeFieldHolderMemento(IDrawableContainer drawableContainer, Field fieldToBeChanged) {
this.drawableContainer = drawableContainer;

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;

View file

@ -31,8 +31,8 @@ namespace Greenshot.Memento {
/// The DrawableContainerBoundsChangeMemento makes it possible to undo-redo an IDrawableContainer resize & move
/// </summary>
public class DrawableContainerBoundsChangeMemento : IMemento {
List<Point> points = new List<Point>();
List<Size> sizes = new List<Size>();
readonly List<Point> points = new List<Point>();
readonly List<Size> sizes = new List<Size>();
List<IDrawableContainer> listOfdrawableContainer;
private void StoreBounds() {

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;

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

@ -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

@ -21,9 +21,7 @@
using System;
using System.Windows.Forms;
using GreenshotPlugin.Core;
using GreenshotPlugin.UnmanagedHelpers;
using Greenshot.IniFile;
using log4net;
namespace GreenshotPlugin.Controls {
@ -33,8 +31,8 @@ namespace GreenshotPlugin.Controls {
public class AnimatingForm : GreenshotForm {
private static readonly ILog LOG = LogManager.GetLogger(typeof(AnimatingForm));
private const int DEFAULT_VREFRESH = 60;
private int vRefresh = 0;
private Timer timer = null;
private int _vRefresh;
private Timer _timer;
/// <summary>
/// This flag specifies if any animation is used
@ -49,27 +47,27 @@ namespace GreenshotPlugin.Controls {
/// </summary>
protected int VRefresh {
get {
if (vRefresh == 0) {
if (_vRefresh == 0) {
// get te hDC of the desktop to get the VREFRESH
using (SafeWindowDCHandle desktopHandle = SafeWindowDCHandle.fromDesktop()) {
vRefresh = GDI32.GetDeviceCaps(desktopHandle, DeviceCaps.VREFRESH);
using (SafeWindowDCHandle desktopHandle = SafeWindowDCHandle.FromDesktop()) {
_vRefresh = GDI32.GetDeviceCaps(desktopHandle, DeviceCaps.VREFRESH);
}
}
// A vertical refresh rate value of 0 or 1 represents the display hardware's default refresh rate.
// As there is currently no know way to get the default, we guess it.
if (vRefresh <= 1) {
vRefresh = DEFAULT_VREFRESH;
if (_vRefresh <= 1) {
_vRefresh = DEFAULT_VREFRESH;
}
return vRefresh;
return _vRefresh;
}
}
/// <summary>
/// Check if we are in a Terminal Server session OR need to optimize for RDP / remote desktop connections
/// </summary>
protected bool isTerminalServerSession {
protected bool IsTerminalServerSession {
get {
return coreConfiguration.OptimizeForRDP || SystemInformation.TerminalServerSession;
return !coreConfiguration.DisableRDPOptimizing && (coreConfiguration.OptimizeForRDP || SystemInformation.TerminalServerSession);
}
}
@ -80,7 +78,7 @@ namespace GreenshotPlugin.Controls {
/// <returns>Number of frames, 1 if in Terminal Server Session</returns>
protected int FramesForMillis(int milliseconds) {
// If we are in a Terminal Server Session we return 1
if (isTerminalServerSession) {
if (IsTerminalServerSession) {
return 1;
}
return milliseconds / VRefresh;
@ -92,17 +90,17 @@ namespace GreenshotPlugin.Controls {
protected AnimatingForm() {
Load += delegate {
if (EnableAnimation) {
timer = new Timer();
timer.Interval = 1000 / VRefresh;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
_timer = new Timer();
_timer.Interval = 1000 / VRefresh;
_timer.Tick += timer_Tick;
_timer.Start();
}
};
// Unregister at close
FormClosing += delegate {
if (timer != null) {
timer.Stop();
if (_timer != null) {
_timer.Stop();
}
};
}

View file

@ -29,7 +29,7 @@ namespace GreenshotPlugin.Controls {
/// Description of PleaseWaitForm.
/// </summary>
public partial class BackgroundForm : Form {
private volatile bool shouldClose = false;
private volatile bool _shouldClose;
private void BackgroundShowDialog() {
ShowDialog();
@ -38,7 +38,7 @@ namespace GreenshotPlugin.Controls {
public static BackgroundForm ShowAndWait(string title, string text) {
BackgroundForm backgroundForm = new BackgroundForm(title, text);
// Show form in background thread
Thread backgroundTask = new Thread (new ThreadStart(backgroundForm.BackgroundShowDialog));
Thread backgroundTask = new Thread (backgroundForm.BackgroundShowDialog);
backgroundForm.Name = "Background form";
backgroundTask.IsBackground = true;
backgroundTask.SetApartmentState(ApartmentState.STA);
@ -52,7 +52,7 @@ namespace GreenshotPlugin.Controls {
//
InitializeComponent();
Icon = GreenshotResources.getGreenshotIcon();
shouldClose = false;
_shouldClose = false;
Text = title;
label_pleasewait.Text = text;
FormClosing += PreventFormClose;
@ -76,20 +76,20 @@ namespace GreenshotPlugin.Controls {
}
private void PreventFormClose(object sender, FormClosingEventArgs e) {
if(!shouldClose) {
if(!_shouldClose) {
e.Cancel = true;
}
}
private void Timer_checkforcloseTick(object sender, EventArgs e) {
if (shouldClose) {
if (_shouldClose) {
timer_checkforclose.Stop();
BeginInvoke(new EventHandler( delegate {Close();}));
}
}
public void CloseDialog() {
shouldClose = true;
_shouldClose = true;
Application.DoEvents();
}

View file

@ -19,8 +19,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using GreenshotInterop.Interop;
@ -30,7 +28,7 @@ namespace GreenshotPlugin.Controls {
const int OLECMDID_SHOWSCRIPTERROR = 40;
const int OLECMDID_SHOWMESSAGE = 41;
static Guid CGID_DocHostCommandHandler = new Guid("F38BC242-B950-11D1-8918-00C04FC2C836");
static readonly Guid CGID_DocHostCommandHandler = new Guid("F38BC242-B950-11D1-8918-00C04FC2C836");
const int S_OK = 0;
const int OLECMDERR_E_NOTSUPPORTED = (-2147221248);

View file

@ -18,7 +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.Windows.Forms;
namespace GreenshotPlugin.Controls {

View file

@ -18,7 +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.ComponentModel;
using System.Windows.Forms;

View file

@ -18,7 +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.ComponentModel;
using System.Windows.Forms;
@ -33,16 +33,8 @@ namespace GreenshotPlugin.Controls {
set;
}
private string sectionName = "Core";
[Category("Greenshot"), DefaultValue("Core"), Description("Specifies the Ini-Section to map this control with.")]
public string SectionName {
get {
return sectionName;
}
set {
sectionName = value;
}
}
public string SectionName { get; set; } = "Core";
[Category("Greenshot"), DefaultValue(null), Description("Specifies the property name to map the configuration.")]
public string PropertyName {

View file

@ -29,28 +29,28 @@ namespace GreenshotPlugin.Controls {
/// <summary>
/// Specifies the column to be sorted
/// </summary>
private int ColumnToSort;
private int _columnToSort;
/// <summary>
/// Specifies the order in which to sort (i.e. 'Ascending').
/// </summary>
private SortOrder OrderOfSort;
private SortOrder _orderOfSort;
/// <summary>
/// Case insensitive comparer object
/// </summary>
private CaseInsensitiveComparer ObjectCompare;
private readonly CaseInsensitiveComparer _objectCompare;
/// <summary>
/// Class constructor. Initializes various elements
/// </summary>
public GreenshotColumnSorter() {
// Initialize the column to '0'
ColumnToSort = 0;
_columnToSort = 0;
// Initialize the sort order to 'none'
OrderOfSort = SortOrder.None;
_orderOfSort = SortOrder.None;
// Initialize the CaseInsensitiveComparer object
ObjectCompare = new CaseInsensitiveComparer();
_objectCompare = new CaseInsensitiveComparer();
}
/// <summary>
@ -60,45 +60,44 @@ namespace GreenshotPlugin.Controls {
/// <param name="y">Second object to be compared</param>
/// <returns>The result of the comparison. "0" if equal, negative if 'x' is less than 'y' and positive if 'x' is greater than 'y'</returns>
public int Compare(object x, object y) {
int compareResult;
ListViewItem listviewX, listviewY;
if (x == null && y == null) {
return 0;
} else if (x == null && y != null) {
}
if (x == null) {
return -1;
} else if (x != null && y == null) {
}
if (y == null) {
return 1;
}
// Cast the objects to be compared to ListViewItem objects
listviewX = (ListViewItem)x;
listviewY = (ListViewItem)y;
var listviewX = (ListViewItem)x;
var listviewY = (ListViewItem)y;
// Compare the two items
compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);
var compareResult = _objectCompare.Compare(listviewX.SubItems[_columnToSort].Text, listviewY.SubItems[_columnToSort].Text);
// Calculate correct return value based on object comparison
if (OrderOfSort == SortOrder.Ascending) {
if (_orderOfSort == SortOrder.Ascending) {
// Ascending sort is selected, return normal result of compare operation
return compareResult;
} else if (OrderOfSort == SortOrder.Descending) {
}
if (_orderOfSort == SortOrder.Descending) {
// Descending sort is selected, return negative result of compare operation
return (-compareResult);
} else {
return -compareResult;
}
// Return '0' to indicate they are equal
return 0;
}
}
/// <summary>
/// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0').
/// </summary>
public int SortColumn {
set {
ColumnToSort = value;
_columnToSort = value;
}
get {
return ColumnToSort;
return _columnToSort;
}
}
@ -107,10 +106,10 @@ namespace GreenshotPlugin.Controls {
/// </summary>
public SortOrder Order {
set {
OrderOfSort = value;
_orderOfSort = value;
}
get {
return OrderOfSort;
return _orderOfSort;
}
}
}

View file

@ -25,18 +25,11 @@ using GreenshotPlugin.Core;
namespace GreenshotPlugin.Controls {
public class GreenshotComboBox : ComboBox, IGreenshotConfigBindable {
private Type enumType = null;
private Enum selectedEnum = null;
private string sectionName = "Core";
private Type _enumType;
private Enum _selectedEnum;
[Category("Greenshot"), DefaultValue("Core"), Description("Specifies the Ini-Section to map this control with.")]
public string SectionName {
get {
return sectionName;
}
set {
sectionName = value;
}
}
public string SectionName { get; set; } = "Core";
[Category("Greenshot"), DefaultValue(null), Description("Specifies the property name to map the configuration.")]
public string PropertyName {
@ -52,7 +45,7 @@ namespace GreenshotPlugin.Controls {
public void SetValue(Enum currentValue) {
if (currentValue != null) {
selectedEnum = currentValue;
_selectedEnum = currentValue;
SelectedItem = Language.Translate(currentValue);
}
}
@ -64,11 +57,10 @@ namespace GreenshotPlugin.Controls {
/// <param name="enumType">TEnum to populate with</param>
public void Populate(Type enumType) {
// Store the enum-type, so we can work with it
this.enumType = enumType;
_enumType = enumType;
var availableValues = Enum.GetValues(enumType);
Items.Clear();
string enumTypeName = enumType.Name;
foreach (var enumValue in availableValues) {
Items.Add(Language.Translate((Enum)enumValue));
}
@ -78,26 +70,27 @@ namespace GreenshotPlugin.Controls {
/// Store the selected value internally
/// </summary>
private void StoreSelectedEnum() {
string enumTypeName = enumType.Name;
string enumTypeName = _enumType.Name;
string selectedValue = SelectedItem as string;
var availableValues = Enum.GetValues(enumType);
var availableValues = Enum.GetValues(_enumType);
object returnValue = null;
try {
returnValue = Enum.Parse(enumType, selectedValue);
returnValue = Enum.Parse(_enumType, selectedValue);
} catch (Exception) {
// Ignore
}
foreach (Enum enumValue in availableValues) {
string enumKey = enumTypeName + "." + enumValue.ToString();
string enumKey = enumTypeName + "." + enumValue;
if (Language.hasKey(enumKey)) {
string translation = Language.GetString(enumTypeName + "." + enumValue.ToString());
string translation = Language.GetString(enumTypeName + "." + enumValue);
if (translation.Equals(selectedValue)) {
returnValue = enumValue;
}
}
}
selectedEnum = (Enum)returnValue;
_selectedEnum = (Enum)returnValue;
}
/// <summary>
@ -105,7 +98,7 @@ namespace GreenshotPlugin.Controls {
/// </summary>
/// <returns>The enum value of the combobox</returns>
public Enum GetSelectedEnum() {
return selectedEnum;
return _selectedEnum;
}
}
}

View file

@ -34,13 +34,13 @@ namespace GreenshotPlugin.Controls {
/// This form is used for automatically binding the elements of the form to the language
/// </summary>
public class GreenshotForm : Form, IGreenshotLanguageBindable {
private static ILog LOG = LogManager.GetLogger(typeof(GreenshotForm));
private static readonly ILog LOG = LogManager.GetLogger(typeof(GreenshotForm));
protected static CoreConfiguration coreConfiguration;
private static IDictionary<Type, FieldInfo[]> reflectionCache = new Dictionary<Type, FieldInfo[]>();
private static readonly IDictionary<Type, FieldInfo[]> reflectionCache = new Dictionary<Type, FieldInfo[]>();
private IComponentChangeService m_changeService;
private bool _isDesignModeLanguageSet = false;
private bool _applyLanguageManually = false;
private bool _storeFieldsManually = false;
private bool _isDesignModeLanguageSet;
private bool _applyLanguageManually;
private bool _storeFieldsManually;
private IDictionary<string, Control> _designTimeControls;
private IDictionary<string, ToolStripItem> _designTimeToolStripItems;
@ -210,16 +210,16 @@ namespace GreenshotPlugin.Controls {
// Clear our the component change events to prepare for re-siting.
if (m_changeService != null) {
m_changeService.ComponentChanged -= new ComponentChangedEventHandler(OnComponentChanged);
m_changeService.ComponentAdded -= new ComponentEventHandler(OnComponentAdded);
m_changeService.ComponentChanged -= OnComponentChanged;
m_changeService.ComponentAdded -= OnComponentAdded;
}
}
private void RegisterChangeNotifications() {
// Register the event handlers for the IComponentChangeService events
if (m_changeService != null) {
m_changeService.ComponentChanged += new ComponentChangedEventHandler(OnComponentChanged);
m_changeService.ComponentAdded += new ComponentEventHandler(OnComponentAdded);
m_changeService.ComponentChanged += OnComponentChanged;
m_changeService.ComponentAdded += OnComponentAdded;
}
}
@ -277,7 +277,7 @@ namespace GreenshotPlugin.Controls {
}
protected void ApplyLanguage(ToolStripItem applyTo, string languageKey) {
string langString = null;
string langString;
if (!string.IsNullOrEmpty(languageKey)) {
if (!Language.TryGetString(languageKey, out langString)) {
LOG.WarnFormat("Unknown language key '{0}' configured for control '{1}', this might be okay.", languageKey, applyTo.Name);
@ -473,7 +473,6 @@ namespace GreenshotPlugin.Controls {
comboxBox.Populate(iniValue.ValueType);
comboxBox.SetValue((Enum)iniValue.Value);
comboxBox.Enabled = !iniValue.IsFixed;
continue;
}
}
}

View file

@ -18,7 +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.Windows.Forms;
using System.ComponentModel;

View file

@ -18,7 +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.Windows.Forms;
using System.ComponentModel;

View file

@ -18,7 +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.ComponentModel;
using System.Windows.Forms;

View file

@ -18,7 +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.Windows.Forms;
using System.ComponentModel;

View file

@ -18,22 +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.ComponentModel;
using System.Windows.Forms;
namespace GreenshotPlugin.Controls {
public class GreenshotTextBox : TextBox, IGreenshotConfigBindable {
private string sectionName = "Core";
[Category("Greenshot"), DefaultValue("Core"), Description("Specifies the Ini-Section to map this control with.")]
public string SectionName {
get {
return sectionName;
}
set {
sectionName = value;
}
}
public string SectionName { get; set; } = "Core";
[Category("Greenshot"), DefaultValue(null), Description("Specifies the property name to map the configuration.")]
public string PropertyName {

View file

@ -18,7 +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.ComponentModel;
using System.Windows.Forms;

View file

@ -18,7 +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.ComponentModel;
using System.Windows.Forms;

View file

@ -18,7 +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.Windows.Forms;
using System.ComponentModel;

View file

@ -18,7 +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.ComponentModel;
using System.Windows.Forms;

View file

@ -22,6 +22,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
@ -37,13 +38,13 @@ namespace GreenshotPlugin.Controls {
/// But is modified to fit in Greenshot, and have localized support
/// </summary>
public class HotkeyControl : GreenshotTextBox {
private static ILog LOG = LogManager.GetLogger(typeof(HotkeyControl));
private static readonly ILog LOG = LogManager.GetLogger(typeof(HotkeyControl));
private static EventDelay eventDelay = new EventDelay(TimeSpan.FromMilliseconds(600).Ticks);
private static bool isWindows7OrOlder = Environment.OSVersion.Version.Major >= 6 && Environment.OSVersion.Version.Minor >= 1;
private static readonly EventDelay eventDelay = new EventDelay(TimeSpan.FromMilliseconds(600).Ticks);
private static readonly bool isWindows7OrOlder = Environment.OSVersion.Version.Major >= 6 && Environment.OSVersion.Version.Minor >= 1;
// Holds the list of hotkeys
private static Dictionary<int, HotKeyHandler> keyHandlers = new Dictionary<int, HotKeyHandler>();
private static readonly IDictionary<int, HotKeyHandler> keyHandlers = new Dictionary<int, HotKeyHandler>();
private static int hotKeyCounter = 1;
private const uint WM_HOTKEY = 0x312;
private static IntPtr hotkeyHWND;
@ -57,6 +58,7 @@ namespace GreenshotPlugin.Controls {
// }
// }
[SuppressMessage("ReSharper", "InconsistentNaming")]
public enum Modifiers : uint {
NONE = 0,
ALT = 1,
@ -66,6 +68,7 @@ namespace GreenshotPlugin.Controls {
NO_REPEAT = 0x4000
}
[SuppressMessage("ReSharper", "InconsistentNaming")]
private enum MapType : uint {
MAPVK_VK_TO_VSC = 0, //The uCode parameter is a virtual-key code and is translated into a scan code. If it is a virtual-key code that does not distinguish between left- and right-hand keys, the left-hand scan code is returned. If there is no translation, the function returns 0.
MAPVK_VSC_TO_VK = 1, //The uCode parameter is a scan code and is translated into a virtual-key code that does not distinguish between left- and right-hand keys. If there is no translation, the function returns 0.
@ -93,10 +96,10 @@ namespace GreenshotPlugin.Controls {
// ArrayLists used to enforce the use of proper modifiers.
// Shift+A isn't a valid hotkey, for instance, as it would screw up when the user is typing.
private ArrayList needNonShiftModifier = null;
private ArrayList needNonAltGrModifier = null;
private readonly ArrayList needNonShiftModifier;
private readonly ArrayList needNonAltGrModifier;
private ContextMenu dummy = new ContextMenu();
private readonly ContextMenu dummy = new ContextMenu();
/// <summary>
/// Used to make sure that there is no right-click menu available
@ -131,9 +134,9 @@ namespace GreenshotPlugin.Controls {
Text = "None";
// Handle events that occurs when keys are pressed
KeyPress += new KeyPressEventHandler(HotkeyControl_KeyPress);
KeyUp += new KeyEventHandler(HotkeyControl_KeyUp);
KeyDown += new KeyEventHandler(HotkeyControl_KeyDown);
KeyPress += HotkeyControl_KeyPress;
KeyUp += HotkeyControl_KeyUp;
KeyDown += HotkeyControl_KeyDown;
// Fill the ArrayLists that contain all invalid hotkey combinations
needNonShiftModifier = new ArrayList();

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 GreenshotPlugin.Controls {
public interface IGreenshotConfigBindable {

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 GreenshotPlugin.Controls {
/// <summary>

View file

@ -20,12 +20,8 @@
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Web;
using System.Collections.Specialized;
using GreenshotPlugin.Core;
using log4net;
@ -35,8 +31,8 @@ namespace GreenshotPlugin.Controls {
/// </summary>
public partial class OAuthLoginForm : Form {
private static readonly ILog LOG = LogManager.GetLogger(typeof(OAuthLoginForm));
private string _callbackUrl = null;
private IDictionary<string, string> _callbackParameters = null;
private readonly string _callbackUrl;
private IDictionary<string, string> _callbackParameters;
public IDictionary<string, string> CallbackParameters {
get {

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