diff --git a/Greenshot/Configuration/EditorConfiguration.cs b/Greenshot/Configuration/EditorConfiguration.cs index f019b44af..e7c90623c 100644 --- a/Greenshot/Configuration/EditorConfiguration.cs +++ b/Greenshot/Configuration/EditorConfiguration.cs @@ -26,6 +26,7 @@ using Greenshot.Drawing.Fields; using GreenshotPlugin.UnmanagedHelpers; using Greenshot.IniFile; using Greenshot.Core; +using GreenshotPlugin.Effects; using GreenshotPlugin.Interfaces.Drawing; namespace Greenshot.Configuration { @@ -99,9 +100,10 @@ namespace Greenshot.Configuration { } else { LastUsedFieldValues.Add(requestedField, fieldValue); } - Field returnField = new Field(fieldType, requestingType); - returnField.Value = fieldValue; - return returnField; + return new Field(fieldType, requestingType) + { + Value = fieldValue + }; } public void UpdateLastFieldValue(IField field) diff --git a/Greenshot/Controls/BindableToolStripButton.cs b/Greenshot/Controls/BindableToolStripButton.cs index 52dfcd3e8..7c1c50b85 100644 --- a/Greenshot/Controls/BindableToolStripButton.cs +++ b/Greenshot/Controls/BindableToolStripButton.cs @@ -41,8 +41,9 @@ namespace Greenshot.Controls { CheckedChanged += BindableToolStripButton_CheckedChanged; } - private void BindableToolStripButton_CheckedChanged(object sender, EventArgs e) { - if(PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Checked")); + private void BindableToolStripButton_CheckedChanged(object sender, EventArgs e) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Checked")); } } } diff --git a/Greenshot/Controls/BindableToolStripComboBox.cs b/Greenshot/Controls/BindableToolStripComboBox.cs index 14560ca12..d0f706260 100644 --- a/Greenshot/Controls/BindableToolStripComboBox.cs +++ b/Greenshot/Controls/BindableToolStripComboBox.cs @@ -41,11 +41,9 @@ namespace Greenshot.Controls { SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged; } - private void BindableToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e) { - if(PropertyChanged != null) { - PropertyChanged(this, new PropertyChangedEventArgs("SelectedItem")); - - } + private void BindableToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedItem")); } } } diff --git a/Greenshot/Controls/BindableToolStripDropDownButton.cs b/Greenshot/Controls/BindableToolStripDropDownButton.cs index 05df712b6..da638d481 100644 --- a/Greenshot/Controls/BindableToolStripDropDownButton.cs +++ b/Greenshot/Controls/BindableToolStripDropDownButton.cs @@ -48,7 +48,7 @@ namespace Greenshot.Controls { if(Tag == null || !Tag.Equals(clickedItem.Tag)) { Tag = clickedItem.Tag; Image = clickedItem.Image; - if(PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("SelectedTag")); + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedTag")); } base.OnDropDownItemClicked(e); } @@ -63,7 +63,7 @@ namespace Greenshot.Controls { } } Tag = tag; - if(PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("SelectedTag")); + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedTag")); } } } diff --git a/Greenshot/Controls/ColorButton.cs b/Greenshot/Controls/ColorButton.cs index 50546a3d8..d37fbf1c9 100644 --- a/Greenshot/Controls/ColorButton.cs +++ b/Greenshot/Controls/ColorButton.cs @@ -72,14 +72,16 @@ namespace Greenshot.Controls { colorDialog.Color = SelectedColor; // Using the parent to make sure the dialog doesn't show on another window colorDialog.ShowDialog(Parent.Parent); - if (colorDialog.DialogResult != DialogResult.Cancel) { - if (!colorDialog.Color.Equals(SelectedColor)) { - SelectedColor = colorDialog.Color; - if(PropertyChanged != null) { - PropertyChanged(this, new PropertyChangedEventArgs("SelectedColor")); - } - } + if (colorDialog.DialogResult == DialogResult.Cancel) + { + return; } + if (colorDialog.Color.Equals(SelectedColor)) + { + return; + } + SelectedColor = colorDialog.Color; + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedColor")); } } } diff --git a/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs b/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs index f3e110bb2..d3e8b5db2 100644 --- a/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs +++ b/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs @@ -29,18 +29,16 @@ namespace Greenshot.Controls { /// ToolStripProfessionalRenderer which draws the Check correctly when the icons are larger /// public class ContextMenuToolStripProfessionalRenderer : ToolStripProfessionalRenderer { - private static readonly CoreConfiguration coreConfiguration = IniConfig.GetIniSection(); - private static Image scaledCheckbox; + private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); + private static Image _scaledCheckbox; protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) { - if (scaledCheckbox == null || scaledCheckbox.Size != coreConfiguration.IconSize) { - if (scaledCheckbox != null) { - scaledCheckbox.Dispose(); - } - scaledCheckbox = ImageHelper.ResizeImage(e.Image, true, coreConfiguration.IconSize.Width, coreConfiguration.IconSize.Height, null); + if (_scaledCheckbox == null || _scaledCheckbox.Size != CoreConfig.IconSize) { + _scaledCheckbox?.Dispose(); + _scaledCheckbox = ImageHelper.ResizeImage(e.Image, true, CoreConfig.IconSize.Width, CoreConfig.IconSize.Height, null); } Rectangle old = e.ImageRectangle; - ToolStripItemImageRenderEventArgs clone = new ToolStripItemImageRenderEventArgs(e.Graphics, e.Item, scaledCheckbox, new Rectangle(old.X, 0, old.Width, old.Height)); + ToolStripItemImageRenderEventArgs clone = new ToolStripItemImageRenderEventArgs(e.Graphics, e.Item, _scaledCheckbox, new Rectangle(old.X, 0, old.Width, old.Height)); base.OnRenderItemCheck(clone); } } diff --git a/Greenshot/Controls/Pipette.cs b/Greenshot/Controls/Pipette.cs index f59b898f9..662b30931 100644 --- a/Greenshot/Controls/Pipette.cs +++ b/Greenshot/Controls/Pipette.cs @@ -84,9 +84,7 @@ namespace Greenshot.Controls { if (_cursor != null) { _cursor.Dispose(); } - if (_movableShowColorForm != null) { - _movableShowColorForm.Dispose(); - } + _movableShowColorForm?.Dispose(); } _movableShowColorForm = null; _cursor = null; @@ -114,10 +112,7 @@ namespace Greenshot.Controls { { //Release Capture should consume MouseUp when canceled with the escape key User32.ReleaseCapture(); - if (PipetteUsed != null) - { - PipetteUsed(this, new PipetteUsedArgs(_movableShowColorForm.color)); - } + PipetteUsed?.Invoke(this, new PipetteUsedArgs(_movableShowColorForm.color)); } base.OnMouseUp(e); } diff --git a/Greenshot/Controls/ToolStripColorButton.cs b/Greenshot/Controls/ToolStripColorButton.cs index 05391bfd7..ac4fcd736 100644 --- a/Greenshot/Controls/ToolStripColorButton.cs +++ b/Greenshot/Controls/ToolStripColorButton.cs @@ -70,14 +70,16 @@ namespace Greenshot.Controls { colorDialog.Color = SelectedColor; // Using the parent to make sure the dialog doesn't show on another window colorDialog.ShowDialog(Parent.Parent); - if (colorDialog.DialogResult != DialogResult.Cancel) { - if (!colorDialog.Color.Equals(SelectedColor)) { - SelectedColor = colorDialog.Color; - if (PropertyChanged != null) { - PropertyChanged(this, new PropertyChangedEventArgs("SelectedColor")); - } - } + if (colorDialog.DialogResult == DialogResult.Cancel) + { + return; } + if (colorDialog.Color.Equals(SelectedColor)) + { + return; + } + SelectedColor = colorDialog.Color; + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedColor")); } } } diff --git a/Greenshot/Controls/ToolStripNumericUpDown.cs b/Greenshot/Controls/ToolStripNumericUpDown.cs index f368f8409..f683f7c9b 100644 --- a/Greenshot/Controls/ToolStripNumericUpDown.cs +++ b/Greenshot/Controls/ToolStripNumericUpDown.cs @@ -34,16 +34,13 @@ namespace Greenshot.Controls { { } - public NumericUpDown NumericUpDown - { - get {return Control as NumericUpDown;} - } - + public NumericUpDown NumericUpDown => Control as NumericUpDown; + public decimal Value - { - get { return NumericUpDown.Value; } - set { NumericUpDown.Value = value;} - } + { + get { return NumericUpDown.Value; } + set { NumericUpDown.Value = value;} + } public decimal Minimum { get { return NumericUpDown.Minimum; } set { NumericUpDown.Minimum = value; } @@ -74,8 +71,9 @@ namespace Greenshot.Controls { NumericUpDown.ValueChanged -= _valueChanged; } - private void _valueChanged(object sender, EventArgs e) { - if(PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Value")); + private void _valueChanged(object sender, EventArgs e) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value")); } } } diff --git a/Greenshot/Destinations/EditorDestination.cs b/Greenshot/Destinations/EditorDestination.cs index ac300f386..ab66cd04e 100644 --- a/Greenshot/Destinations/EditorDestination.cs +++ b/Greenshot/Destinations/EditorDestination.cs @@ -66,7 +66,7 @@ namespace Greenshot.Destinations { } } - public override bool isDynamic { + public override bool IsDynamic { get { return true; } diff --git a/Greenshot/Destinations/EmailDestination.cs b/Greenshot/Destinations/EmailDestination.cs index 01593fded..5c6b7e013 100644 --- a/Greenshot/Destinations/EmailDestination.cs +++ b/Greenshot/Destinations/EmailDestination.cs @@ -32,77 +32,57 @@ namespace Greenshot.Destinations { /// Description of EmailDestination. /// public class EmailDestination : AbstractDestination { - private static readonly Image mailIcon = GreenshotResources.getImage("Email.Image"); - private static bool isActiveFlag; - private static string mapiClient; + private static readonly Image MailIcon = GreenshotResources.getImage("Email.Image"); + private static bool _isActiveFlag; + private static string _mapiClient; public const string DESIGNATION = "EMail"; static EmailDestination() { // Logic to decide what email implementation we use - if (EmailConfigHelper.HasMAPI()) { - isActiveFlag = true; - mapiClient = EmailConfigHelper.GetMapiClient(); - if (!string.IsNullOrEmpty(mapiClient)) { + if (EmailConfigHelper.HasMapi()) { + _isActiveFlag = true; + _mapiClient = EmailConfigHelper.GetMapiClient(); + if (!string.IsNullOrEmpty(_mapiClient)) { // Active as we have a mapi client, can be disabled later - isActiveFlag = true; + _isActiveFlag = true; } } } - public EmailDestination() { - - } - - public override string Designation { - get { - return DESIGNATION; - } - } + public override string Designation => DESIGNATION; public override string Description { get { // Make sure there is some kind of "mail" name - if (mapiClient == null) { - mapiClient = Language.GetString(LangKey.editor_email); + if (_mapiClient == null) { + _mapiClient = Language.GetString(LangKey.editor_email); } - return mapiClient; + return _mapiClient; } } - public override int Priority { - get { - return 3; - } - } + public override int Priority => 3; - public override bool isActive { + public override bool IsActive { get { - if (isActiveFlag) { + if (_isActiveFlag) { // Disable if the office plugin is installed and the client is outlook // TODO: Change this! It always creates an exception, as the plugin has not been loaded the type is not there :( Type outlookdestination = Type.GetType("GreenshotOfficePlugin.OutlookDestination,GreenshotOfficePlugin"); if (outlookdestination != null) { - if (mapiClient.ToLower().Contains("microsoft outlook")) { - isActiveFlag = false; + if (_mapiClient.ToLower().Contains("microsoft outlook")) { + _isActiveFlag = false; } } } - return base.isActive && isActiveFlag; + return base.IsActive && _isActiveFlag; } } - public override Keys EditorShortcutKeys { - get { - return Keys.Control | Keys.E; - } - } + public override Keys EditorShortcutKeys => Keys.Control | Keys.E; + + public override Image DisplayIcon => MailIcon; - public override Image DisplayIcon { - get { - return mailIcon; - } - } - public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { ExportInformation exportInformation = new ExportInformation(Designation, Description); MapiMailMessage.SendImage(surface, captureDetails); diff --git a/Greenshot/Destinations/FileDestination.cs b/Greenshot/Destinations/FileDestination.cs index 0a70073cd..d3f1a2cb4 100644 --- a/Greenshot/Destinations/FileDestination.cs +++ b/Greenshot/Destinations/FileDestination.cs @@ -35,60 +35,40 @@ namespace Greenshot.Destinations { /// Description of FileSaveAsDestination. /// public class FileDestination : AbstractDestination { - private static readonly ILog LOG = LogManager.GetLogger(typeof(FileDestination)); - private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly ILog Log = LogManager.GetLogger(typeof(FileDestination)); + private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); public const string DESIGNATION = "FileNoDialog"; - public override string Designation { - get { - return DESIGNATION; - } - } + public override string Designation => DESIGNATION; - public override string Description { - get { - return Language.GetString(LangKey.quicksettings_destination_file); - } - } + public override string Description => Language.GetString(LangKey.quicksettings_destination_file); - public override int Priority { - get { - return 0; - } - } + public override int Priority => 0; - public override Keys EditorShortcutKeys { - get { - return Keys.Control | Keys.S; - } - } - - public override Image DisplayIcon { - get { - return GreenshotResources.getImage("Save.Image"); - } - } + public override Keys EditorShortcutKeys => Keys.Control | Keys.S; + + public override Image DisplayIcon => GreenshotResources.getImage("Save.Image"); public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { ExportInformation exportInformation = new ExportInformation(Designation, Description); bool outputMade; - bool overwrite; - string fullPath; + bool overwrite; + string fullPath; // Get output settings from the configuration SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(); - if (captureDetails != null && captureDetails.Filename != null) { - // As we save a pre-selected file, allow to overwrite. - overwrite = true; - LOG.InfoFormat("Using previous filename"); - fullPath = captureDetails.Filename; + if (captureDetails?.Filename != null) { + // As we save a pre-selected file, allow to overwrite. + overwrite = true; + Log.InfoFormat("Using previous filename"); + fullPath = captureDetails.Filename; outputSettings.Format = ImageOutput.FormatForFilename(fullPath); - } else { - fullPath = CreateNewFilename(captureDetails); - // As we generate a file, the configuration tells us if we allow to overwrite - overwrite = conf.OutputFileAllowOverwrite; - } - if (conf.OutputFilePromptQuality) { + } else { + fullPath = CreateNewFilename(captureDetails); + // As we generate a file, the configuration tells us if we allow to overwrite + overwrite = CoreConfig.OutputFileAllowOverwrite; + } + if (CoreConfig.OutputFilePromptQuality) { QualityDialog qualityDialog = new QualityDialog(outputSettings); qualityDialog.ShowDialog(); } @@ -96,16 +76,16 @@ namespace Greenshot.Destinations { // Catching any exception to prevent that the user can't write in the directory. // This is done for e.g. bugs #2974608, #2963943, #2816163, #2795317, #2789218, #3004642 try { - ImageOutput.Save(surface, fullPath, overwrite, outputSettings, conf.OutputFileCopyPathToClipboard); + ImageOutput.Save(surface, fullPath, overwrite, outputSettings, CoreConfig.OutputFileCopyPathToClipboard); outputMade = true; } catch (ArgumentException ex1) { // Our generated filename exists, display 'save-as' - LOG.InfoFormat("Not overwriting: {0}", ex1.Message); + Log.InfoFormat("Not overwriting: {0}", ex1.Message); // when we don't allow to overwrite present a new SaveWithDialog fullPath = ImageOutput.SaveWithDialog(surface, captureDetails); outputMade = fullPath != null; } catch (Exception ex2) { - LOG.Error("Error saving screenshot!", 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 @@ -120,7 +100,7 @@ namespace Greenshot.Destinations { { captureDetails.Filename = fullPath; } - conf.OutputFileAsFullpath = fullPath; + CoreConfig.OutputFileAsFullpath = fullPath; } ProcessExport(exportInformation, surface); @@ -129,18 +109,18 @@ namespace Greenshot.Destinations { private static string CreateNewFilename(ICaptureDetails captureDetails) { string fullPath; - LOG.InfoFormat("Creating new filename"); - string pattern = conf.OutputFileFilenamePattern; + Log.InfoFormat("Creating new filename"); + string pattern = CoreConfig.OutputFileFilenamePattern; if (string.IsNullOrEmpty(pattern)) { pattern = "greenshot ${capturetime}"; } - string filename = FilenameHelper.GetFilenameFromPattern(pattern, conf.OutputFileFormat, captureDetails); - string filepath = FilenameHelper.FillVariables(conf.OutputFilePath, false); + string filename = FilenameHelper.GetFilenameFromPattern(pattern, CoreConfig.OutputFileFormat, captureDetails); + string filepath = FilenameHelper.FillVariables(CoreConfig.OutputFilePath, false); try { fullPath = Path.Combine(filepath, filename); } catch (ArgumentException) { // configured filename or path not valid, show error message... - LOG.InfoFormat("Generated path or filename not valid: {0}, {1}", filepath, filename); + Log.InfoFormat("Generated path or filename not valid: {0}, {1}", filepath, filename); MessageBox.Show(Language.GetString(LangKey.error_save_invalid_chars), Language.GetString(LangKey.error)); // ... lets get the pattern fixed.... diff --git a/Greenshot/Destinations/PickerDestination.cs b/Greenshot/Destinations/PickerDestination.cs index b185d112c..6a7fc29be 100644 --- a/Greenshot/Destinations/PickerDestination.cs +++ b/Greenshot/Destinations/PickerDestination.cs @@ -24,36 +24,20 @@ using Greenshot.Configuration; using GreenshotPlugin.Core; using Greenshot.Plugin; using Greenshot.Helpers; -using Greenshot.IniFile; -using log4net; namespace Greenshot.Destinations { /// /// The PickerDestination shows a context menu with all possible destinations, so the user can "pick" one /// public class PickerDestination : AbstractDestination { - private static ILog LOG = LogManager.GetLogger(typeof(PickerDestination)); - private static CoreConfiguration conf = IniConfig.GetIniSection(); public const string DESIGNATION = "Picker"; - public override string Designation { - get { - return DESIGNATION; - } - } + public override string Designation => DESIGNATION; - public override string Description { - get { - return Language.GetString(LangKey.settings_destination_picker); - } - } + public override string Description => Language.GetString(LangKey.settings_destination_picker); + + public override int Priority => 1; - public override int Priority { - get { - return 1; - } - } - /// /// Export the capture with the destination picker @@ -68,7 +52,7 @@ namespace Greenshot.Destinations { if ("Picker".Equals(destination.Designation)) { continue; } - if (!destination.isActive) { + if (!destination.IsActive) { continue; } destinations.Add(destination); diff --git a/Greenshot/Destinations/PrinterDestination.cs b/Greenshot/Destinations/PrinterDestination.cs index 846d2bd99..8fa0c5f2e 100644 --- a/Greenshot/Destinations/PrinterDestination.cs +++ b/Greenshot/Destinations/PrinterDestination.cs @@ -76,7 +76,7 @@ namespace Greenshot.Destinations { } } - public override bool isDynamic { + public override bool IsDynamic { get { return true; } diff --git a/Greenshot/Drawing/Adorners/MoveAdorner.cs b/Greenshot/Drawing/Adorners/MoveAdorner.cs index 0cc39bb33..2d0c8d390 100644 --- a/Greenshot/Drawing/Adorners/MoveAdorner.cs +++ b/Greenshot/Drawing/Adorners/MoveAdorner.cs @@ -45,13 +45,7 @@ namespace Greenshot.Drawing.Adorners /// /// Returns the cursor for when the mouse is over the adorner /// - public override Cursor Cursor - { - get - { - return Cursors.SizeAll; - } - } + public override Cursor Cursor => Cursors.SizeAll; /// /// Handle the mouse down @@ -147,7 +141,6 @@ namespace Greenshot.Drawing.Adorners public override void Paint(PaintEventArgs paintEventArgs) { Graphics targetGraphics = paintEventArgs.Graphics; - Rectangle clipRectangle = paintEventArgs.ClipRectangle; var bounds = Bounds; GraphicsState state = targetGraphics.Save(); diff --git a/Greenshot/Drawing/Adorners/ResizeAdorner.cs b/Greenshot/Drawing/Adorners/ResizeAdorner.cs index ea6ab3843..55635e098 100644 --- a/Greenshot/Drawing/Adorners/ResizeAdorner.cs +++ b/Greenshot/Drawing/Adorners/ResizeAdorner.cs @@ -168,7 +168,6 @@ namespace Greenshot.Drawing.Adorners public override void Paint(PaintEventArgs paintEventArgs) { Graphics targetGraphics = paintEventArgs.Graphics; - Rectangle clipRectangle = paintEventArgs.ClipRectangle; var bounds = Bounds; GraphicsState state = targetGraphics.Save(); diff --git a/Greenshot/Drawing/Adorners/TargetAdorner.cs b/Greenshot/Drawing/Adorners/TargetAdorner.cs index cbb80e63a..92c51b5b9 100644 --- a/Greenshot/Drawing/Adorners/TargetAdorner.cs +++ b/Greenshot/Drawing/Adorners/TargetAdorner.cs @@ -95,7 +95,6 @@ namespace Greenshot.Drawing.Adorners public override void Paint(PaintEventArgs paintEventArgs) { Graphics targetGraphics = paintEventArgs.Graphics; - Rectangle clipRectangle = paintEventArgs.ClipRectangle; var bounds = Bounds; targetGraphics.FillRectangle(Brushes.Green, bounds.X, bounds.Y, bounds.Width, bounds.Height); diff --git a/Greenshot/Drawing/DrawableContainer.cs b/Greenshot/Drawing/DrawableContainer.cs index 7cdd62b61..92c3a92d7 100644 --- a/Greenshot/Drawing/DrawableContainer.cs +++ b/Greenshot/Drawing/DrawableContainer.cs @@ -383,12 +383,12 @@ namespace Greenshot.Drawing Rectangle drawingRect = new Rectangle(Bounds.Location, Bounds.Size); drawingRect.Intersect(clipRectangle); if(filter is MagnifierFilter) { - // quick&dirty bugfix, because MagnifierFilter behaves differently when drawn only partially - // what we should actually do to resolve this is add a better magnifier which is not that special - filter.Apply(graphics, bmp, Bounds, renderMode); - } else { - filter.Apply(graphics, bmp, drawingRect, renderMode); - } + // quick&dirty bugfix, because MagnifierFilter behaves differently when drawn only partially + // what we should actually do to resolve this is add a better magnifier which is not that special + filter.Apply(graphics, bmp, Bounds, renderMode); + } else { + filter.Apply(graphics, bmp, drawingRect, renderMode); + } } } } @@ -517,7 +517,7 @@ namespace Greenshot.Drawing /// public void HandleFieldChanged(object sender, FieldChangedEventArgs e) { LOG.DebugFormat("Field {0} changed", e.Field.FieldType); - if (e.Field.FieldType == FieldType.SHADOW) { + if (Equals(e.Field.FieldType, FieldType.SHADOW)) { accountForShadowChange = true; } } diff --git a/Greenshot/Drawing/Fields/AbstractFieldHolder.cs b/Greenshot/Drawing/Fields/AbstractFieldHolder.cs index 3a8fd54bc..e0f1c864c 100644 --- a/Greenshot/Drawing/Fields/AbstractFieldHolder.cs +++ b/Greenshot/Drawing/Fields/AbstractFieldHolder.cs @@ -20,6 +20,7 @@ */ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Drawing; using System.Runtime.Serialization; @@ -37,52 +38,55 @@ namespace Greenshot.Drawing.Fields public abstract class AbstractFieldHolder : IFieldHolder { private static readonly ILog LOG = LogManager.GetLogger(typeof(AbstractFieldHolder)); - private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); + private static readonly EditorConfiguration EditorConfig = IniConfig.GetIniSection(); + private readonly IDictionary _handlers = new Dictionary(); /// /// called when a field's value has changed /// [NonSerialized] - private FieldChangedEventHandler fieldChanged; + private FieldChangedEventHandler _fieldChanged; + public event FieldChangedEventHandler FieldChanged { - add { fieldChanged += value; } - remove { fieldChanged -= value; } + add { _fieldChanged += value; } + remove { _fieldChanged -= value; } } // we keep two Collections of our fields, dictionary for quick access, list for serialization // this allows us to use default serialization [NonSerialized] - private IDictionary fieldsByType = new Dictionary(); - private IList fields = new List(); - - public AbstractFieldHolder() { } + private IDictionary _fieldsByType = new Dictionary(); + private readonly IList fields = new List(); [OnDeserialized] private void OnDeserialized(StreamingContext context) { - fieldsByType = new Dictionary(); + _fieldsByType = new Dictionary(); // listen to changing properties - foreach (Field field in fields) + foreach (var field in fields) { field.PropertyChanged += delegate { - if (fieldChanged != null) - { - fieldChanged(this, new FieldChangedEventArgs(field)); - } + _fieldChanged?.Invoke(this, new FieldChangedEventArgs(field)); }; - fieldsByType[field.FieldType] = field; + _fieldsByType[field.FieldType] = field; } } public void AddField(Type requestingType, IFieldType fieldType, object fieldValue) { - AddField(editorConfiguration.CreateField(requestingType, fieldType, fieldValue)); + AddField(EditorConfig.CreateField(requestingType, fieldType, fieldValue)); } public virtual void AddField(IField field) { - if (fieldsByType != null && fieldsByType.ContainsKey(field.FieldType)) + fields.Add(field); + if (_fieldsByType == null) + { + return; + } + + if (_fieldsByType.ContainsKey(field.FieldType)) { if (LOG.IsDebugEnabled) { @@ -90,21 +94,21 @@ namespace Greenshot.Drawing.Fields } } - fields.Add(field); - fieldsByType[field.FieldType] = field; - field.PropertyChanged += delegate { if (fieldChanged != null) fieldChanged(this, new FieldChangedEventArgs(field)); }; + _fieldsByType[field.FieldType] = field; + + _handlers[field] = (sender, args) => + { + _fieldChanged?.Invoke(this, new FieldChangedEventArgs(field)); + }; + field.PropertyChanged += _handlers[field]; } public void RemoveField(IField field) { fields.Remove(field); - fieldsByType.Remove(field.FieldType); - field.PropertyChanged -= delegate { - if (fieldChanged != null) - { - fieldChanged(this, new FieldChangedEventArgs(field)); - } - }; + _fieldsByType.Remove(field.FieldType); + field.PropertyChanged -= _handlers[field]; + _handlers.Remove(field); } public IList GetFields() @@ -117,7 +121,7 @@ namespace Greenshot.Drawing.Fields { try { - return fieldsByType[fieldType]; + return _fieldsByType[fieldType]; } catch (KeyNotFoundException e) { @@ -169,19 +173,19 @@ namespace Greenshot.Drawing.Fields public bool HasField(IFieldType fieldType) { - return fieldsByType.ContainsKey(fieldType); + return _fieldsByType.ContainsKey(fieldType); } public bool HasFieldValue(IFieldType fieldType) { - return HasField(fieldType) && fieldsByType[fieldType].HasValue; + return HasField(fieldType) && _fieldsByType[fieldType].HasValue; } public void SetFieldValue(IFieldType fieldType, object value) { try { - fieldsByType[fieldType].Value = value; + _fieldsByType[fieldType].Value = value; } catch (KeyNotFoundException e) { @@ -191,10 +195,7 @@ namespace Greenshot.Drawing.Fields protected void OnFieldChanged(object sender, FieldChangedEventArgs e) { - if (fieldChanged != null) - { - fieldChanged(sender, e); - } + _fieldChanged?.Invoke(sender, e); } } } diff --git a/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs b/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs index 55c810d27..6aac87393 100644 --- a/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs +++ b/Greenshot/Drawing/Fields/AbstractFieldHolderWithChildren.cs @@ -34,7 +34,7 @@ namespace Greenshot.Drawing.Fields [Serializable()] public abstract class AbstractFieldHolderWithChildren : AbstractFieldHolder { - private FieldChangedEventHandler fieldChangedEventHandler; + private readonly FieldChangedEventHandler _fieldChangedEventHandler; [NonSerialized] private EventHandler childrenChanged; @@ -48,7 +48,7 @@ namespace Greenshot.Drawing.Fields public AbstractFieldHolderWithChildren() { - fieldChangedEventHandler = OnFieldChanged; + _fieldChangedEventHandler = OnFieldChanged; } [OnDeserialized()] @@ -57,28 +57,28 @@ namespace Greenshot.Drawing.Fields // listen to changing properties foreach (IFieldHolder fieldHolder in Children) { - fieldHolder.FieldChanged += fieldChangedEventHandler; + fieldHolder.FieldChanged += _fieldChangedEventHandler; } - if (childrenChanged != null) childrenChanged(this, EventArgs.Empty); + childrenChanged?.Invoke(this, EventArgs.Empty); } public void AddChild(IFieldHolder fieldHolder) { Children.Add(fieldHolder); - fieldHolder.FieldChanged += fieldChangedEventHandler; - if (childrenChanged != null) childrenChanged(this, EventArgs.Empty); + fieldHolder.FieldChanged += _fieldChangedEventHandler; + childrenChanged?.Invoke(this, EventArgs.Empty); } public void RemoveChild(IFieldHolder fieldHolder) { Children.Remove(fieldHolder); - fieldHolder.FieldChanged -= fieldChangedEventHandler; - if (childrenChanged != null) childrenChanged(this, EventArgs.Empty); + fieldHolder.FieldChanged -= _fieldChangedEventHandler; + childrenChanged?.Invoke(this, EventArgs.Empty); } public new IList GetFields() { - List ret = new List(); + var ret = new List(); ret.AddRange(base.GetFields()); foreach (IFieldHolder fh in Children) { diff --git a/Greenshot/Drawing/Fields/Binding/BidirectionalBinding.cs b/Greenshot/Drawing/Fields/Binding/BidirectionalBinding.cs index 3a3833d4b..69aa3feae 100644 --- a/Greenshot/Drawing/Fields/Binding/BidirectionalBinding.cs +++ b/Greenshot/Drawing/Fields/Binding/BidirectionalBinding.cs @@ -129,7 +129,7 @@ namespace Greenshot.Drawing.Fields.Binding { targetPropertyInfo.SetValue(targetObject, bValue, null); } } catch (Exception e) { - throw new MemberAccessException("Could not set property '"+targetProperty+"' to '"+bValue+"' ["+(bValue!=null?bValue.GetType().Name:"")+"] on "+targetObject+". Probably other type than expected, IBindingCoverter to the rescue.", e); + throw new MemberAccessException("Could not set property '"+targetProperty+"' to '"+bValue+"' ["+(bValue?.GetType().Name ?? "")+"] on "+targetObject+". Probably other type than expected, IBindingCoverter to the rescue.", e); } } diff --git a/Greenshot/Drawing/Fields/Field.cs b/Greenshot/Drawing/Fields/Field.cs index cf6c1b81b..f6434b73a 100644 --- a/Greenshot/Drawing/Fields/Field.cs +++ b/Greenshot/Drawing/Fields/Field.cs @@ -47,10 +47,7 @@ namespace Greenshot.Drawing.Fields if (!Equals(_myValue, value)) { _myValue = value; - if (PropertyChanged != null) - { - PropertyChanged(this, new PropertyChangedEventArgs("Value")); - } + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value")); } } } @@ -93,10 +90,7 @@ namespace Greenshot.Drawing.Fields /// /// Returns true if this field holds a value other than null. /// - public bool HasValue - { - get { return Value != null; } - } + public bool HasValue => Value != null; /// /// Creates a flat clone of this Field. The fields value itself is not cloned. @@ -104,9 +98,7 @@ namespace Greenshot.Drawing.Fields /// public Field Clone() { - Field ret = new Field(FieldType, Scope); - ret.Value = Value; - return ret; + return new Field(FieldType, Scope) {Value = Value}; } public override int GetHashCode() @@ -123,7 +115,7 @@ namespace Greenshot.Drawing.Fields public override bool Equals(object obj) { - Field other = obj as Field; + var other = obj as Field; if (other == null) { return false; diff --git a/Greenshot/Drawing/Fields/FieldAggregator.cs b/Greenshot/Drawing/Fields/FieldAggregator.cs index efeab79bd..8f3631f87 100644 --- a/Greenshot/Drawing/Fields/FieldAggregator.cs +++ b/Greenshot/Drawing/Fields/FieldAggregator.cs @@ -24,7 +24,6 @@ using Greenshot.IniFile; using Greenshot.Plugin; using Greenshot.Plugin.Drawing; using GreenshotPlugin.Interfaces.Drawing; -using log4net; using System.Collections.Generic; using System.ComponentModel; @@ -41,26 +40,25 @@ namespace Greenshot.Drawing.Fields /// Properties that do not apply for ALL selected elements are null (or 0 respectively) /// If the property values of the selected elements differ, the value of the last bound element wins. /// - public class FieldAggregator : AbstractFieldHolder + public sealed class FieldAggregator : AbstractFieldHolder { - private IDrawableContainerList boundContainers; - private bool internalUpdateRunning = false; + private readonly IDrawableContainerList _boundContainers; + private bool _internalUpdateRunning; - private enum Status { IDLE, BINDING, UPDATING }; - - private static readonly ILog LOG = LogManager.GetLogger(typeof(FieldAggregator)); - private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); + private static readonly EditorConfiguration EditorConfig = IniConfig.GetIniSection(); public FieldAggregator(ISurface parent) { - foreach (FieldType fieldType in FieldType.Values) + foreach (var fieldType in FieldType.Values) { - Field field = new Field(fieldType, GetType()); + var field = new Field(fieldType, GetType()); AddField(field); } - boundContainers = new DrawableContainerList(); - boundContainers.Parent = parent; + _boundContainers = new DrawableContainerList + { + Parent = parent + }; } public override void AddField(IField field) @@ -71,7 +69,7 @@ namespace Greenshot.Drawing.Fields public void BindElements(IDrawableContainerList dcs) { - foreach (DrawableContainer dc in dcs) + foreach (var dc in dcs) { BindElement(dc); } @@ -80,14 +78,15 @@ namespace Greenshot.Drawing.Fields public void BindElement(IDrawableContainer dc) { DrawableContainer container = dc as DrawableContainer; - if (container != null && !boundContainers.Contains(container)) + if (container == null || _boundContainers.Contains(container)) { - boundContainers.Add(container); - container.ChildrenChanged += delegate { - UpdateFromBoundElements(); - }; - UpdateFromBoundElements(); + return; } + _boundContainers.Add(container); + container.ChildrenChanged += delegate { + UpdateFromBoundElements(); + }; + UpdateFromBoundElements(); } public void BindAndUpdateElement(IDrawableContainer dc) @@ -103,8 +102,8 @@ namespace Greenshot.Drawing.Fields { return; } - internalUpdateRunning = true; - foreach (Field field in GetFields()) + _internalUpdateRunning = true; + foreach (var field in GetFields()) { if (container.HasField(field.FieldType) && field.HasValue) { @@ -112,14 +111,14 @@ namespace Greenshot.Drawing.Fields container.SetFieldValue(field.FieldType, field.Value); } } - internalUpdateRunning = false; + _internalUpdateRunning = false; } public void UnbindElement(IDrawableContainer dc) { - if (boundContainers.Contains(dc)) + if (_boundContainers.Contains(dc)) { - boundContainers.Remove(dc); + _boundContainers.Remove(dc); UpdateFromBoundElements(); } } @@ -127,7 +126,7 @@ namespace Greenshot.Drawing.Fields public void Clear() { ClearFields(); - boundContainers.Clear(); + _boundContainers.Clear(); UpdateFromBoundElements(); } @@ -136,12 +135,12 @@ namespace Greenshot.Drawing.Fields /// private void ClearFields() { - internalUpdateRunning = true; - foreach (Field field in GetFields()) + _internalUpdateRunning = true; + foreach (var field in GetFields()) { field.Value = null; } - internalUpdateRunning = false; + _internalUpdateRunning = false; } /// @@ -152,27 +151,27 @@ namespace Greenshot.Drawing.Fields private void UpdateFromBoundElements() { ClearFields(); - internalUpdateRunning = true; + _internalUpdateRunning = true; foreach (var field in FindCommonFields()) { SetFieldValue(field.FieldType, field.Value); } - internalUpdateRunning = false; + _internalUpdateRunning = false; } private IList FindCommonFields() { IList returnFields = null; - if (boundContainers.Count > 0) + if (_boundContainers.Count > 0) { // take all fields from the least selected container... - DrawableContainer leastSelectedContainer = boundContainers[boundContainers.Count - 1] as DrawableContainer; + DrawableContainer leastSelectedContainer = _boundContainers[_boundContainers.Count - 1] as DrawableContainer; if (leastSelectedContainer != null) { returnFields = leastSelectedContainer.GetFields(); - for (int i = 0; i < boundContainers.Count - 1; i++) + for (int i = 0; i < _boundContainers.Count - 1; i++) { - DrawableContainer dc = boundContainers[i] as DrawableContainer; + DrawableContainer dc = _boundContainers[i] as DrawableContainer; if (dc != null) { IList fieldsToRemove = new List(); @@ -184,7 +183,7 @@ namespace Greenshot.Drawing.Fields fieldsToRemove.Add(field); } } - foreach (IField field in fieldsToRemove) + foreach (var field in fieldsToRemove) { returnFields.Remove(field); } @@ -192,31 +191,30 @@ namespace Greenshot.Drawing.Fields } } } - if (returnFields == null) - { - returnFields = new List(); - } - return returnFields; + return returnFields ?? new List(); } public void OwnPropertyChanged(object sender, PropertyChangedEventArgs ea) { IField field = (IField)sender; - if (!internalUpdateRunning && field.Value != null) + if (_internalUpdateRunning || field.Value == null) { - foreach (DrawableContainer drawableContainer in boundContainers) + return; + } + foreach (var drawableContainer1 in _boundContainers) + { + var drawableContainer = (DrawableContainer) drawableContainer1; + if (!drawableContainer.HasField(field.FieldType)) { - if (drawableContainer.HasField(field.FieldType)) - { - IField drawableContainerField = drawableContainer.GetField(field.FieldType); - // Notify before change, so we can e.g. invalidate the area - drawableContainer.BeforeFieldChange(drawableContainerField, field.Value); - - drawableContainerField.Value = field.Value; - // update last used from DC field, so that scope is honored - editorConfiguration.UpdateLastFieldValue(drawableContainerField); - } + continue; } + IField drawableContainerField = drawableContainer.GetField(field.FieldType); + // Notify before change, so we can e.g. invalidate the area + drawableContainer.BeforeFieldChange(drawableContainerField, field.Value); + + drawableContainerField.Value = field.Value; + // update last used from DC field, so that scope is honored + EditorConfig.UpdateLastFieldValue(drawableContainerField); } } diff --git a/Greenshot/Drawing/Filters/AbstractFilter.cs b/Greenshot/Drawing/Filters/AbstractFilter.cs index e648c4291..e84d8913f 100644 --- a/Greenshot/Drawing/Filters/AbstractFilter.cs +++ b/Greenshot/Drawing/Filters/AbstractFilter.cs @@ -72,10 +72,9 @@ namespace Greenshot.Drawing.Filters { public abstract void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode); - protected void OnPropertyChanged(string propertyName) { - if (propertyChanged != null) { - propertyChanged(this, new PropertyChangedEventArgs(propertyName)); - } + protected void OnPropertyChanged(string propertyName) + { + propertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } diff --git a/Greenshot/Drawing/FreehandContainer.cs b/Greenshot/Drawing/FreehandContainer.cs index 2f672a4ff..e8654bc4e 100644 --- a/Greenshot/Drawing/FreehandContainer.cs +++ b/Greenshot/Drawing/FreehandContainer.cs @@ -34,7 +34,7 @@ namespace Greenshot.Drawing { /// [Serializable] public class FreehandContainer : DrawableContainer { - private static readonly float [] POINT_OFFSET = new float[]{0.5f, 0.25f, 0.75f}; + private static readonly float [] PointOffset = {0.5f, 0.25f, 0.75f}; [NonSerialized] private GraphicsPath freehandPath = new GraphicsPath(); @@ -77,10 +77,9 @@ namespace Greenshot.Drawing { /// When disposing==true all non-managed resources should be freed too! protected override void Dispose(bool disposing) { base.Dispose(disposing); - if (disposing) { - if (freehandPath != null) { - freehandPath.Dispose(); - } + if (disposing) + { + freehandPath?.Dispose(); } freehandPath = null; } @@ -133,9 +132,7 @@ namespace Greenshot.Drawing { private void RecalculatePath() { isRecalculated = true; // Dispose the previous path, if we have one - if (freehandPath != null) { - freehandPath.Dispose(); - } + freehandPath?.Dispose(); freehandPath = new GraphicsPath(); // Here we can put some cleanup... like losing all the uninteresting points. @@ -143,7 +140,7 @@ namespace Greenshot.Drawing { int index = 0; while ((capturePoints.Count - 1) % 3 != 0) { // duplicate points, first at 50% than 25% than 75% - capturePoints.Insert((int)(capturePoints.Count*POINT_OFFSET[index]), capturePoints[(int)(capturePoints.Count*POINT_OFFSET[index++])]); + capturePoints.Insert((int)(capturePoints.Count*PointOffset[index]), capturePoints[(int)(capturePoints.Count*PointOffset[index++])]); } freehandPath.AddBeziers(capturePoints.ToArray()); } else if (capturePoints.Count == 2) { @@ -228,9 +225,9 @@ namespace Greenshot.Drawing { /// public override bool Equals(object obj) { bool ret = false; - if(obj != null && GetType().Equals(obj.GetType())) { + if(obj != null && GetType() == obj.GetType()) { FreehandContainer other = obj as FreehandContainer; - if(freehandPath.Equals(other.freehandPath)) { + if(other != null && freehandPath.Equals(other.freehandPath)) { ret = true; } } diff --git a/Greenshot/Drawing/HighlightContainer.cs b/Greenshot/Drawing/HighlightContainer.cs index 2f77fc158..82a352469 100644 --- a/Greenshot/Drawing/HighlightContainer.cs +++ b/Greenshot/Drawing/HighlightContainer.cs @@ -57,7 +57,7 @@ namespace Greenshot.Drawing { if (!sender.Equals(this)) { return; } - if (e.Field.FieldType == FieldType.PREPARED_FILTER_HIGHLIGHT) { + if (Equals(e.Field.FieldType, FieldType.PREPARED_FILTER_HIGHLIGHT)) { ConfigurePreparedFilters(); } } @@ -72,12 +72,16 @@ namespace Greenshot.Drawing { Add(new HighlightFilter(this)); break; case PreparedFilter.AREA_HIGHLIGHT: - AbstractFilter bf = new BrightnessFilter(this); - bf.Invert = true; - Add(bf); - bf = new BlurFilter(this); - bf.Invert = true; - Add(bf); + var brightnessFilter = new BrightnessFilter(this) + { + Invert = true + }; + Add(brightnessFilter); + var blurFilter = new BlurFilter(this) + { + Invert = true + }; + Add(blurFilter); break; case PreparedFilter.GRAYSCALE: AbstractFilter f = new GrayscaleFilter(this); diff --git a/Greenshot/Drawing/IconContainer.cs b/Greenshot/Drawing/IconContainer.cs index 8e5647a08..2277bd48a 100644 --- a/Greenshot/Drawing/IconContainer.cs +++ b/Greenshot/Drawing/IconContainer.cs @@ -32,7 +32,7 @@ namespace Greenshot.Drawing { /// [Serializable] public class IconContainer : DrawableContainer, IIconContainer { - private static readonly ILog LOG = LogManager.GetLogger(typeof(IconContainer)); + private static readonly ILog Log = LogManager.GetLogger(typeof(IconContainer)); protected Icon icon; @@ -57,9 +57,7 @@ namespace Greenshot.Drawing { public Icon Icon { set { - if (icon != null) { - icon.Dispose(); - } + icon?.Dispose(); icon = (Icon)value.Clone(); Width = value.Width; Height = value.Height; @@ -72,10 +70,9 @@ namespace Greenshot.Drawing { * When disposing==true all non-managed resources should be freed too! */ protected override void Dispose(bool disposing) { - if (disposing) { - if (icon != null) { - icon.Dispose(); - } + if (disposing) + { + icon?.Dispose(); } icon = null; base.Dispose(disposing); @@ -85,7 +82,7 @@ namespace Greenshot.Drawing { if (File.Exists(filename)) { using (Icon fileIcon = new Icon(filename)) { Icon = fileIcon; - LOG.Debug("Loaded file: " + filename + " with resolution: " + Height + "," + Width); + Log.Debug("Loaded file: " + filename + " with resolution: " + Height + "," + Width); } } } @@ -100,16 +97,8 @@ namespace Greenshot.Drawing { } } - public override bool HasDefaultSize { - get { - return true; - } - } + public override bool HasDefaultSize => true; - public override Size DefaultSize { - get { - return icon.Size; - } - } + public override Size DefaultSize => icon.Size; } } diff --git a/Greenshot/Drawing/ImageContainer.cs b/Greenshot/Drawing/ImageContainer.cs index 172ac7e9a..b29a92683 100644 --- a/Greenshot/Drawing/ImageContainer.cs +++ b/Greenshot/Drawing/ImageContainer.cs @@ -28,6 +28,7 @@ using System.Drawing.Drawing2D; using Greenshot.Core; using log4net; using System.Runtime.Serialization; +using GreenshotPlugin.Effects; using GreenshotPlugin.Interfaces.Drawing; namespace Greenshot.Drawing { diff --git a/Greenshot/Drawing/ObfuscateContainer.cs b/Greenshot/Drawing/ObfuscateContainer.cs index 19782afab..ec3b0d734 100644 --- a/Greenshot/Drawing/ObfuscateContainer.cs +++ b/Greenshot/Drawing/ObfuscateContainer.cs @@ -52,7 +52,7 @@ namespace Greenshot.Drawing { protected void ObfuscateContainer_OnFieldChanged(object sender, FieldChangedEventArgs e) { if(sender.Equals(this)) { - if(e.Field.FieldType == FieldType.PREPARED_FILTER_OBFUSCATE) { + if(Equals(e.Field.FieldType, FieldType.PREPARED_FILTER_OBFUSCATE)) { ConfigurePreparedFilters(); } } diff --git a/Greenshot/Drawing/RoundedRectangle.cs b/Greenshot/Drawing/RoundedRectangle.cs index 751cc9ea1..54553ac37 100644 --- a/Greenshot/Drawing/RoundedRectangle.cs +++ b/Greenshot/Drawing/RoundedRectangle.cs @@ -19,6 +19,7 @@ * along with this program. If not, see . */ +using System; using System.Drawing; using System.Drawing.Drawing2D; @@ -27,6 +28,7 @@ namespace Greenshot.Drawing { /// TODO: currently this is only used in the capture form, we might move this code directly to there! /// public abstract class RoundedRectangle { + [Flags] public enum RectangleCorners { None = 0, TopLeft = 1, TopRight = 2, BottomLeft = 4, BottomRight = 8, diff --git a/Greenshot/Drawing/StepLabelContainer.cs b/Greenshot/Drawing/StepLabelContainer.cs index fd1da0091..d47f2ad0f 100644 --- a/Greenshot/Drawing/StepLabelContainer.cs +++ b/Greenshot/Drawing/StepLabelContainer.cs @@ -84,9 +84,11 @@ namespace Greenshot.Drawing { protected override void OnDeserialized(StreamingContext context) { Init(); - _stringFormat = new StringFormat(); - _stringFormat.Alignment = StringAlignment.Center; - _stringFormat.LineAlignment = StringAlignment.Center; + _stringFormat = new StringFormat + { + Alignment = StringAlignment.Center, + LineAlignment = StringAlignment.Center + }; } /// @@ -98,20 +100,14 @@ namespace Greenshot.Drawing { { return; } - if (Parent != null) { - ((Surface)Parent).RemoveStepLabel(this); - } + ((Surface) Parent)?.RemoveStepLabel(this); base.SwitchParent(newParent); if (newParent != null) { ((Surface)Parent)?.AddStepLabel(this); } } - public override Size DefaultSize { - get { - return new Size(30, 30); - } - } + public override Size DefaultSize => new Size(30, 30); public override bool InitContent() { _defaultEditMode = EditStatus.IDLE; @@ -148,14 +144,13 @@ namespace Greenshot.Drawing { if (!disposing) { return; } - if (Parent != null) + ((Surface) Parent)?.RemoveStepLabel(this); + if (_stringFormat == null) { - ((Surface)Parent).RemoveStepLabel(this); - } - if (_stringFormat != null) { - _stringFormat.Dispose(); - _stringFormat = null; + return; } + _stringFormat.Dispose(); + _stringFormat = null; } public override bool HandleMouseMove(int x, int y) { diff --git a/Greenshot/Drawing/Surface.cs b/Greenshot/Drawing/Surface.cs index 3edf59364..3754b9f7f 100644 --- a/Greenshot/Drawing/Surface.cs +++ b/Greenshot/Drawing/Surface.cs @@ -40,6 +40,7 @@ using System.Drawing.Imaging; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Windows.Forms; +using GreenshotPlugin.Effects; namespace Greenshot.Drawing { @@ -48,9 +49,9 @@ namespace Greenshot.Drawing /// public sealed class Surface : Control, ISurface { - private static ILog LOG = LogManager.GetLogger(typeof(Surface)); - public static int Count = 0; - private static CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly ILog LOG = LogManager.GetLogger(typeof(Surface)); + public static int Count; + private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); // Property to identify the Surface ID private Guid _uniqueId = Guid.NewGuid(); @@ -276,11 +277,6 @@ namespace Greenshot.Drawing /// private IDrawableContainer _cursorContainer; - /// - /// the capture details, needed with serialization - /// - private ICaptureDetails _captureDetails; - /// /// the modified flag specifies if the surface has had modifications after the last export. /// Initial state is modified, as "it's not saved" @@ -325,31 +321,19 @@ namespace Greenshot.Drawing /// /// The cursor container has it's own accessor so we can find and remove this (when needed) /// - public IDrawableContainer CursorContainer - { - get - { - return _cursorContainer; - } - } + public IDrawableContainer CursorContainer => _cursorContainer; /// /// A simple getter to ask if this surface has a cursor /// - public bool HasCursor - { - get - { - return _cursorContainer != null; - } - } + public bool HasCursor => _cursorContainer != null; /// /// A simple helper method to remove the cursor from the surface /// public void RemoveCursor() { - RemoveElement(_cursorContainer, true); + RemoveElement(_cursorContainer); _cursorContainer = null; } @@ -409,8 +393,10 @@ namespace Greenshot.Drawing _drawingMode = value; if (_drawingModeChanged != null) { - SurfaceDrawingModeEventArgs eventArgs = new SurfaceDrawingModeEventArgs(); - eventArgs.DrawingMode = _drawingMode; + SurfaceDrawingModeEventArgs eventArgs = new SurfaceDrawingModeEventArgs + { + DrawingMode = _drawingMode + }; _drawingModeChanged.Invoke(this, eventArgs); } DeselectAllElements(); @@ -445,22 +431,12 @@ namespace Greenshot.Drawing /// /// Property for accessing the capture details /// - public ICaptureDetails CaptureDetails - { - get - { - return _captureDetails; - } - set - { - _captureDetails = value; - } - } + public ICaptureDetails CaptureDetails { get; set; } /// /// Base Surface constructor /// - public Surface() : base() + public Surface() { _fieldAggregator = new FieldAggregator(this); Count++; @@ -537,7 +513,7 @@ namespace Greenshot.Drawing // Make sure the image is NOT disposed, we took the reference directly into ourselves ((Capture)capture).NullImage(); - _captureDetails = capture.CaptureDetails; + CaptureDetails = capture.CaptureDetails; } protected override void Dispose(bool disposing) @@ -615,46 +591,22 @@ namespace Greenshot.Drawing /// /// Returns if the surface can do a undo /// - public bool CanUndo - { - get - { - return _undoStack.Count > 0; - } - } + public bool CanUndo => _undoStack.Count > 0; /// /// Returns if the surface can do a redo /// - public bool CanRedo - { - get - { - return _redoStack.Count > 0; - } - } + public bool CanRedo => _redoStack.Count > 0; /// /// Get the language key for the undo action /// - public LangKey UndoActionLanguageKey - { - get - { - return LangKey.none; - } - } + public LangKey UndoActionLanguageKey => LangKey.none; /// /// Get the language key for redo action /// - public LangKey RedoActionLanguageKey - { - get - { - return LangKey.none; - } - } + public LangKey RedoActionLanguageKey => LangKey.none; /// /// Make an action undo-able @@ -722,9 +674,7 @@ namespace Greenshot.Drawing IDrawableContainerList loadedElements = (IDrawableContainerList)binaryRead.Deserialize(streamRead); loadedElements.Parent = this; // Make sure the steplabels are sorted accoring to their number - _stepLabels.Sort(delegate (StepLabelContainer p1, StepLabelContainer p2) { - return p1.Number.CompareTo(p2.Number); - }); + _stepLabels.Sort((p1, p2) => p1.Number.CompareTo(p2.Number)); DeselectAllElements(); AddElements(loadedElements); SelectElements(loadedElements); @@ -799,10 +749,12 @@ namespace Greenshot.Drawing #region Plugin interface implementations public IImageContainer AddImageContainer(Image image, int x, int y) { - ImageContainer bitmapContainer = new ImageContainer(this); - bitmapContainer.Image = image; - bitmapContainer.Left = x; - bitmapContainer.Top = y; + ImageContainer bitmapContainer = new ImageContainer(this) + { + Image = image, + Left = x, + Top = y + }; AddElement(bitmapContainer); return bitmapContainer; } @@ -818,10 +770,12 @@ namespace Greenshot.Drawing } public IIconContainer AddIconContainer(Icon icon, int x, int y) { - IconContainer iconContainer = new IconContainer(this); - iconContainer.Icon = icon; - iconContainer.Left = x; - iconContainer.Top = y; + IconContainer iconContainer = new IconContainer(this) + { + Icon = icon, + Left = x, + Top = y + }; AddElement(iconContainer); return iconContainer; } @@ -836,10 +790,12 @@ namespace Greenshot.Drawing } public ICursorContainer AddCursorContainer(Cursor cursor, int x, int y) { - CursorContainer cursorContainer = new CursorContainer(this); - cursorContainer.Cursor = cursor; - cursorContainer.Left = x; - cursorContainer.Top = y; + CursorContainer cursorContainer = new CursorContainer(this) + { + Cursor = cursor, + Left = x, + Top = y + }; AddElement(cursorContainer); return cursorContainer; } @@ -855,8 +811,7 @@ namespace Greenshot.Drawing public ITextContainer AddTextContainer(string text, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment, FontFamily family, float size, bool italic, bool bold, bool shadow, int borderSize, Color color, Color fillColor) { - TextContainer textContainer = new TextContainer(this); - textContainer.Text = text; + TextContainer textContainer = new TextContainer(this) {Text = text}; textContainer.SetFieldValue(FieldType.FONT_FAMILY, family.Name); textContainer.SetFieldValue(FieldType.FONT_BOLD, bold); textContainer.SetFieldValue(FieldType.FONT_ITALIC, italic); @@ -1069,10 +1024,12 @@ namespace Greenshot.Drawing { if (_surfaceMessage != null) { - SurfaceMessageEventArgs eventArgs = new SurfaceMessageEventArgs(); - eventArgs.Message = message; - eventArgs.MessageType = messageType; - eventArgs.Surface = this; + var eventArgs = new SurfaceMessageEventArgs + { + Message = message, + MessageType = messageType, + Surface = this + }; _surfaceMessage(source, eventArgs); } } @@ -1133,10 +1090,7 @@ namespace Greenshot.Drawing { _elements.Transform(matrix); } - if (_surfaceSizeChanged != null) - { - _surfaceSizeChanged(this, null); - } + _surfaceSizeChanged?.Invoke(this, null); Invalidate(); } /// @@ -1196,8 +1150,7 @@ namespace Greenshot.Drawing IDrawableContainer rightClickedContainer = _elements.ClickableElementAt(_mouseStart.X, _mouseStart.Y); if (rightClickedContainer != null) { - selectedList = new DrawableContainerList(ID); - selectedList.Add(rightClickedContainer); + selectedList = new DrawableContainerList(ID) {rightClickedContainer}; } } if (selectedList != null && selectedList.Count > 0) @@ -1231,7 +1184,10 @@ namespace Greenshot.Drawing // if a new element has been drawn, set location and register it if (_drawingElement != null) { - _drawingElement.Status = _undrawnElement.DefaultEditMode; + if (_undrawnElement != null) + { + _drawingElement.Status = _undrawnElement.DefaultEditMode; + } if (!_drawingElement.HandleMouseDown(_mouseStart.X, _mouseStart.Y)) { _drawingElement.Left = _mouseStart.X; @@ -1362,14 +1318,7 @@ namespace Greenshot.Drawing Point currentMouse = e.Location; - if (DrawingMode != DrawingModes.None) - { - Cursor = Cursors.Cross; - } - else - { - Cursor = Cursors.Default; - } + Cursor = DrawingMode != DrawingModes.None ? Cursors.Cross : Cursors.Default; if (_mouseDown) { @@ -1597,8 +1546,7 @@ namespace Greenshot.Drawing Invalidate(); if (_movingElementChanged != null) { - SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs(); - eventArgs.Elements = cloned; + SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs {Elements = cloned}; _movingElementChanged(this, eventArgs); } } @@ -1663,13 +1611,7 @@ namespace Greenshot.Drawing /// Returns if this surface has selected elements /// /// - public bool HasSelectedElements - { - get - { - return (selectedElements != null && selectedElements.Count > 0); - } - } + public bool HasSelectedElements => (selectedElements != null && selectedElements.Count > 0); /// /// Remove all the selected elements @@ -1764,29 +1706,14 @@ namespace Greenshot.Drawing if (dcs != null) { // Make element(s) only move 10,10 if the surface is the same - Point moveOffset; bool isSameSurface = (dcs.ParentID == _uniqueId); dcs.Parent = this; - if (isSameSurface) - { - moveOffset = new Point(10, 10); - } - else - { - moveOffset = Point.Empty; - } + var moveOffset = isSameSurface ? new Point(10, 10) : Point.Empty; // Here a fix for bug #1475, first calculate the bounds of the complete IDrawableContainerList Rectangle drawableContainerListBounds = Rectangle.Empty; - foreach (IDrawableContainer element in dcs) + foreach (var element in dcs) { - if (drawableContainerListBounds == Rectangle.Empty) - { - drawableContainerListBounds = element.DrawingBounds; - } - else - { - drawableContainerListBounds = Rectangle.Union(drawableContainerListBounds, element.DrawingBounds); - } + drawableContainerListBounds = drawableContainerListBounds == Rectangle.Empty ? element.DrawingBounds : Rectangle.Union(drawableContainerListBounds, element.DrawingBounds); } // And find a location inside the target surface to paste to bool containersCanFit = drawableContainerListBounds.Width < Bounds.Width && drawableContainerListBounds.Height < Bounds.Height; @@ -1797,15 +1724,7 @@ namespace Greenshot.Drawing if (!Bounds.Contains(containersLocation)) { // Easy fix for same surface - if (isSameSurface) - { - moveOffset = new Point(-10, -10); - } - else - { - // For different surface, which is most likely smaller, we move to "10,10" - moveOffset = new Point(-drawableContainerListBounds.Location.X + 10, -drawableContainerListBounds.Location.Y + 10); - } + moveOffset = isSameSurface ? new Point(-10, -10) : new Point(-drawableContainerListBounds.Location.X + 10, -drawableContainerListBounds.Location.Y + 10); } } else @@ -1932,8 +1851,10 @@ namespace Greenshot.Drawing } if (_movingElementChanged != null) { - SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs(); - eventArgs.Elements = selectedElements; + SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs + { + Elements = selectedElements + }; _movingElementChanged(this, eventArgs); } Invalidate(); @@ -1962,8 +1883,10 @@ namespace Greenshot.Drawing FieldAggregator.BindElement(container); if (generateEvents && _movingElementChanged != null) { - SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs(); - eventArgs.Elements = selectedElements; + SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs + { + Elements = selectedElements + }; _movingElementChanged(this, eventArgs); } if (invalidate) @@ -1988,14 +1911,14 @@ namespace Greenshot.Drawing public void SelectElements(IDrawableContainerList elements) { SuspendLayout(); - foreach (DrawableContainer element in elements) + foreach (var drawableContainer in elements) { + var element = (DrawableContainer) drawableContainer; SelectElement(element, false, false); } if (_movingElementChanged != null) { - SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs(); - eventArgs.Elements = selectedElements; + SurfaceElementEventArgs eventArgs = new SurfaceElementEventArgs {Elements = selectedElements}; _movingElementChanged(this, eventArgs); } ResumeLayout(); @@ -2070,13 +1993,7 @@ namespace Greenshot.Drawing /// /// Property for accessing the elements on the surface /// - public IDrawableContainerList Elements - { - get - { - return _elements; - } - } + public IDrawableContainerList Elements => _elements; /// /// pulls selected elements up one level in hierarchy diff --git a/Greenshot/Drawing/TextContainer.cs b/Greenshot/Drawing/TextContainer.cs index 84deb9868..2761bfe9c 100644 --- a/Greenshot/Drawing/TextContainer.cs +++ b/Greenshot/Drawing/TextContainer.cs @@ -26,6 +26,7 @@ using Greenshot.Plugin.Drawing; using GreenshotPlugin.Interfaces.Drawing; using System; using System.ComponentModel; +using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Text; @@ -321,47 +322,47 @@ namespace Greenshot.Drawing UpdateFormat(); } - private Font CreateFont(string fontFamily, bool fontBold, bool fontItalic, float fontSize) + private Font CreateFont(string fontFamilyName, bool fontBold, bool fontItalic, float fontSize) { - FontStyle fs = FontStyle.Regular; + FontStyle fontStyle = FontStyle.Regular; bool hasStyle = false; - using (FontFamily fam = new FontFamily(fontFamily)) + using (var fontFamily = new FontFamily(fontFamilyName)) { - bool boldAvailable = fam.IsStyleAvailable(FontStyle.Bold); + bool boldAvailable = fontFamily.IsStyleAvailable(FontStyle.Bold); if (fontBold && boldAvailable) { - fs |= FontStyle.Bold; + fontStyle |= FontStyle.Bold; hasStyle = true; } - bool italicAvailable = fam.IsStyleAvailable(FontStyle.Italic); + bool italicAvailable = fontFamily.IsStyleAvailable(FontStyle.Italic); if (fontItalic && italicAvailable) { - fs |= FontStyle.Italic; + fontStyle |= FontStyle.Italic; hasStyle = true; } if (!hasStyle) { - bool regularAvailable = fam.IsStyleAvailable(FontStyle.Regular); + bool regularAvailable = fontFamily.IsStyleAvailable(FontStyle.Regular); if (regularAvailable) { - fs = FontStyle.Regular; + fontStyle = FontStyle.Regular; } else { if (boldAvailable) { - fs = FontStyle.Bold; + fontStyle = FontStyle.Bold; } else if (italicAvailable) { - fs = FontStyle.Italic; + fontStyle = FontStyle.Italic; } } } - return new Font(fam, fontSize, fs, GraphicsUnit.Pixel); + return new Font(fontFamily, fontSize, fontStyle, GraphicsUnit.Pixel); } } @@ -400,7 +401,7 @@ namespace Greenshot.Drawing catch (Exception) { // When this happens... the PC is broken - ex.Data.Add("fontFamily", fontFamily); + ex.Data.Add("fontFamilyName", fontFamily); ex.Data.Add("fontBold", fontBold); ex.Data.Add("fontItalic", fontItalic); ex.Data.Add("fontSize", fontSize); @@ -534,6 +535,14 @@ namespace Greenshot.Drawing /// public static void DrawText(Graphics graphics, Rectangle drawingRectange, int lineThickness, Color fontColor, bool drawShadow, StringFormat stringFormat, string text, Font font) { +#if DEBUG + Debug.Assert(font != null); +#else + if (font == null) + { + return; + } +#endif int textOffset = lineThickness > 0 ? (int)Math.Ceiling(lineThickness / 2d) : 0; // draw shadow before anything else if (drawShadow) diff --git a/Greenshot/Forms/AboutForm.cs b/Greenshot/Forms/AboutForm.cs index e35d281e7..68f2d48a5 100644 --- a/Greenshot/Forms/AboutForm.cs +++ b/Greenshot/Forms/AboutForm.cs @@ -152,7 +152,7 @@ namespace Greenshot { 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(); diff --git a/Greenshot/Forms/CaptureForm.cs b/Greenshot/Forms/CaptureForm.cs index 0f34ca0ab..86ea4054f 100644 --- a/Greenshot/Forms/CaptureForm.cs +++ b/Greenshot/Forms/CaptureForm.cs @@ -43,7 +43,7 @@ namespace Greenshot.Forms { public sealed partial class CaptureForm : AnimatingForm { private enum FixMode {None, Initiated, Horizontal, Vertical}; - private static readonly ILog LOG = LogManager.GetLogger(typeof(CaptureForm)); + private static readonly ILog Log = LogManager.GetLogger(typeof(CaptureForm)); private static readonly CoreConfiguration Conf = IniConfig.GetIniSection(); private static readonly Brush GreenOverlayBrush = new SolidBrush(Color.FromArgb(50, Color.MediumSeaGreen)); private static readonly Pen OverlayPen = new Pen(Color.FromArgb(50, Color.Black)); @@ -79,29 +79,17 @@ namespace Greenshot.Forms { /// /// Property to access the selected capture rectangle /// - public Rectangle CaptureRectangle { - get { - return _captureRect; - } - } + public Rectangle CaptureRectangle => _captureRect; /// /// Property to access the used capture mode /// - public CaptureMode UsedCaptureMode { - get { - return _captureMode; - } - } + public CaptureMode UsedCaptureMode => _captureMode; /// /// Get the selected window /// - public WindowDetails SelectedCaptureWindow { - get { - return _selectedCaptureWindow; - } - } + public WindowDetails SelectedCaptureWindow => _selectedCaptureWindow; /// /// This should prevent childs to draw backgrounds @@ -117,11 +105,11 @@ namespace Greenshot.Forms { private void ClosedHandler(object sender, EventArgs e) { _currentForm = null; - LOG.Debug("Remove CaptureForm from currentForm"); + Log.Debug("Remove CaptureForm from currentForm"); } private void ClosingHandler(object sender, EventArgs e) { - LOG.Debug("Closing captureform"); + Log.Debug("Closing captureform"); WindowDetails.UnregisterIgnoreHandle(Handle); } @@ -132,7 +120,7 @@ namespace Greenshot.Forms { /// public CaptureForm(ICapture capture, List windows) { if (_currentForm != null) { - LOG.Warn("Found currentForm, Closing already opened CaptureForm"); + Log.Warn("Found currentForm, Closing already opened CaptureForm"); _currentForm.Close(); _currentForm = null; Application.DoEvents(); @@ -190,8 +178,10 @@ namespace Greenshot.Forms { // Initialize the zoom with a invalid position _zoomAnimator = new RectangleAnimator(Rectangle.Empty, new Rectangle(int.MaxValue, int.MaxValue, 0, 0), FramesForMillis(1000), EasingType.Quintic, EasingMode.EaseOut); VerifyZoomAnimation(_cursorPos, false); - } else if (_zoomAnimator != null) { - _zoomAnimator.ChangeDestination(new Rectangle(Point.Empty, Size.Empty), FramesForMillis(1000)); + } + else + { + _zoomAnimator?.ChangeDestination(new Rectangle(Point.Empty, Size.Empty), FramesForMillis(1000)); } } @@ -441,16 +431,14 @@ namespace Greenshot.Forms { Point cursorPosition = Cursor.Position; _selectedCaptureWindow = null; lock (_windows) { - foreach (WindowDetails window in _windows) { - if (window.Contains(cursorPosition)) { - // Only go over the children if we are in window mode - if (CaptureMode.Window == _captureMode) { - _selectedCaptureWindow = window.FindChildUnderPoint(cursorPosition); - } else { - _selectedCaptureWindow = window; - } - break; + foreach (var window in _windows) { + if (!window.Contains(cursorPosition)) + { + continue; } + // Only go over the children if we are in window mode + _selectedCaptureWindow = CaptureMode.Window == _captureMode ? window.FindChildUnderPoint(cursorPosition) : window; + break; } } @@ -619,8 +607,10 @@ namespace Greenshot.Forms { if (_isZoomerTransparent) { //create a color matrix object to change the opacy - ColorMatrix opacyMatrix = new ColorMatrix(); - opacyMatrix.Matrix33 = Conf.ZoomerOpacity; + ColorMatrix opacyMatrix = new ColorMatrix + { + Matrix33 = Conf.ZoomerOpacity + }; attributes = new ImageAttributes(); attributes.SetColorMatrix(opacyMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); } else { @@ -695,9 +685,7 @@ namespace Greenshot.Forms { // Horizontal middle + 1 to right graphics.DrawRectangle(pen, destinationRectangle.X + halfWidthEnd + 2 * padding, drawAtHeight, halfWidthEnd - 2 * padding - 1, pixelThickness); } - if (attributes != null) { - attributes.Dispose(); - } + attributes?.Dispose(); } /// @@ -717,15 +705,8 @@ namespace Greenshot.Forms { if (_mouseDown || _captureMode == CaptureMode.Window || IsAnimating(_windowAnimator)) { _captureRect.Intersect(new Rectangle(Point.Empty, _capture.ScreenBounds.Size)); // crop what is outside the screen - - Rectangle fixedRect; - //if (captureMode == CaptureMode.Window) { - if (IsAnimating(_windowAnimator)) { - // Use the animator - fixedRect = _windowAnimator.Current; - } else { - fixedRect = _captureRect; - } + + var fixedRect = IsAnimating(_windowAnimator) ? _windowAnimator.Current : _captureRect; // TODO: enable when the screen capture code works reliable //if (capture.CaptureDetails.CaptureMode == CaptureMode.Video) { @@ -827,7 +808,7 @@ namespace Greenshot.Forms { if (_showDebugInfo && _selectedCaptureWindow != null) { - string title = string.Format("#{0:X} - {1}", _selectedCaptureWindow.Handle.ToInt64(), _selectedCaptureWindow.Text.Length > 0 ? _selectedCaptureWindow.Text : _selectedCaptureWindow.Process.ProcessName); + string title = $"#{_selectedCaptureWindow.Handle.ToInt64():X} - {(_selectedCaptureWindow.Text.Length > 0 ? _selectedCaptureWindow.Text : _selectedCaptureWindow.Process.ProcessName)}"; PointF debugLocation = new PointF(fixedRect.X, fixedRect.Y); graphics.DrawString(title, sizeFont, Brushes.DarkOrange, debugLocation); } diff --git a/Greenshot/Forms/ColorDialog.Designer.cs b/Greenshot/Forms/ColorDialog.Designer.cs index ae06c722d..94dda653d 100644 --- a/Greenshot/Forms/ColorDialog.Designer.cs +++ b/Greenshot/Forms/ColorDialog.Designer.cs @@ -144,7 +144,7 @@ namespace Greenshot { this.textBoxRed.TabIndex = 2; this.textBoxRed.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.textBoxRed.Click += new System.EventHandler(this.TextBoxGotFocus); - this.textBoxRed.TextChanged += new System.EventHandler(this.TextBoxRGBTextChanged); + this.textBoxRed.TextChanged += new System.EventHandler(this.TextBoxRgbTextChanged); this.textBoxRed.GotFocus += new System.EventHandler(this.TextBoxGotFocus); this.textBoxRed.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TextBoxKeyDown); // @@ -156,7 +156,7 @@ namespace Greenshot { this.textBoxGreen.TabIndex = 3; this.textBoxGreen.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.textBoxGreen.Click += new System.EventHandler(this.TextBoxGotFocus); - this.textBoxGreen.TextChanged += new System.EventHandler(this.TextBoxRGBTextChanged); + this.textBoxGreen.TextChanged += new System.EventHandler(this.TextBoxRgbTextChanged); this.textBoxGreen.GotFocus += new System.EventHandler(this.TextBoxGotFocus); this.textBoxGreen.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TextBoxKeyDown); // @@ -168,7 +168,7 @@ namespace Greenshot { this.textBoxBlue.TabIndex = 4; this.textBoxBlue.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.textBoxBlue.Click += new System.EventHandler(this.TextBoxGotFocus); - this.textBoxBlue.TextChanged += new System.EventHandler(this.TextBoxRGBTextChanged); + this.textBoxBlue.TextChanged += new System.EventHandler(this.TextBoxRgbTextChanged); this.textBoxBlue.GotFocus += new System.EventHandler(this.TextBoxGotFocus); this.textBoxBlue.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TextBoxKeyDown); // @@ -189,7 +189,7 @@ namespace Greenshot { this.textBoxAlpha.TabIndex = 5; this.textBoxAlpha.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.textBoxAlpha.Click += new System.EventHandler(this.TextBoxGotFocus); - this.textBoxAlpha.TextChanged += new System.EventHandler(this.TextBoxRGBTextChanged); + this.textBoxAlpha.TextChanged += new System.EventHandler(this.TextBoxRgbTextChanged); this.textBoxAlpha.GotFocus += new System.EventHandler(this.TextBoxGotFocus); this.textBoxAlpha.KeyDown += new System.Windows.Forms.KeyEventHandler(this.TextBoxKeyDown); // diff --git a/Greenshot/Forms/ColorDialog.cs b/Greenshot/Forms/ColorDialog.cs index d4428b407..5cfbf187d 100644 --- a/Greenshot/Forms/ColorDialog.cs +++ b/Greenshot/Forms/ColorDialog.cs @@ -34,8 +34,8 @@ namespace Greenshot { /// Description of ColorDialog. /// public partial class ColorDialog : BaseForm { - private static ColorDialog uniqueInstance; - private static readonly EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); + private static ColorDialog _uniqueInstance; + private static readonly EditorConfiguration EditorConfig = IniConfig.GetIniSection(); private ColorDialog() { SuspendLayout(); @@ -47,11 +47,9 @@ namespace Greenshot { UpdateRecentColorsButtonRow(); } - public static ColorDialog GetInstance() { - if (uniqueInstance == null) { - uniqueInstance = new ColorDialog(); - } - return uniqueInstance; + public static ColorDialog GetInstance() + { + return _uniqueInstance ?? (_uniqueInstance = new ColorDialog()); } private readonly List private void ShowSettings() { - trackBar1.Value = (int)(effect.Darkness * 40); - offsetX.Value = effect.ShadowOffset.X; - offsetY.Value = effect.ShadowOffset.Y; - thickness.Value = effect.ShadowSize; + trackBar1.Value = (int)(_effect.Darkness * 40); + offsetX.Value = _effect.ShadowOffset.X; + offsetY.Value = _effect.ShadowOffset.Y; + thickness.Value = _effect.ShadowSize; } private void ButtonOK_Click(object sender, EventArgs e) { - effect.Darkness = (float)trackBar1.Value / (float)40; - effect.ShadowOffset = new Point((int)offsetX.Value, (int)offsetY.Value); - effect.ShadowSize = (int)thickness.Value; + _effect.Darkness = trackBar1.Value / (float)40; + _effect.ShadowOffset = new Point((int)offsetX.Value, (int)offsetY.Value); + _effect.ShadowSize = (int)thickness.Value; DialogResult = DialogResult.OK; } } diff --git a/Greenshot/Forms/ImageEditorForm.cs b/Greenshot/Forms/ImageEditorForm.cs index cfa1ee0b2..00eeeaf8f 100644 --- a/Greenshot/Forms/ImageEditorForm.cs +++ b/Greenshot/Forms/ImageEditorForm.cs @@ -19,8 +19,15 @@ * along with this program. If not, see . */ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.IO; +using System.Threading; +using System.Windows.Forms; using Greenshot.Configuration; -using Greenshot.Core; using Greenshot.Destinations; using Greenshot.Drawing; using Greenshot.Drawing.Fields; @@ -33,26 +40,19 @@ using Greenshot.Plugin; using Greenshot.Plugin.Drawing; using GreenshotPlugin.Controls; using GreenshotPlugin.Core; +using GreenshotPlugin.Effects; using GreenshotPlugin.Interfaces.Drawing; using GreenshotPlugin.UnmanagedHelpers; using log4net; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.IO; -using System.Threading; -using System.Windows.Forms; namespace Greenshot { /// /// Description of ImageEditorForm. /// public partial class ImageEditorForm : BaseForm, IImageEditor { - private static readonly ILog LOG = LogManager.GetLogger(typeof(ImageEditorForm)); + private static readonly ILog Log = LogManager.GetLogger(typeof(ImageEditorForm)); private static readonly EditorConfiguration EditorConfiguration = IniConfig.GetIniSection(); - private static readonly List IgnoreDestinations = new List() { PickerDestination.DESIGNATION, EditorDestination.DESIGNATION }; + private static readonly List IgnoreDestinations = new List { PickerDestination.DESIGNATION, EditorDestination.DESIGNATION }; private static readonly List EditorList = new List(); private Surface _surface; @@ -69,18 +69,14 @@ namespace Greenshot { /// /// An Implementation for the IImageEditor, this way Plugins have access to the HWND handles wich can be used with Win32 API calls. /// - public IWin32Window WindowHandle { - get { return this; } - } + public IWin32Window WindowHandle => this; public static List Editors { get { try { - EditorList.Sort(delegate(IImageEditor e1, IImageEditor e2) { - return string.Compare(e1.Surface.CaptureDetails.Title, e2.Surface.CaptureDetails.Title, StringComparison.Ordinal); - }); + EditorList.Sort((e1, e2) => string.Compare(e1.Surface.CaptureDetails.Title, e2.Surface.CaptureDetails.Title, StringComparison.Ordinal)); } catch(Exception ex) { - LOG.Warn("Sorting of editors failed.", ex); + Log.Warn("Sorting of editors failed.", ex); } return EditorList; } @@ -104,7 +100,7 @@ namespace Greenshot { }; // Make sure the editor is placed on the same location as the last editor was on close - // But only if this still exists, else it will be reset (BUG-1812 + // But only if this still exists, else it will be reset (BUG-1812) WindowPlacement editorWindowPlacement = EditorConfiguration.GetEditorPlacement(); Rectangle screenbounds = WindowCapture.GetScreenBounds(); if (!screenbounds.Contains(editorWindowPlacement.NormalPosition)) @@ -132,11 +128,13 @@ namespace Greenshot { /// Remove the current surface /// private void RemoveSurface() { - if (_surface != null) { - panel1.Controls.Remove(_surface); - _surface.Dispose(); - _surface = null; + if (_surface == null) + { + return; } + panel1.Controls.Remove(_surface); + _surface.Dispose(); + _surface = null; } /// @@ -174,7 +172,7 @@ namespace Greenshot { BindFieldControls(); RefreshEditorControls(); // Fix title - if (_surface != null && _surface.CaptureDetails != null && _surface.CaptureDetails.Title != null) { + if (_surface?.CaptureDetails?.Title != null) { Text = _surface.CaptureDetails.Title + " - " + Language.GetString(LangKey.editor_title); } } @@ -249,7 +247,7 @@ namespace Greenshot { if (destination.Priority <= 2) { continue; } - if (!destination.isActive) { + if (!destination.IsActive) { continue; } if (destination.DisplayIcon == null) { @@ -258,15 +256,15 @@ namespace Greenshot { try { AddDestinationButton(destination); } catch (Exception addingException) { - LOG.WarnFormat("Problem adding destination {0}", destination.Designation); - LOG.Warn("Exception: ", addingException); + Log.WarnFormat("Problem adding destination {0}", destination.Designation); + Log.Warn("Exception: ", addingException); } } }); } private void AddDestinationButton(IDestination toolstripDestination) { - if (toolstripDestination.isDynamic) { + if (toolstripDestination.IsDynamic) { ToolStripSplitButton destinationButton = new ToolStripSplitButton { DisplayStyle = ToolStripItemDisplayStyle.Image, @@ -302,9 +300,11 @@ namespace Greenshot { subDestinations.Sort(); foreach(IDestination subDestination in subDestinations) { IDestination closureFixedDestination = subDestination; - ToolStripMenuItem destinationMenuItem = new ToolStripMenuItem(closureFixedDestination.Description); - destinationMenuItem.Tag = closureFixedDestination; - destinationMenuItem.Image = closureFixedDestination.DisplayIcon; + ToolStripMenuItem destinationMenuItem = new ToolStripMenuItem(closureFixedDestination.Description) + { + Tag = closureFixedDestination, + Image = closureFixedDestination.DisplayIcon + }; destinationMenuItem.Click += delegate { closureFixedDestination.ExportCapture(true, _surface, _surface.CaptureDetails); }; @@ -351,7 +351,7 @@ namespace Greenshot { if (IgnoreDestinations.Contains(destination.Designation)) { continue; } - if (!destination.isActive) { + if (!destination.IsActive) { continue; } @@ -375,20 +375,20 @@ namespace Greenshot { /// private void SurfaceMessageReceived(object sender, SurfaceMessageEventArgs eventArgs) { if (InvokeRequired) { - Invoke(new SurfaceMessageReceivedThreadSafeDelegate(SurfaceMessageReceived), new object[] { sender, eventArgs }); + Invoke(new SurfaceMessageReceivedThreadSafeDelegate(SurfaceMessageReceived), sender, eventArgs); } else { string dateTime = DateTime.Now.ToLongTimeString(); // TODO: Fix that we only open files, like in the tooltip switch (eventArgs.MessageType) { case SurfaceMessageTyp.FileSaved: // Put the event message on the status label and attach the context menu - updateStatusLabel(dateTime + " - " + eventArgs.Message, fileSavedStatusContextMenu); + UpdateStatusLabel(dateTime + " - " + eventArgs.Message, fileSavedStatusContextMenu); // Change title Text = eventArgs.Surface.LastSaveFullPath + " - " + Language.GetString(LangKey.editor_title); break; default: // Put the event message on the status label - updateStatusLabel(dateTime + " - " + eventArgs.Message); + UpdateStatusLabel(dateTime + " - " + eventArgs.Message); break; } } @@ -434,7 +434,7 @@ namespace Greenshot { if (fullpath == null) { return; } - updateStatusLabel(Language.GetFormattedString(LangKey.editor_imagesaved, fullpath), fileSavedStatusContextMenu); + UpdateStatusLabel(Language.GetFormattedString(LangKey.editor_imagesaved, fullpath), fileSavedStatusContextMenu); Text = Path.GetFileName(fullpath) + " - " + Language.GetString(LangKey.editor_title); } @@ -489,10 +489,8 @@ namespace Greenshot { return _surface.GetImageForExport(); } - public ICaptureDetails CaptureDetails { - get { return _surface.CaptureDetails; } - } - + public ICaptureDetails CaptureDetails => _surface.CaptureDetails; + public ToolStripMenuItem GetPluginMenuItem() { return pluginToolStripMenuItem; } @@ -902,7 +900,7 @@ namespace Greenshot { if (IgnoreDestinations.Contains(destination.Designation)) { continue; } - if (!destination.isActive) { + if (!destination.IsActive) { continue; } @@ -943,9 +941,9 @@ namespace Greenshot { redoToolStripMenuItem.Enabled = canRedo; string redoAction = ""; if (canRedo) { - if (_surface.RedoActionLanguageKey != LangKey.none) { - redoAction = Language.GetString(_surface.RedoActionLanguageKey); - } + if (_surface.RedoActionLanguageKey != LangKey.none) { + redoAction = Language.GetString(_surface.RedoActionLanguageKey); + } } string redoText = Language.GetFormattedString(LangKey.editor_redo, redoAction); btnRedo.Text = redoText; @@ -981,23 +979,18 @@ namespace Greenshot { #endregion #region status label handling - private void updateStatusLabel(string text, ContextMenuStrip contextMenu) { + private void UpdateStatusLabel(string text, ContextMenuStrip contextMenu = null) { statusLabel.Text = text; statusStrip1.ContextMenuStrip = contextMenu; } - - private void updateStatusLabel(string text) { - updateStatusLabel(text, null); - } + private void ClearStatusLabel() { - updateStatusLabel(null, null); + UpdateStatusLabel(null); } private void StatusLabelClicked(object sender, MouseEventArgs e) { ToolStrip ss = (StatusStrip)((ToolStripStatusLabel)sender).Owner; - if(ss.ContextMenuStrip != null) { - ss.ContextMenuStrip.Show(ss, e.X, e.Y); - } + ss.ContextMenuStrip?.Show(ss, e.X, e.Y); } private void CopyPathMenuItemClick(object sender, EventArgs e) { @@ -1005,14 +998,19 @@ namespace Greenshot { } private void OpenDirectoryMenuItemClick(object sender, EventArgs e) { - ProcessStartInfo psi = new ProcessStartInfo("explorer") + var path = Path.GetDirectoryName(_surface.LastSaveFullPath); + if (path == null) { - Arguments = Path.GetDirectoryName(_surface.LastSaveFullPath), + return; + } + var processStartInfo = new ProcessStartInfo("explorer") + { + Arguments = path, UseShellExecute = false }; - using (Process p = new Process()) { - p.StartInfo = psi; - p.Start(); + using (var process = new Process()) { + process.StartInfo = processStartInfo; + process.Start(); } } #endregion @@ -1082,16 +1080,16 @@ namespace Greenshot { /// private void RefreshEditorControls() { int stepLabels = _surface.CountStepLabels(null); - Image icon; + Image icon; if (stepLabels <= 20) { - icon = (Image)resources.GetObject(string.Format("btnStepLabel{0:00}.Image", stepLabels)); + icon = (Image)resources.GetObject($"btnStepLabel{stepLabels:00}.Image"); } else { - icon = (Image)resources.GetObject("btnStepLabel20+.Image"); + icon = (Image)resources.GetObject("btnStepLabel20+.Image"); } - btnStepLabel.Image = icon; - addCounterToolStripMenuItem.Image = icon; + btnStepLabel.Image = icon; + addCounterToolStripMenuItem.Image = icon; - FieldAggregator props = _surface.FieldAggregator; + FieldAggregator props = _surface.FieldAggregator; // if a confirmable element is selected, we must disable most of the controls // since we demand confirmation or cancel for confirmable element if (props.HasFieldValue(FieldType.FLAGS) && ((FieldFlag)props.GetFieldValue(FieldType.FLAGS) & FieldFlag.CONFIRMABLE) == FieldFlag.CONFIRMABLE) @@ -1156,33 +1154,51 @@ namespace Greenshot { fontItalicButton.Checked = _originalItalicCheckState; } - FontFamily fam = fontFamilyComboBox.FontFamily; - - bool boldAvailable = fam.IsStyleAvailable(FontStyle.Bold); - if(!boldAvailable) { - _originalBoldCheckState = fontBoldButton.Checked; - fontBoldButton.Checked = false; - } - fontBoldButton.Enabled = boldAvailable; - - bool italicAvailable = fam.IsStyleAvailable(FontStyle.Italic); - if(!italicAvailable) fontItalicButton.Checked = false; - fontItalicButton.Enabled = italicAvailable; - - bool regularAvailable = fam.IsStyleAvailable(FontStyle.Regular); - if(!regularAvailable) { - if(boldAvailable) { - fontBoldButton.Checked = true; - } else if(italicAvailable) { - fontItalicButton.Checked = true; - } - } - } + var fontFamily = fontFamilyComboBox.FontFamily; + + bool boldAvailable = fontFamily.IsStyleAvailable(FontStyle.Bold); + if (fontBoldButton != null) + { + if (!boldAvailable) + { + _originalBoldCheckState = fontBoldButton.Checked; + fontBoldButton.Checked = false; + } + fontBoldButton.Enabled = boldAvailable; + } + + bool italicAvailable = fontFamily.IsStyleAvailable(FontStyle.Italic); + if (fontItalicButton != null) + { + if (!italicAvailable) + { + fontItalicButton.Checked = false; + } + fontItalicButton.Enabled = italicAvailable; + } + + bool regularAvailable = fontFamily.IsStyleAvailable(FontStyle.Regular); + if (regularAvailable) + { + return; + } + if (boldAvailable) { + if (fontBoldButton != null) + { + fontBoldButton.Checked = true; + } + } else if(italicAvailable) { + if (fontItalicButton != null) + { + fontItalicButton.Checked = true; + } + } + } private void FieldAggregatorFieldChanged(object sender, FieldChangedEventArgs e) { // in addition to selection, deselection of elements, we need to // refresh toolbar if prepared filter mode is changed - if(e.Field.FieldType == FieldType.PREPARED_FILTER_HIGHLIGHT) { + if(Equals(e.Field.FieldType, FieldType.PREPARED_FILTER_HIGHLIGHT)) { RefreshFieldControls(); } } @@ -1204,9 +1220,11 @@ namespace Greenshot { } private void SaveElementsToolStripMenuItemClick(object sender, EventArgs e) { - SaveFileDialog saveFileDialog = new SaveFileDialog(); - saveFileDialog.Filter = "Greenshot templates (*.gst)|*.gst"; - saveFileDialog.FileName = FilenameHelper.GetFilenameWithoutExtensionFromPattern(coreConfiguration.OutputFileFilenamePattern, _surface.CaptureDetails); + SaveFileDialog saveFileDialog = new SaveFileDialog + { + Filter = "Greenshot templates (*.gst)|*.gst", + FileName = FilenameHelper.GetFilenameWithoutExtensionFromPattern(coreConfiguration.OutputFileFilenamePattern, _surface.CaptureDetails) + }; DialogResult dialogResult = saveFileDialog.ShowDialog(); if(dialogResult.Equals(DialogResult.OK)) { using (Stream streamWrite = File.OpenWrite(saveFileDialog.FileName)) { @@ -1216,8 +1234,10 @@ namespace Greenshot { } private void LoadElementsToolStripMenuItemClick(object sender, EventArgs e) { - OpenFileDialog openFileDialog = new OpenFileDialog(); - openFileDialog.Filter = "Greenshot templates (*.gst)|*.gst"; + OpenFileDialog openFileDialog = new OpenFileDialog + { + Filter = "Greenshot templates (*.gst)|*.gst" + }; if (openFileDialog.ShowDialog() == DialogResult.OK) { using (Stream streamRead = File.OpenRead(openFileDialog.FileName)) { _surface.LoadElementsFromStream(streamRead); @@ -1228,23 +1248,27 @@ namespace Greenshot { private void DestinationToolStripMenuItemClick(object sender, EventArgs e) { IDestination clickedDestination = null; - if (sender is Control) { - Control clickedControl = sender as Control; + var control = sender as Control; + if (control != null) { + Control clickedControl = control; if (clickedControl.ContextMenuStrip != null) { clickedControl.ContextMenuStrip.Show(Cursor.Position); return; } clickedDestination = (IDestination)clickedControl.Tag; - } else if (sender is ToolStripMenuItem) { - ToolStripMenuItem clickedMenuItem = sender as ToolStripMenuItem; - clickedDestination = (IDestination)clickedMenuItem.Tag; } - if (clickedDestination != null) { - ExportInformation exportInformation = clickedDestination.ExportCapture(true, _surface, _surface.CaptureDetails); - if (exportInformation != null && exportInformation.ExportMade) { - _surface.Modified = false; + else + { + var item = sender as ToolStripMenuItem; + if (item != null) { + ToolStripMenuItem clickedMenuItem = item; + clickedDestination = (IDestination)clickedMenuItem.Tag; } } + ExportInformation exportInformation = clickedDestination?.ExportCapture(true, _surface, _surface.CaptureDetails); + if (exportInformation != null && exportInformation.ExportMade) { + _surface.Modified = false; + } } protected void FilterPresetDropDownItemClicked(object sender, ToolStripItemClickedEventArgs e) { @@ -1284,7 +1308,7 @@ namespace Greenshot { windowToCapture = CaptureHelper.SelectCaptureWindow(windowToCapture); if (windowToCapture != null) { capture = CaptureHelper.CaptureWindow(windowToCapture, capture, coreConfiguration.WindowCaptureMode); - if (capture != null && capture.CaptureDetails != null && capture.Image != null) { + if (capture?.CaptureDetails != null && capture.Image != null) { ((Bitmap)capture.Image).SetResolution(capture.CaptureDetails.DpiX, capture.CaptureDetails.DpiY); _surface.AddImageContainer((Bitmap)capture.Image, 100, 100); } @@ -1292,11 +1316,9 @@ namespace Greenshot { WindowDetails.ToForeground(Handle); } - if (capture!= null) { - capture.Dispose(); - } + capture?.Dispose(); } catch (Exception exception) { - LOG.Error(exception); + Log.Error(exception); } } @@ -1440,17 +1462,13 @@ namespace Greenshot { } private void ImageEditorFormResize(object sender, EventArgs e) { - if (Surface == null || Surface.Image == null || panel1 == null) { + if (Surface?.Image == null || panel1 == null) { return; } Size imageSize = Surface.Image.Size; Size currentClientSize = panel1.ClientSize; var canvas = Surface as Control; - if (canvas == null) - { - return; - } - Panel panel = (Panel)canvas.Parent; + Panel panel = (Panel) canvas?.Parent; if (panel == null) { return; } diff --git a/Greenshot/Forms/MainForm.Designer.cs b/Greenshot/Forms/MainForm.Designer.cs index 0415a8070..d77a39c10 100644 --- a/Greenshot/Forms/MainForm.Designer.cs +++ b/Greenshot/Forms/MainForm.Designer.cs @@ -162,7 +162,7 @@ namespace Greenshot { // this.contextmenu_captureiefromlist.Name = "contextmenu_captureiefromlist"; this.contextmenu_captureiefromlist.Size = new System.Drawing.Size(170, 22); - this.contextmenu_captureiefromlist.DropDownOpening += new System.EventHandler(this.CaptureIEMenuDropDownOpening); + this.contextmenu_captureiefromlist.DropDownOpening += new System.EventHandler(this.CaptureIeMenuDropDownOpening); // // toolStripOtherSourcesSeparator // diff --git a/Greenshot/Forms/MainForm.cs b/Greenshot/Forms/MainForm.cs index 6810a8500..5ded41e26 100644 --- a/Greenshot/Forms/MainForm.cs +++ b/Greenshot/Forms/MainForm.cs @@ -56,15 +56,14 @@ namespace Greenshot { private static CoreConfiguration _conf; public static string LogFileLocation; - public static void Start(string[] args) { - bool isAlreadyRunning = false; - List filesToOpen = new List(); + public static void Start(string[] arguments) { + var filesToOpen = new List(); // Set the Thread name, is better than "1" Thread.CurrentThread.Name = Application.ProductName; // Init Log4NET - LogFileLocation = LogHelper.InitializeLog4NET(); + LogFileLocation = LogHelper.InitializeLog4Net(); // Get logger LOG = LogManager.GetLogger(typeof(MainForm)); @@ -84,18 +83,19 @@ namespace Greenshot { // check whether there's an local instance running already _applicationMutex = ResourceMutex.Create("F48E86D3-E34C-4DB7-8F8F-9A0EA55F0D08", "Greenshot", false); - isAlreadyRunning = !_applicationMutex.IsLocked; + var isAlreadyRunning = !_applicationMutex.IsLocked; - if (args.Length > 0 && LOG.IsDebugEnabled) { + if (arguments.Length > 0 && LOG.IsDebugEnabled) { StringBuilder argumentString = new StringBuilder(); - for(int argumentNr = 0; argumentNr < args.Length; argumentNr++) { - argumentString.Append("[").Append(args[argumentNr]).Append("] "); + foreach (string argument in arguments) + { + argumentString.Append("[").Append(argument).Append("] "); } LOG.Debug("Greenshot arguments: " + argumentString); } - for(int argumentNr = 0; argumentNr < args.Length; argumentNr++) { - string argument = args[argumentNr]; + for(int argumentNr = 0; argumentNr < arguments.Length; argumentNr++) { + string argument = arguments[argumentNr]; // Help if (argument.ToLower().Equals("/help") || argument.ToLower().Equals("/h") || argument.ToLower().Equals("/?")) { // Try to attach to the console @@ -104,7 +104,7 @@ namespace Greenshot { if (!attachedToConsole) { Kernel32.AllocConsole(); } - StringBuilder helpOutput = new StringBuilder(); + var helpOutput = new StringBuilder(); helpOutput.AppendLine(); helpOutput.AppendLine("Greenshot commandline options:"); helpOutput.AppendLine(); @@ -173,14 +173,14 @@ namespace Greenshot { // Language if (argument.ToLower().Equals("/language")) { - _conf.Language = args[++argumentNr]; + _conf.Language = arguments[++argumentNr]; IniConfig.Save(); continue; } // Setting the INI-directory if (argument.ToLower().Equals("/inidirectory")) { - IniConfig.IniDirectory = args[++argumentNr]; + IniConfig.IniDirectory = arguments[++argumentNr]; continue; } @@ -296,11 +296,7 @@ namespace Greenshot { } private static MainForm _instance; - public static MainForm Instance { - get { - return _instance; - } - } + public static MainForm Instance => _instance; private readonly CopyData _copyData; @@ -313,11 +309,7 @@ namespace Greenshot { // Timer for the double click test private readonly Timer _doubleClickTimer = new Timer(); - public NotifyIcon NotifyIcon { - get { - return notifyIcon; - } - } + public NotifyIcon NotifyIcon => notifyIcon; public MainForm(CopyDataTransport dataTransport) { _instance = this; @@ -341,12 +333,12 @@ namespace Greenshot { contextmenu_settings.Visible = !_conf.DisableSettings; // Make sure all hotkeys pass this window! - HotkeyControl.RegisterHotkeyHWND(Handle); + HotkeyControl.RegisterHotkeyHwnd(Handle); RegisterHotkeys(); new ToolTip(); - UpdateUI(); + UpdateUi(); // This forces the registration of all destinations inside Greenshot itself. DestinationHelper.GetAllDestinations(); @@ -452,7 +444,7 @@ namespace Greenshot { IniConfig.Reload(); Invoke((MethodInvoker) delegate { // Even update language when needed - UpdateUI(); + UpdateUi(); // Update the hotkey // Make sure the current hotkeys are disabled HotkeyControl.UnregisterHotkeys(); @@ -480,9 +472,10 @@ namespace Greenshot { } } - public ContextMenuStrip MainMenu { - get {return contextMenu;} - } + /// + /// Main context menu + /// + public ContextMenuStrip MainMenu => contextMenu; protected override void WndProc(ref Message m) { if (HotkeyControl.HandleMessages(ref m)) { @@ -659,7 +652,7 @@ namespace Greenshot { } #endregion - public void UpdateUI() { + public void UpdateUi() { // As the form is never loaded, call ApplyLanguage ourselves ApplyLanguage(); @@ -693,8 +686,10 @@ namespace Greenshot { } private void CaptureFile() { - var openFileDialog = new OpenFileDialog(); - openFileDialog.Filter = "Image files (*.greenshot, *.png, *.jpg, *.gif, *.bmp, *.ico, *.tiff, *.wmf)|*.greenshot; *.png; *.jpg; *.jpeg; *.gif; *.bmp; *.ico; *.tiff; *.tif; *.wmf"; + var openFileDialog = new OpenFileDialog + { + Filter = "Image files (*.greenshot, *.png, *.jpg, *.gif, *.bmp, *.ico, *.tiff, *.wmf)|*.greenshot; *.png; *.jpg; *.jpeg; *.gif; *.bmp; *.ico; *.tiff; *.tif; *.wmf" + }; if (openFileDialog.ShowDialog() == DialogResult.OK) { if (File.Exists(openFileDialog.FileName)) { CaptureHelper.CaptureFile(openFileDialog.FileName); @@ -712,7 +707,7 @@ namespace Greenshot { private void CaptureIE() { if (_conf.IECapture) { - CaptureHelper.CaptureIE(true, null); + CaptureHelper.CaptureIe(true, null); } } @@ -734,7 +729,7 @@ namespace Greenshot { // IE context menu code try { - if (_conf.IECapture && IECaptureHelper.IsIERunning()) { + if (_conf.IECapture && IeCaptureHelper.IsIeRunning()) { contextmenu_captureie.Enabled = true; contextmenu_captureiefromlist.Enabled = true; } else { @@ -773,12 +768,12 @@ namespace Greenshot { /// /// Build a selectable list of IE tabs when we enter the menu item /// - private void CaptureIEMenuDropDownOpening(object sender, EventArgs e) { + private void CaptureIeMenuDropDownOpening(object sender, EventArgs e) { if (!_conf.IECapture) { return; } try { - List> tabs = IECaptureHelper.GetBrowserTabs(); + List> tabs = IeCaptureHelper.GetBrowserTabs(); contextmenu_captureiefromlist.DropDownItems.Clear(); if (tabs.Count > 0) { contextmenu_captureie.Enabled = true; @@ -793,12 +788,12 @@ namespace Greenshot { if (title.Length > _conf.MaxMenuItemLength) { title = title.Substring(0, Math.Min(title.Length, _conf.MaxMenuItemLength)); } - ToolStripItem captureIETabItem = contextmenu_captureiefromlist.DropDownItems.Add(title); + var captureIeTabItem = contextmenu_captureiefromlist.DropDownItems.Add(title); int index = counter.ContainsKey(tabData.Key) ? counter[tabData.Key] : 0; - captureIETabItem.Image = tabData.Key.DisplayIcon; - captureIETabItem.Tag = new KeyValuePair(tabData.Key, index++); - captureIETabItem.Click += Contextmenu_captureiefromlist_Click; - contextmenu_captureiefromlist.DropDownItems.Add(captureIETabItem); + captureIeTabItem.Image = tabData.Key.DisplayIcon; + captureIeTabItem.Tag = new KeyValuePair(tabData.Key, index++); + captureIeTabItem.Click += Contextmenu_captureiefromlist_Click; + contextmenu_captureiefromlist.DropDownItems.Add(captureIeTabItem); if (counter.ContainsKey(tabData.Key)) { counter[tabData.Key] = index; } else { @@ -823,10 +818,9 @@ namespace Greenshot { ToolStripMenuItem captureScreenMenuItem = (ToolStripMenuItem)sender; captureScreenMenuItem.DropDownItems.Clear(); if (Screen.AllScreens.Length > 1) { - ToolStripMenuItem captureScreenItem; Rectangle allScreensBounds = WindowCapture.GetScreenBounds(); - captureScreenItem = new ToolStripMenuItem(Language.GetString(LangKey.contextmenu_capturefullscreen_all)); + var captureScreenItem = new ToolStripMenuItem(Language.GetString(LangKey.contextmenu_capturefullscreen_all)); captureScreenItem.Click += delegate { BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureFullscreen(false, ScreenCaptureMode.FullScreen); @@ -893,17 +887,18 @@ namespace Greenshot { } } - private void HideThumbnailOnLeave(object sender, EventArgs e) { - if (_thumbnailForm != null) { - _thumbnailForm.Hide(); - } + private void HideThumbnailOnLeave(object sender, EventArgs e) + { + _thumbnailForm?.Hide(); } private void CleanupThumbnail() { - if (_thumbnailForm != null) { - _thumbnailForm.Close(); - _thumbnailForm = null; + if (_thumbnailForm == null) + { + return; } + _thumbnailForm.Close(); + _thumbnailForm = null; } public void AddCaptureWindowMenuItems(ToolStripMenuItem menuItem, EventHandler eventHandler) { @@ -938,15 +933,11 @@ namespace Greenshot { } private void CaptureClipboardToolStripMenuItemClick(object sender, EventArgs e) { - BeginInvoke((MethodInvoker)delegate { - CaptureHelper.CaptureClipboard(); - }); + BeginInvoke((MethodInvoker)CaptureHelper.CaptureClipboard); } private void OpenFileToolStripMenuItemClick(object sender, EventArgs e) { - BeginInvoke((MethodInvoker)delegate { - CaptureFile(); - }); + BeginInvoke((MethodInvoker)CaptureFile); } private void CaptureFullScreenToolStripMenuItemClick(object sender, EventArgs e) { @@ -996,12 +987,12 @@ namespace Greenshot { ieWindowToCapture.Restore(); } try { - IECaptureHelper.ActivateIETab(ieWindowToCapture, tabData.Value); + IeCaptureHelper.ActivateIeTab(ieWindowToCapture, tabData.Value); } catch (Exception exception) { LOG.Error(exception); } try { - CaptureHelper.CaptureIE(false, ieWindowToCapture); + CaptureHelper.CaptureIe(false, ieWindowToCapture); } catch (Exception exception) { LOG.Error(exception); } @@ -1025,9 +1016,7 @@ namespace Greenshot { /// /// private void Contextmenu_settingsClick(object sender, EventArgs e) { - BeginInvoke((MethodInvoker)delegate { - ShowSetting(); - }); + BeginInvoke((MethodInvoker)ShowSetting); } /// @@ -1110,10 +1099,12 @@ namespace Greenshot { // Only add if the value is not fixed if (!_conf.Values["CaptureMousepointer"].IsFixed) { // For the capture mousecursor option - ToolStripMenuSelectListItem captureMouseItem = new ToolStripMenuSelectListItem(); - captureMouseItem.Text = Language.GetString("settings_capture_mousepointer"); - captureMouseItem.Checked = _conf.CaptureMousepointer; - captureMouseItem.CheckOnClick = true; + ToolStripMenuSelectListItem captureMouseItem = new ToolStripMenuSelectListItem + { + Text = Language.GetString("settings_capture_mousepointer"), + Checked = _conf.CaptureMousepointer, + CheckOnClick = true + }; captureMouseItem.CheckStateChanged += CheckStateChangedHandler; contextmenu_quicksettings.DropDownItems.Add(captureMouseItem); @@ -1121,10 +1112,12 @@ namespace Greenshot { ToolStripMenuSelectList selectList; if (!_conf.Values["Destinations"].IsFixed) { // screenshot destination - selectList = new ToolStripMenuSelectList("destinations", true); - selectList.Text = Language.GetString(LangKey.settings_destination); + selectList = new ToolStripMenuSelectList("destinations", true) + { + Text = Language.GetString(LangKey.settings_destination) + }; // Working with IDestination: - foreach (IDestination destination in DestinationHelper.GetAllDestinations()) { + foreach (var destination in DestinationHelper.GetAllDestinations()) { selectList.AddItem(destination.Description, destination, _conf.OutputDestinations.Contains(destination.Designation)); } selectList.CheckedChanged += QuickSettingDestinationChanged; @@ -1133,20 +1126,24 @@ namespace Greenshot { if (!_conf.Values["WindowCaptureMode"].IsFixed) { // Capture Modes - selectList = new ToolStripMenuSelectList("capturemodes", false); - selectList.Text = Language.GetString(LangKey.settings_window_capture_mode); + selectList = new ToolStripMenuSelectList("capturemodes", false) + { + Text = Language.GetString(LangKey.settings_window_capture_mode) + }; string enumTypeName = typeof(WindowCaptureMode).Name; foreach (WindowCaptureMode captureMode in Enum.GetValues(typeof(WindowCaptureMode))) { - selectList.AddItem(Language.GetString(enumTypeName + "." + captureMode.ToString()), captureMode, _conf.WindowCaptureMode == captureMode); + selectList.AddItem(Language.GetString(enumTypeName + "." + captureMode), captureMode, _conf.WindowCaptureMode == captureMode); } selectList.CheckedChanged += QuickSettingCaptureModeChanged; contextmenu_quicksettings.DropDownItems.Add(selectList); } // print options - selectList = new ToolStripMenuSelectList("printoptions",true); - selectList.Text = Language.GetString(LangKey.settings_printoptions); - + selectList = new ToolStripMenuSelectList("printoptions", true) + { + Text = Language.GetString(LangKey.settings_printoptions) + }; + IniValue iniValue; foreach(string propertyName in _conf.Values.Keys) { if (propertyName.StartsWith("OutputPrint")) { @@ -1162,8 +1159,10 @@ namespace Greenshot { } // effects - selectList = new ToolStripMenuSelectList("effects",true); - selectList.Text = Language.GetString(LangKey.settings_visualization); + selectList = new ToolStripMenuSelectList("effects", true) + { + Text = Language.GetString(LangKey.settings_visualization) + }; iniValue = _conf.Values["PlayCameraSound"]; if (!iniValue.IsFixed) { @@ -1383,7 +1382,7 @@ namespace Greenshot { // Close all open forms (except this), use a separate List to make sure we don't get a "InvalidOperationException: Collection was modified" List
formsToClose = new List(); foreach(Form form in Application.OpenForms) { - if (form.Handle != Handle && !form.GetType().Equals(typeof(ImageEditorForm))) { + if (form.Handle != Handle && form.GetType() != typeof(ImageEditorForm)) { formsToClose.Add(form); } } @@ -1459,9 +1458,11 @@ namespace Greenshot { if (UpdateHelper.IsUpdateCheckNeeded()) { LOG.Debug("BackgroundWorkerTimerTick checking for update"); // Start update check in the background - Thread backgroundTask = new Thread (UpdateHelper.CheckAndAskForUpdate); - backgroundTask.Name = "Update check"; - backgroundTask.IsBackground = true; + var backgroundTask = new Thread(UpdateHelper.CheckAndAskForUpdate) + { + Name = "Update check", + IsBackground = true + }; backgroundTask.Start(); } } diff --git a/Greenshot/Forms/MovableShowColorForm.cs b/Greenshot/Forms/MovableShowColorForm.cs index 7547a04d0..86f193206 100644 --- a/Greenshot/Forms/MovableShowColorForm.cs +++ b/Greenshot/Forms/MovableShowColorForm.cs @@ -86,7 +86,7 @@ namespace Greenshot.Forms { /// Point with the coordinates /// Color at the specified screenCoordinates private static Color GetPixelColor(Point screenCoordinates) { - using (SafeWindowDCHandle screenDC = SafeWindowDCHandle.FromDesktop()) { + using (SafeWindowDcHandle screenDC = SafeWindowDcHandle.FromDesktop()) { try { uint pixel = GDI32.GetPixel(screenDC, screenCoordinates.X, screenCoordinates.Y); Color color = Color.FromArgb(255, (int)(pixel & 0xFF), (int)(pixel & 0xFF00) >> 8, (int)(pixel & 0xFF0000) >> 16); diff --git a/Greenshot/Forms/ResizeSettingsForm.cs b/Greenshot/Forms/ResizeSettingsForm.cs index 2b5489ff6..4471ed443 100644 --- a/Greenshot/Forms/ResizeSettingsForm.cs +++ b/Greenshot/Forms/ResizeSettingsForm.cs @@ -21,137 +21,130 @@ using System; using System.Drawing; using System.Windows.Forms; -using Greenshot.Core; using GreenshotPlugin.Core; +using GreenshotPlugin.Effects; namespace Greenshot.Forms { /// /// A form to set the resize settings /// public partial class ResizeSettingsForm : BaseForm { - private readonly ResizeEffect effect; - private readonly string value_pixel; - private readonly string value_percent; - private double newWidth, newHeight; + private readonly ResizeEffect _effect; + private readonly string _valuePercent; + private double _newWidth, _newHeight; public ResizeSettingsForm(ResizeEffect effect) { - this.effect = effect; + _effect = effect; InitializeComponent(); - value_pixel = Language.GetString("editor_resize_pixel"); - value_percent = Language.GetString("editor_resize_percent"); - combobox_width.Items.Add(value_pixel); - combobox_width.Items.Add(value_percent); - combobox_width.SelectedItem = value_pixel; - combobox_height.Items.Add(value_pixel); - combobox_height.Items.Add(value_percent); - combobox_height.SelectedItem = value_pixel; + var valuePixel = Language.GetString("editor_resize_pixel"); + _valuePercent = Language.GetString("editor_resize_percent"); + combobox_width.Items.Add(valuePixel); + combobox_width.Items.Add(_valuePercent); + combobox_width.SelectedItem = valuePixel; + combobox_height.Items.Add(valuePixel); + combobox_height.Items.Add(_valuePercent); + combobox_height.SelectedItem = valuePixel; textbox_width.Text = effect.Width.ToString(); textbox_height.Text = effect.Height.ToString(); - newWidth = effect.Width; - newHeight = effect.Height; - combobox_width.SelectedIndexChanged += new EventHandler(combobox_SelectedIndexChanged); - combobox_height.SelectedIndexChanged += new EventHandler(combobox_SelectedIndexChanged); + _newWidth = effect.Width; + _newHeight = effect.Height; + combobox_width.SelectedIndexChanged += combobox_SelectedIndexChanged; + combobox_height.SelectedIndexChanged += combobox_SelectedIndexChanged; checkbox_aspectratio.Checked = effect.MaintainAspectRatio; } private void buttonOK_Click(object sender, EventArgs e) { - if (newWidth != effect.Width || newHeight != effect.Height) { - effect.Width = (int)newWidth; - effect.Height = (int)newHeight; - effect.MaintainAspectRatio = checkbox_aspectratio.Checked; + if (_newWidth != _effect.Width || _newHeight != _effect.Height) { + _effect.Width = (int)_newWidth; + _effect.Height = (int)_newHeight; + _effect.MaintainAspectRatio = checkbox_aspectratio.Checked; DialogResult = DialogResult.OK; } } - private bool validate(object sender) { + private static bool Validate(object sender) { TextBox textbox = sender as TextBox; if (textbox != null) { double numberEntered; if (!double.TryParse(textbox.Text, out numberEntered)) { textbox.BackColor = Color.Red; return false; - } else { - textbox.BackColor = Color.White; } + textbox.BackColor = Color.White; } return true; } - private void displayWidth() { + private void DisplayWidth() { double displayValue; - if (value_percent.Equals(combobox_width.SelectedItem)) { - displayValue = (double)newWidth / (double)effect.Width * 100d; + if (_valuePercent.Equals(combobox_width.SelectedItem)) { + displayValue = _newWidth / _effect.Width * 100d; } else { - displayValue = newWidth; + displayValue = _newWidth; } textbox_width.Text = ((int)displayValue).ToString(); } - private void displayHeight() { + private void DisplayHeight() { double displayValue; - if (value_percent.Equals(combobox_height.SelectedItem)) { - displayValue = (double)newHeight / (double)effect.Height * 100d; + if (_valuePercent.Equals(combobox_height.SelectedItem)) { + displayValue = _newHeight / _effect.Height * 100d; } else { - displayValue = newHeight; + displayValue = _newHeight; } textbox_height.Text = ((int)displayValue).ToString(); } private void textbox_KeyUp(object sender, KeyEventArgs e) { - if (!validate(sender)) { + if (!Validate(sender)) { return; } TextBox textbox = sender as TextBox; - if (textbox.Text.Length == 0) { + if (string.IsNullOrEmpty(textbox?.Text)) { return; } bool isWidth = textbox == textbox_width; if (!checkbox_aspectratio.Checked) { if (isWidth) { - newWidth = double.Parse(textbox_width.Text); + _newWidth = double.Parse(textbox_width.Text); } else { - newHeight = double.Parse(textbox_height.Text); + _newHeight = double.Parse(textbox_height.Text); } return; } - bool isPercent = false; - if (isWidth) { - isPercent = value_percent.Equals(combobox_width.SelectedItem); - } else { - isPercent = value_percent.Equals(combobox_height.SelectedItem); - } + var isPercent = _valuePercent.Equals(isWidth ? combobox_width.SelectedItem : combobox_height.SelectedItem); double percent; if (isWidth) { if (isPercent) { percent = double.Parse(textbox_width.Text); - newWidth = (double)effect.Width / 100d * percent; + _newWidth = _effect.Width / 100d * percent; } else { - newWidth = double.Parse(textbox_width.Text); - percent = (double)double.Parse(textbox_width.Text) / (double)effect.Width * 100d; + _newWidth = double.Parse(textbox_width.Text); + percent = double.Parse(textbox_width.Text) / _effect.Width * 100d; } if (checkbox_aspectratio.Checked) { - newHeight = (double)effect.Height / 100d * percent; - displayHeight(); + _newHeight = _effect.Height / 100d * percent; + DisplayHeight(); } } else { if (isPercent) { percent = double.Parse(textbox_height.Text); - newHeight = (double)effect.Height / 100d * percent; + _newHeight = _effect.Height / 100d * percent; } else { - newHeight = double.Parse(textbox_height.Text); - percent = (double)double.Parse(textbox_height.Text) / (double)effect.Height * 100d; + _newHeight = double.Parse(textbox_height.Text); + percent = double.Parse(textbox_height.Text) / _effect.Height * 100d; } if (checkbox_aspectratio.Checked) { - newWidth = (double)effect.Width / 100d * percent; - displayWidth(); + _newWidth = _effect.Width / 100d * percent; + DisplayWidth(); } } } private void textbox_Validating(object sender, System.ComponentModel.CancelEventArgs e) { - validate(sender); + Validate(sender); } /// @@ -160,11 +153,11 @@ namespace Greenshot.Forms { /// /// private void combobox_SelectedIndexChanged(object sender, EventArgs e) { - if (validate(textbox_width)) { - displayWidth(); + if (Validate(textbox_width)) { + DisplayWidth(); } - if (validate(textbox_height)) { - displayHeight(); + if (Validate(textbox_height)) { + DisplayHeight(); } } } diff --git a/Greenshot/Forms/SettingsForm.cs b/Greenshot/Forms/SettingsForm.cs index 21a584fe2..126a13b57 100644 --- a/Greenshot/Forms/SettingsForm.cs +++ b/Greenshot/Forms/SettingsForm.cs @@ -43,8 +43,7 @@ namespace Greenshot { /// Description of SettingsForm. /// public partial class SettingsForm : BaseForm { - private static readonly ILog LOG = LogManager.GetLogger(typeof(SettingsForm)); - private static EditorConfiguration editorConfiguration = IniConfig.GetIniSection(); + private static readonly ILog Log = LogManager.GetLogger(typeof(SettingsForm)); private readonly ToolTip _toolTip = new ToolTip(); private bool _inHotkey; @@ -59,11 +58,7 @@ namespace Greenshot { base.OnLoad(e); // Fix for Vista/XP differences - if (Environment.OSVersion.Version.Major >= 6) { - trackBarJpegQuality.BackColor = SystemColors.Window; - } else { - trackBarJpegQuality.BackColor = SystemColors.Control; - } + trackBarJpegQuality.BackColor = Environment.OSVersion.Version.Major >= 6 ? SystemColors.Window : SystemColors.Control; // This makes it possible to still capture the settings screen fullscreen_hotkeyControl.Enter += EnterHotkeyControl; @@ -78,7 +73,7 @@ namespace Greenshot { lastregion_hotkeyControl.Leave += LeaveHotkeyControl; DisplayPluginTab(); - UpdateUI(); + UpdateUi(); ExpertSettingsEnableState(false); DisplaySettings(); CheckSettings(); @@ -116,9 +111,9 @@ namespace Greenshot { /// ComboBox to populate /// /// - private void PopulateComboBox(ComboBox comboBox, ET[] availableValues, ET selectedValue) where ET : struct { + private void PopulateComboBox(ComboBox comboBox, TEnum[] availableValues, TEnum selectedValue) where TEnum : struct { comboBox.Items.Clear(); - foreach(ET enumValue in availableValues) { + foreach(TEnum enumValue in availableValues) { comboBox.Items.Add(Language.Translate(enumValue)); } comboBox.SelectedItem = Language.Translate(selectedValue); @@ -130,13 +125,13 @@ namespace Greenshot { ///
/// Combobox to get the value from /// The generics value of the combobox - private ET GetSelected(ComboBox comboBox) { - string enumTypeName = typeof(ET).Name; + private TEnum GetSelected(ComboBox comboBox) { + string enumTypeName = typeof(TEnum).Name; string selectedValue = comboBox.SelectedItem as string; - ET[] availableValues = (ET[])Enum.GetValues(typeof(ET)); - ET returnValue = availableValues[0]; - foreach(ET enumValue in availableValues) { - string translation = Language.GetString(enumTypeName + "." + enumValue.ToString()); + TEnum[] availableValues = (TEnum[])Enum.GetValues(typeof(TEnum)); + TEnum returnValue = availableValues[0]; + foreach(TEnum enumValue in availableValues) { + string translation = Language.GetString(enumTypeName + "." + enumValue); if (translation.Equals(selectedValue)) { returnValue = enumValue; break; @@ -196,7 +191,7 @@ namespace Greenshot { /// /// Update the UI to reflect the language and other text settings /// - private void UpdateUI() { + private void UpdateUi() { if (coreConfiguration.HideExpertSettings) { tabcontrol.Controls.Remove(tab_expert); } @@ -229,14 +224,13 @@ namespace Greenshot { return CheckFilenamePattern() && CheckStorageLocationPath(); } - private bool CheckFilenamePattern() { - bool settingsOk = true; + private bool CheckFilenamePattern() { string filename = FilenameHelper.GetFilenameFromPattern(textbox_screenshotname.Text, coreConfiguration.OutputFileFormat, null); // we allow dynamically created subfolders, need to check for them, too string[] pathParts = filename.Split(Path.DirectorySeparatorChar); string filenamePart = pathParts[pathParts.Length-1]; - settingsOk = FilenameHelper.IsFilenameValid(filenamePart); + var settingsOk = FilenameHelper.IsFilenameValid(filenamePart); for (int i = 0; settingsOk && i= 6) { - textbox.BackColor = SystemColors.Window; - } else { - textbox.BackColor = SystemColors.Control; - } + textbox.BackColor = Environment.OSVersion.Version.Major >= 6 ? SystemColors.Window : SystemColors.Control; } else { textbox.BackColor = Color.Red; } @@ -464,7 +451,7 @@ namespace Greenshot { } } } catch (Exception e) { - LOG.Warn("Problem checking registry, ignoring for now: ", e); + Log.Warn("Problem checking registry, ignoring for now: ", e); } } @@ -480,7 +467,7 @@ namespace Greenshot { MainForm.RegisterHotkeys(); // Make sure the current language & settings are reflected in the Main-context menu - MainForm.Instance.UpdateUI(); + MainForm.Instance.UpdateUi(); DialogResult = DialogResult.OK; } else { tabcontrol.SelectTab(tab_output); @@ -511,7 +498,7 @@ namespace Greenshot { } private void Listview_pluginsSelectedIndexChanged(object sender, EventArgs e) { - button_pluginconfigure.Enabled = PluginHelper.Instance.isSelectedItemConfigurable(listview_plugins); + button_pluginconfigure.Enabled = PluginHelper.Instance.IsSelectedItemConfigurable(listview_plugins); } private void Button_pluginconfigureClick(object sender, EventArgs e) { @@ -523,11 +510,11 @@ namespace Greenshot { //EmailFormat selectedEmailFormat = GetSelected(combobox_emailformat); WindowCaptureMode selectedWindowCaptureMode = GetSelected(combobox_window_capture_mode); if (combobox_language.SelectedItem != null) { - LOG.Debug("Setting language to: " + (string)combobox_language.SelectedValue); + Log.Debug("Setting language to: " + (string)combobox_language.SelectedValue); Language.CurrentLanguage = (string)combobox_language.SelectedValue; } // Reflect language changes to the settings form - UpdateUI(); + UpdateUi(); // Reflect Language changes form ApplyLanguage(); @@ -652,7 +639,7 @@ namespace Greenshot { return 1; } if (firstDestination != null && firstDestination.Priority == secondDestination.Priority) { - return firstDestination.Description.CompareTo(secondDestination.Description); + return string.Compare(firstDestination.Description, secondDestination.Description, StringComparison.Ordinal); } if (firstDestination != null) { return firstDestination.Priority - secondDestination.Priority; diff --git a/Greenshot/Forms/ToolStripMenuSelectList.cs b/Greenshot/Forms/ToolStripMenuSelectList.cs index 88546a6bc..e6a77f53b 100644 --- a/Greenshot/Forms/ToolStripMenuSelectList.cs +++ b/Greenshot/Forms/ToolStripMenuSelectList.cs @@ -31,11 +31,11 @@ namespace Greenshot.Forms { /// /// the ToolStripMenuSelectList makes it possible to have a single or multi-check menu /// - public class ToolStripMenuSelectList : ToolStripMenuItem { - private static readonly CoreConfiguration coreConfiguration = IniConfig.GetIniSection(); - private readonly bool multiCheckAllowed; - private bool updateInProgress; - private static Image defaultImage; + public sealed class ToolStripMenuSelectList : ToolStripMenuItem { + private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); + private readonly bool _multiCheckAllowed; + private bool _updateInProgress; + private static Image _defaultImage; /// /// Occurs when one of the list's child element's Checked state changes. @@ -49,14 +49,12 @@ namespace Greenshot.Forms { public ToolStripMenuSelectList(object identifier, bool allowMultiCheck) { Identifier = identifier; CheckOnClick = false; - multiCheckAllowed = allowMultiCheck; - if (defaultImage == null || defaultImage.Size != coreConfiguration.IconSize) { - if (defaultImage != null) { - defaultImage.Dispose(); - } - defaultImage = ImageHelper.CreateEmpty(coreConfiguration.IconSize.Width, coreConfiguration.IconSize.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb, Color.Transparent, 96f, 96f); + _multiCheckAllowed = allowMultiCheck; + if (_defaultImage == null || _defaultImage.Size != CoreConfig.IconSize) { + _defaultImage?.Dispose(); + _defaultImage = ImageHelper.CreateEmpty(CoreConfig.IconSize.Width, CoreConfig.IconSize.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb, Color.Transparent, 96f, 96f); } - Image = defaultImage; + Image = _defaultImage; } public ToolStripMenuSelectList() : this(null,false) {} public ToolStripMenuSelectList(object identifier) : this(identifier,false) {} @@ -70,7 +68,7 @@ namespace Greenshot.Forms { IEnumerator items = DropDownItems.GetEnumerator(); while (items.MoveNext()) { ToolStripMenuSelectListItem tsmi = (ToolStripMenuSelectListItem)items.Current; - if (tsmi.Checked) { + if (tsmi != null && tsmi.Checked) { return tsmi; } } @@ -80,9 +78,9 @@ namespace Greenshot.Forms { IEnumerator items = DropDownItems.GetEnumerator(); while (items.MoveNext()) { ToolStripMenuSelectListItem tsmi = (ToolStripMenuSelectListItem)items.Current; - if (!multiCheckAllowed && !tsmi.Equals(value)) { + if (tsmi != null && !_multiCheckAllowed && !tsmi.Equals(value)) { tsmi.Checked = false; - } else if (tsmi.Equals(value)) { + } else if (tsmi != null && tsmi.Equals(value)) { tsmi.Checked = true; } } @@ -98,30 +96,31 @@ namespace Greenshot.Forms { IEnumerator items = DropDownItems.GetEnumerator(); while(items.MoveNext()) { ToolStripMenuSelectListItem tsmi = (ToolStripMenuSelectListItem)items.Current; - if (tsmi.Checked) { + if (tsmi != null && tsmi.Checked) { sel.Add(tsmi); } } return sel.ToArray(); } set { - if (!multiCheckAllowed) { + if (!_multiCheckAllowed) { throw new ArgumentException("Writing to checkedItems is only allowed in multi-check mode. Either set allowMultiCheck to true or use set SelectedItem instead of SelectedItems."); } IEnumerator items = DropDownItems.GetEnumerator(); IEnumerator sel = value.GetEnumerator(); while (items.MoveNext()) { - ToolStripMenuSelectListItem tsmi = (ToolStripMenuSelectListItem)items.Current; - while (sel.MoveNext()) { - if (tsmi.Equals(sel.Current)) { - tsmi.Checked = true; - } else { - tsmi.Checked = false; - } - if (!multiCheckAllowed && !tsmi.Equals(sel.Current)) { - tsmi.Checked = false; - } else if (tsmi.Equals(value)) { - tsmi.Checked = true; + var toolStripMenuSelectListItem = (ToolStripMenuSelectListItem)items.Current; + if (toolStripMenuSelectListItem == null) + { + continue; + } + while (sel.MoveNext()) + { + toolStripMenuSelectListItem.Checked = toolStripMenuSelectListItem.Equals(sel.Current); + if (!_multiCheckAllowed && !toolStripMenuSelectListItem.Equals(sel.Current)) { + toolStripMenuSelectListItem.Checked = false; + } else if (toolStripMenuSelectListItem.Equals(value)) { + toolStripMenuSelectListItem.Checked = true; } } } @@ -129,19 +128,17 @@ namespace Greenshot.Forms { } private void ItemCheckStateChanged(object sender, EventArgs e) { - if (updateInProgress) { + if (_updateInProgress) { return; } - ToolStripMenuSelectListItem tsmi = (ToolStripMenuSelectListItem)sender; - updateInProgress = true; - if (tsmi.Checked && !multiCheckAllowed) { + var toolStripMenuSelectListItem = (ToolStripMenuSelectListItem)sender; + _updateInProgress = true; + if (toolStripMenuSelectListItem.Checked && !_multiCheckAllowed) { UncheckAll(); - tsmi.Checked = true; - } - updateInProgress = false; - if (CheckedChanged != null) { - CheckedChanged(this, new ItemCheckedChangedEventArgs(tsmi)); + toolStripMenuSelectListItem.Checked = true; } + _updateInProgress = false; + CheckedChanged?.Invoke(this, new ItemCheckedChangedEventArgs(toolStripMenuSelectListItem)); } /// @@ -151,26 +148,28 @@ namespace Greenshot.Forms { /// the icon to be displayed /// the data to be returned when an item is queried /// whether the item is initially checked - public void AddItem(string label, Image image, Object data, bool isChecked) { - ToolStripMenuSelectListItem newItem = new ToolStripMenuSelectListItem(); - newItem.Text = label; + public void AddItem(string label, Image image, object data, bool isChecked) { + var toolStripMenuSelectListItem = new ToolStripMenuSelectListItem + { + Text = label + }; if (image == null) { - image = defaultImage; + image = _defaultImage; } - newItem.DisplayStyle = ToolStripItemDisplayStyle.Text; - newItem.Image = image; - newItem.CheckOnClick = true; - newItem.CheckStateChanged += ItemCheckStateChanged; - newItem.Data = data; + toolStripMenuSelectListItem.DisplayStyle = ToolStripItemDisplayStyle.Text; + toolStripMenuSelectListItem.Image = image; + toolStripMenuSelectListItem.CheckOnClick = true; + toolStripMenuSelectListItem.CheckStateChanged += ItemCheckStateChanged; + toolStripMenuSelectListItem.Data = data; if (isChecked) { - if (!multiCheckAllowed) { - updateInProgress = true; + if (!_multiCheckAllowed) { + _updateInProgress = true; UncheckAll(); - updateInProgress = false; + _updateInProgress = false; } - newItem.Checked = isChecked; + toolStripMenuSelectListItem.Checked = true; } - DropDownItems.Add(newItem); + DropDownItems.Add(toolStripMenuSelectListItem); } /// @@ -187,7 +186,7 @@ namespace Greenshot.Forms { /// /// the label to be displayed /// the data to be returned when an item is queried - public void AddItem(string label, Object data) { + public void AddItem(string label, object data) { AddItem(label, null, data, false); } @@ -216,7 +215,7 @@ namespace Greenshot.Forms { /// the label to be displayed /// the data to be returned when an item is queried /// whether the item is initially checked - public void AddItem(string label, Object data, bool isChecked) { + public void AddItem(string label, object data, bool isChecked) { AddItem(label, null, data, isChecked); } @@ -234,8 +233,13 @@ namespace Greenshot.Forms { /// public void UncheckAll() { IEnumerator items = DropDownItems.GetEnumerator(); - while (items.MoveNext()) { - ((ToolStripMenuSelectListItem)items.Current).Checked = false; + while (items.MoveNext()) + { + var toolStripMenuSelectListItem = (ToolStripMenuSelectListItem)items.Current; + if (toolStripMenuSelectListItem != null) + { + toolStripMenuSelectListItem.Checked = false; + } } } } diff --git a/Greenshot/Forms/TornEdgeSettingsForm.cs b/Greenshot/Forms/TornEdgeSettingsForm.cs index 3b0bda4d3..1eb9b7e53 100644 --- a/Greenshot/Forms/TornEdgeSettingsForm.cs +++ b/Greenshot/Forms/TornEdgeSettingsForm.cs @@ -21,41 +21,41 @@ using System; using System.Drawing; using System.Windows.Forms; -using Greenshot.Core; +using GreenshotPlugin.Effects; namespace Greenshot.Forms { public partial class TornEdgeSettingsForm : BaseForm { - private readonly TornEdgeEffect effect; + private readonly TornEdgeEffect _effect; public TornEdgeSettingsForm(TornEdgeEffect effect) { - this.effect = effect; + _effect = effect; InitializeComponent(); ShowSettings(); } private void ShowSettings() { - shadowCheckbox.Checked = effect.GenerateShadow; + shadowCheckbox.Checked = _effect.GenerateShadow; // Fix to prevent BUG-1753 - shadowDarkness.Value = Math.Max(shadowDarkness.Minimum, Math.Min(shadowDarkness.Maximum, (int)(effect.Darkness * shadowDarkness.Maximum))); - offsetX.Value = effect.ShadowOffset.X; - offsetY.Value = effect.ShadowOffset.Y; - toothsize.Value = effect.ToothHeight; - verticaltoothrange.Value = effect.VerticalToothRange; - horizontaltoothrange.Value = effect.HorizontalToothRange; - top.Checked = effect.Edges[0]; - right.Checked = effect.Edges[1]; - bottom.Checked = effect.Edges[2]; - left.Checked = effect.Edges[3]; + shadowDarkness.Value = Math.Max(shadowDarkness.Minimum, Math.Min(shadowDarkness.Maximum, (int)(_effect.Darkness * shadowDarkness.Maximum))); + offsetX.Value = _effect.ShadowOffset.X; + offsetY.Value = _effect.ShadowOffset.Y; + toothsize.Value = _effect.ToothHeight; + verticaltoothrange.Value = _effect.VerticalToothRange; + horizontaltoothrange.Value = _effect.HorizontalToothRange; + top.Checked = _effect.Edges[0]; + right.Checked = _effect.Edges[1]; + bottom.Checked = _effect.Edges[2]; + left.Checked = _effect.Edges[3]; } private void ButtonOK_Click(object sender, EventArgs e) { - effect.Darkness = (float)shadowDarkness.Value / (float)40; - effect.ShadowOffset = new Point((int)offsetX.Value, (int)offsetY.Value); - effect.ShadowSize = (int)thickness.Value; - effect.ToothHeight = (int)toothsize.Value; - effect.VerticalToothRange = (int)verticaltoothrange.Value; - effect.HorizontalToothRange = (int)horizontaltoothrange.Value; - effect.Edges = new bool[] { top.Checked, right.Checked, bottom.Checked, left.Checked }; - effect.GenerateShadow = shadowCheckbox.Checked; + _effect.Darkness = shadowDarkness.Value / (float)40; + _effect.ShadowOffset = new Point((int)offsetX.Value, (int)offsetY.Value); + _effect.ShadowSize = (int)thickness.Value; + _effect.ToothHeight = (int)toothsize.Value; + _effect.VerticalToothRange = (int)verticaltoothrange.Value; + _effect.HorizontalToothRange = (int)horizontaltoothrange.Value; + _effect.Edges = new[] { top.Checked, right.Checked, bottom.Checked, left.Checked }; + _effect.GenerateShadow = shadowCheckbox.Checked; DialogResult = DialogResult.OK; } @@ -66,37 +66,37 @@ namespace Greenshot.Forms { shadowDarkness.Enabled = shadowCheckbox.Checked; } - + - private void all_CheckedChanged(object sender, EventArgs e) { - AnySideChangeChecked(top, all.Checked); - AnySideChangeChecked(right, all.Checked); - AnySideChangeChecked(bottom, all.Checked); - AnySideChangeChecked(left, all.Checked); - } + private void all_CheckedChanged(object sender, EventArgs e) { + AnySideChangeChecked(top, all.Checked); + AnySideChangeChecked(right, all.Checked); + AnySideChangeChecked(bottom, all.Checked); + AnySideChangeChecked(left, all.Checked); + } - private void AnySideCheckedChanged(object sender, EventArgs e) { - all.CheckedChanged -= all_CheckedChanged; - all.Checked = top.Checked && right.Checked && bottom.Checked && left.Checked; - all.CheckedChanged += all_CheckedChanged; - } + private void AnySideCheckedChanged(object sender, EventArgs e) { + all.CheckedChanged -= all_CheckedChanged; + all.Checked = top.Checked && right.Checked && bottom.Checked && left.Checked; + all.CheckedChanged += all_CheckedChanged; + } - /// - /// changes the Checked property of top/right/bottom/left checkboxes without triggering AnySideCheckedChange - /// - /// Checkbox to change Checked - /// true to check - private void AnySideChangeChecked(CheckBox cb, bool status) { - if (status != cb.Checked) { - cb.CheckedChanged -= AnySideCheckedChanged; - cb.Checked = status; - cb.CheckedChanged += AnySideCheckedChanged; - } - } + /// + /// changes the Checked property of top/right/bottom/left checkboxes without triggering AnySideCheckedChange + /// + /// Checkbox to change Checked + /// true to check + private void AnySideChangeChecked(CheckBox cb, bool status) { + if (status != cb.Checked) { + cb.CheckedChanged -= AnySideCheckedChanged; + cb.Checked = status; + cb.CheckedChanged += AnySideCheckedChanged; + } + } - private void TornEdgeSettingsForm_Load(object sender, EventArgs e) - { + private void TornEdgeSettingsForm_Load(object sender, EventArgs e) + { - } + } } } diff --git a/Greenshot/Help/HelpFileLoader.cs b/Greenshot/Help/HelpFileLoader.cs index a2ebf9331..d51fffcc4 100644 --- a/Greenshot/Help/HelpFileLoader.cs +++ b/Greenshot/Help/HelpFileLoader.cs @@ -29,21 +29,14 @@ namespace Greenshot.Help /// /// Description of HelpFileLoader. /// - public sealed class HelpFileLoader + public static class HelpFileLoader { + private static readonly ILog Log = LogManager.GetLogger(typeof(HelpFileLoader)); - private static readonly ILog LOG = LogManager.GetLogger(typeof(HelpFileLoader)); - - private const string EXT_HELP_URL = @"http://getgreenshot.org/help/"; - - private HelpFileLoader() { - } - + private const string ExtHelpUrl = @"http://getgreenshot.org/help/"; + public static void LoadHelp() { - string uri = FindOnlineHelpUrl(Language.CurrentLanguage); - if(uri == null) { - uri = Language.HelpFilePath; - } + string uri = FindOnlineHelpUrl(Language.CurrentLanguage) ?? Language.HelpFilePath; Process.Start(uri); } @@ -51,7 +44,7 @@ namespace Greenshot.Help private static string FindOnlineHelpUrl(string currentIETF) { string ret = null; - string extHelpUrlForCurrrentIETF = EXT_HELP_URL; + string extHelpUrlForCurrrentIETF = ExtHelpUrl; if(!currentIETF.Equals("en-US")) { extHelpUrlForCurrrentIETF += currentIETF.ToLower() + "/"; @@ -60,16 +53,16 @@ namespace Greenshot.Help HttpStatusCode? httpStatusCode = GetHttpStatus(extHelpUrlForCurrrentIETF); if(httpStatusCode == HttpStatusCode.OK) { ret = extHelpUrlForCurrrentIETF; - } else if(httpStatusCode != null && !extHelpUrlForCurrrentIETF.Equals(EXT_HELP_URL)) { - LOG.DebugFormat("Localized online help not found at {0}, will try {1} as fallback", extHelpUrlForCurrrentIETF, EXT_HELP_URL); - httpStatusCode = GetHttpStatus(EXT_HELP_URL); + } else if(httpStatusCode != null && !extHelpUrlForCurrrentIETF.Equals(ExtHelpUrl)) { + Log.DebugFormat("Localized online help not found at {0}, will try {1} as fallback", extHelpUrlForCurrrentIETF, ExtHelpUrl); + httpStatusCode = GetHttpStatus(ExtHelpUrl); if(httpStatusCode == HttpStatusCode.OK) { - ret = EXT_HELP_URL; + ret = ExtHelpUrl; } else { - LOG.WarnFormat("{0} returned status {1}", EXT_HELP_URL, httpStatusCode); + Log.WarnFormat("{0} returned status {1}", ExtHelpUrl, httpStatusCode); } } else if(httpStatusCode == null){ - LOG.Info("Internet connection does not seem to be available, will load help from file system."); + Log.Info("Internet connection does not seem to be available, will load help from file system."); } return ret; @@ -88,11 +81,7 @@ namespace Greenshot.Help return res.StatusCode; } } catch (WebException e) { - if (e.Response != null) - { - return ((HttpWebResponse)e.Response).StatusCode; - } - return null; + return ((HttpWebResponse) e.Response)?.StatusCode; } } } diff --git a/Greenshot/Helpers/CaptureHelper.cs b/Greenshot/Helpers/CaptureHelper.cs index 74975f82f..e62afabe7 100644 --- a/Greenshot/Helpers/CaptureHelper.cs +++ b/Greenshot/Helpers/CaptureHelper.cs @@ -41,8 +41,8 @@ namespace Greenshot.Helpers { /// CaptureHelper contains all the capture logic /// public class CaptureHelper : IDisposable { - private static readonly ILog LOG = LogManager.GetLogger(typeof(CaptureHelper)); - private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly ILog Log = LogManager.GetLogger(typeof(CaptureHelper)); + private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); // TODO: when we get the screen capture code working correctly, this needs to be enabled //private static ScreenCaptureHelper screenCapture = null; private List _windows = new List(); @@ -78,7 +78,7 @@ namespace Greenshot.Helpers { _selectedCaptureWindow = null; _capture = null; // Empty working set after capturing - if (conf.MinimizeWorkingSetSize) { + if (CoreConfig.MinimizeWorkingSetSize) { PsAPI.EmptyWorkingSet(); } } @@ -114,7 +114,7 @@ namespace Greenshot.Helpers { } } - public static void CaptureIE(bool captureMouse, WindowDetails windowToCapture) { + public static void CaptureIe(bool captureMouse, WindowDetails windowToCapture) { using (CaptureHelper captureHelper = new CaptureHelper(CaptureMode.IE, captureMouse)) { captureHelper.SelectedCaptureWindow = windowToCapture; captureHelper.MakeCapture(); @@ -192,7 +192,7 @@ namespace Greenshot.Helpers { } private void DoCaptureFeedback() { - if(conf.PlayCameraSound) { + if(CoreConfig.PlayCameraSound) { SoundHelper.Play(); } } @@ -224,11 +224,11 @@ namespace Greenshot.Helpers { // This fixes a problem when a balloon is still visible and a capture needs to be taken // forcefully removes the balloon! - if (!conf.HideTrayicon) { + if (!CoreConfig.HideTrayicon) { MainForm.Instance.NotifyIcon.Visible = false; MainForm.Instance.NotifyIcon.Visible = true; } - LOG.Debug(String.Format("Capturing with mode {0} and using Cursor {1}", _captureMode, _captureMouseCursor)); + Log.Debug($"Capturing with mode {_captureMode} and using Cursor {_captureMouseCursor}"); _capture.CaptureDetails.CaptureMode = _captureMode; // Get the windows details in a seperate thread, only for those captures that have a Feedback @@ -251,27 +251,24 @@ namespace Greenshot.Helpers { } // Delay for the Context menu - if (conf.CaptureDelay > 0) { - Thread.Sleep(conf.CaptureDelay); + if (CoreConfig.CaptureDelay > 0) { + Thread.Sleep(CoreConfig.CaptureDelay); } else { - conf.CaptureDelay = 0; + CoreConfig.CaptureDelay = 0; } // Capture Mousecursor if we are not loading from file or clipboard, only show when needed - if (_captureMode != CaptureMode.File && _captureMode != CaptureMode.Clipboard) { + if (_captureMode != CaptureMode.File && _captureMode != CaptureMode.Clipboard) + { _capture = WindowCapture.CaptureCursor(_capture); - if (_captureMouseCursor) { - _capture.CursorVisible = conf.CaptureMousepointer; - } else { - _capture.CursorVisible = false; - } + _capture.CursorVisible = _captureMouseCursor && CoreConfig.CaptureMousepointer; } switch(_captureMode) { case CaptureMode.Window: _capture = WindowCapture.CaptureScreen(_capture); _capture.CaptureDetails.AddMetaData("source", "Screen"); - SetDPI(); + SetDpi(); CaptureWithFeedback(); break; case CaptureMode.ActiveWindow: @@ -285,13 +282,13 @@ namespace Greenshot.Helpers { _capture.CaptureDetails.AddMetaData("source", "Screen"); _capture.CaptureDetails.Title = "Screen"; } - SetDPI(); + SetDpi(); HandleCapture(); break; case CaptureMode.IE: - if (IECaptureHelper.CaptureIE(_capture, SelectedCaptureWindow) != null) { + if (IeCaptureHelper.CaptureIe(_capture, SelectedCaptureWindow) != null) { _capture.CaptureDetails.AddMetaData("source", "Internet Explorer"); - SetDPI(); + SetDpi(); HandleCapture(); } break; @@ -310,8 +307,8 @@ namespace Greenshot.Helpers { } break; case ScreenCaptureMode.Fixed: - if (conf.ScreenToCapture > 0 && conf.ScreenToCapture <= Screen.AllScreens.Length) { - _capture = WindowCapture.CaptureRectangle(_capture, Screen.AllScreens[conf.ScreenToCapture].Bounds); + if (CoreConfig.ScreenToCapture > 0 && CoreConfig.ScreenToCapture <= Screen.AllScreens.Length) { + _capture = WindowCapture.CaptureRectangle(_capture, Screen.AllScreens[CoreConfig.ScreenToCapture].Bounds); captureTaken = true; } break; @@ -322,7 +319,7 @@ namespace Greenshot.Helpers { if (!captureTaken) { _capture = WindowCapture.CaptureScreen(_capture); } - SetDPI(); + SetDpi(); HandleCapture(); break; case CaptureMode.Clipboard: @@ -363,13 +360,13 @@ namespace Greenshot.Helpers { break; } } catch (Exception e) { - LOG.Error(e.Message, e); + Log.Error(e.Message, e); MessageBox.Show(Language.GetFormattedString(LangKey.error_openfile, filename)); } try { fileImage = ImageHelper.LoadImage(filename); } catch (Exception e) { - LOG.Error(e.Message, e); + Log.Error(e.Message, e); MessageBox.Show(Language.GetFormattedString(LangKey.error_openfile, filename)); } } @@ -395,8 +392,8 @@ namespace Greenshot.Helpers { } break; case CaptureMode.LastRegion: - if (!conf.LastCapturedRegion.IsEmpty) { - _capture = WindowCapture.CaptureRectangle(_capture, conf.LastCapturedRegion); + if (!CoreConfig.LastCapturedRegion.IsEmpty) { + _capture = WindowCapture.CaptureRectangle(_capture, CoreConfig.LastCapturedRegion); // TODO: Reactive / check if the elements code is activated //if (windowDetailsThread != null) { // windowDetailsThread.Join(); @@ -404,7 +401,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(CoreConfig.LastCapturedRegion.X + CoreConfig.LastCapturedRegion.Width / 2, CoreConfig.LastCapturedRegion.Y + CoreConfig.LastCapturedRegion.Height / 2); if (window.Contains(estimatedLocation)) { _selectedCaptureWindow = window; _capture.CaptureDetails.Title = _selectedCaptureWindow.Text; @@ -416,7 +413,7 @@ namespace Greenshot.Helpers { //capture.MoveElements(capture.ScreenBounds.Location.X - capture.Location.X, capture.ScreenBounds.Location.Y - capture.Location.Y); _capture.CaptureDetails.AddMetaData("source", "screen"); - SetDPI(); + SetDpi(); HandleCapture(); } break; @@ -425,25 +422,23 @@ namespace Greenshot.Helpers { if (Rectangle.Empty.Equals(_captureRect)) { _capture = WindowCapture.CaptureScreen(_capture); _capture.CaptureDetails.AddMetaData("source", "screen"); - SetDPI(); + SetDpi(); CaptureWithFeedback(); } else { _capture = WindowCapture.CaptureRectangle(_capture, _captureRect); _capture.CaptureDetails.AddMetaData("source", "screen"); - SetDPI(); + SetDpi(); HandleCapture(); } break; default: - LOG.Warn("Unknown capture mode: " + _captureMode); + Log.Warn("Unknown capture mode: " + _captureMode); break; } // Wait for thread, otherwise we can't dipose the CaptureHelper - if (retrieveWindowDetailsThread != null) { - retrieveWindowDetailsThread.Join(); - } + retrieveWindowDetailsThread?.Join(); if (_capture != null) { - LOG.Debug("Disposing capture"); + Log.Debug("Disposing capture"); _capture.Dispose(); } } @@ -471,7 +466,7 @@ namespace Greenshot.Helpers { } private void RetrieveWindowDetails() { - LOG.Debug("start RetrieveWindowDetails"); + Log.Debug("start RetrieveWindowDetails"); // Start Enumeration of "active" windows foreach (var window in WindowDetails.GetVisibleWindows()) { // Make sure the details are retrieved once @@ -479,7 +474,7 @@ namespace Greenshot.Helpers { // Force children retrieval, sometimes windows close on losing focus and this is solved by caching int goLevelDeep = 3; - if (conf.WindowCaptureAllChildLocations) { + if (CoreConfig.WindowCaptureAllChildLocations) { goLevelDeep = 20; } window.GetChildren(goLevelDeep); @@ -487,11 +482,11 @@ namespace Greenshot.Helpers { _windows.Add(window); } } - LOG.Debug("end RetrieveWindowDetails"); + Log.Debug("end RetrieveWindowDetails"); } private void AddConfiguredDestination() { - foreach(string destinationDesignation in conf.OutputDestinations) { + foreach(string destinationDesignation in CoreConfig.OutputDestinations) { IDestination destination = DestinationHelper.GetDestination(destinationDesignation); if (destination != null) { _capture.CaptureDetails.AddDestination(destination); @@ -507,7 +502,7 @@ namespace Greenshot.Helpers { private void OpenCaptureOnClick(object sender, EventArgs e) { SurfaceMessageEventArgs eventArgs = MainForm.Instance.NotifyIcon.Tag as SurfaceMessageEventArgs; if (eventArgs == null) { - LOG.Warn("OpenCaptureOnClick called without SurfaceMessageEventArgs"); + Log.Warn("OpenCaptureOnClick called without SurfaceMessageEventArgs"); RemoveEventHandler(sender, e); return; } @@ -515,14 +510,19 @@ namespace Greenshot.Helpers { if (surface != null && eventArgs.MessageType == SurfaceMessageTyp.FileSaved) { if (!string.IsNullOrEmpty(surface.LastSaveFullPath)) { string errorMessage = null; - + var path = Path.GetDirectoryName(surface.LastSaveFullPath); try { - ProcessStartInfo psi = new ProcessStartInfo("explorer.exe"); - psi.Arguments = Path.GetDirectoryName(surface.LastSaveFullPath); - psi.UseShellExecute = false; - using (Process p = new Process()) { - p.StartInfo = psi; - p.Start(); + if (path != null) + { + var processStartInfo = new ProcessStartInfo("explorer.exe") + { + Arguments = path, + UseShellExecute = false + }; + using (var process = new Process()) { + process.StartInfo = processStartInfo; + process.Start(); + } } } catch (Exception ex) { errorMessage = ex.Message; @@ -531,28 +531,41 @@ namespace Greenshot.Helpers { if (errorMessage != null) { try { string windowsPath = Environment.GetEnvironmentVariable("SYSTEMROOT"); - string explorerPath = Path.Combine(windowsPath, "explorer.exe"); - if (File.Exists(explorerPath)) { - ProcessStartInfo psi = new ProcessStartInfo(explorerPath); - psi.Arguments = Path.GetDirectoryName(surface.LastSaveFullPath); - psi.UseShellExecute = false; - using (Process p = new Process()) { - p.StartInfo = psi; - p.Start(); + if (windowsPath != null) + { + string explorerPath = Path.Combine(windowsPath, "explorer.exe"); + if (File.Exists(explorerPath)) + { + var lastSaveDirectory = Path.GetDirectoryName(surface.LastSaveFullPath); + if (lastSaveDirectory != null) + { + var processStartInfo = new ProcessStartInfo(explorerPath) + { + Arguments = lastSaveDirectory, + UseShellExecute = false + }; + using (var process = new Process()) { + process.StartInfo = processStartInfo; + process.Start(); + } + } + errorMessage = null; } - errorMessage = null; } - } catch { + } + catch + { + // ignored } } if (errorMessage != null) { - MessageBox.Show(string.Format("{0}\r\nexplorer.exe {1}", errorMessage, surface.LastSaveFullPath), "explorer.exe", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"{errorMessage}\r\nexplorer.exe {surface.LastSaveFullPath}", "explorer.exe", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - } else if (surface != null && !string.IsNullOrEmpty(surface.UploadUrl)) { + } else if (!string.IsNullOrEmpty(surface?.UploadUrl)) { Process.Start(surface.UploadUrl); } - LOG.DebugFormat("Deregistering the BalloonTipClicked"); + Log.DebugFormat("Deregistering the BalloonTipClicked"); RemoveEventHandler(sender, e); } @@ -568,7 +581,11 @@ namespace Greenshot.Helpers { /// /// private void SurfaceMessageReceived(object sender, SurfaceMessageEventArgs eventArgs) { - if (eventArgs == null || string.IsNullOrEmpty(eventArgs.Message)) { + if (string.IsNullOrEmpty(eventArgs?.Message)) { + return; + } + if (MainForm.Instance == null) + { return; } switch (eventArgs.MessageType) { @@ -602,13 +619,13 @@ namespace Greenshot.Helpers { outputMade = true; } else { // Make sure the resolution is set correctly! - if (_capture.CaptureDetails != null && _capture.Image != null) { - ((Bitmap)_capture.Image).SetResolution(_capture.CaptureDetails.DpiX, _capture.CaptureDetails.DpiY); + if (_capture.CaptureDetails != null) { + ((Bitmap) _capture.Image)?.SetResolution(_capture.CaptureDetails.DpiX, _capture.CaptureDetails.DpiY); } DoCaptureFeedback(); } - LOG.Debug("A capture of: " + _capture.CaptureDetails.Title); + Log.Debug("A capture of: " + _capture.CaptureDetails.Title); // check if someone has passed a destination if (_capture.CaptureDetails.CaptureDestinations == null || _capture.CaptureDetails.CaptureDestinations.Count == 0) { @@ -616,18 +633,20 @@ namespace Greenshot.Helpers { } // Create Surface with capture, this way elements can be added automatically (like the mouse cursor) - Surface surface = new Surface(_capture); - surface.Modified = !outputMade; + Surface surface = new Surface(_capture) + { + Modified = !outputMade + }; // Register notify events if this is wanted - if (conf.ShowTrayNotification && !conf.HideTrayicon) { + if (CoreConfig.ShowTrayNotification && !CoreConfig.HideTrayicon) { surface.SurfaceMessage += SurfaceMessageReceived; } // Let the processors do their job foreach(IProcessor processor in ProcessorHelper.GetAllProcessors()) { if (processor.isActive) { - LOG.InfoFormat("Calling processor {0}", processor.Description); + Log.InfoFormat("Calling processor {0}", processor.Description); processor.ProcessCapture(surface, _capture.CaptureDetails); } } @@ -659,7 +678,7 @@ namespace Greenshot.Helpers { if (PickerDestination.DESIGNATION.Equals(destination.Designation)) { continue; } - LOG.InfoFormat("Calling destination {0}", destination.Description); + Log.InfoFormat("Calling destination {0}", destination.Description); ExportInformation exportInformation = destination.ExportCapture(false, surface, captureDetails); if (EditorDestination.DESIGNATION.Equals(destination.Designation) && exportInformation.ExportMade) { @@ -674,21 +693,21 @@ namespace Greenshot.Helpers { private bool CaptureActiveWindow() { bool presupplied = false; - LOG.Debug("CaptureActiveWindow"); + Log.Debug("CaptureActiveWindow"); if (_selectedCaptureWindow != null) { - LOG.Debug("Using supplied window"); + Log.Debug("Using supplied window"); presupplied = true; } else { _selectedCaptureWindow = WindowDetails.GetActiveWindow(); if (_selectedCaptureWindow != null) { - if (LOG.IsDebugEnabled) + if (Log.IsDebugEnabled) { - LOG.DebugFormat("Capturing window: {0} with {1}", _selectedCaptureWindow.Text, _selectedCaptureWindow.WindowRectangle); + Log.DebugFormat("Capturing window: {0} with {1}", _selectedCaptureWindow.Text, _selectedCaptureWindow.WindowRectangle); } } } if (_selectedCaptureWindow == null || (!presupplied && _selectedCaptureWindow.Iconic)) { - LOG.Warn("No window to capture!"); + Log.Warn("No window to capture!"); // Nothing to capture, code up in the stack will capture the full screen return false; } @@ -699,13 +718,13 @@ namespace Greenshot.Helpers { } _selectedCaptureWindow = SelectCaptureWindow(_selectedCaptureWindow); if (_selectedCaptureWindow == null) { - LOG.Warn("No window to capture, after SelectCaptureWindow!"); + Log.Warn("No window to capture, after SelectCaptureWindow!"); // Nothing to capture, code up in the stack will capture the full screen return false; } // Fix for Bug #3430560 - conf.LastCapturedRegion = _selectedCaptureWindow.WindowRectangle; - bool returnValue = CaptureWindow(_selectedCaptureWindow, _capture, conf.WindowCaptureMode) != null; + CoreConfig.LastCapturedRegion = _selectedCaptureWindow.WindowRectangle; + bool returnValue = CaptureWindow(_selectedCaptureWindow, _capture, CoreConfig.WindowCaptureMode) != null; return returnValue; } @@ -718,7 +737,7 @@ namespace Greenshot.Helpers { public static WindowDetails SelectCaptureWindow(WindowDetails windowToCapture) { Rectangle windowRectangle = windowToCapture.WindowRectangle; if (windowRectangle.Width == 0 || windowRectangle.Height == 0) { - LOG.WarnFormat("Window {0} has nothing to capture, using workaround to find other window of same process.", windowToCapture.Text); + Log.WarnFormat("Window {0} has nothing to capture, using workaround to find other window of same process.", windowToCapture.Text); // Trying workaround, the size 0 arrises with e.g. Toad.exe, has a different Window when minimized WindowDetails linkedWindow = WindowDetails.GetLinkedWindow(windowToCapture); if (linkedWindow != null) { @@ -735,18 +754,18 @@ namespace Greenshot.Helpers { ///
/// Proces to check for the presentation framework /// true if the process uses WPF - private static bool isWPF(Process process) { + private static bool IsWpf(Process process) { if (process != null) { try { foreach (ProcessModule module in process.Modules) { if (module.ModuleName.StartsWith("PresentationFramework")) { - LOG.InfoFormat("Found that Process {0} uses {1}, assuming it's using WPF", process.ProcessName, module.FileName); + Log.InfoFormat("Found that Process {0} uses {1}, assuming it's using WPF", process.ProcessName, module.FileName); return true; } } } catch (Exception) { // Access denied on the modules - LOG.WarnFormat("No access on the modules from process {0}, assuming WPF is used.", process.ProcessName); + Log.WarnFormat("No access on the modules from process {0}, assuming WPF is used.", process.ProcessName); return true; } } @@ -776,14 +795,14 @@ namespace Greenshot.Helpers { // 2) Is Windows >= Vista & DWM enabled: use DWM // 3) Otherwise use GDI (Screen might be also okay but might lose content) if (isAutoMode) { - if (conf.IECapture && IECaptureHelper.IsIEWindow(windowToCapture)) { + if (CoreConfig.IECapture && IeCaptureHelper.IsIeWindow(windowToCapture)) { try { - ICapture ieCapture = IECaptureHelper.CaptureIE(captureForWindow, windowToCapture); + ICapture ieCapture = IeCaptureHelper.CaptureIe(captureForWindow, windowToCapture); if (ieCapture != null) { return ieCapture; } } catch (Exception ex) { - LOG.WarnFormat("Problem capturing IE, skipping to normal capture. Exception message was: {0}", ex.Message); + Log.WarnFormat("Problem capturing IE, skipping to normal capture. Exception message was: {0}", ex.Message); } } @@ -792,9 +811,9 @@ namespace Greenshot.Helpers { // Change to GDI, if allowed if (!windowToCapture.IsMetroApp && WindowCapture.IsGdiAllowed(process)) { - if (!dwmEnabled && isWPF(process)) { + if (!dwmEnabled && IsWpf(process)) { // do not use GDI, as DWM is not enabled and the application uses PresentationFramework.dll -> isWPF - LOG.InfoFormat("Not using GDI for windows of process {0}, as the process uses WPF", process.ProcessName); + Log.InfoFormat("Not using GDI for windows of process {0}, as the process uses WPF", process.ProcessName); } else { windowCaptureMode = WindowCaptureMode.GDI; } @@ -820,7 +839,7 @@ namespace Greenshot.Helpers { windowCaptureMode = WindowCaptureMode.Screen; } - LOG.InfoFormat("Capturing window with mode {0}", windowCaptureMode); + Log.InfoFormat("Capturing window with mode {0}", windowCaptureMode); bool captureTaken = false; windowRectangle.Intersect(captureForWindow.ScreenBounds); // Try to capture @@ -852,7 +871,7 @@ namespace Greenshot.Helpers { // "easy compare", both have the same size // If GDI has more black, use the screen capture. if (blackPercentageGdi > blackPercentageScreen) { - LOG.Debug("Using screen capture, as GDI had additional black."); + Log.Debug("Using screen capture, as GDI had additional black."); // changeing the image will automatically dispose the previous tmpCapture.Image = screenCapture.Image; // Make sure it's not disposed, else the picture is gone! @@ -861,7 +880,7 @@ namespace Greenshot.Helpers { } else if (screenPixels < gdiPixels) { // Screen capture is cropped, window is outside of screen if (blackPercentageGdi > 50 && blackPercentageGdi > blackPercentageScreen) { - LOG.Debug("Using screen capture, as GDI had additional black."); + Log.Debug("Using screen capture, as GDI had additional black."); // changeing the image will automatically dispose the previous tmpCapture.Image = screenCapture.Image; // Make sure it's not disposed, else the picture is gone! @@ -869,7 +888,7 @@ namespace Greenshot.Helpers { } } else { // Use the GDI capture by doing nothing - LOG.Debug("This should not happen, how can there be more screen as GDI pixels?"); + Log.Debug("This should not happen, how can there be more screen as GDI pixels?"); } } } @@ -910,7 +929,7 @@ namespace Greenshot.Helpers { captureForWindow = WindowCapture.CaptureRectangleFromDesktopScreen(captureForWindow, windowRectangle); captureTaken = true; } catch (Exception e) { - LOG.Error("Problem capturing", e); + Log.Error("Problem capturing", e); return null; } break; @@ -918,16 +937,15 @@ namespace Greenshot.Helpers { } } - if (captureForWindow != null) { - if (windowToCapture != null) { - captureForWindow.CaptureDetails.Title = windowToCapture.Text; - } + if (captureForWindow != null) + { + captureForWindow.CaptureDetails.Title = windowToCapture.Text; } return captureForWindow; } - private void SetDPI() { + private void SetDpi() { // Workaround for proble with DPI retrieval, the FromHwnd activates the window... WindowDetails previouslyActiveWindow = WindowDetails.GetActiveWindow(); // Workaround for changed DPI settings in Windows 7 @@ -935,12 +953,10 @@ namespace Greenshot.Helpers { _capture.CaptureDetails.DpiX = graphics.DpiX; _capture.CaptureDetails.DpiY = graphics.DpiY; } - if (previouslyActiveWindow != null) { - // Set previouslyActiveWindow as foreground window - previouslyActiveWindow.ToForeground(); - } - if (_capture.CaptureDetails != null && _capture.Image != null) { - ((Bitmap)_capture.Image).SetResolution(_capture.CaptureDetails.DpiX, _capture.CaptureDetails.DpiY); + // Set previouslyActiveWindow as foreground window + previouslyActiveWindow?.ToForeground(); + if (_capture.CaptureDetails != null) { + ((Bitmap) _capture.Image)?.SetResolution(_capture.CaptureDetails.DpiX, _capture.CaptureDetails.DpiY); } } @@ -958,7 +974,7 @@ namespace Greenshot.Helpers { using (CaptureForm captureForm = new CaptureForm(_capture, _windows)) { // Make sure the form is hidden after showing, even if an exception occurs, so all errors will be shown - DialogResult result = DialogResult.Cancel; + DialogResult result; try { result = captureForm.ShowDialog(MainForm.Instance); } finally { @@ -980,7 +996,7 @@ namespace Greenshot.Helpers { // Important here is that the location needs to be offsetted back to screen coordinates! Rectangle tmpRectangle = _captureRect; tmpRectangle.Offset(_capture.ScreenBounds.Location.X, _capture.ScreenBounds.Location.Y); - conf.LastCapturedRegion = tmpRectangle; + CoreConfig.LastCapturedRegion = tmpRectangle; HandleCapture(); } } diff --git a/Greenshot/Helpers/CopyData.cs b/Greenshot/Helpers/CopyData.cs index 1d489fd68..131684e9d 100644 --- a/Greenshot/Helpers/CopyData.cs +++ b/Greenshot/Helpers/CopyData.cs @@ -39,9 +39,8 @@ namespace Greenshot.Helpers { [Serializable()] public class CopyDataTransport { private readonly List> _commands; - public List> Commands { - get {return _commands;} - } + public List> Commands => _commands; + public CopyDataTransport() { _commands = new List>(); } @@ -100,9 +99,9 @@ namespace Greenshot.Helpers { ///
/// The Windows Message information. protected override void WndProc (ref Message m ) { - if (m.Msg == WM_COPYDATA) { - COPYDATASTRUCT cds = new COPYDATASTRUCT(); - cds = (COPYDATASTRUCT) Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT)); + if (m.Msg == WM_COPYDATA) + { + var cds = (COPYDATASTRUCT) Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT)); if (cds.cbData > 0) { byte[] data = new byte[cds.cbData]; Marshal.Copy(cds.lpData, data, 0, cds.cbData); @@ -120,9 +119,7 @@ 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(); - } + _channels?.OnHandleChange(); base.OnHandleChange(); } base.WndProc(ref m); @@ -134,10 +131,7 @@ namespace Greenshot.Helpers { /// The data which has been received. protected void OnCopyDataReceived(CopyDataReceivedEventArgs e) { - if (CopyDataReceived != null) - { - CopyDataReceived(this, e); - } + CopyDataReceived?.Invoke(this, e); } /// @@ -149,20 +143,14 @@ namespace Greenshot.Helpers { /// protected override void OnHandleChange () { // need to clear up everything we had set. - if (_channels != null) { - _channels.OnHandleChange(); - } + _channels?.OnHandleChange(); base.OnHandleChange(); } /// /// Gets the collection of channels. /// - public CopyDataChannels Channels { - get { - return _channels; - } - } + public CopyDataChannels Channels => _channels; public void Dispose() { Dispose(true); @@ -204,7 +192,7 @@ namespace Greenshot.Helpers { /// /// Gets the channel name that this data was sent on. /// - public string ChannelName { get; } = ""; + public string ChannelName { get; } /// /// Gets the data object which was sent. @@ -274,11 +262,8 @@ namespace Greenshot.Helpers { /// /// Returns the CopyDataChannel for the specified channelName /// - public CopyDataChannel this[string channelName] { - get { - return (CopyDataChannel) Dictionary[channelName]; - } - } + public CopyDataChannel this[string channelName] => (CopyDataChannel) Dictionary[channelName]; + /// /// Adds a new channel on which this application can send and /// receive messages. @@ -320,7 +305,7 @@ namespace Greenshot.Helpers { /// The channelName /// The CopyDataChannel object which has /// just been removed - protected override void OnRemoveComplete ( Object key , Object data ) { + protected override void OnRemoveComplete ( object key , object data ) { ( (CopyDataChannel) data).Dispose(); OnRemove(key, data); } diff --git a/Greenshot/Helpers/DestinationHelper.cs b/Greenshot/Helpers/DestinationHelper.cs index 94402e936..6ce287460 100644 --- a/Greenshot/Helpers/DestinationHelper.cs +++ b/Greenshot/Helpers/DestinationHelper.cs @@ -31,9 +31,9 @@ namespace Greenshot.Helpers { /// Description of DestinationHelper. /// public static class DestinationHelper { - private static readonly ILog LOG = LogManager.GetLogger(typeof(DestinationHelper)); + private static readonly ILog Log = LogManager.GetLogger(typeof(DestinationHelper)); private static readonly Dictionary RegisteredDestinations = new Dictionary(); - private static readonly CoreConfiguration coreConfig = IniConfig.GetIniSection(); + private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); /// Initialize the destinations static DestinationHelper() { @@ -47,15 +47,15 @@ namespace Greenshot.Helpers { try { destination = (IDestination)Activator.CreateInstance(destinationType); } catch (Exception e) { - LOG.ErrorFormat("Can't create instance of {0}", destinationType); - LOG.Error(e); + Log.ErrorFormat("Can't create instance of {0}", destinationType); + Log.Error(e); continue; } - if (destination.isActive) { - LOG.DebugFormat("Found destination {0} with designation {1}", destinationType.Name, destination.Designation); + if (destination.IsActive) { + Log.DebugFormat("Found destination {0} with designation {1}", destinationType.Name, destination.Designation); RegisterDestination(destination); } else { - LOG.DebugFormat("Ignoring destination {0} with designation {1}", destinationType.Name, destination.Designation); + Log.DebugFormat("Ignoring destination {0} with designation {1}", destinationType.Name, destination.Designation); } } } @@ -66,7 +66,7 @@ namespace Greenshot.Helpers { /// /// public static void RegisterDestination(IDestination destination) { - if (coreConfig.ExcludeDestinations == null || !coreConfig.ExcludeDestinations.Contains(destination.Designation)) { + if (CoreConfig.ExcludeDestinations == null || !CoreConfig.ExcludeDestinations.Contains(destination.Designation)) { // don't test the key, an exception should happen wenn it's not unique RegisteredDestinations.Add(destination.Designation, destination); } @@ -82,13 +82,13 @@ namespace Greenshot.Helpers { IGreenshotPlugin plugin = PluginHelper.Instance.Plugins[pluginAttribute]; try { foreach (IDestination destination in plugin.Destinations()) { - if (coreConfig.ExcludeDestinations == null || !coreConfig.ExcludeDestinations.Contains(destination.Designation)) { + if (CoreConfig.ExcludeDestinations == null || !CoreConfig.ExcludeDestinations.Contains(destination.Designation)) { destinations.Add(destination); } } } catch (Exception ex) { - LOG.ErrorFormat("Couldn't get destinations from the plugin {0}", pluginAttribute.Name); - LOG.Error(ex); + Log.ErrorFormat("Couldn't get destinations from the plugin {0}", pluginAttribute.Name); + Log.Error(ex); } } destinations.Sort(); @@ -136,7 +136,7 @@ namespace Greenshot.Helpers { /// public static ExportInformation ExportCapture(bool manuallyInitiated, string designation, ISurface surface, ICaptureDetails captureDetails) { IDestination destination = GetDestination(designation); - if (destination != null && destination.isActive) { + if (destination != null && destination.IsActive) { return destination.ExportCapture(manuallyInitiated, surface, captureDetails); } return null; diff --git a/Greenshot/Helpers/EnvironmentInfo.cs b/Greenshot/Helpers/EnvironmentInfo.cs index f772444a8..70ce20a8c 100644 --- a/Greenshot/Helpers/EnvironmentInfo.cs +++ b/Greenshot/Helpers/EnvironmentInfo.cs @@ -62,7 +62,7 @@ namespace Greenshot.Helpers if (IniConfig.IsPortable) { environment.Append(" Portable"); } - environment.Append(" (" + OSInfo.Bits + " bit)"); + environment.Append(" (" + OsInfo.Bits + " bit)"); if (newline) { @@ -98,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(); @@ -152,9 +152,9 @@ namespace Greenshot.Helpers StringBuilder report = new StringBuilder(); - report.AppendLine("Exception: " + ex.GetType().ToString()); + report.AppendLine("Exception: " + ex.GetType()); report.AppendLine("Message: " + ex.Message); - if (ex.Data != null && ex.Data.Count > 0) + if (ex.Data.Count > 0) { report.AppendLine(); report.AppendLine("Additional Information:"); @@ -207,7 +207,7 @@ 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/ ///
- public static class OSInfo + public static class OsInfo { #region BITS /// @@ -261,16 +261,7 @@ namespace Greenshot.Helpers } else if (productType == VER_NT_SERVER) { - if ((suiteMask & VER_SUITE_ENTERPRISE) != 0) - { - // Windows NT 4.0 Server Enterprise - edition = "Enterprise Server"; - } - else - { - // Windows NT 4.0 Server - edition = "Standard Server"; - } + edition = (suiteMask & VER_SUITE_ENTERPRISE) != 0 ? "Enterprise Server" : "Standard Server"; } } #endregion VERSION 4 @@ -470,7 +461,7 @@ namespace Greenshot.Helpers #endregion EDITION #region NAME - private static string s_Name; + private static string _name; /// /// Gets the name of the operating system running on this computer. /// @@ -478,16 +469,18 @@ namespace Greenshot.Helpers { get { - if (s_Name != null) + if (_name != null) { - return s_Name; //***** RETURN *****// + return _name; //***** RETURN *****// } string name = "unknown"; 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)) { @@ -514,14 +507,7 @@ namespace Greenshot.Helpers } break; case 10: - if (csdVersion == "A") - { - name = "Windows 98 Second Edition"; - } - else - { - name = "Windows 98"; - } + name = csdVersion == "A" ? "Windows 98 Second Edition" : "Windows 98"; break; case 90: name = "Windows Me"; @@ -629,7 +615,7 @@ namespace Greenshot.Helpers } } - s_Name = name; + _name = name; return name; } } @@ -735,9 +721,11 @@ namespace Greenshot.Helpers get { string servicePack = string.Empty; - OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX(); + OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX + { + dwOSVersionInfoSize = Marshal.SizeOf(typeof(OSVERSIONINFOEX)) + }; - osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf(typeof(OSVERSIONINFOEX)); if (GetVersionEx(ref osVersionInfo)) { @@ -754,13 +742,8 @@ namespace Greenshot.Helpers /// /// Gets the build version number of the operating system running on this computer. /// - public static int BuildVersion - { - get - { - return Environment.OSVersion.Version.Build; - } - } + public static int BuildVersion => Environment.OSVersion.Version.Build; + #endregion BUILD #region FULL diff --git a/Greenshot/Helpers/GeometryHelper.cs b/Greenshot/Helpers/GeometryHelper.cs index 3818e7efd..56b6a5381 100644 --- a/Greenshot/Helpers/GeometryHelper.cs +++ b/Greenshot/Helpers/GeometryHelper.cs @@ -34,8 +34,6 @@ namespace Greenshot.Helpers { /// The point on the y-axis of the second point /// public static int Distance2D(int x1, int y1, int x2, int y2) { - //Our end result - int result = 0; //Take x2-x1, then square it double part1 = Math.Pow(x2 - x1, 2); //Take y2-y1, then square it @@ -43,9 +41,7 @@ namespace Greenshot.Helpers { //Add both of the parts together double underRadical = part1 + part2; //Get the square root of the parts - result = (int)Math.Sqrt(underRadical); - //Return our result - return result; + return (int)Math.Sqrt(underRadical); } /// diff --git a/Greenshot/Helpers/IECaptureHelper.cs b/Greenshot/Helpers/IECaptureHelper.cs index 6780190b2..b7440825b 100644 --- a/Greenshot/Helpers/IECaptureHelper.cs +++ b/Greenshot/Helpers/IECaptureHelper.cs @@ -22,6 +22,7 @@ using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; +using System.Linq; using System.Runtime.InteropServices; using Greenshot.Configuration; using Greenshot.Helpers.IEInterop; @@ -41,18 +42,18 @@ namespace Greenshot.Helpers { /// On top I modified it to use the already available code in Greenshot. /// Many thanks to all the people who contributed here! /// - public static class IECaptureHelper { - private static readonly ILog LOG = LogManager.GetLogger(typeof(IECaptureHelper)); - private static readonly CoreConfiguration configuration = IniConfig.GetIniSection(); + public static class IeCaptureHelper { + private static readonly ILog Log = LogManager.GetLogger(typeof(IeCaptureHelper)); + private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); // Helper method to activate a certain IE Tab - public static void ActivateIETab(WindowDetails ieWindowDetails, int tabIndex) { - WindowDetails directUIWindowDetails = IEHelper.GetDirectUI(ieWindowDetails); - if(directUIWindowDetails != null) { + public static void ActivateIeTab(WindowDetails ieWindowDetails, int tabIndex) { + WindowDetails directUiWindowDetails = IEHelper.GetDirectUI(ieWindowDetails); + if(directUiWindowDetails != null) { // Bring window to the front ieWindowDetails.Restore(); // Get accessible - Accessible ieAccessible = new Accessible(directUIWindowDetails.Handle); + Accessible ieAccessible = new Accessible(directUiWindowDetails.Handle); // Activate Tab ieAccessible.ActivateIETab(tabIndex); } @@ -64,13 +65,13 @@ namespace Greenshot.Helpers { /// WindowDetails to check /// min percentage /// - public static bool IsMostlyIEWindow(WindowDetails someWindow, int minimumPercentage) { + public static bool IsMostlyIeWindow(WindowDetails someWindow, int minimumPercentage) { WindowDetails ieWindow = someWindow.GetChild("Internet Explorer_Server"); 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)); - LOG.InfoFormat("Window {0}, ie part {1}, percentage {2}", wholeClient, partClient, percentage); + int percentage = (int)(100*(float)(partClient.Width * partClient.Height) / (wholeClient.Width * wholeClient.Height)); + Log.InfoFormat("Window {0}, ie part {1}, percentage {2}", wholeClient, partClient, percentage); if (percentage > minimumPercentage) { return true; } @@ -83,11 +84,11 @@ namespace Greenshot.Helpers { /// /// /// - public static bool IsIEWindow(WindowDetails someWindow) { + public static bool IsIeWindow(WindowDetails someWindow) { if ("IEFrame".Equals(someWindow.ClassName)) { return true; } - if (configuration.WindowClassesToCheckForIE != null && configuration.WindowClassesToCheckForIE.Contains(someWindow.ClassName)) { + if (CoreConfig.WindowClassesToCheckForIE != null && CoreConfig.WindowClassesToCheckForIE.Contains(someWindow.ClassName)) { return someWindow.GetChild("Internet Explorer_Server") != null; } return false; @@ -97,16 +98,16 @@ namespace Greenshot.Helpers { /// Get Windows displaying an IE /// /// IEnumerable WindowDetails - public static IEnumerable GetIEWindows() { - foreach (WindowDetails possibleIEWindow in WindowDetails.GetAllWindows()) { - if (possibleIEWindow.Text.Length == 0) { + public static IEnumerable GetIeWindows() { + foreach (var possibleIeWindow in WindowDetails.GetAllWindows()) { + if (possibleIeWindow.Text.Length == 0) { continue; } - if (possibleIEWindow.ClientRectangle.IsEmpty) { + if (possibleIeWindow.ClientRectangle.IsEmpty) { continue; } - if (IsIEWindow(possibleIEWindow)) { - yield return possibleIEWindow; + if (IsIeWindow(possibleIeWindow)) { + yield return possibleIeWindow; } } } @@ -115,11 +116,9 @@ namespace Greenshot.Helpers { /// Simple check if IE is running /// /// bool - public static bool IsIERunning() { - foreach (WindowDetails ieWindow in GetIEWindows()) { - return true; - } - return false; + public static bool IsIeRunning() + { + return GetIeWindows().Any(); } /// @@ -127,44 +126,46 @@ namespace Greenshot.Helpers { /// /// List with KeyValuePair of WindowDetails and string public static List> GetBrowserTabs() { - List ieHandleList = new List(); - Dictionary> browserWindows = new Dictionary>(); + var ieHandleList = new List(); + var browserWindows = new Dictionary>(); // Find the IE windows - foreach (WindowDetails ieWindow in GetIEWindows()) { + foreach (var ieWindow in GetIeWindows()) { try { - if (!ieHandleList.Contains(ieWindow.Handle)) { - if ("IEFrame".Equals(ieWindow.ClassName)) { - WindowDetails directUIWD = IEHelper.GetDirectUI(ieWindow); - if (directUIWD != null) { - Accessible accessible = new Accessible(directUIWD.Handle); - browserWindows.Add(ieWindow, accessible.IETabCaptions); - } - } else if (configuration.WindowClassesToCheckForIE != null && configuration.WindowClassesToCheckForIE.Contains(ieWindow.ClassName)) { - List singleWindowText = new List(); - try { - IHTMLDocument2 document2 = GetHtmlDocument(ieWindow); - string title = document2.title; - Marshal.ReleaseComObject(document2); - if (string.IsNullOrEmpty(title)) { - singleWindowText.Add(ieWindow.Text); - } else { - singleWindowText.Add(ieWindow.Text + " - " + title); - } - } catch { - singleWindowText.Add(ieWindow.Text); - } - browserWindows.Add(ieWindow, singleWindowText); - } - ieHandleList.Add(ieWindow.Handle); + if (ieHandleList.Contains(ieWindow.Handle)) + { + continue; } + if ("IEFrame".Equals(ieWindow.ClassName)) { + var directUiwd = IEHelper.GetDirectUI(ieWindow); + if (directUiwd != null) { + var accessible = new Accessible(directUiwd.Handle); + browserWindows.Add(ieWindow, accessible.IETabCaptions); + } + } else if (CoreConfig.WindowClassesToCheckForIE != null && CoreConfig.WindowClassesToCheckForIE.Contains(ieWindow.ClassName)) { + var singleWindowText = new List(); + try { + var document2 = GetHtmlDocument(ieWindow); + string title = document2.title; + Marshal.ReleaseComObject(document2); + if (string.IsNullOrEmpty(title)) { + singleWindowText.Add(ieWindow.Text); + } else { + singleWindowText.Add(ieWindow.Text + " - " + title); + } + } catch { + singleWindowText.Add(ieWindow.Text); + } + browserWindows.Add(ieWindow, singleWindowText); + } + ieHandleList.Add(ieWindow.Handle); } catch (Exception) { - LOG.Warn("Can't get Info from " + ieWindow.ClassName); + Log.Warn("Can't get Info from " + ieWindow.ClassName); } } - List> returnList = new List>(); - foreach(WindowDetails windowDetails in browserWindows.Keys) { + var returnList = new List>(); + foreach(var windowDetails in browserWindows.Keys) { foreach(string tab in browserWindows[windowDetails]) { returnList.Add(new KeyValuePair(windowDetails, tab)); } @@ -178,35 +179,30 @@ namespace Greenshot.Helpers { /// /// private static IHTMLDocument2 GetHtmlDocument(WindowDetails mainWindow) { - WindowDetails ieServer; - if ("Internet Explorer_Server".Equals(mainWindow.ClassName)) { - ieServer = mainWindow; - } else { - ieServer = mainWindow.GetChild("Internet Explorer_Server"); - } + var ieServer = "Internet Explorer_Server".Equals(mainWindow.ClassName) ? mainWindow : mainWindow.GetChild("Internet Explorer_Server"); if (ieServer == null) { - LOG.WarnFormat("No Internet Explorer_Server for {0}", mainWindow.Text); + Log.WarnFormat("No Internet Explorer_Server for {0}", mainWindow.Text); return null; } - IHTMLDocument2 document2 = null; uint windowMessage = User32.RegisterWindowMessage("WM_HTML_GETOBJECT"); if (windowMessage == 0) { - LOG.WarnFormat("Couldn't register WM_HTML_GETOBJECT"); + Log.WarnFormat("Couldn't register WM_HTML_GETOBJECT"); return null; } - LOG.DebugFormat("Trying WM_HTML_GETOBJECT on {0}", ieServer.ClassName); + Log.DebugFormat("Trying WM_HTML_GETOBJECT on {0}", ieServer.ClassName); UIntPtr response; User32.SendMessageTimeout(ieServer.Handle, windowMessage, IntPtr.Zero, IntPtr.Zero, SendMessageTimeoutFlags.SMTO_NORMAL, 5000, out response); + IHTMLDocument2 document2; if (response != UIntPtr.Zero) { document2 = (IHTMLDocument2)Accessible.ObjectFromLresult(response, typeof(IHTMLDocument).GUID, IntPtr.Zero); if (document2 == null) { - LOG.Error("No IHTMLDocument2 found"); + Log.Error("No IHTMLDocument2 found"); return null; } } else { - LOG.Error("No answer on WM_HTML_GETOBJECT."); + Log.Error("No answer on WM_HTML_GETOBJECT."); return null; } return document2; @@ -227,23 +223,23 @@ namespace Greenshot.Helpers { IHTMLDocument2 alternativeReturnDocument2 = null; // Find the IE windows - foreach (WindowDetails ieWindow in GetIEWindows()) { - LOG.DebugFormat("Processing {0} - {1}", ieWindow.ClassName, ieWindow.Text); + foreach (WindowDetails ieWindow in GetIeWindows()) { + Log.DebugFormat("Processing {0} - {1}", ieWindow.ClassName, ieWindow.Text); Accessible ieAccessible = null; - WindowDetails directUIWD = IEHelper.GetDirectUI(ieWindow); - if (directUIWD != null) { - ieAccessible = new Accessible(directUIWD.Handle); + WindowDetails directUiwd = IEHelper.GetDirectUI(ieWindow); + if (directUiwd != null) { + ieAccessible = new Accessible(directUiwd.Handle); } if (ieAccessible == null) { if (browserWindow != null) { - LOG.InfoFormat("Active Window is {0}", browserWindow.Text); + Log.InfoFormat("Active Window is {0}", browserWindow.Text); } if (!ieWindow.Equals(browserWindow)) { - LOG.WarnFormat("No ieAccessible for {0}", ieWindow.Text); + Log.WarnFormat("No ieAccessible for {0}", ieWindow.Text); continue; } - LOG.DebugFormat("No ieAccessible, but the active window is an IE window: {0}, ", ieWindow.Text); + Log.DebugFormat("No ieAccessible, but the active window is an IE window: {0}, ", ieWindow.Text); } try { @@ -256,9 +252,7 @@ namespace Greenshot.Helpers { // Get the content window handle for the shellWindow.Document IOleWindow oleWindow = (IOleWindow)document2; IntPtr contentWindowHandle = IntPtr.Zero; - if (oleWindow != null) { - oleWindow.GetWindow(out contentWindowHandle); - } + oleWindow?.GetWindow(out contentWindowHandle); if (contentWindowHandle != IntPtr.Zero) { // Get the HTMLDocument to check the hasFocus @@ -266,7 +260,7 @@ namespace Greenshot.Helpers { IHTMLDocument4 document4 = (IHTMLDocument4)document2; if (document4.hasFocus()) { - LOG.DebugFormat("Matched focused document: {0}", document2.title); + Log.DebugFormat("Matched focused document: {0}", document2.title); // Look no further, we got what we wanted! returnDocument2 = document2; returnWindow = new WindowDetails(contentWindowHandle); @@ -279,7 +273,7 @@ namespace Greenshot.Helpers { break; } if (ieAccessible != null && returnWindow == null && document2.title.Equals(ieAccessible.IEActiveTabCaption) ) { - LOG.DebugFormat("Title: {0}", document2.title); + Log.DebugFormat("Title: {0}", document2.title); returnDocument2 = document2; returnWindow = new WindowDetails(contentWindowHandle); } else { @@ -292,8 +286,8 @@ namespace Greenshot.Helpers { } } } catch (Exception e) { - LOG.ErrorFormat("Major problem: Problem retrieving Document from {0}", ieWindow.Text); - LOG.Error(e); + Log.ErrorFormat("Major problem: Problem retrieving Document from {0}", ieWindow.Text); + Log.Error(e); } } @@ -307,8 +301,8 @@ namespace Greenshot.Helpers { try { returnDocumentContainer = new DocumentContainer(returnDocument2, returnWindow); } catch (Exception e) { - LOG.Error("Major problem: Problem retrieving Document."); - LOG.Error(e); + Log.Error("Major problem: Problem retrieving Document."); + Log.Error(e); } } @@ -320,8 +314,8 @@ namespace Greenshot.Helpers { try { returnDocumentContainer = new DocumentContainer(alternativeReturnDocument2, alternativeReturnWindow); } catch (Exception e) { - LOG.Error("Major problem: Problem retrieving Document."); - LOG.Error(e); + Log.Error("Major problem: Problem retrieving Document."); + Log.Error(e); } } return returnDocumentContainer; @@ -332,8 +326,8 @@ namespace Greenshot.Helpers { /// /// ICapture where the capture needs to be stored /// ICapture with the content (if any) - public static ICapture CaptureIE(ICapture capture) { - return CaptureIE(capture, WindowDetails.GetActiveWindow()); + public static ICapture CaptureIe(ICapture capture) { + return CaptureIe(capture, WindowDetails.GetActiveWindow()); } /// /// Here the logic for capturing the IE Content is located @@ -341,7 +335,7 @@ namespace Greenshot.Helpers { /// ICapture where the capture needs to be stored /// window to use /// ICapture with the content (if any) - public static ICapture CaptureIE(ICapture capture, WindowDetails windowToCapture) { + public static ICapture CaptureIe(ICapture capture, WindowDetails windowToCapture) { if (windowToCapture == null) { windowToCapture = WindowDetails.GetActiveWindow(); } @@ -355,15 +349,15 @@ namespace Greenshot.Helpers { // Nothing found if (documentContainer == null) { - LOG.Debug("Nothing to capture found"); + Log.Debug("Nothing to capture found"); return null; } try { - LOG.DebugFormat("Window class {0}", documentContainer.ContentWindow.ClassName); - LOG.DebugFormat("Window location {0}", documentContainer.ContentWindow.Location); + Log.DebugFormat("Window class {0}", documentContainer.ContentWindow.ClassName); + Log.DebugFormat("Window location {0}", documentContainer.ContentWindow.Location); } catch (Exception ex) { - LOG.Warn("Error while logging information.", ex); + Log.Warn("Error while logging information.", ex); } // bitmap to return @@ -372,12 +366,12 @@ namespace Greenshot.Helpers { Size pageSize = PrepareCapture(documentContainer, capture); returnBitmap = CapturePage(documentContainer, pageSize); } catch (Exception captureException) { - LOG.Error("Exception found, ignoring and returning nothing! Error was: ", captureException); + Log.Error("Exception found, ignoring and returning nothing! Error was: ", captureException); } // TODO: Enable when the elements are usable again. // Capture the element on the page //try { - // if (configuration.IEFieldCapture && capture.CaptureDetails.HasDestination("Editor")) { + // if (CoreConfig.IEFieldCapture && capture.CaptureDetails.HasDestination("Editor")) { // // clear the current elements, as they are for the window itself // capture.Elements.Clear(); // CaptureElement documentCaptureElement = documentContainer.CreateCaptureElements(pageSize); @@ -414,13 +408,9 @@ namespace Greenshot.Helpers { // The URL is available unter "document2.url" and can be used to enhance the meta-data etc. capture.CaptureDetails.AddMetaData("url", documentContainer.Url); // Store the title of the page - if (documentContainer.Name != null) { - capture.CaptureDetails.Title = documentContainer.Name; - } else { - capture.CaptureDetails.Title = windowToCapture.Text; - } + capture.CaptureDetails.Title = documentContainer.Name ?? windowToCapture.Text; } catch (Exception ex) { - LOG.Warn("Problems getting some attributes...", ex); + Log.Warn("Problems getting some attributes...", ex); } // Store the URL of the page @@ -446,7 +436,7 @@ namespace Greenshot.Helpers { } capture.CaptureDetails.AddMetaData("URL_PORT", uri.Port.ToString()); } catch(Exception e) { - LOG.Warn("Exception when trying to use url in metadata "+documentContainer.Url,e); + Log.Warn("Exception when trying to use url in metadata "+documentContainer.Url,e); } } try { @@ -454,7 +444,7 @@ namespace Greenshot.Helpers { capture.MoveMouseLocation(-documentContainer.ViewportRectangle.X, -documentContainer.ViewportRectangle.Y); // Used to be: capture.MoveMouseLocation(-(capture.Location.X + documentContainer.CaptureOffset.X), -(capture.Location.Y + documentContainer.CaptureOffset.Y)); } catch (Exception ex) { - LOG.Warn("Error while correcting the mouse offset.", ex); + Log.Warn("Error while correcting the mouse offset.", ex); } } finally { // Always close the background form @@ -480,7 +470,7 @@ namespace Greenshot.Helpers { movedFrame = false; foreach(DocumentContainer currentFrame in documentContainer.Frames) { foreach(DocumentContainer otherFrame in documentContainer.Frames) { - if (otherFrame.ID == currentFrame.ID) { + if (otherFrame.Id == currentFrame.Id) { continue; } // check if we need to move @@ -494,16 +484,16 @@ namespace Greenshot.Helpers { if ((horizalResize || horizalMove) && leftOf) { // Current frame resized horizontally, so move other horizontally - LOG.DebugFormat("Moving Frame {0} horizontally to the right of {1}", otherFrame.Name, currentFrame.Name); + Log.DebugFormat("Moving Frame {0} horizontally to the right of {1}", otherFrame.Name, currentFrame.Name); otherFrame.DestinationLeft = currentFrame.DestinationRight; movedFrame = true; } else if ((verticalResize || verticalMove) && belowOf){ // Current frame resized vertically, so move other vertically - LOG.DebugFormat("Moving Frame {0} vertically to the bottom of {1}", otherFrame.Name, currentFrame.Name); + Log.DebugFormat("Moving Frame {0} vertically to the bottom of {1}", otherFrame.Name, currentFrame.Name); otherFrame.DestinationTop = currentFrame.DestinationBottom; movedFrame = true; } else { - LOG.DebugFormat("Frame {0} intersects with {1}", otherFrame.Name, currentFrame.Name); + Log.DebugFormat("Frame {0} intersects with {1}", otherFrame.Name, currentFrame.Name); } } } @@ -539,11 +529,11 @@ namespace Greenshot.Helpers { // Limit the size as the editor currently can't work with sizes > short.MaxValue if (pageWidth > short.MaxValue) { - LOG.WarnFormat("Capture has a width of {0} which bigger than the maximum supported {1}, cutting width to the maxium.", pageWidth, short.MaxValue); + Log.WarnFormat("Capture has a width of {0} which bigger than the maximum supported {1}, cutting width to the maxium.", pageWidth, short.MaxValue); pageWidth = Math.Min(pageWidth, short.MaxValue); } if (pageHeight > short.MaxValue) { - LOG.WarnFormat("Capture has a height of {0} which bigger than the maximum supported {1}, cutting height to the maxium", pageHeight, short.MaxValue); + Log.WarnFormat("Capture has a height of {0} which bigger than the maximum supported {1}, cutting height to the maxium", pageHeight, short.MaxValue); pageHeight = Math.Min(pageHeight, short.MaxValue); } return new Size(pageWidth, pageHeight); @@ -563,7 +553,7 @@ namespace Greenshot.Helpers { using (Graphics graphicsTarget = Graphics.FromImage(returnBitmap)) { // Clear the target with the backgroundcolor Color clearColor = documentContainer.BackgroundColor; - LOG.DebugFormat("Clear color: {0}", clearColor); + Log.DebugFormat("Clear color: {0}", clearColor); graphicsTarget.Clear(clearColor); // Get the base document & draw it @@ -597,7 +587,7 @@ namespace Greenshot.Helpers { int pageWidth = documentContainer.ScrollWidth; int pageHeight = documentContainer.ScrollHeight; if (pageWidth * pageHeight == 0) { - LOG.WarnFormat("Empty page for DocumentContainer {0}: {1}", documentContainer.Name, documentContainer.Url); + Log.WarnFormat("Empty page for DocumentContainer {0}: {1}", documentContainer.Name, documentContainer.Url); return; } @@ -605,7 +595,7 @@ namespace Greenshot.Helpers { int viewportWidth = documentContainer.ClientWidth; int viewportHeight = documentContainer.ClientHeight; if (viewportWidth * viewportHeight == 0) { - LOG.WarnFormat("Empty viewport for DocumentContainer {0}: {1}", documentContainer.Name, documentContainer.Url); + Log.WarnFormat("Empty viewport for DocumentContainer {0}: {1}", documentContainer.Name, documentContainer.Url); return; } @@ -613,7 +603,7 @@ namespace Greenshot.Helpers { int startLeft = documentContainer.ScrollLeft; int startTop = documentContainer.ScrollTop; - LOG.DebugFormat("Capturing {4} with total size {0},{1} displayed with size {2},{3}", pageWidth, pageHeight, viewportWidth, viewportHeight, documentContainer.Name); + Log.DebugFormat("Capturing {4} with total size {0},{1} displayed with size {2},{3}", pageWidth, pageHeight, viewportWidth, viewportHeight, documentContainer.Name); // Variable used for looping horizontally int horizontalPage = 0; @@ -640,34 +630,34 @@ namespace Greenshot.Helpers { Rectangle clientRectangle = new Rectangle(documentContainer.SourceLocation, viewPortSize); Image fragment = contentWindowDetails.PrintWindow(); if (fragment != null) { - LOG.DebugFormat("Captured fragment size: {0}x{1}", fragment.Width, fragment.Height); + Log.DebugFormat("Captured fragment size: {0}x{1}", fragment.Width, fragment.Height); try { // cut all junk, due to IE "border" we need to remove some parts Rectangle viewportRect = documentContainer.ViewportRectangle; if (!viewportRect.IsEmpty) { - LOG.DebugFormat("Cropping to viewport: {0}", viewportRect); + Log.DebugFormat("Cropping to viewport: {0}", viewportRect); ImageHelper.Crop(ref fragment, ref viewportRect); } - LOG.DebugFormat("Cropping to clientRectangle: {0}", clientRectangle); + Log.DebugFormat("Cropping to clientRectangle: {0}", clientRectangle); // Crop to clientRectangle if (ImageHelper.Crop(ref fragment, ref clientRectangle)) { Point targetLocation = new Point(documentContainer.DestinationLocation.X, documentContainer.DestinationLocation.Y); - LOG.DebugFormat("Fragment targetLocation is {0}", targetLocation); + Log.DebugFormat("Fragment targetLocation is {0}", targetLocation); targetLocation.Offset(targetOffset); - LOG.DebugFormat("After offsetting the fragment targetLocation is {0}", targetLocation); - LOG.DebugFormat("Drawing fragment of size {0} to {1}", fragment.Size, targetLocation); + Log.DebugFormat("After offsetting the fragment targetLocation is {0}", targetLocation); + Log.DebugFormat("Drawing fragment of size {0} to {1}", fragment.Size, targetLocation); graphicsTarget.DrawImage(fragment, targetLocation); graphicsTarget.Flush(); } else { // somehow we are capturing nothing!? - LOG.WarnFormat("Crop of {0} failed?", documentContainer.Name); + Log.WarnFormat("Crop of {0} failed?", documentContainer.Name); break; } } finally { fragment.Dispose(); } } else { - LOG.WarnFormat("Capture of {0} failed!", documentContainer.Name); + Log.WarnFormat("Capture of {0} failed!", documentContainer.Name); } verticalPage++; } diff --git a/Greenshot/Helpers/IEInterop/IEContainer.cs b/Greenshot/Helpers/IEInterop/IEContainer.cs index de77597a0..f0c3de49f 100644 --- a/Greenshot/Helpers/IEInterop/IEContainer.cs +++ b/Greenshot/Helpers/IEInterop/IEContainer.cs @@ -36,15 +36,12 @@ namespace Greenshot.Helpers.IEInterop { 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; - 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; @@ -58,7 +55,7 @@ namespace Greenshot.Helpers.IEInterop { IHTMLDocument2 document2 = GetDocumentFromWindow(frameWindow); try { LOG.DebugFormat("frameWindow.name {0}", frameWindow.name); - _name = frameWindow.name; + Name = frameWindow.name; } catch { // Ignore } @@ -91,7 +88,7 @@ namespace Greenshot.Helpers.IEInterop { 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); } /// @@ -119,7 +116,7 @@ namespace Greenshot.Helpers.IEInterop { //compatibility mode affects how height is computed _isDtd = false; try { - if (_document3 != null && (_document3.documentElement != null) && !document5.compatMode.Equals("BackCompat")) { + if (_document3?.documentElement != null && !document5.compatMode.Equals("BackCompat")) { _isDtd = true; } } catch (Exception ex) { @@ -176,15 +173,15 @@ namespace Greenshot.Helpers.IEInterop { try { LOG.DebugFormat("Calculated location {0} for {1}", _startLocation, document2.title); - if (_name == null) { - _name = 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); } @@ -202,7 +199,7 @@ namespace Greenshot.Helpers.IEInterop { 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); + 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); @@ -341,18 +338,10 @@ namespace Greenshot.Helpers.IEInterop { } } - public Rectangle ViewportRectangle { - get { - return _viewportRectangle; - } - } + public Rectangle ViewportRectangle => _viewportRectangle; + + public WindowDetails ContentWindow => _contentWindow; - public WindowDetails ContentWindow { - get { - return _contentWindow; - } - } - public DocumentContainer Parent { get { return _parent; @@ -391,12 +380,7 @@ namespace Greenshot.Helpers.IEInterop { /// Attribute to set /// Value to set public void SetAttribute(string attribute, string value) { - IHTMLElement element = null; - if (!_isDtd) { - element = _document2.body; - } else { - element = _document3.documentElement; - } + var element = !_isDtd ? _document2.body : _document3.documentElement; element.setAttribute(attribute, value, 1); // Release IHTMLElement com object releaseCom(element); @@ -408,12 +392,7 @@ namespace Greenshot.Helpers.IEInterop { /// Attribute to get /// object with the attribute value public object GetAttribute(string attribute) { - IHTMLElement element; - if (!_isDtd) { - element = _document2.body; - } else { - element = _document3.documentElement; - } + var element = !_isDtd ? _document2.body : _document3.documentElement; var retVal = element.getAttribute(attribute, 1); // Release IHTMLElement com object releaseCom(element); @@ -428,53 +407,21 @@ namespace Greenshot.Helpers.IEInterop { return retVal; } - public int ID { - get { - return _id; - } - } + public int Id { get; } = _counter++; - public string Name { - get { - return _name; - } - } + public string Name { get; private set; } - public string Url { - get { - return _url; - } - } + public string Url { get; private set; } - public bool IsHidden { - get { - return ClientWidth == 0 || ClientHeight == 0; - } - } + public bool IsHidden => ClientWidth == 0 || ClientHeight == 0; - public int ClientWidth { - get { - return ScaleX(GetAttributeAsInt("clientWidth")); - } - } + public int ClientWidth => ScaleX(GetAttributeAsInt("clientWidth")); - public int ClientHeight { - get { - return ScaleY(GetAttributeAsInt("clientHeight")); - } - } + public int ClientHeight => ScaleY(GetAttributeAsInt("clientHeight")); - public int ScrollWidth { - get { - return ScaleX(GetAttributeAsInt("scrollWidth")); - } - } + public int ScrollWidth => ScaleX(GetAttributeAsInt("scrollWidth")); - public int ScrollHeight { - get { - return ScaleY(GetAttributeAsInt("scrollHeight")); - } - } + public int ScrollHeight => ScaleY(GetAttributeAsInt("scrollHeight")); public Point SourceLocation { get { @@ -485,41 +432,17 @@ namespace Greenshot.Helpers.IEInterop { } } - public Size SourceSize { - get { - return new Size(ClientWidth, ClientHeight); - } - } + public Size SourceSize => new Size(ClientWidth, ClientHeight); - public Rectangle SourceRectangle { - get { - return new Rectangle(SourceLocation, SourceSize); - } - } + public Rectangle SourceRectangle => new Rectangle(SourceLocation, SourceSize); - public int SourceLeft { - get { - return _sourceLocation.X; - } - } + public int SourceLeft => _sourceLocation.X; - public int SourceTop { - get { - return _sourceLocation.Y; - } - } + public int SourceTop => _sourceLocation.Y; - public int SourceRight { - get { - return _sourceLocation.X + ClientWidth; - } - } + public int SourceRight => _sourceLocation.X + ClientWidth; - public int SourceBottom { - get { - return _sourceLocation.Y + ClientHeight; - } - } + public int SourceBottom => _sourceLocation.Y + ClientHeight; public Point DestinationLocation { get { @@ -531,17 +454,9 @@ namespace Greenshot.Helpers.IEInterop { } - public Size DestinationSize { - get { - return new Size(ScrollWidth, ScrollHeight); - } - } - - public Rectangle DestinationRectangle { - get { - return new Rectangle(DestinationLocation, DestinationSize); - } - } + public Size DestinationSize => new Size(ScrollWidth, ScrollHeight); + + public Rectangle DestinationRectangle => new Rectangle(DestinationLocation, DestinationSize); public int DestinationLeft { get { @@ -561,17 +476,9 @@ namespace Greenshot.Helpers.IEInterop { } } - public int DestinationRight { - get { - return _destinationLocation.X + ScrollWidth; - } - } + public int DestinationRight => _destinationLocation.X + ScrollWidth; - public int DestinationBottom { - get { - return _destinationLocation.Y + ScrollHeight; - } - } + public int DestinationBottom => _destinationLocation.Y + ScrollHeight; public int ScrollLeft { get{ @@ -591,10 +498,6 @@ namespace Greenshot.Helpers.IEInterop { } } - public IList Frames { - get { - return _frames; - } - } + public IList Frames => _frames; } } diff --git a/Greenshot/Helpers/MailHelper.cs b/Greenshot/Helpers/MailHelper.cs index c2e5a190c..f2dfbbfd9 100644 --- a/Greenshot/Helpers/MailHelper.cs +++ b/Greenshot/Helpers/MailHelper.cs @@ -43,8 +43,8 @@ namespace Greenshot.Helpers { /// Represents an email message to be sent through MAPI. /// public class MapiMailMessage : IDisposable { - private static readonly ILog LOG = LogManager.GetLogger(typeof(MapiMailMessage)); - private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly ILog Log = LogManager.GetLogger(typeof(MapiMailMessage)); + private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); /// /// Helper Method for creating an Email with Attachment @@ -54,14 +54,14 @@ namespace Greenshot.Helpers { public static void SendImage(string fullPath, string title) { using (MapiMailMessage message = new MapiMailMessage(title, null)) { message.Files.Add(fullPath); - if (!string.IsNullOrEmpty(conf.MailApiTo)) { - message._recipientCollection.Add(new Recipient(conf.MailApiTo, RecipientType.To)); + if (!string.IsNullOrEmpty(CoreConfig.MailApiTo)) { + message.Recipients.Add(new Recipient(CoreConfig.MailApiTo, RecipientType.To)); } - if (!string.IsNullOrEmpty(conf.MailApiCC)) { - message._recipientCollection.Add(new Recipient(conf.MailApiCC, RecipientType.CC)); + if (!string.IsNullOrEmpty(CoreConfig.MailApiCC)) { + message.Recipients.Add(new Recipient(CoreConfig.MailApiCC, RecipientType.CC)); } - if (!string.IsNullOrEmpty(conf.MailApiBCC)) { - message._recipientCollection.Add(new Recipient(conf.MailApiBCC, RecipientType.BCC)); + if (!string.IsNullOrEmpty(CoreConfig.MailApiBCC)) { + message.Recipients.Add(new Recipient(CoreConfig.MailApiBCC, RecipientType.BCC)); } message.ShowDialog(); } @@ -80,10 +80,10 @@ namespace Greenshot.Helpers { // Store the list of currently active windows, so we can make sure we show the email window later! var windowsBefore = WindowDetails.GetVisibleWindows(); //bool isEmailSend = false; - //if (EmailConfigHelper.HasOutlook() && (conf.OutputEMailFormat == EmailFormat.OUTLOOK_HTML || conf.OutputEMailFormat == EmailFormat.OUTLOOK_TXT)) { + //if (EmailConfigHelper.HasOutlook() && (CoreConfig.OutputEMailFormat == EmailFormat.OUTLOOK_HTML || CoreConfig.OutputEMailFormat == EmailFormat.OUTLOOK_TXT)) { // isEmailSend = OutlookExporter.ExportToOutlook(tmpFile, captureDetails); //} - if (/*!isEmailSend &&*/ EmailConfigHelper.HasMAPI()) { + if (/*!isEmailSend &&*/ EmailConfigHelper.HasMapi()) { // Fallback to MAPI // Send the email SendImage(tmpFile, captureDetails.Title); @@ -132,9 +132,6 @@ namespace Greenshot.Helpers { #region Member Variables - private string _subject; - private string _body; - private RecipientCollection _recipientCollection; private readonly ManualResetEvent _manualResetEvent; #endregion Member Variables @@ -146,7 +143,7 @@ namespace Greenshot.Helpers { /// public MapiMailMessage() { Files = new List(); - _recipientCollection = new RecipientCollection(); + Recipients = new RecipientCollection(); _manualResetEvent = new ManualResetEvent(false); } @@ -154,15 +151,15 @@ namespace Greenshot.Helpers { /// Creates a new mail message with the specified subject. /// public MapiMailMessage(string subject) : this() { - _subject = subject; + Subject = subject; } /// /// Creates a new mail message with the specified subject and body. /// public MapiMailMessage(string subject, string body) : this() { - _subject = subject; - _body = body; + Subject = subject; + Body = body; } #endregion Constructors @@ -172,35 +169,17 @@ namespace Greenshot.Helpers { /// /// Gets or sets the subject of this mail message. /// - public string Subject { - get { - return _subject; - } - set { - _subject = value; - } - } + public string Subject { get; set; } /// /// Gets or sets the body of this mail message. /// - public string Body { - get { - return _body; - } - set { - _body = value; - } - } + public string Body { get; set; } /// /// Gets the recipient list for this mail message. /// - public RecipientCollection Recipients { - get { - return _recipientCollection; - } - } + public RecipientCollection Recipients { get; private set; } /// /// Gets the file list for this mail message. @@ -216,11 +195,13 @@ namespace Greenshot.Helpers { /// public void ShowDialog() { // Create the mail message in an STA thread - Thread t = new Thread(_ShowMail); - t.IsBackground = true; - t.Name = "Create MAPI mail"; - t.SetApartmentState(ApartmentState.STA); - t.Start(); + var thread = new Thread(_ShowMail) + { + IsBackground = true, + Name = "Create MAPI mail" + }; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); // only return when the new thread has built it's interop representation _manualResetEvent.WaitOne(); @@ -240,10 +221,7 @@ namespace Greenshot.Helpers { if (!disposing) { return; } - if (_manualResetEvent != null) { - _manualResetEvent.Close(); - } - + _manualResetEvent?.Close(); } /// @@ -252,12 +230,12 @@ namespace Greenshot.Helpers { private void _ShowMail() { var message = new MapiHelperInterop.MapiMessage(); - using (var interopRecipients = _recipientCollection.GetInteropRepresentation()) { - message.Subject = _subject; - message.NoteText = _body; + using (var interopRecipients = Recipients.GetInteropRepresentation()) { + message.Subject = Subject; + message.NoteText = Body; message.Recipients = interopRecipients.Handle; - message.RecipientCount = _recipientCollection.Count; + message.RecipientCount = Recipients.Count; // Check if we need to add attachments if (Files.Count > 0) { @@ -284,14 +262,14 @@ namespace Greenshot.Helpers { return; } string errorText = GetMapiError(errorCode); - LOG.Error("Error sending MAPI Email. Error: " + errorText + " (code = " + errorCode + ")."); + Log.Error("Error sending MAPI Email. Error: " + errorText + " (code = " + errorCode + ")."); MessageBox.Show(errorText, "Mail (MAPI) destination", MessageBoxButtons.OK, MessageBoxIcon.Error); // Recover from bad settings, show again if (errorCode != MAPI_CODES.INVALID_RECIPS) { return; } - _recipientCollection = new RecipientCollection(); + Recipients = new RecipientCollection(); _ShowMail(); } } @@ -340,8 +318,8 @@ namespace Greenshot.Helpers { position = -1 }; IntPtr runptr = ptra; - for (int i = 0; i < Files.Count; i++) { - string path = Files[i]; + foreach (string path in Files) + { mfd.name = Path.GetFileName(path); mfd.path = path; Marshal.StructureToPtr(mfd, runptr, false); @@ -664,11 +642,7 @@ namespace Greenshot.Helpers { /// /// Returns the recipient stored in this collection at the specified index. /// - public Recipient this[int index] { - get { - return (Recipient)List[index]; - } - } + public Recipient this[int index] => (Recipient)List[index]; internal InteropRecipientCollection GetInteropRepresentation() { return new InteropRecipientCollection(this); @@ -680,7 +654,6 @@ namespace Greenshot.Helpers { internal struct InteropRecipientCollection : IDisposable { #region Member Variables - private IntPtr _handle; private int _count; #endregion Member Variables @@ -695,16 +668,16 @@ namespace Greenshot.Helpers { _count = outer.Count; if (_count == 0) { - _handle = IntPtr.Zero; + Handle = IntPtr.Zero; return; } // allocate enough memory to hold all recipients int size = Marshal.SizeOf(typeof(MapiMailMessage.MapiHelperInterop.MapiRecipDesc)); - _handle = Marshal.AllocHGlobal(_count * size); + Handle = Marshal.AllocHGlobal(_count * size); // place all interop recipients into the memory just allocated - IntPtr ptr = _handle; + IntPtr ptr = Handle; foreach (Recipient native in outer) { MapiMailMessage.MapiHelperInterop.MapiRecipDesc interop = native.GetInteropRepresentation(); @@ -718,11 +691,7 @@ namespace Greenshot.Helpers { #region Public Properties - public IntPtr Handle { - get { - return _handle; - } - } + public IntPtr Handle { get; private set; } #endregion Public Properties @@ -732,21 +701,21 @@ namespace Greenshot.Helpers { /// Disposes of resources. /// public void Dispose() { - if (_handle != IntPtr.Zero) { + if (Handle != IntPtr.Zero) { Type type = typeof(MapiMailMessage.MapiHelperInterop.MapiRecipDesc); int size = Marshal.SizeOf(type); // destroy all the structures in the memory area - IntPtr ptr = _handle; + IntPtr ptr = Handle; for (int i = 0; i < _count; i++) { Marshal.DestroyStructure(ptr, type); ptr = new IntPtr(ptr.ToInt64() + size); } // free the memory - Marshal.FreeHGlobal(_handle); + Marshal.FreeHGlobal(Handle); - _handle = IntPtr.Zero; + Handle = IntPtr.Zero; _count = 0; } } diff --git a/Greenshot/Helpers/PluginHelper.cs b/Greenshot/Helpers/PluginHelper.cs index 0143aa50f..ed4adc649 100644 --- a/Greenshot/Helpers/PluginHelper.cs +++ b/Greenshot/Helpers/PluginHelper.cs @@ -35,42 +35,31 @@ namespace Greenshot.Helpers { /// [Serializable] public class PluginHelper : IGreenshotHost { - private static readonly ILog LOG = LogManager.GetLogger(typeof(PluginHelper)); - private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly ILog Log = LogManager.GetLogger(typeof(PluginHelper)); + private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); - 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 string PluginPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),Application.ProductName); + private static readonly string ApplicationPath = Path.GetDirectoryName(Application.ExecutablePath); + private static readonly string PafPath = Path.Combine(Application.StartupPath, @"App\Greenshot"); private static readonly IDictionary plugins = new SortedDictionary(); private static readonly PluginHelper instance = new PluginHelper(); - public static PluginHelper Instance { - get { - return instance; - } - } + + public static PluginHelper Instance => instance; private PluginHelper() { PluginUtils.Host = this; } - public Form GreenshotForm { - get { - return MainForm.Instance; - } - } + public Form GreenshotForm => MainForm.Instance; - public NotifyIcon NotifyIcon { - get { - return MainForm.Instance.NotifyIcon; - } - } + public NotifyIcon NotifyIcon => MainForm.Instance.NotifyIcon; public bool HasPlugins() { return plugins != null && plugins.Count > 0; } public void Shutdown() { - foreach(IGreenshotPlugin plugin in plugins.Values) { + foreach(var plugin in plugins.Values) { plugin.Shutdown(); plugin.Dispose(); } @@ -79,42 +68,49 @@ namespace Greenshot.Helpers { // Add plugins to the Listview public void FillListview(ListView listview) { - foreach(PluginAttribute pluginAttribute in plugins.Keys) { - ListViewItem item = new ListViewItem(pluginAttribute.Name); + foreach(var pluginAttribute in plugins.Keys) { + var item = new ListViewItem(pluginAttribute.Name) + { + Tag = pluginAttribute + }; item.SubItems.Add(pluginAttribute.Version); item.SubItems.Add(pluginAttribute.CreatedBy); item.SubItems.Add(pluginAttribute.DllFile); - item.Tag = pluginAttribute; listview.Items.Add(item); } } - public bool isSelectedItemConfigurable(ListView listview) { - if (listview.SelectedItems.Count > 0) { - PluginAttribute pluginAttribute = (PluginAttribute)listview.SelectedItems[0].Tag; - if (pluginAttribute != null) { - return pluginAttribute.Configurable; - } + public bool IsSelectedItemConfigurable(ListView listview) { + if (listview.SelectedItems.Count <= 0) + { + return false; } - return false; + var pluginAttribute = (PluginAttribute)listview.SelectedItems[0].Tag; + return pluginAttribute != null && pluginAttribute.Configurable; } public void ConfigureSelectedItem(ListView listview) { - if (listview.SelectedItems.Count > 0) { - PluginAttribute pluginAttribute = (PluginAttribute)listview.SelectedItems[0].Tag; - if (pluginAttribute != null) { - IGreenshotPlugin plugin = plugins[pluginAttribute]; - plugin.Configure(); - } + if (listview.SelectedItems.Count <= 0) + { + return; } + var pluginAttribute = (PluginAttribute)listview.SelectedItems[0].Tag; + if (pluginAttribute == null) + { + return; + } + var plugin = plugins[pluginAttribute]; + plugin.Configure(); } #region Implementation of IGreenshotPluginHost - + /// /// Create a Thumbnail /// /// Image of which we need a Thumbnail + /// Thumbnail width + /// Thumbnail height /// Image with Thumbnail public Image GetThumbnail(Image image, int width, int height) { return image.GetThumbnailImage(width, height, ThumbnailCallback, IntPtr.Zero); @@ -128,15 +124,9 @@ namespace Greenshot.Helpers { return true; } - public ContextMenuStrip MainMenu { - get { - return MainForm.Instance.MainMenu; - } - } - - public IDictionary Plugins { - get {return plugins;} - } + public ContextMenuStrip MainMenu => MainForm.Instance.MainMenu; + + public IDictionary Plugins => plugins; public IDestination GetDestination(string designation) { return DestinationHelper.GetDestination(designation); @@ -161,7 +151,7 @@ namespace Greenshot.Helpers { /// /// Use the supplied image, and handle it as if it's captured. /// - /// Image to handle + /// Image to handle public void ImportCapture(ICapture captureToImport) { MainForm.Instance.BeginInvoke((MethodInvoker)delegate { CaptureHelper.ImportCapture(captureToImport); @@ -173,10 +163,14 @@ namespace Greenshot.Helpers { /// /// public ICapture GetCapture(Image imageToCapture) { - Capture capture = new Capture(imageToCapture); - capture.CaptureDetails = new CaptureDetails(); - capture.CaptureDetails.CaptureMode = CaptureMode.Import; - capture.CaptureDetails.Title = "Imported"; + var capture = new Capture(imageToCapture) + { + CaptureDetails = new CaptureDetails + { + CaptureMode = CaptureMode.Import, + Title = "Imported" + } + }; return capture; } #endregion @@ -220,9 +214,8 @@ namespace Greenshot.Helpers { pluginFiles.Add(pluginFile); } } catch (UnauthorizedAccessException) { - return; } catch (Exception ex) { - LOG.Error("Error loading plugin: ", ex); + Log.Error("Error loading plugin: ", ex); } } } @@ -234,10 +227,10 @@ namespace Greenshot.Helpers { List pluginFiles = new List(); if (IniConfig.IsPortable) { - findPluginsOnPath(pluginFiles, pafPath); + findPluginsOnPath(pluginFiles, PafPath); } else { - findPluginsOnPath(pluginFiles, pluginPath); - findPluginsOnPath(pluginFiles, applicationPath); + findPluginsOnPath(pluginFiles, PluginPath); + findPluginsOnPath(pluginFiles, ApplicationPath); } Dictionary tmpAttributes = new Dictionary(); @@ -277,36 +270,36 @@ namespace Greenshot.Helpers { } if (checkPluginAttribute != null) { - LOG.WarnFormat("Duplicate plugin {0} found", pluginAttribute.Name); + Log.WarnFormat("Duplicate plugin {0} found", pluginAttribute.Name); if (isNewer(pluginAttribute.Version, checkPluginAttribute.Version)) { // Found is newer tmpAttributes[pluginAttribute.Name] = pluginAttribute; tmpAssemblies[pluginAttribute.Name] = assembly; - LOG.InfoFormat("Loading the newer plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile); + Log.InfoFormat("Loading the newer plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile); } else { - LOG.InfoFormat("Skipping (as the duplicate is newer or same version) the plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile); + Log.InfoFormat("Skipping (as the duplicate is newer or same version) the plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile); } continue; } - if (conf.ExcludePlugins != null && conf.ExcludePlugins.Contains(pluginAttribute.Name)) { - LOG.WarnFormat("Exclude list: {0}", conf.ExcludePlugins.ToArray()); - LOG.WarnFormat("Skipping the excluded plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile); + if (CoreConfig.ExcludePlugins != null && CoreConfig.ExcludePlugins.Contains(pluginAttribute.Name)) { + Log.WarnFormat("Exclude list: {0}", CoreConfig.ExcludePlugins.ToArray()); + Log.WarnFormat("Skipping the excluded plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile); continue; } - if (conf.IncludePlugins != null && conf.IncludePlugins.Count > 0 && !conf.IncludePlugins.Contains(pluginAttribute.Name)) { + if (CoreConfig.IncludePlugins != null && CoreConfig.IncludePlugins.Count > 0 && !CoreConfig.IncludePlugins.Contains(pluginAttribute.Name)) { // Whitelist is set - LOG.WarnFormat("Include list: {0}", conf.IncludePlugins.ToArray()); - LOG.WarnFormat("Skipping the not included plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile); + Log.WarnFormat("Include list: {0}", CoreConfig.IncludePlugins.ToArray()); + Log.WarnFormat("Skipping the not included plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile); continue; } - LOG.InfoFormat("Loading the plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile); + Log.InfoFormat("Loading the plugin {0} with version {1} from {2}", pluginAttribute.Name, pluginAttribute.Version, pluginAttribute.DllFile); tmpAttributes[pluginAttribute.Name] = pluginAttribute; tmpAssemblies[pluginAttribute.Name] = assembly; } else { - LOG.ErrorFormat("Can't find the needed Plugin Attribute ({0}) in the assembly of the file \"{1}\", skipping this file.", typeof(PluginAttribute), pluginFile); + Log.ErrorFormat("Can't find the needed Plugin Attribute ({0}) in the assembly of the file \"{1}\", skipping this file.", typeof(PluginAttribute), pluginFile); } } catch (Exception e) { - LOG.Warn("Can't load file: " + pluginFile, e); + Log.Warn("Can't load file: " + pluginFile, e); } } foreach(string pluginName in tmpAttributes.Keys) { @@ -315,7 +308,7 @@ namespace Greenshot.Helpers { Assembly assembly = tmpAssemblies[pluginName]; Type entryType = assembly.GetType(pluginAttribute.EntryType); if (entryType == null) { - LOG.ErrorFormat("Can't find the in the PluginAttribute referenced type {0} in \"{1}\"", pluginAttribute.EntryType, pluginAttribute.DllFile); + Log.ErrorFormat("Can't find the in the PluginAttribute referenced type {0} in \"{1}\"", pluginAttribute.EntryType, pluginAttribute.DllFile); continue; } try { @@ -324,16 +317,16 @@ namespace Greenshot.Helpers { if (plugin.Initialize(this, pluginAttribute)) { plugins.Add(pluginAttribute, plugin); } else { - LOG.InfoFormat("Plugin {0} not initialized!", pluginAttribute.Name); + Log.InfoFormat("Plugin {0} not initialized!", pluginAttribute.Name); } } else { - LOG.ErrorFormat("Can't create an instance of the in the PluginAttribute referenced type {0} from \"{1}\"", pluginAttribute.EntryType, pluginAttribute.DllFile); + Log.ErrorFormat("Can't create an instance of the in the PluginAttribute referenced type {0} from \"{1}\"", pluginAttribute.EntryType, pluginAttribute.DllFile); } } catch(Exception e) { - LOG.Error("Can't load Plugin: " + pluginAttribute.Name, e); + Log.Error("Can't load Plugin: " + pluginAttribute.Name, e); } } catch(Exception e) { - LOG.Error("Can't load Plugin: " + pluginName, e); + Log.Error("Can't load Plugin: " + pluginName, e); } } } diff --git a/Greenshot/Helpers/PrintHelper.cs b/Greenshot/Helpers/PrintHelper.cs index 95b01552c..ad10d48d1 100644 --- a/Greenshot/Helpers/PrintHelper.cs +++ b/Greenshot/Helpers/PrintHelper.cs @@ -28,7 +28,7 @@ using Greenshot.Forms; using Greenshot.Plugin; using GreenshotPlugin.Core; using Greenshot.IniFile; -using Greenshot.Core; +using GreenshotPlugin.Effects; using log4net; namespace Greenshot.Helpers { @@ -36,21 +36,21 @@ namespace Greenshot.Helpers { /// Description of PrintHelper. /// public class PrintHelper : IDisposable { - private static readonly ILog LOG = LogManager.GetLogger(typeof(PrintHelper)); - private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly ILog Log = LogManager.GetLogger(typeof(PrintHelper)); + private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); - private ISurface surface; - private readonly ICaptureDetails captureDetails; - private PrintDocument printDocument = new PrintDocument(); - private PrintDialog printDialog = new PrintDialog(); + private ISurface _surface; + private readonly ICaptureDetails _captureDetails; + private PrintDocument _printDocument = new PrintDocument(); + private PrintDialog _printDialog = new PrintDialog(); public PrintHelper(ISurface surface, ICaptureDetails captureDetails) { - this.surface = surface; - this.captureDetails = captureDetails; - printDialog.UseEXDialog = true; - printDocument.DocumentName = FilenameHelper.GetFilenameWithoutExtensionFromPattern(conf.OutputFileFilenamePattern, captureDetails); - printDocument.PrintPage += DrawImageForPrint; - printDialog.Document = printDocument; + _surface = surface; + _captureDetails = captureDetails; + _printDialog.UseEXDialog = true; + _printDocument.DocumentName = FilenameHelper.GetFilenameWithoutExtensionFromPattern(CoreConfig.OutputFileFilenamePattern, captureDetails); + _printDocument.PrintPage += DrawImageForPrint; + _printDialog.Document = _printDocument; } /** @@ -75,16 +75,12 @@ namespace Greenshot.Helpers { */ protected virtual void Dispose(bool disposing) { if (disposing) { - if (printDocument != null) { - printDocument.Dispose(); - } - if (printDialog != null) { - printDialog.Dispose(); - } + _printDocument?.Dispose(); + _printDialog?.Dispose(); } - surface = null; - printDocument = null; - printDialog = null; + _surface = null; + _printDocument = null; + _printDialog = null; } /// @@ -97,15 +93,15 @@ namespace Greenshot.Helpers { DialogResult? printOptionsResult = ShowPrintOptionsDialog(); try { if (printOptionsResult == null || printOptionsResult == DialogResult.OK) { - printDocument.PrinterSettings.PrinterName = printerName; + _printDocument.PrinterSettings.PrinterName = printerName; if (!IsColorPrint()) { - printDocument.DefaultPageSettings.Color = false; + _printDocument.DefaultPageSettings.Color = false; } - printDocument.Print(); - returnPrinterSettings = printDocument.PrinterSettings; + _printDocument.Print(); + returnPrinterSettings = _printDocument.PrinterSettings; } } catch (Exception e) { - LOG.Error("An error ocurred while trying to print", e); + Log.Error("An error ocurred while trying to print", e); MessageBox.Show(Language.GetString(LangKey.print_error), Language.GetString(LangKey.error)); } return returnPrinterSettings; @@ -118,18 +114,18 @@ namespace Greenshot.Helpers { /// printer settings if actually printed, or null if print was cancelled or has failed public PrinterSettings PrintWithDialog() { PrinterSettings returnPrinterSettings = null; - if (printDialog.ShowDialog() == DialogResult.OK) { + if (_printDialog.ShowDialog() == DialogResult.OK) { DialogResult? printOptionsResult = ShowPrintOptionsDialog(); try { if (printOptionsResult == null || printOptionsResult == DialogResult.OK) { if (!IsColorPrint()) { - printDocument.DefaultPageSettings.Color = false; + _printDocument.DefaultPageSettings.Color = false; } - printDocument.Print(); - returnPrinterSettings = printDialog.PrinterSettings; + _printDocument.Print(); + returnPrinterSettings = _printDialog.PrinterSettings; } } catch (Exception e) { - LOG.Error("An error ocurred while trying to print", e); + Log.Error("An error ocurred while trying to print", e); MessageBox.Show(Language.GetString(LangKey.print_error), Language.GetString(LangKey.error)); } @@ -138,7 +134,7 @@ namespace Greenshot.Helpers { } private bool IsColorPrint() { - return !conf.OutputPrintGrayscale && !conf.OutputPrintMonochrome; + return !CoreConfig.OutputPrintGrayscale && !CoreConfig.OutputPrintMonochrome; } /// @@ -147,7 +143,7 @@ namespace Greenshot.Helpers { /// result of the print dialog, or null if the dialog has not been displayed by config private DialogResult? ShowPrintOptionsDialog() { DialogResult? ret = null; - if (conf.OutputPrintPromptOptions) { + if (CoreConfig.OutputPrintPromptOptions) { using (PrintOptionsDialog printOptionsDialog = new PrintOptionsDialog()) { ret = printOptionsDialog.ShowDialog(); } @@ -164,16 +160,16 @@ namespace Greenshot.Helpers { ApplyEffects(printOutputSettings); Image image; - bool disposeImage = ImageOutput.CreateImageFromSurface(surface, printOutputSettings, out image); + bool disposeImage = ImageOutput.CreateImageFromSurface(_surface, printOutputSettings, out image); try { - ContentAlignment alignment = conf.OutputPrintCenter ? ContentAlignment.MiddleCenter : ContentAlignment.TopLeft; + ContentAlignment alignment = CoreConfig.OutputPrintCenter ? ContentAlignment.MiddleCenter : ContentAlignment.TopLeft; // prepare timestamp float footerStringWidth = 0; float footerStringHeight = 0; string footerString = null; //DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString(); - if (conf.OutputPrintFooter) { - footerString = FilenameHelper.FillPattern(conf.OutputPrintFooterPattern, captureDetails, false); + if (CoreConfig.OutputPrintFooter) { + footerString = FilenameHelper.FillPattern(CoreConfig.OutputPrintFooterPattern, _captureDetails, false); using (Font f = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular)) { footerStringWidth = e.Graphics.MeasureString(footerString, f).Width; footerStringHeight = e.Graphics.MeasureString(footerString, f).Height; @@ -194,7 +190,7 @@ namespace Greenshot.Helpers { GraphicsUnit gu = GraphicsUnit.Pixel; RectangleF imageRect = image.GetBounds(ref gu); // rotate the image if it fits the page better - if (conf.OutputPrintAllowRotate) { + if (CoreConfig.OutputPrintAllowRotate) { if ((pageRect.Width > pageRect.Height && imageRect.Width < imageRect.Height) || (pageRect.Width < pageRect.Height && imageRect.Width > imageRect.Height)) { image.RotateFlip(RotateFlipType.Rotate270FlipNone); imageRect = image.GetBounds(ref gu); @@ -206,16 +202,16 @@ namespace Greenshot.Helpers { RectangleF printRect = new RectangleF(0, 0, imageRect.Width, imageRect.Height); // scale the image to fit the page better - if (conf.OutputPrintAllowEnlarge || conf.OutputPrintAllowShrink) { + if (CoreConfig.OutputPrintAllowEnlarge || CoreConfig.OutputPrintAllowShrink) { SizeF resizedRect = ScaleHelper.GetScaledSize(imageRect.Size, pageRect.Size, false); - if ((conf.OutputPrintAllowShrink && resizedRect.Width < printRect.Width) || conf.OutputPrintAllowEnlarge && resizedRect.Width > printRect.Width) { + if ((CoreConfig.OutputPrintAllowShrink && resizedRect.Width < printRect.Width) || CoreConfig.OutputPrintAllowEnlarge && resizedRect.Width > printRect.Width) { printRect.Size = resizedRect; } } // align the image printRect = ScaleHelper.GetAlignedRectangle(printRect, new RectangleF(0, 0, pageRect.Width, pageRect.Height), alignment); - if (conf.OutputPrintFooter) { + if (CoreConfig.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); @@ -224,9 +220,8 @@ namespace Greenshot.Helpers { e.Graphics.DrawImage(image, printRect, imageRect, GraphicsUnit.Pixel); } finally { - if (disposeImage && image != null) { - image.Dispose(); - image = null; + if (disposeImage) { + image?.Dispose(); } } } @@ -234,14 +229,14 @@ namespace Greenshot.Helpers { private void ApplyEffects(SurfaceOutputSettings printOutputSettings) { // TODO: // add effects here - if (conf.OutputPrintMonochrome) { - byte threshold = conf.OutputPrintMonochromeThreshold; + if (CoreConfig.OutputPrintMonochrome) { + byte threshold = CoreConfig.OutputPrintMonochromeThreshold; printOutputSettings.Effects.Add(new MonochromeEffect(threshold)); printOutputSettings.ReduceColors = true; } // the invert effect should probably be the last - if (conf.OutputPrintInverted) { + if (CoreConfig.OutputPrintInverted) { printOutputSettings.Effects.Add(new InvertEffect()); } } diff --git a/Greenshot/Helpers/SoundHelper.cs b/Greenshot/Helpers/SoundHelper.cs index d1355d30c..581a18051 100644 --- a/Greenshot/Helpers/SoundHelper.cs +++ b/Greenshot/Helpers/SoundHelper.cs @@ -36,10 +36,10 @@ namespace Greenshot.Helpers { /// See: http://www.codeproject.com/KB/audio-video/soundplayerbug.aspx?msg=2487569 /// public static class SoundHelper { - private static readonly ILog LOG = LogManager.GetLogger(typeof(SoundHelper)); - private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); + private static readonly ILog Log = LogManager.GetLogger(typeof(SoundHelper)); + private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); private static GCHandle? _gcHandle; - private static byte[] _soundBuffer; + private static byte[] _soundBuffer; public static void Initialize() { if (_gcHandle == null) { @@ -47,49 +47,49 @@ namespace Greenshot.Helpers { ResourceManager resources = new ResourceManager("Greenshot.Sounds", Assembly.GetExecutingAssembly()); _soundBuffer = (byte[])resources.GetObject("camera"); - if (conf.NotificationSound != null && conf.NotificationSound.EndsWith(".wav")) { + if (CoreConfig.NotificationSound != null && CoreConfig.NotificationSound.EndsWith(".wav")) { try { - if (File.Exists(conf.NotificationSound)) { - _soundBuffer = File.ReadAllBytes(conf.NotificationSound); + if (File.Exists(CoreConfig.NotificationSound)) { + _soundBuffer = File.ReadAllBytes(CoreConfig.NotificationSound); } } catch (Exception ex) { - LOG.WarnFormat("couldn't load {0}: {1}", conf.NotificationSound, ex.Message); + Log.WarnFormat("couldn't load {0}: {1}", CoreConfig.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); } catch (Exception e) { - LOG.Error("Error initializing.", e); + Log.Error("Error initializing.", e); } } } public static void Play() { - 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); - } catch (Exception e) { - LOG.Error("Error in play.", e); - } - //}); - //playSoundThread.Name = "Play camera sound"; - //playSoundThread.IsBackground = true; - //playSoundThread.Start(); - } - } + if (_soundBuffer != null) { + //Thread playSoundThread = new Thread(delegate() { + SoundFlags flags = SoundFlags.SND_ASYNC | SoundFlags.SND_MEMORY | SoundFlags.SND_NOWAIT | SoundFlags.SND_NOSTOP; + try { + if (_gcHandle != null) WinMM.PlaySound(_gcHandle.Value.AddrOfPinnedObject(), (UIntPtr)0, (uint)flags); + } catch (Exception e) { + Log.Error("Error in play.", e); + } + //}); + //playSoundThread.Name = "Play camera sound"; + //playSoundThread.IsBackground = true; + //playSoundThread.Start(); + } + } - public static void Deinitialize() { - try { + public static void Deinitialize() { + try { if (_gcHandle != null) { - WinMM.PlaySound((byte[])null, (UIntPtr)0, (uint)0); + WinMM.PlaySound(null, (UIntPtr)0, 0); _gcHandle.Value.Free(); _gcHandle = null; } - } catch (Exception e) { - LOG.Error("Error in deinitialize.", e); - } - } + } catch (Exception e) { + Log.Error("Error in deinitialize.", e); + } + } } } diff --git a/Greenshot/Helpers/StartupHelper.cs b/Greenshot/Helpers/StartupHelper.cs index 8b9147edf..4944d4dee 100644 --- a/Greenshot/Helpers/StartupHelper.cs +++ b/Greenshot/Helpers/StartupHelper.cs @@ -29,12 +29,12 @@ namespace Greenshot.Helpers { /// A helper class for the startup registry /// public static class StartupHelper { - private static readonly ILog LOG = LogManager.GetLogger(typeof(StartupHelper)); + private static readonly ILog Log = LogManager.GetLogger(typeof(StartupHelper)); - private const string RUNKEY6432 = @"Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run"; - private const string RUNKEY = @"Software\Microsoft\Windows\CurrentVersion\Run"; + private const string RunKey6432 = @"Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run"; + private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run"; - private const string APPLICATIONNAME = "Greenshot"; + private const string ApplicationName = "Greenshot"; private static string GetExecutablePath() { return "\"" + Application.ExecutablePath + "\""; @@ -46,7 +46,8 @@ namespace Greenshot.Helpers { /// true if Greenshot can write key public static bool CanWriteRunAll() { try { - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(RUNKEY, true)) { + using (Registry.LocalMachine.OpenSubKey(RunKey, true)) + { } } catch { return false; @@ -60,7 +61,8 @@ namespace Greenshot.Helpers { /// true if Greenshot can write key public static bool CanWriteRunUser() { try { - using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RUNKEY, true)) { + using (Registry.CurrentUser.OpenSubKey(RunKey, true)) + { } } catch { return false; @@ -72,24 +74,27 @@ namespace Greenshot.Helpers { /// Return the RUN key value of the local machine /// /// the RUN key value of the local machine - public static Object GetRunAllValue() { - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(RUNKEY, false)) { - if (key != null) { - object runValue = key.GetValue(APPLICATIONNAME); - if (runValue != null) { - return runValue; - } + public static object GetRunAllValue() + { + using (var key = Registry.LocalMachine.OpenSubKey(RunKey, false)) + { + object runValue = key?.GetValue(ApplicationName); + if (runValue != null) + { + return runValue; } } // for 64-bit systems we need to check the 32-bit keys too - if (IntPtr.Size == 8) { - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(RUNKEY6432, false)) { - if (key != null) { - object runValue = key.GetValue(APPLICATIONNAME); - if (runValue != null) { - return runValue; - } - } + if (IntPtr.Size != 8) + { + return null; + } + using (var key = Registry.LocalMachine.OpenSubKey(RunKey6432, false)) + { + object runValue = key?.GetValue(ApplicationName); + if (runValue != null) + { + return runValue; } } return null; @@ -99,24 +104,22 @@ namespace Greenshot.Helpers { /// Return the RUN key value of the current user /// /// the RUN key value of the current user - public static Object GetRunUserValue() { - using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RUNKEY, false)) { - if (key != null) { - object runValue = key.GetValue(APPLICATIONNAME); - if (runValue != null) { - return runValue; - } + public static object GetRunUserValue() { + using (var key = Registry.CurrentUser.OpenSubKey(RunKey, false)) { + object runValue = key?.GetValue(ApplicationName); + if (runValue != null) { + return runValue; } } // for 64-bit systems we need to check the 32-bit keys too - if (IntPtr.Size == 8) { - using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RUNKEY6432, false)) { - if (key != null) { - object runValue = key.GetValue(APPLICATIONNAME); - if (runValue != null) { - return runValue; - } - } + if (IntPtr.Size != 8) + { + return null; + } + using (var key = Registry.CurrentUser.OpenSubKey(RunKey6432, false)) { + object runValue = key?.GetValue(ApplicationName); + if (runValue != null) { + return runValue; } } return null; @@ -130,7 +133,7 @@ namespace Greenshot.Helpers { try { return GetRunAllValue() != null; } catch (Exception e) { - LOG.Error("Error retrieving RunAllValue", e); + Log.Error("Error retrieving RunAllValue", e); } return false; } @@ -140,11 +143,11 @@ namespace Greenshot.Helpers { /// /// true if there is a run key public static bool HasRunUser() { - Object runValue = null; + object runValue = null; try { runValue = GetRunUserValue(); } catch (Exception e) { - LOG.Error("Error retrieving RunUserValue", e); + Log.Error("Error retrieving RunUserValue", e); } return runValue != null; } @@ -153,24 +156,29 @@ namespace Greenshot.Helpers { /// Delete the RUN key for the localmachine ("ALL") /// public static void DeleteRunAll() { - if (HasRunAll()) { - try { - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(RUNKEY, true)) { - key.DeleteValue(APPLICATIONNAME); - } - } catch (Exception e) { - LOG.Error("Error in deleteRunAll.", e); + if (!HasRunAll()) + { + return; + } + try { + using (var key = Registry.LocalMachine.OpenSubKey(RunKey, true)) { + key?.DeleteValue(ApplicationName); } - try { - // for 64-bit systems we need to delete the 32-bit keys too - if (IntPtr.Size == 8) { - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(RUNKEY6432, false)) { - key.DeleteValue(APPLICATIONNAME); - } - } - } catch (Exception e) { - LOG.Error("Error in deleteRunAll.", e); + } catch (Exception e) { + Log.Error("Error in deleteRunAll.", e); + } + try + { + // for 64-bit systems we need to delete the 32-bit keys too + if (IntPtr.Size != 8) + { + return; } + using (var key = Registry.LocalMachine.OpenSubKey(RunKey6432, false)) { + key?.DeleteValue(ApplicationName); + } + } catch (Exception e) { + Log.Error("Error in deleteRunAll.", e); } } @@ -178,24 +186,29 @@ namespace Greenshot.Helpers { /// Delete the RUN key for the current user /// public static void DeleteRunUser() { - if (HasRunUser()) { - try { - using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RUNKEY, true)) { - key.DeleteValue(APPLICATIONNAME); - } - } catch (Exception e) { - LOG.Error("Error in deleteRunUser.", e); + if (!HasRunUser()) + { + return; + } + try { + using (var key = Registry.CurrentUser.OpenSubKey(RunKey, true)) { + key?.DeleteValue(ApplicationName); } - try { - // for 64-bit systems we need to delete the 32-bit keys too - if (IntPtr.Size == 8) { - using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RUNKEY6432, false)) { - key.DeleteValue(APPLICATIONNAME); - } - } - } catch (Exception e) { - LOG.Error("Error in deleteRunUser.", e); + } catch (Exception e) { + Log.Error("Error in deleteRunUser.", e); + } + try + { + // for 64-bit systems we need to delete the 32-bit keys too + if (IntPtr.Size != 8) + { + return; } + using (var key = Registry.CurrentUser.OpenSubKey(RunKey6432, false)) { + key?.DeleteValue(ApplicationName); + } + } catch (Exception e) { + Log.Error("Error in deleteRunUser.", e); } } @@ -204,11 +217,12 @@ namespace Greenshot.Helpers { /// public static void SetRunUser() { try { - using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RUNKEY, true)) { - key.SetValue(APPLICATIONNAME, GetExecutablePath()); + using (var key = Registry.CurrentUser.OpenSubKey(RunKey, true)) + { + key?.SetValue(ApplicationName, GetExecutablePath()); } } catch (Exception e) { - LOG.Error("Error in setRunUser.", e); + Log.Error("Error in setRunUser.", e); } } @@ -221,19 +235,22 @@ namespace Greenshot.Helpers { string lnkName = Path.GetFileNameWithoutExtension(Application.ExecutablePath) + ".lnk"; string startupPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup); if (Directory.Exists(startupPath)) { - LOG.DebugFormat("Startup path: {0}", startupPath); + Log.DebugFormat("Startup path: {0}", startupPath); if (File.Exists(Path.Combine(startupPath, lnkName))) { return true; } } string startupAll = Environment.GetEnvironmentVariable("ALLUSERSPROFILE") + @"\Microsoft\Windows\Start Menu\Programs\Startup"; if (Directory.Exists(startupAll)) { - LOG.DebugFormat("Startup all path: {0}", startupAll); + Log.DebugFormat("Startup all path: {0}", startupAll); if (File.Exists(Path.Combine(startupAll, lnkName))) { return true; } } - } catch { + } + catch + { + // ignored } return false; } diff --git a/Greenshot/Helpers/UpdateHelper.cs b/Greenshot/Helpers/UpdateHelper.cs index 1d2231c39..68d5d5d9f 100644 --- a/Greenshot/Helpers/UpdateHelper.cs +++ b/Greenshot/Helpers/UpdateHelper.cs @@ -34,35 +34,37 @@ namespace Greenshot.Experimental { /// Description of RssFeedHelper. /// public static class UpdateHelper { - private static readonly ILog LOG = LogManager.GetLogger(typeof(UpdateHelper)); - private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); - private const string STABLE_DOWNLOAD_LINK = "http://getgreenshot.org/downloads/"; - private const string VERSION_HISTORY_LINK = "http://getgreenshot.org/version-history/"; + private static readonly ILog Log = LogManager.GetLogger(typeof(UpdateHelper)); + private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); + private const string StableDownloadLink = "http://getgreenshot.org/downloads/"; + private const string VersionHistoryLink = "http://getgreenshot.org/version-history/"; private static readonly object LockObject = new object(); private static RssFile _latestGreenshot; - private static string _downloadLink = STABLE_DOWNLOAD_LINK; + private static string _downloadLink = StableDownloadLink; /// /// Is an update check needed? /// /// bool true if yes public static bool IsUpdateCheckNeeded() { - lock (LockObject) { - if (conf.UpdateCheckInterval == 0) { + lock (LockObject) + { + if (CoreConfig.UpdateCheckInterval == 0) + { return false; } - if (conf.LastUpdateCheck != null) { - DateTime checkTime = conf.LastUpdateCheck; - checkTime = checkTime.AddDays(conf.UpdateCheckInterval); - if (DateTime.Now.CompareTo(checkTime) < 0) { - LOG.DebugFormat("No need to check RSS feed for updates, feed check will be after {0}", checkTime); - return false; - } - LOG.DebugFormat("Update check is due, last check was {0} check needs to be made after {1} (which is one {2} later)", conf.LastUpdateCheck, checkTime, conf.UpdateCheckInterval); - if (!RssHelper.IsRSSModifiedAfter(conf.LastUpdateCheck)) { - LOG.DebugFormat("RSS feed has not been updated since after {0}", conf.LastUpdateCheck); - return false; - } + DateTime checkTime = CoreConfig.LastUpdateCheck; + checkTime = checkTime.AddDays(CoreConfig.UpdateCheckInterval); + if (DateTime.Now.CompareTo(checkTime) < 0) + { + Log.DebugFormat("No need to check RSS feed for updates, feed check will be after {0}", checkTime); + return false; + } + Log.DebugFormat("Update check is due, last check was {0} check needs to be made after {1} (which is one {2} later)", CoreConfig.LastUpdateCheck, checkTime, CoreConfig.UpdateCheckInterval); + if (!RssHelper.IsRssModifiedAfter(CoreConfig.LastUpdateCheck)) + { + Log.DebugFormat("RSS feed has not been updated since after {0}", CoreConfig.LastUpdateCheck); + return false; } } return true; @@ -79,15 +81,15 @@ namespace Greenshot.Experimental { try { _latestGreenshot = null; - ProcessRSSInfo(currentVersion); + ProcessRssInfo(currentVersion); if (_latestGreenshot != null) { MainForm.Instance.NotifyIcon.BalloonTipClicked += HandleBalloonTipClick; MainForm.Instance.NotifyIcon.BalloonTipClosed += CleanupBalloonTipClick; MainForm.Instance.NotifyIcon.ShowBalloonTip(10000, "Greenshot", Language.GetFormattedString(LangKey.update_found, "'" + _latestGreenshot.File + "'"), ToolTipIcon.Info); } - conf.LastUpdateCheck = DateTime.Now; + CoreConfig.LastUpdateCheck = DateTime.Now; } catch (Exception e) { - LOG.Error("An error occured while checking for updates, the error will be ignored: ", e); + Log.Error("An error occured while checking for updates, the error will be ignored: ", e); } } } @@ -112,9 +114,9 @@ namespace Greenshot.Experimental { } } - private static void ProcessRSSInfo(Version currentVersion) { + private static void ProcessRssInfo(Version currentVersion) { // Reset latest Greenshot - IList rssFiles = RssHelper.readRSS(); + IList rssFiles = RssHelper.ReadRss(); if (rssFiles == null) { return; @@ -124,29 +126,29 @@ namespace Greenshot.Experimental { foreach(RssFile rssFile in rssFiles) { if (rssFile.File.StartsWith("Greenshot")) { // check for exe - if (!rssFile.isExe) { + if (!rssFile.IsExe) { continue; } // do we have a version? if (rssFile.Version == null) { - LOG.DebugFormat("Skipping unversioned exe {0} which is published at {1} : {2}", rssFile.File, rssFile.Pubdate.ToLocalTime(), rssFile.Link); + Log.DebugFormat("Skipping unversioned exe {0} which is published at {1} : {2}", rssFile.File, rssFile.Pubdate.ToLocalTime(), rssFile.Link); continue; } // if the file is unstable, we will skip it when: // the current version is a release or release candidate AND check unstable is turned off. - if (rssFile.isUnstable) { + if (rssFile.IsUnstable) { // Skip if we shouldn't check unstables - if ((conf.BuildState == BuildStates.RELEASE) && !conf.CheckForUnstable) { + if ((CoreConfig.BuildState == BuildStates.RELEASE) && !CoreConfig.CheckForUnstable) { continue; } } // if the file is a release candidate, we will skip it when: // the current version is a release AND check unstable is turned off. - if (rssFile.isReleaseCandidate) { - if (conf.BuildState == BuildStates.RELEASE && !conf.CheckForUnstable) { + if (rssFile.IsReleaseCandidate) { + if (CoreConfig.BuildState == BuildStates.RELEASE && !CoreConfig.CheckForUnstable) { continue; } } @@ -154,19 +156,19 @@ namespace Greenshot.Experimental { // Compare versions int versionCompare = rssFile.Version.CompareTo(currentVersion); if (versionCompare > 0) { - LOG.DebugFormat("Found newer Greenshot '{0}' with version {1} published at {2} : {3}", rssFile.File, rssFile.Version, rssFile.Pubdate.ToLocalTime(), rssFile.Link); + Log.DebugFormat("Found newer Greenshot '{0}' with version {1} published at {2} : {3}", rssFile.File, rssFile.Version, rssFile.Pubdate.ToLocalTime(), rssFile.Link); if (_latestGreenshot == null || rssFile.Version.CompareTo(_latestGreenshot.Version) > 0) { _latestGreenshot = rssFile; - if (rssFile.isReleaseCandidate || rssFile.isUnstable) { - _downloadLink = VERSION_HISTORY_LINK; + if (rssFile.IsReleaseCandidate || rssFile.IsUnstable) { + _downloadLink = VersionHistoryLink; } else { - _downloadLink = STABLE_DOWNLOAD_LINK; + _downloadLink = StableDownloadLink; } } } else if (versionCompare < 0) { - LOG.DebugFormat("Skipping older greenshot with version {0}", rssFile.Version); + Log.DebugFormat("Skipping older greenshot with version {0}", rssFile.Version); } else if (versionCompare == 0) { - LOG.DebugFormat("Found current version as exe {0} with version {1} published at {2} : {3}", rssFile.File, rssFile.Version, rssFile.Pubdate.ToLocalTime(), rssFile.Link); + Log.DebugFormat("Found current version as exe {0} with version {1} published at {2} : {3}", rssFile.File, rssFile.Version, rssFile.Pubdate.ToLocalTime(), rssFile.Link); } } } diff --git a/Greenshot/Helpers/WindowWrapper.cs b/Greenshot/Helpers/WindowWrapper.cs index a1d7e74be..63cb51e81 100644 --- a/Greenshot/Helpers/WindowWrapper.cs +++ b/Greenshot/Helpers/WindowWrapper.cs @@ -24,13 +24,9 @@ using System.Windows.Forms; namespace Greenshot.Helpers { public class WindowWrapper : IWin32Window { public WindowWrapper(IntPtr handle) { - _hwnd = handle; + Handle = handle; } - public IntPtr Handle { - get { return _hwnd; } - } - - private readonly IntPtr _hwnd; + public IntPtr Handle { get; } } } diff --git a/Greenshot/Memento/AddElementsMemento.cs b/Greenshot/Memento/AddElementsMemento.cs index 5b3885f30..b28543512 100644 --- a/Greenshot/Memento/AddElementsMemento.cs +++ b/Greenshot/Memento/AddElementsMemento.cs @@ -46,10 +46,7 @@ namespace Greenshot.Memento { if (disposing) { - if (_containerList != null) - { - _containerList.Dispose(); - } + _containerList?.Dispose(); } _containerList = null; _surface = null; @@ -62,9 +59,6 @@ namespace Greenshot.Memento public IMemento Restore() { - // Store the selected state, as it's overwritten by the RemoveElement - bool selected = _containerList.Selected; - var oldState = new DeleteElementsMemento(_surface, _containerList); _surface.RemoveElements(_containerList, false); diff --git a/Greenshot/Memento/ChangeFieldHolderMemento.cs b/Greenshot/Memento/ChangeFieldHolderMemento.cs index 688baf81a..0e5c371f3 100644 --- a/Greenshot/Memento/ChangeFieldHolderMemento.cs +++ b/Greenshot/Memento/ChangeFieldHolderMemento.cs @@ -30,8 +30,8 @@ namespace Greenshot.Memento public class ChangeFieldHolderMemento : IMemento { private IDrawableContainer _drawableContainer; - private IField _fieldToBeChanged; - private object _oldValue; + private readonly IField _fieldToBeChanged; + private readonly object _oldValue; public ChangeFieldHolderMemento(IDrawableContainer drawableContainer, IField fieldToBeChanged) { @@ -49,10 +49,7 @@ namespace Greenshot.Memento { if (disposing) { - if (_drawableContainer != null) - { - _drawableContainer.Dispose(); - } + _drawableContainer?.Dispose(); } _drawableContainer = null; } diff --git a/Greenshot/Memento/DeleteElementsMemento.cs b/Greenshot/Memento/DeleteElementsMemento.cs index a42e06b36..e0178a36e 100644 --- a/Greenshot/Memento/DeleteElementsMemento.cs +++ b/Greenshot/Memento/DeleteElementsMemento.cs @@ -46,10 +46,7 @@ namespace Greenshot.Memento { if (disposing) { - if (_containerList != null) - { - _containerList.Dispose(); - } + _containerList?.Dispose(); } _containerList = null; _surface = null; diff --git a/Greenshot/Memento/DrawableContainerBoundsChangeMemento.cs b/Greenshot/Memento/DrawableContainerBoundsChangeMemento.cs index 01f372b10..08b4db616 100644 --- a/Greenshot/Memento/DrawableContainerBoundsChangeMemento.cs +++ b/Greenshot/Memento/DrawableContainerBoundsChangeMemento.cs @@ -31,30 +31,32 @@ namespace Greenshot.Memento /// public class DrawableContainerBoundsChangeMemento : IMemento { - private List points = new List(); - private List sizes = new List(); - private IDrawableContainerList listOfdrawableContainer; + private readonly List _points = new List(); + private readonly List _sizes = new List(); + private IDrawableContainerList _listOfdrawableContainer; private void StoreBounds() { - foreach (IDrawableContainer drawableContainer in listOfdrawableContainer) + foreach (IDrawableContainer drawableContainer in _listOfdrawableContainer) { - points.Add(drawableContainer.Location); - sizes.Add(drawableContainer.Size); + _points.Add(drawableContainer.Location); + _sizes.Add(drawableContainer.Size); } } public DrawableContainerBoundsChangeMemento(IDrawableContainerList listOfdrawableContainer) { - this.listOfdrawableContainer = listOfdrawableContainer; + _listOfdrawableContainer = listOfdrawableContainer; StoreBounds(); } public DrawableContainerBoundsChangeMemento(IDrawableContainer drawableContainer) { - listOfdrawableContainer = new DrawableContainerList(); - listOfdrawableContainer.Add(drawableContainer); - listOfdrawableContainer.Parent = drawableContainer.Parent; + _listOfdrawableContainer = new DrawableContainerList + { + drawableContainer + }; + _listOfdrawableContainer.Parent = drawableContainer.Parent; StoreBounds(); } @@ -67,12 +69,9 @@ namespace Greenshot.Memento { if (disposing) { - if (listOfdrawableContainer != null) - { - listOfdrawableContainer.Dispose(); - } + _listOfdrawableContainer?.Dispose(); } - listOfdrawableContainer = null; + _listOfdrawableContainer = null; } public bool Merge(IMemento otherMemento) @@ -80,7 +79,7 @@ namespace Greenshot.Memento var other = otherMemento as DrawableContainerBoundsChangeMemento; if (other != null) { - if (ObjectExtensions.CompareLists(listOfdrawableContainer, other.listOfdrawableContainer)) + if (ObjectExtensions.CompareLists(_listOfdrawableContainer, other._listOfdrawableContainer)) { // Lists are equal, as we have the state already we can ignore the new memento return true; @@ -91,16 +90,16 @@ namespace Greenshot.Memento public IMemento Restore() { - var oldState = new DrawableContainerBoundsChangeMemento(listOfdrawableContainer); - for (int index = 0; index < listOfdrawableContainer.Count; index++) + var oldState = new DrawableContainerBoundsChangeMemento(_listOfdrawableContainer); + for (int index = 0; index < _listOfdrawableContainer.Count; index++) { - IDrawableContainer drawableContainer = listOfdrawableContainer[index]; + IDrawableContainer drawableContainer = _listOfdrawableContainer[index]; // Before drawableContainer.Invalidate(); - drawableContainer.Left = points[index].X; - drawableContainer.Top = points[index].Y; - drawableContainer.Width = sizes[index].Width; - drawableContainer.Height = sizes[index].Height; + drawableContainer.Left = _points[index].X; + drawableContainer.Top = _points[index].Y; + drawableContainer.Width = _sizes[index].Width; + drawableContainer.Height = _sizes[index].Height; // After drawableContainer.Invalidate(); drawableContainer.Parent.Modified = true; diff --git a/GreenshotBoxPlugin/BoxConfiguration.cs b/GreenshotBoxPlugin/BoxConfiguration.cs index 4745f2baa..4fb64cd2f 100644 --- a/GreenshotBoxPlugin/BoxConfiguration.cs +++ b/GreenshotBoxPlugin/BoxConfiguration.cs @@ -68,7 +68,7 @@ namespace GreenshotBoxPlugin { /// /// bool true if OK was pressed, false if cancel public bool ShowConfigDialog() { - DialogResult result = new SettingsForm(this).ShowDialog(); + DialogResult result = new SettingsForm().ShowDialog(); if (result == DialogResult.OK) { return true; } diff --git a/GreenshotBoxPlugin/BoxUtils.cs b/GreenshotBoxPlugin/BoxUtils.cs index b7910d0f7..4f375a28c 100644 --- a/GreenshotBoxPlugin/BoxUtils.cs +++ b/GreenshotBoxPlugin/BoxUtils.cs @@ -33,7 +33,7 @@ namespace GreenshotBoxPlugin { /// Description of ImgurUtils. /// public static class BoxUtils { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(BoxUtils)); + private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(BoxUtils)); private static readonly BoxConfiguration Config = IniConfig.GetIniSection(); private const string UploadFileUri = "https://upload.box.com/api/2.0/files/content"; private const string FilesUri = "https://www.box.com/api/2.0/files/{0}"; @@ -66,21 +66,23 @@ namespace GreenshotBoxPlugin { public static string UploadToBox(SurfaceContainer image, string title, string filename) { // Fill the OAuth2Settings - OAuth2Settings settings = new OAuth2Settings(); + var settings = new OAuth2Settings + { + AuthUrlPattern = "https://app.box.com/api/oauth2/authorize?client_id={ClientId}&response_type=code&state={State}&redirect_uri={RedirectUrl}", + TokenUrl = "https://api.box.com/oauth2/token", + CloudServiceName = "Box", + ClientId = BoxCredentials.ClientId, + ClientSecret = BoxCredentials.ClientSecret, + RedirectUrl = "https://www.box.com/home/", + BrowserSize = new Size(1060, 600), + AuthorizeMode = OAuth2AuthorizeMode.EmbeddedBrowser, + RefreshToken = Config.RefreshToken, + AccessToken = Config.AccessToken, + AccessTokenExpires = Config.AccessTokenExpires + }; - settings.AuthUrlPattern = "https://app.box.com/api/oauth2/authorize?client_id={ClientId}&response_type=code&state={State}&redirect_uri={RedirectUrl}"; - settings.TokenUrl = "https://api.box.com/oauth2/token"; - settings.CloudServiceName = "Box"; - settings.ClientId = BoxCredentials.ClientId; - settings.ClientSecret = BoxCredentials.ClientSecret; - settings.RedirectUrl = "https://www.box.com/home/"; - settings.BrowserSize = new Size(1060, 600); - settings.AuthorizeMode = OAuth2AuthorizeMode.EmbeddedBrowser; // Copy the settings from the config, which is kept in memory and on the disk - settings.RefreshToken = Config.RefreshToken; - settings.AccessToken = Config.AccessToken; - settings.AccessTokenExpires = Config.AccessTokenExpires; try { var webRequest = OAuth2Helper.CreateOAuth2WebRequest(HTTPMethod.POST, UploadFileUri, settings); @@ -92,17 +94,17 @@ namespace GreenshotBoxPlugin { var response = NetworkHelper.GetResponseAsString(webRequest); - LOG.DebugFormat("Box response: {0}", response); + Log.DebugFormat("Box response: {0}", response); var upload = JsonSerializer.Deserialize(response); - if (upload == null || upload.Entries == null || upload.Entries.Count == 0) return null; + if (upload?.Entries == null || upload.Entries.Count == 0) return null; if (Config.UseSharedLink) { string filesResponse = HttpPut(string.Format(FilesUri, upload.Entries[0].Id), "{\"shared_link\": {\"access\": \"open\"}}", settings); var file = JsonSerializer.Deserialize(filesResponse); return file.SharedLink.Url; } - return string.Format("http://www.box.com/files/0/f/0/1/f_{0}", upload.Entries[0].Id); + return $"http://www.box.com/files/0/f/0/1/f_{upload.Entries[0].Id}"; } finally { // Copy the settings back to the config, so they are stored. Config.RefreshToken = settings.RefreshToken; diff --git a/GreenshotBoxPlugin/Forms/SettingsForm.cs b/GreenshotBoxPlugin/Forms/SettingsForm.cs index 973620771..df1c50134 100644 --- a/GreenshotBoxPlugin/Forms/SettingsForm.cs +++ b/GreenshotBoxPlugin/Forms/SettingsForm.cs @@ -26,7 +26,7 @@ namespace GreenshotBoxPlugin { /// Description of PasswordRequestForm. /// public partial class SettingsForm : BoxForm { - public SettingsForm(BoxConfiguration config) { + public SettingsForm() { // // The InitializeComponent() call is required for Windows Forms designer support. // diff --git a/GreenshotConfluencePlugin/Confluence.cs b/GreenshotConfluencePlugin/Confluence.cs index 714d3d20e..fdda7c31b 100644 --- a/GreenshotConfluencePlugin/Confluence.cs +++ b/GreenshotConfluencePlugin/Confluence.cs @@ -222,19 +222,17 @@ namespace Confluence { } } - public bool IsLoggedIn { - get { - return _loggedIn; - } - } - + public bool IsLoggedIn => _loggedIn; + public void AddAttachment(long pageId, string mime, string comment, string filename, IBinaryContainer image) { CheckCredentials(); - RemoteAttachment attachment = new RemoteAttachment(); // Comment is ignored, see: http://jira.atlassian.com/browse/CONF-9395 - attachment.comment = comment; - attachment.fileName = filename; - attachment.contentType = mime; + var attachment = new RemoteAttachment + { + comment = comment, + fileName = filename, + contentType = mime + }; _confluence.addAttachment(_credentials, pageId, attachment, image.ToByteArray()); } @@ -284,7 +282,6 @@ namespace Confluence { public IEnumerable GetPageChildren(Page parentPage) { CheckCredentials(); - List returnPages = new List(); RemotePageSummary[] pages = _confluence.getChildren(_credentials, parentPage.Id); foreach(RemotePageSummary page in pages) { yield return new Page(page); diff --git a/GreenshotConfluencePlugin/ConfluenceDestination.cs b/GreenshotConfluencePlugin/ConfluenceDestination.cs index fa9ccb7a1..50330f109 100644 --- a/GreenshotConfluencePlugin/ConfluenceDestination.cs +++ b/GreenshotConfluencePlugin/ConfluenceDestination.cs @@ -84,15 +84,15 @@ namespace GreenshotConfluencePlugin { } } - public override bool isDynamic { + public override bool IsDynamic { get { return true; } } - public override bool isActive { + public override bool IsActive { get { - return base.isActive && !string.IsNullOrEmpty(ConfluenceConfig.Url); + return base.IsActive && !string.IsNullOrEmpty(ConfluenceConfig.Url); } } @@ -127,7 +127,7 @@ namespace GreenshotConfluencePlugin { string filename = FilenameHelper.GetFilenameWithoutExtensionFromPattern(CoreConfig.OutputFileFilenamePattern, captureDetails); if (selectedPage == null) { ConfluenceUpload confluenceUpload = new ConfluenceUpload(filename); - Nullable dialogResult = confluenceUpload.ShowDialog(); + bool? dialogResult = confluenceUpload.ShowDialog(); if (dialogResult.HasValue && dialogResult.Value) { selectedPage = confluenceUpload.SelectedPage; if (confluenceUpload.IsOpenPageSelected) { diff --git a/GreenshotConfluencePlugin/ConfluencePlugin.cs b/GreenshotConfluencePlugin/ConfluencePlugin.cs index 4ba405800..eabc34b19 100644 --- a/GreenshotConfluencePlugin/ConfluencePlugin.cs +++ b/GreenshotConfluencePlugin/ConfluencePlugin.cs @@ -124,7 +124,7 @@ namespace GreenshotConfluencePlugin { ConfluenceConfiguration clonedConfig = _config.Clone(); ConfluenceConfigurationForm configForm = new ConfluenceConfigurationForm(clonedConfig); string url = _config.Url; - Nullable dialogResult = configForm.ShowDialog(); + bool? dialogResult = configForm.ShowDialog(); if (dialogResult.HasValue && dialogResult.Value) { // copy the new object to the old... clonedConfig.CloneTo(_config); diff --git a/GreenshotConfluencePlugin/ConfluenceUtils.cs b/GreenshotConfluencePlugin/ConfluenceUtils.cs index 64a8b9a3e..19c417136 100644 --- a/GreenshotConfluencePlugin/ConfluenceUtils.cs +++ b/GreenshotConfluencePlugin/ConfluenceUtils.cs @@ -95,7 +95,6 @@ namespace GreenshotConfluencePlugin { pages.Add(page); } - continue; } catch (Exception ex) { // Preventing security problems LOG.DebugFormat("Couldn't get page details for space {0} / title {1}", space, title); @@ -133,7 +132,7 @@ namespace GreenshotConfluencePlugin { if (pattern.ProgrammaticName != "ValuePatternIdentifiers.Pattern") { continue; } - string url = (docElement.GetCurrentPattern(pattern) as ValuePattern).Current.Value.ToString(); + string url = (docElement.GetCurrentPattern(pattern) as ValuePattern).Current.Value; if (!string.IsNullOrEmpty(url)) { urls.Add(url); break; diff --git a/GreenshotConfluencePlugin/EnumDisplayer.cs b/GreenshotConfluencePlugin/EnumDisplayer.cs index 9c31f2972..ca55afa40 100644 --- a/GreenshotConfluencePlugin/EnumDisplayer.cs +++ b/GreenshotConfluencePlugin/EnumDisplayer.cs @@ -30,11 +30,9 @@ using GreenshotPlugin.Core; namespace GreenshotConfluencePlugin { public class EnumDisplayer : IValueConverter { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(EnumDisplayer)); - - private Type type; - private IDictionary displayValues; - private IDictionary reverseValues; + private Type _type; + private IDictionary _displayValues; + private IDictionary _reverseValues; public EnumDisplayer() { } @@ -44,22 +42,30 @@ namespace GreenshotConfluencePlugin { } public Type Type { - get { return type; } + get { return _type; } set { if (!value.IsEnum) { - throw new ArgumentException("parameter is not an Enumerated type", "value"); + throw new ArgumentException("parameter is not an Enumerated type", nameof(value)); } - type = value; + _type = value; } } public ReadOnlyCollection DisplayNames { get { - reverseValues = (IDictionary) Activator.CreateInstance(typeof(Dictionary<,>).GetGenericTypeDefinition().MakeGenericType(typeof(string),type)); - - displayValues = (IDictionary)Activator.CreateInstance(typeof(Dictionary<,>).GetGenericTypeDefinition().MakeGenericType(type, typeof(string))); - - var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static); + var genericTypeDefinition = typeof(Dictionary<,>).GetGenericTypeDefinition(); + if (genericTypeDefinition != null) + { + _reverseValues = (IDictionary) Activator.CreateInstance(genericTypeDefinition.MakeGenericType(typeof(string),_type)); + } + + var typeDefinition = typeof(Dictionary<,>).GetGenericTypeDefinition(); + if (typeDefinition != null) + { + _displayValues = (IDictionary)Activator.CreateInstance(typeDefinition.MakeGenericType(_type, typeof(string))); + } + + var fields = _type.GetFields(BindingFlags.Public | BindingFlags.Static); foreach (var field in fields) { DisplayKeyAttribute[] a = (DisplayKeyAttribute[])field.GetCustomAttributes(typeof(DisplayKeyAttribute), false); @@ -67,25 +73,19 @@ namespace GreenshotConfluencePlugin { object enumValue = field.GetValue(null); string displayString; - if (displayKey != null && Language.hasKey(displayKey)) { + if (displayKey != null && Language.HasKey(displayKey)) { displayString = Language.GetString(displayKey); } - if (displayKey != null) { - displayString = displayKey; - } else { - displayString = enumValue.ToString(); - } - - if (displayString != null) { - displayValues.Add(enumValue, displayString); - reverseValues.Add(displayString, enumValue); - } + displayString = displayKey ?? enumValue.ToString(); + + _displayValues.Add(enumValue, displayString); + _reverseValues.Add(displayString, enumValue); } - return new List((IEnumerable)displayValues.Values).AsReadOnly(); + return new List((IEnumerable)_displayValues.Values).AsReadOnly(); } } - private string GetDisplayKeyValue(DisplayKeyAttribute[] a) { + private static string GetDisplayKeyValue(DisplayKeyAttribute[] a) { if (a == null || a.Length == 0) { return null; } @@ -94,11 +94,11 @@ namespace GreenshotConfluencePlugin { } object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) { - return displayValues[value]; + return _displayValues[value]; } object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { - return reverseValues[value]; + return _reverseValues[value]; } } } diff --git a/GreenshotConfluencePlugin/Forms/ConfluenceConfigurationForm.xaml.cs b/GreenshotConfluencePlugin/Forms/ConfluenceConfigurationForm.xaml.cs index d194fddcb..4ce336f3c 100644 --- a/GreenshotConfluencePlugin/Forms/ConfluenceConfigurationForm.xaml.cs +++ b/GreenshotConfluencePlugin/Forms/ConfluenceConfigurationForm.xaml.cs @@ -26,16 +26,11 @@ namespace GreenshotConfluencePlugin { /// Interaction logic for ConfluenceConfigurationForm.xaml /// public partial class ConfluenceConfigurationForm : Window { - private readonly ConfluenceConfiguration config; - public ConfluenceConfiguration Config { - get { - return config; - } - } - + public ConfluenceConfiguration Config { get; } + public ConfluenceConfigurationForm(ConfluenceConfiguration config) { DataContext = config; - this.config = config; + Config = config; InitializeComponent(); } diff --git a/GreenshotConfluencePlugin/Forms/ConfluencePagePicker.xaml.cs b/GreenshotConfluencePlugin/Forms/ConfluencePagePicker.xaml.cs index cc237ccbe..0d5f78bfb 100644 --- a/GreenshotConfluencePlugin/Forms/ConfluencePagePicker.xaml.cs +++ b/GreenshotConfluencePlugin/Forms/ConfluencePagePicker.xaml.cs @@ -26,12 +26,12 @@ namespace GreenshotConfluencePlugin { /// /// Interaction logic for ConfluencePagePicker.xaml /// - public partial class ConfluencePagePicker : System.Windows.Controls.Page { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ConfluencePagePicker)); - private readonly ConfluenceUpload confluenceUpload = null; + public partial class ConfluencePagePicker + { + private readonly ConfluenceUpload _confluenceUpload; public ConfluencePagePicker(ConfluenceUpload confluenceUpload, List pagesToPick) { - this.confluenceUpload = confluenceUpload; + _confluenceUpload = confluenceUpload; DataContext = pagesToPick; InitializeComponent(); } @@ -42,11 +42,11 @@ namespace GreenshotConfluencePlugin { private void SelectionChanged() { if (PageListView.HasItems && PageListView.SelectedItems.Count > 0) { - confluenceUpload.SelectedPage = (Page)PageListView.SelectedItem; + _confluenceUpload.SelectedPage = (Page)PageListView.SelectedItem; // Make sure the uploader knows we selected an already opened page - confluenceUpload.IsOpenPageSelected = true; + _confluenceUpload.IsOpenPageSelected = true; } else { - confluenceUpload.SelectedPage = null; + _confluenceUpload.SelectedPage = null; } } diff --git a/GreenshotConfluencePlugin/Support/LanguageChangedEventManager.cs b/GreenshotConfluencePlugin/Support/LanguageChangedEventManager.cs index 056f9dfb0..8fe9289d3 100644 --- a/GreenshotConfluencePlugin/Support/LanguageChangedEventManager.cs +++ b/GreenshotConfluencePlugin/Support/LanguageChangedEventManager.cs @@ -26,7 +26,7 @@ namespace TranslationByMarkupExtension manager.LanguageChanged += OnLanguageChanged; } - protected override void StopListening(Object source) + protected override void StopListening(object source) { var manager = (TranslationManager)source; manager.LanguageChanged -= OnLanguageChanged; diff --git a/GreenshotConfluencePlugin/Support/LanguageXMLTranslationProvider.cs b/GreenshotConfluencePlugin/Support/LanguageXMLTranslationProvider.cs index 72a94da31..e5cf3bfe8 100644 --- a/GreenshotConfluencePlugin/Support/LanguageXMLTranslationProvider.cs +++ b/GreenshotConfluencePlugin/Support/LanguageXMLTranslationProvider.cs @@ -1,38 +1,30 @@ using GreenshotPlugin.Core; namespace TranslationByMarkupExtension { - /// - /// - /// - public class LanguageXMLTranslationProvider : ITranslationProvider { - #region Private Members + /// + /// + /// + public class LanguageXMLTranslationProvider : ITranslationProvider { + #region Private Members - #endregion + #endregion - #region Construction + #region Construction - /// - /// Initializes a new instance of the class. - /// - /// Name of the base. - /// The assembly. - public LanguageXMLTranslationProvider() { - } + #endregion - #endregion + #region ITranslationProvider Members - #region ITranslationProvider Members - - /// - /// See - /// - public object Translate(string key) { - if (Language.hasKey("confluence", key)) { + /// + /// See + /// + public object Translate(string key) { + if (Language.HasKey("confluence", key)) { return Language.GetString("confluence", key); - } - return key; - } + } + return key; + } - #endregion - } + #endregion + } } diff --git a/GreenshotConfluencePlugin/Support/TranslationData.cs b/GreenshotConfluencePlugin/Support/TranslationData.cs index e9be13aff..287cca4c0 100644 --- a/GreenshotConfluencePlugin/Support/TranslationData.cs +++ b/GreenshotConfluencePlugin/Support/TranslationData.cs @@ -3,62 +3,55 @@ using System.ComponentModel; using System.Windows; namespace TranslationByMarkupExtension { - public class TranslationData : IWeakEventListener, INotifyPropertyChanged { - #region Private Members + public class TranslationData : IWeakEventListener, INotifyPropertyChanged { + #region Private Members - private readonly string _key; + private readonly string _key; - #endregion + #endregion - /// - /// Initializes a new instance of the class. - /// - /// The key. - public TranslationData( string key) { - _key = key; - LanguageChangedEventManager.AddListener(TranslationManager.Instance, this); - } + /// + /// Initializes a new instance of the class. + /// + /// The key. + public TranslationData( string key) { + _key = key; + LanguageChangedEventManager.AddListener(TranslationManager.Instance, this); + } - /// - /// Releases unmanaged resources and performs other cleanup operations before the - /// is reclaimed by garbage collection. - /// - ~TranslationData() { - LanguageChangedEventManager.RemoveListener(TranslationManager.Instance, this); - } + /// + /// Releases unmanaged resources and performs other cleanup operations before the + /// is reclaimed by garbage collection. + /// + ~TranslationData() { + LanguageChangedEventManager.RemoveListener(TranslationManager.Instance, this); + } - public object Value { - get { - return TranslationManager.Instance.Translate(_key); - } - } + public object Value => TranslationManager.Instance.Translate(_key); - #region IWeakEventListener Members + #region IWeakEventListener Members - public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e) - { - if (managerType == typeof(LanguageChangedEventManager)) - { - OnLanguageChanged(sender, e); - return true; - } - return false; - } + public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e) + { + if (managerType == typeof(LanguageChangedEventManager)) + { + OnLanguageChanged(sender, e); + return true; + } + return false; + } - private void OnLanguageChanged(object sender, EventArgs e) - { - if( PropertyChanged != null ) - { - PropertyChanged( this, new PropertyChangedEventArgs("Value")); - } - } + private void OnLanguageChanged(object sender, EventArgs e) + { + PropertyChanged?.Invoke( this, new PropertyChangedEventArgs("Value")); + } - #endregion + #endregion - #region INotifyPropertyChanged Members + #region INotifyPropertyChanged Members - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler PropertyChanged; - #endregion - } + #endregion + } } diff --git a/GreenshotConfluencePlugin/Support/TranslationManager.cs b/GreenshotConfluencePlugin/Support/TranslationManager.cs index 7e9516271..bf315a5d5 100644 --- a/GreenshotConfluencePlugin/Support/TranslationManager.cs +++ b/GreenshotConfluencePlugin/Support/TranslationManager.cs @@ -1,55 +1,45 @@ using System; namespace TranslationByMarkupExtension { - public class TranslationManager { - private static TranslationManager _translationManager; + public class TranslationManager { + private static TranslationManager _translationManager; - public event EventHandler LanguageChanged; + public event EventHandler LanguageChanged; - /*public CultureInfo CurrentLanguage { - get { return Thread.CurrentThread.CurrentUICulture; } - set { - if( value != Thread.CurrentThread.CurrentUICulture) { - Thread.CurrentThread.CurrentUICulture = value; - OnLanguageChanged(); - } - } - } - - public IEnumerable Languages { - get { - if( TranslationProvider != null) { - return TranslationProvider.Languages; - } - return Enumerable.Empty(); - } - }*/ - - public static TranslationManager Instance { - get { - if (_translationManager == null) { - _translationManager = new TranslationManager(); + /*public CultureInfo CurrentLanguage { + get { return Thread.CurrentThread.CurrentUICulture; } + set { + if( value != Thread.CurrentThread.CurrentUICulture) { + Thread.CurrentThread.CurrentUICulture = value; + OnLanguageChanged(); } - return _translationManager; - } - } + } + } - public ITranslationProvider TranslationProvider { get; set; } + public IEnumerable Languages { + get { + if( TranslationProvider != null) { + return TranslationProvider.Languages; + } + return Enumerable.Empty(); + } + }*/ - private void OnLanguageChanged() { - if (LanguageChanged != null) { - LanguageChanged(this, EventArgs.Empty); - } - } + public static TranslationManager Instance => _translationManager ?? (_translationManager = new TranslationManager()); - public object Translate(string key) { - if( TranslationProvider != null) { - object translatedValue = TranslationProvider.Translate(key); - if( translatedValue != null) { - return translatedValue; - } - } - return string.Format("!{0}!", key); - } - } + public ITranslationProvider TranslationProvider { get; set; } + + private void OnLanguageChanged() + { + LanguageChanged?.Invoke(this, EventArgs.Empty); + } + + public object Translate(string key) { + object translatedValue = TranslationProvider?.Translate(key); + if( translatedValue != null) { + return translatedValue; + } + return $"!{key}!"; + } + } } diff --git a/GreenshotDropboxPlugin/DropboxDestination.cs b/GreenshotDropboxPlugin/DropboxDestination.cs index 4faf9f9a1..1e378a7a1 100644 --- a/GreenshotDropboxPlugin/DropboxDestination.cs +++ b/GreenshotDropboxPlugin/DropboxDestination.cs @@ -23,27 +23,19 @@ using System.Drawing; using Greenshot.IniFile; using Greenshot.Plugin; using GreenshotPlugin.Core; + namespace GreenshotDropboxPlugin { internal class DropboxDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(DropboxDestination)); - private static readonly DropboxPluginConfiguration config = IniConfig.GetIniSection(); + private static readonly DropboxPluginConfiguration DropboxConfig = IniConfig.GetIniSection(); - private readonly DropboxPlugin plugin = null; + private readonly DropboxPlugin _plugin; public DropboxDestination(DropboxPlugin plugin) { - this.plugin = plugin; + _plugin = plugin; } - public override string Designation { - get { - return "Dropbox"; - } - } + public override string Designation => "Dropbox"; - public override string Description { - get { - return Language.GetString("dropbox", LangKey.upload_menu_item); - } - } + public override string Description => Language.GetString("dropbox", LangKey.upload_menu_item); public override Image DisplayIcon { get { @@ -55,11 +47,11 @@ namespace GreenshotDropboxPlugin { public override ExportInformation ExportCapture(bool manually, ISurface surface, ICaptureDetails captureDetails) { ExportInformation exportInformation = new ExportInformation(Designation, Description); string uploadUrl; - bool uploaded = plugin.Upload(captureDetails, surface, out uploadUrl); + bool uploaded = _plugin.Upload(captureDetails, surface, out uploadUrl); if (uploaded) { exportInformation.Uri = uploadUrl; exportInformation.ExportMade = true; - if (config.AfterUploadLinkToClipBoard) { + if (DropboxConfig.AfterUploadLinkToClipBoard) { ClipboardHelper.SetClipboardData(uploadUrl); } } diff --git a/GreenshotDropboxPlugin/DropboxPlugin.cs b/GreenshotDropboxPlugin/DropboxPlugin.cs index d6f9ab083..9bd6115c5 100644 --- a/GreenshotDropboxPlugin/DropboxPlugin.cs +++ b/GreenshotDropboxPlugin/DropboxPlugin.cs @@ -55,9 +55,6 @@ namespace GreenshotDropboxPlugin { } } - public DropboxPlugin() { - } - public IEnumerable Destinations() { yield return new DropboxDestination(this); } @@ -123,7 +120,8 @@ namespace GreenshotDropboxPlugin { try { string dropboxUrl = null; new PleaseWaitForm().ShowAndWait(Attributes.Name, Language.GetString("dropbox", LangKey.communication_wait), - delegate() { + delegate + { string filename = Path.GetFileName(FilenameHelper.GetFilename(_config.UploadFormat, captureDetails)); dropboxUrl = DropboxUtils.UploadToDropbox(surfaceToUpload, outputSettings, filename); } diff --git a/GreenshotDropboxPlugin/DropboxUtils.cs b/GreenshotDropboxPlugin/DropboxUtils.cs index 49237374f..f8a180f4c 100644 --- a/GreenshotDropboxPlugin/DropboxUtils.cs +++ b/GreenshotDropboxPlugin/DropboxUtils.cs @@ -30,36 +30,38 @@ namespace GreenshotDropboxPlugin { /// Description of DropboxUtils. /// public class DropboxUtils { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(DropboxUtils)); - private static readonly DropboxPluginConfiguration config = IniConfig.GetIniSection(); + private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(DropboxUtils)); + private static readonly DropboxPluginConfiguration DropboxConfig = IniConfig.GetIniSection(); private DropboxUtils() { } public static string UploadToDropbox(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string filename) { - OAuthSession oAuth = new OAuthSession(DropBoxCredentials.CONSUMER_KEY, DropBoxCredentials.CONSUMER_SECRET); - oAuth.BrowserSize = new Size(1080, 650); - oAuth.CheckVerifier = false; - oAuth.AccessTokenUrl = "https://api.dropbox.com/1/oauth/access_token"; - oAuth.AuthorizeUrl = "https://api.dropbox.com/1/oauth/authorize"; - oAuth.RequestTokenUrl = "https://api.dropbox.com/1/oauth/request_token"; - oAuth.LoginTitle = "Dropbox authorization"; - oAuth.Token = config.DropboxToken; - oAuth.TokenSecret = config.DropboxTokenSecret; + var oAuth = new OAuthSession(DropBoxCredentials.CONSUMER_KEY, DropBoxCredentials.CONSUMER_SECRET) + { + BrowserSize = new Size(1080, 650), + CheckVerifier = false, + AccessTokenUrl = "https://api.dropbox.com/1/oauth/access_token", + AuthorizeUrl = "https://api.dropbox.com/1/oauth/authorize", + RequestTokenUrl = "https://api.dropbox.com/1/oauth/request_token", + LoginTitle = "Dropbox authorization", + Token = DropboxConfig.DropboxToken, + TokenSecret = DropboxConfig.DropboxTokenSecret + }; try { SurfaceContainer imageToUpload = new SurfaceContainer(surfaceToUpload, outputSettings, filename); string uploadResponse = oAuth.MakeOAuthRequest(HTTPMethod.POST, "https://api-content.dropbox.com/1/files_put/sandbox/" + OAuthSession.UrlEncode3986(filename), null, null, imageToUpload); - LOG.DebugFormat("Upload response: {0}", uploadResponse); + Log.DebugFormat("Upload response: {0}", uploadResponse); } catch (Exception ex) { - LOG.Error("Upload error: ", ex); + Log.Error("Upload error: ", ex); throw; } finally { if (!string.IsNullOrEmpty(oAuth.Token)) { - config.DropboxToken = oAuth.Token; + DropboxConfig.DropboxToken = oAuth.Token; } if (!string.IsNullOrEmpty(oAuth.TokenSecret)) { - config.DropboxTokenSecret = oAuth.TokenSecret; + DropboxConfig.DropboxTokenSecret = oAuth.TokenSecret; } } @@ -67,16 +69,16 @@ namespace GreenshotDropboxPlugin { try { string responseString = oAuth.MakeOAuthRequest(HTTPMethod.GET, "https://api.dropbox.com/1/shares/sandbox/" + OAuthSession.UrlEncode3986(filename), null, null, null); if (responseString != null) { - LOG.DebugFormat("Parsing output: {0}", responseString); + Log.DebugFormat("Parsing output: {0}", responseString); IDictionary returnValues = JSONHelper.JsonDecode(responseString); if (returnValues.ContainsKey("url")) { return returnValues["url"] as string; } } } catch (Exception ex) { - LOG.Error("Can't parse response.", ex); + Log.Error("Can't parse response.", ex); } return null; - } + } } } diff --git a/GreenshotDropboxPlugin/Forms/SettingsForm.cs b/GreenshotDropboxPlugin/Forms/SettingsForm.cs index 62e6bf25f..d057b10dc 100644 --- a/GreenshotDropboxPlugin/Forms/SettingsForm.cs +++ b/GreenshotDropboxPlugin/Forms/SettingsForm.cs @@ -20,16 +20,12 @@ */ using GreenshotDropboxPlugin.Forms; -using Greenshot.IniFile; namespace GreenshotDropboxPlugin { /// /// Description of PasswordRequestForm. /// public partial class SettingsForm : DropboxForm { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(SettingsForm)); - private static DropboxPluginConfiguration config = IniConfig.GetIniSection(); - public SettingsForm() { // // The InitializeComponent() call is required for Windows Forms designer support. diff --git a/GreenshotExternalCommandPlugin/SettingsFormDetail.cs b/GreenshotExternalCommandPlugin/SettingsFormDetail.cs index dbe2aaf20..00a306a6d 100644 --- a/GreenshotExternalCommandPlugin/SettingsFormDetail.cs +++ b/GreenshotExternalCommandPlugin/SettingsFormDetail.cs @@ -31,8 +31,8 @@ namespace ExternalCommand { /// Description of SettingsFormDetail. /// public partial class SettingsFormDetail : ExternalCommandForm { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(SettingsFormDetail)); - private static readonly ExternalCommandConfiguration config = IniConfig.GetIniSection(); + private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(SettingsFormDetail)); + private static readonly ExternalCommandConfiguration ExternalCommandConfig = IniConfig.GetIniSection(); private readonly string _commando; private readonly int _commandIndex; @@ -45,9 +45,9 @@ namespace ExternalCommand { if(commando != null) { textBox_name.Text = commando; - textBox_commandline.Text = config.Commandline[commando]; - textBox_arguments.Text = config.Argument[commando]; - _commandIndex = config.Commands.FindIndex(delegate(string s) { return s == commando; }); + textBox_commandline.Text = ExternalCommandConfig.Commandline[commando]; + textBox_arguments.Text = ExternalCommandConfig.Argument[commando]; + _commandIndex = ExternalCommandConfig.Commands.FindIndex(s => s == commando); } else { textBox_arguments.Text = "\"{0}\""; } @@ -59,15 +59,15 @@ namespace ExternalCommand { string commandLine = textBox_commandline.Text; string arguments = textBox_arguments.Text; if(_commando != null) { - config.Commands[_commandIndex] = commandName; - config.Commandline.Remove(_commando); - config.Commandline.Add(commandName, commandLine); - config.Argument.Remove(_commando); - config.Argument.Add(commandName, arguments); + ExternalCommandConfig.Commands[_commandIndex] = commandName; + ExternalCommandConfig.Commandline.Remove(_commando); + ExternalCommandConfig.Commandline.Add(commandName, commandLine); + ExternalCommandConfig.Argument.Remove(_commando); + ExternalCommandConfig.Argument.Add(commandName, arguments); } else { - config.Commands.Add(commandName); - config.Commandline.Add(commandName, commandLine); - config.Argument.Add(commandName, arguments); + ExternalCommandConfig.Commands.Add(commandName); + ExternalCommandConfig.Commandline.Add(commandName, commandLine); + ExternalCommandConfig.Argument.Add(commandName, arguments); } } @@ -86,8 +86,8 @@ namespace ExternalCommand { } catch (Exception ex) { - LOG.WarnFormat("Can't get the initial path via {0}", textBox_commandline.Text); - LOG.Warn("Exception: ", ex); + Log.WarnFormat("Can't get the initial path via {0}", textBox_commandline.Text); + Log.Warn("Exception: ", ex); } if(initialPath != null && Directory.Exists(initialPath)) { openFileDialog.InitialDirectory = initialPath; @@ -95,7 +95,7 @@ namespace ExternalCommand { initialPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); openFileDialog.InitialDirectory = initialPath; } - LOG.DebugFormat("Starting OpenFileDialog at {0}", initialPath); + Log.DebugFormat("Starting OpenFileDialog at {0}", initialPath); if(openFileDialog.ShowDialog() == DialogResult.OK) { textBox_commandline.Text = openFileDialog.FileName; } @@ -112,7 +112,7 @@ namespace ExternalCommand { buttonOk.Enabled = false; } // Check if commandname is unique - if(_commando == null && !string.IsNullOrEmpty(textBox_name.Text) && config.Commands.Contains(textBox_name.Text)) { + if(_commando == null && !string.IsNullOrEmpty(textBox_name.Text) && ExternalCommandConfig.Commands.Contains(textBox_name.Text)) { buttonOk.Enabled = false; textBox_name.BackColor = Color.Red; } diff --git a/GreenshotFlickrPlugin/FlickrConfiguration.cs b/GreenshotFlickrPlugin/FlickrConfiguration.cs index 3a5a53433..0d6ad0574 100644 --- a/GreenshotFlickrPlugin/FlickrConfiguration.cs +++ b/GreenshotFlickrPlugin/FlickrConfiguration.cs @@ -70,7 +70,7 @@ namespace GreenshotFlickrPlugin { /// /// bool true if OK was pressed, false if cancel public bool ShowConfigDialog() { - DialogResult result = new SettingsForm(this).ShowDialog(); + DialogResult result = new SettingsForm().ShowDialog(); if (result == DialogResult.OK) { return true; } diff --git a/GreenshotFlickrPlugin/FlickrDestination.cs b/GreenshotFlickrPlugin/FlickrDestination.cs index 9edd0befe..70778e1f7 100644 --- a/GreenshotFlickrPlugin/FlickrDestination.cs +++ b/GreenshotFlickrPlugin/FlickrDestination.cs @@ -22,27 +22,17 @@ using System.ComponentModel; using System.Drawing; using Greenshot.Plugin; using GreenshotPlugin.Core; -using log4net; namespace GreenshotFlickrPlugin { public class FlickrDestination : AbstractDestination { - private static ILog LOG = LogManager.GetLogger(typeof(FlickrDestination)); - private readonly FlickrPlugin plugin; + private readonly FlickrPlugin _plugin; public FlickrDestination(FlickrPlugin plugin) { - this.plugin = plugin; + _plugin = plugin; } - public override string Designation { - get { - return "Flickr"; - } - } + public override string Designation => "Flickr"; - public override string Description { - get { - return Language.GetString("flickr", LangKey.upload_menu_item); - } - } + public override string Description => Language.GetString("flickr", LangKey.upload_menu_item); public override Image DisplayIcon { get { @@ -53,11 +43,11 @@ namespace GreenshotFlickrPlugin { public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { ExportInformation exportInformation = new ExportInformation(Designation, Description); - string uploadURL; - bool uploaded = plugin.Upload(captureDetails, surface, out uploadURL); + string uploadUrl; + bool uploaded = _plugin.Upload(captureDetails, surface, out uploadUrl); if (uploaded) { exportInformation.ExportMade = true; - exportInformation.Uri = uploadURL; + exportInformation.Uri = uploadUrl; } ProcessExport(exportInformation, surface); return exportInformation; diff --git a/GreenshotFlickrPlugin/FlickrPlugin.cs b/GreenshotFlickrPlugin/FlickrPlugin.cs index ea6866ead..5533ba643 100644 --- a/GreenshotFlickrPlugin/FlickrPlugin.cs +++ b/GreenshotFlickrPlugin/FlickrPlugin.cs @@ -37,7 +37,7 @@ namespace GreenshotFlickrPlugin /// This is the Flickr base code /// public class FlickrPlugin : IGreenshotPlugin { - private static readonly ILog LOG = LogManager.GetLogger(typeof(FlickrPlugin)); + private static readonly ILog Log = LogManager.GetLogger(typeof(FlickrPlugin)); private static FlickrConfiguration _config; public static PluginAttribute Attributes; private IGreenshotHost _host; @@ -83,10 +83,12 @@ namespace GreenshotFlickrPlugin _config = IniConfig.GetIniSection(); _resources = new ComponentResourceManager(typeof(FlickrPlugin)); - _itemPlugInConfig = new ToolStripMenuItem(); - _itemPlugInConfig.Text = Language.GetString("flickr", LangKey.Configure); - _itemPlugInConfig.Tag = _host; - _itemPlugInConfig.Image = (Image)_resources.GetObject("flickr"); + _itemPlugInConfig = new ToolStripMenuItem + { + Text = Language.GetString("flickr", LangKey.Configure), + Tag = _host, + Image = (Image) _resources.GetObject("flickr") + }; _itemPlugInConfig.Click += ConfigMenuClick; PluginUtils.AddToContextMenu(_host, _itemPlugInConfig); @@ -101,7 +103,7 @@ namespace GreenshotFlickrPlugin } public virtual void Shutdown() { - LOG.Debug("Flickr Plugin shutdown."); + Log.Debug("Flickr Plugin shutdown."); } /// @@ -137,7 +139,7 @@ namespace GreenshotFlickrPlugin } return true; } catch (Exception e) { - LOG.Error("Error uploading.", e); + Log.Error("Error uploading.", e); MessageBox.Show(Language.GetString("flickr", LangKey.upload_failure) + " " + e.Message); } return false; diff --git a/GreenshotFlickrPlugin/FlickrUtils.cs b/GreenshotFlickrPlugin/FlickrUtils.cs index 0cf84a58e..00cb56ed4 100644 --- a/GreenshotFlickrPlugin/FlickrUtils.cs +++ b/GreenshotFlickrPlugin/FlickrUtils.cs @@ -57,15 +57,17 @@ namespace GreenshotFlickrPlugin { /// /// url to image public static string UploadToFlickr(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string title, string filename) { - OAuthSession oAuth = new OAuthSession(FlickrCredentials.ConsumerKey, FlickrCredentials.ConsumerSecret); - oAuth.BrowserSize = new Size(520, 800); - oAuth.CheckVerifier = false; - oAuth.AccessTokenUrl = FLICKR_ACCESS_TOKEN_URL; - oAuth.AuthorizeUrl = FLICKR_AUTHORIZE_URL; - oAuth.RequestTokenUrl = FLICKR_REQUEST_TOKEN_URL; - oAuth.LoginTitle = "Flickr authorization"; - oAuth.Token = config.FlickrToken; - oAuth.TokenSecret = config.FlickrTokenSecret; + var oAuth = new OAuthSession(FlickrCredentials.ConsumerKey, FlickrCredentials.ConsumerSecret) + { + BrowserSize = new Size(520, 800), + CheckVerifier = false, + AccessTokenUrl = FLICKR_ACCESS_TOKEN_URL, + AuthorizeUrl = FLICKR_AUTHORIZE_URL, + RequestTokenUrl = FLICKR_REQUEST_TOKEN_URL, + LoginTitle = "Flickr authorization", + Token = config.FlickrToken, + TokenSecret = config.FlickrTokenSecret + }; if (string.IsNullOrEmpty(oAuth.Token)) { if (!oAuth.Authorize()) { return null; @@ -85,7 +87,7 @@ namespace GreenshotFlickrPlugin { signedParameters.Add("is_public", config.IsPublic ? "1" : "0"); signedParameters.Add("is_friend", config.IsFriend ? "1" : "0"); signedParameters.Add("is_family", config.IsFamily ? "1" : "0"); - signedParameters.Add("safety_level", string.Format("{0}", (int)config.SafetyLevel)); + signedParameters.Add("safety_level", $"{(int) config.SafetyLevel}"); signedParameters.Add("hidden", config.HiddenFromSearch ? "1" : "2"); IDictionary otherParameters = new Dictionary(); otherParameters.Add("photo", new SurfaceContainer(surfaceToUpload, outputSettings, filename)); @@ -125,16 +127,13 @@ namespace GreenshotFlickrPlugin { XmlNodeList nodes = doc.GetElementsByTagName("photo"); if (nodes.Count > 0) { var item = nodes.Item(0); - if (item != null) { - if (item.Attributes != null) { - string farmId = item.Attributes["farm"].Value; - string serverId = item.Attributes["server"].Value; - string photoId = item.Attributes["id"].Value; - string secret = item.Attributes["secret"].Value; - return string.Format(FLICKR_FARM_URL, farmId, serverId, photoId, secret); - } + if (item?.Attributes != null) { + string farmId = item.Attributes["farm"].Value; + string serverId = item.Attributes["server"].Value; + string photoId = item.Attributes["id"].Value; + string secret = item.Attributes["secret"].Value; + return string.Format(FLICKR_FARM_URL, farmId, serverId, photoId, secret); } - } } } catch (Exception ex) { diff --git a/GreenshotFlickrPlugin/Forms/SettingsForm.cs b/GreenshotFlickrPlugin/Forms/SettingsForm.cs index 874617db3..5c1e24551 100644 --- a/GreenshotFlickrPlugin/Forms/SettingsForm.cs +++ b/GreenshotFlickrPlugin/Forms/SettingsForm.cs @@ -26,9 +26,7 @@ namespace GreenshotFlickrPlugin { /// Description of PasswordRequestForm. /// public partial class SettingsForm : FlickrForm { - private string flickrFrob = string.Empty; - - public SettingsForm(FlickrConfiguration config) { + public SettingsForm() { // // The InitializeComponent() call is required for Windows Forms designer support. // diff --git a/GreenshotImgurPlugin/Forms/ImgurForm.cs b/GreenshotImgurPlugin/Forms/ImgurForm.cs index f74815e2b..00d3c01fd 100644 --- a/GreenshotImgurPlugin/Forms/ImgurForm.cs +++ b/GreenshotImgurPlugin/Forms/ImgurForm.cs @@ -26,7 +26,5 @@ namespace GreenshotImgurPlugin { /// This class is needed for design-time resolving of the language files /// public class ImgurForm : GreenshotForm { - public ImgurForm() : base() { - } } } diff --git a/GreenshotImgurPlugin/Forms/ImgurHistory.cs b/GreenshotImgurPlugin/Forms/ImgurHistory.cs index e8a8d4cba..4d67ab528 100644 --- a/GreenshotImgurPlugin/Forms/ImgurHistory.cs +++ b/GreenshotImgurPlugin/Forms/ImgurHistory.cs @@ -81,8 +81,10 @@ namespace GreenshotImgurPlugin { listview_imgur_uploads.Columns.Add(column); } foreach (ImgurInfo imgurInfo in Config.runtimeImgurHistory.Values) { - ListViewItem item = new ListViewItem(imgurInfo.Hash); - item.Tag = imgurInfo; + var item = new ListViewItem(imgurInfo.Hash) + { + Tag = imgurInfo + }; item.SubItems.Add(imgurInfo.Title); item.SubItems.Add(imgurInfo.DeleteHash); item.SubItems.Add(imgurInfo.Timestamp.ToString("yyyy-MM-dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo)); @@ -101,7 +103,7 @@ namespace GreenshotImgurPlugin { private void Listview_imgur_uploadsSelectedIndexChanged(object sender, EventArgs e) { pictureBox1.Image = pictureBox1.ErrorImage; - if (listview_imgur_uploads.SelectedItems != null && listview_imgur_uploads.SelectedItems.Count > 0) { + if (listview_imgur_uploads.SelectedItems.Count > 0) { deleteButton.Enabled = true; openButton.Enabled = true; clipboardButton.Enabled = true; @@ -118,25 +120,27 @@ namespace GreenshotImgurPlugin { } private void DeleteButtonClick(object sender, EventArgs e) { - if (listview_imgur_uploads.SelectedItems != null && listview_imgur_uploads.SelectedItems.Count > 0) { + if (listview_imgur_uploads.SelectedItems.Count > 0) { for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++) { ImgurInfo imgurInfo = (ImgurInfo)listview_imgur_uploads.SelectedItems[i].Tag; DialogResult result = MessageBox.Show(Language.GetFormattedString("imgur", LangKey.delete_question, imgurInfo.Title), Language.GetFormattedString("imgur", LangKey.delete_title, imgurInfo.Hash), MessageBoxButtons.YesNo, MessageBoxIcon.Question); - if (result == DialogResult.Yes) { - // Should fix Bug #3378699 - pictureBox1.Image = pictureBox1.ErrorImage; - try { - new PleaseWaitForm().ShowAndWait(ImgurPlugin.Attributes.Name, Language.GetString("imgur", LangKey.communication_wait), - delegate() { - ImgurUtils.DeleteImgurImage(imgurInfo); - } - ); - } catch (Exception ex) { - Log.Warn("Problem communicating with Imgur: ", ex); - } - - imgurInfo.Dispose(); + if (result != DialogResult.Yes) + { + continue; } + // Should fix Bug #3378699 + pictureBox1.Image = pictureBox1.ErrorImage; + try { + new PleaseWaitForm().ShowAndWait(ImgurPlugin.Attributes.Name, Language.GetString("imgur", LangKey.communication_wait), + delegate { + ImgurUtils.DeleteImgurImage(imgurInfo); + } + ); + } catch (Exception ex) { + Log.Warn("Problem communicating with Imgur: ", ex); + } + + imgurInfo.Dispose(); } } Redraw(); @@ -144,14 +148,11 @@ namespace GreenshotImgurPlugin { private void ClipboardButtonClick(object sender, EventArgs e) { StringBuilder links = new StringBuilder(); - if (listview_imgur_uploads.SelectedItems != null && listview_imgur_uploads.SelectedItems.Count > 0) { - for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++) { + if (listview_imgur_uploads.SelectedItems.Count > 0) { + for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++) + { ImgurInfo imgurInfo = (ImgurInfo)listview_imgur_uploads.SelectedItems[i].Tag; - if (Config.UsePageLink) { - links.AppendLine(imgurInfo.Page); - } else { - links.AppendLine(imgurInfo.Original); - } + links.AppendLine(Config.UsePageLink ? imgurInfo.Page : imgurInfo.Original); } } ClipboardHelper.SetClipboardData(links.ToString()); @@ -173,7 +174,7 @@ namespace GreenshotImgurPlugin { } private void OpenButtonClick(object sender, EventArgs e) { - if (listview_imgur_uploads.SelectedItems != null && listview_imgur_uploads.SelectedItems.Count > 0) { + if (listview_imgur_uploads.SelectedItems.Count > 0) { for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++) { ImgurInfo imgurInfo = (ImgurInfo)listview_imgur_uploads.SelectedItems[i].Tag; System.Diagnostics.Process.Start(imgurInfo.Page); @@ -185,11 +186,7 @@ namespace GreenshotImgurPlugin { // Determine if clicked column is already the column that is being sorted. if (e.Column == _columnSorter.SortColumn) { // Reverse the current sort direction for this column. - if (_columnSorter.Order == SortOrder.Ascending) { - _columnSorter.Order = SortOrder.Descending; - } else { - _columnSorter.Order = SortOrder.Ascending; - } + _columnSorter.Order = _columnSorter.Order == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending; } else { // Set the column number that is to be sorted; default to ascending. _columnSorter.SortColumn = e.Column; diff --git a/GreenshotImgurPlugin/Forms/SettingsForm.cs b/GreenshotImgurPlugin/Forms/SettingsForm.cs index dcf17fbf5..e7afda70c 100644 --- a/GreenshotImgurPlugin/Forms/SettingsForm.cs +++ b/GreenshotImgurPlugin/Forms/SettingsForm.cs @@ -25,7 +25,8 @@ namespace GreenshotImgurPlugin { /// Description of PasswordRequestForm. /// public partial class SettingsForm : ImgurForm { - public SettingsForm(ImgurConfiguration config) : base() { + public SettingsForm(ImgurConfiguration config) + { // // The InitializeComponent() call is required for Windows Forms designer support. // @@ -35,11 +36,7 @@ namespace GreenshotImgurPlugin { ImgurUtils.LoadHistory(); - if (config.runtimeImgurHistory.Count > 0) { - historyButton.Enabled = true; - } else { - historyButton.Enabled = false; - } + historyButton.Enabled = config.runtimeImgurHistory.Count > 0; } private void ButtonHistoryClick(object sender, EventArgs e) { diff --git a/GreenshotImgurPlugin/ImgurConfiguration.cs b/GreenshotImgurPlugin/ImgurConfiguration.cs index 2c010adb7..2889c9501 100644 --- a/GreenshotImgurPlugin/ImgurConfiguration.cs +++ b/GreenshotImgurPlugin/ImgurConfiguration.cs @@ -98,7 +98,7 @@ namespace GreenshotImgurPlugin { SettingsForm settingsForm = null; new PleaseWaitForm().ShowAndWait(ImgurPlugin.Attributes.Name, Language.GetString("imgur", LangKey.communication_wait), - delegate() { + delegate { settingsForm = new SettingsForm(this); } ); diff --git a/GreenshotImgurPlugin/ImgurDestination.cs b/GreenshotImgurPlugin/ImgurDestination.cs index f41425c76..030a6e81a 100644 --- a/GreenshotImgurPlugin/ImgurDestination.cs +++ b/GreenshotImgurPlugin/ImgurDestination.cs @@ -20,7 +20,6 @@ */ using System.ComponentModel; using System.Drawing; -using Greenshot.IniFile; using Greenshot.Plugin; using GreenshotPlugin.Core; @@ -29,25 +28,15 @@ namespace GreenshotImgurPlugin { /// Description of ImgurDestination. /// public class ImgurDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImgurDestination)); - private static ImgurConfiguration config = IniConfig.GetIniSection(); - private readonly ImgurPlugin plugin = null; + private readonly ImgurPlugin _plugin; public ImgurDestination(ImgurPlugin plugin) { - this.plugin = plugin; + _plugin = plugin; } - public override string Designation { - get { - return "Imgur"; - } - } + public override string Designation => "Imgur"; - public override string Description { - get { - return Language.GetString("imgur", LangKey.upload_menu_item); - } - } + public override string Description => Language.GetString("imgur", LangKey.upload_menu_item); public override Image DisplayIcon { get { @@ -59,7 +48,7 @@ namespace GreenshotImgurPlugin { public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { ExportInformation exportInformation = new ExportInformation(Designation, Description); string uploadUrl; - exportInformation.ExportMade = plugin.Upload(captureDetails, surface, out uploadUrl); + exportInformation.ExportMade = _plugin.Upload(captureDetails, surface, out uploadUrl); exportInformation.Uri = uploadUrl; ProcessExport(exportInformation, surface); return exportInformation; diff --git a/GreenshotImgurPlugin/ImgurInfo.cs b/GreenshotImgurPlugin/ImgurInfo.cs index c8e66cb35..61f16a17e 100644 --- a/GreenshotImgurPlugin/ImgurInfo.cs +++ b/GreenshotImgurPlugin/ImgurInfo.cs @@ -29,7 +29,7 @@ namespace GreenshotImgurPlugin /// public class ImgurInfo : IDisposable { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImgurInfo)); + private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ImgurInfo)); public string Hash { @@ -37,13 +37,13 @@ namespace GreenshotImgurPlugin set; } - private string deleteHash; + private string _deleteHash; public string DeleteHash { - get { return deleteHash; } + get { return _deleteHash; } set { - deleteHash = value; + _deleteHash = value; DeletePage = "https://imgur.com/delete/" + value; } } @@ -96,24 +96,17 @@ namespace GreenshotImgurPlugin set; } - private Image image; + private Image _image; public Image Image { - get { return image; } + get { return _image; } set { - if (image != null) - { - image.Dispose(); - } - image = value; + _image?.Dispose(); + _image = value; } } - public ImgurInfo() - { - } - /// /// The public accessible Dispose /// Will call the GarbageCollector to SuppressFinalize, preventing being cleaned twice @@ -133,16 +126,13 @@ namespace GreenshotImgurPlugin { if (disposing) { - if (image != null) - { - image.Dispose(); - } + _image?.Dispose(); } - image = null; + _image = null; } public static ImgurInfo ParseResponse(string response) { - LOG.Debug(response); + Log.Debug(response); // This is actually a hack for BUG-1695 // The problem is the (C) sign, we send it HTML encoded "®" to Imgur and get it HTML encoded in the XML back // Added all the encodings I found quickly, I guess these are not all... but it should fix the issue for now. @@ -161,34 +151,34 @@ namespace GreenshotImgurPlugin XmlNodeList nodes = doc.GetElementsByTagName("id"); if (nodes.Count > 0) { - imgurInfo.Hash = nodes.Item(0).InnerText; + imgurInfo.Hash = nodes.Item(0)?.InnerText; } nodes = doc.GetElementsByTagName("hash"); if (nodes.Count > 0) { - imgurInfo.Hash = nodes.Item(0).InnerText; + imgurInfo.Hash = nodes.Item(0)?.InnerText; } nodes = doc.GetElementsByTagName("deletehash"); if (nodes.Count > 0) { - imgurInfo.DeleteHash = nodes.Item(0).InnerText; + imgurInfo.DeleteHash = nodes.Item(0)?.InnerText; } nodes = doc.GetElementsByTagName("type"); if (nodes.Count > 0) { - imgurInfo.ImageType = nodes.Item(0).InnerText; + imgurInfo.ImageType = nodes.Item(0)?.InnerText; } nodes = doc.GetElementsByTagName("title"); if (nodes.Count > 0) { - imgurInfo.Title = nodes.Item(0).InnerText; + imgurInfo.Title = nodes.Item(0)?.InnerText; } nodes = doc.GetElementsByTagName("datetime"); if (nodes.Count > 0) { // Version 3 has seconds since Epoch double secondsSince; - if (double.TryParse(nodes.Item(0).InnerText, out secondsSince)) + if (double.TryParse(nodes.Item(0)?.InnerText, out secondsSince)) { var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); imgurInfo.Timestamp = epoch.AddSeconds(secondsSince).DateTime; @@ -197,37 +187,30 @@ namespace GreenshotImgurPlugin nodes = doc.GetElementsByTagName("original"); if (nodes.Count > 0) { - imgurInfo.Original = nodes.Item(0).InnerText.Replace("http:", "https:"); + imgurInfo.Original = nodes.Item(0)?.InnerText.Replace("http:", "https:"); } // Version 3 API only has Link nodes = doc.GetElementsByTagName("link"); if (nodes.Count > 0) { - imgurInfo.Original = nodes.Item(0).InnerText.Replace("http:", "https:"); + imgurInfo.Original = nodes.Item(0)?.InnerText.Replace("http:", "https:"); } nodes = doc.GetElementsByTagName("imgur_page"); if (nodes.Count > 0) { - imgurInfo.Page = nodes.Item(0).InnerText.Replace("http:", "https:"); + imgurInfo.Page = nodes.Item(0)?.InnerText.Replace("http:", "https:"); } else { // Version 3 doesn't have a page link in the response - imgurInfo.Page = string.Format("https://imgur.com/{0}", imgurInfo.Hash); + imgurInfo.Page = $"https://imgur.com/{imgurInfo.Hash}"; } nodes = doc.GetElementsByTagName("small_square"); - if (nodes.Count > 0) - { - imgurInfo.SmallSquare = nodes.Item(0).InnerText; - } - else - { - imgurInfo.SmallSquare = string.Format("http://i.imgur.com/{0}s.png",imgurInfo.Hash); - } + imgurInfo.SmallSquare = nodes.Count > 0 ? nodes.Item(0)?.InnerText : $"http://i.imgur.com/{imgurInfo.Hash}s.png"; } catch (Exception e) { - LOG.ErrorFormat("Could not parse Imgur response due to error {0}, response was: {1}", e.Message, response); + Log.ErrorFormat("Could not parse Imgur response due to error {0}, response was: {1}", e.Message, response); } return imgurInfo; } diff --git a/GreenshotImgurPlugin/ImgurPlugin.cs b/GreenshotImgurPlugin/ImgurPlugin.cs index 895c482fd..93b8ede40 100644 --- a/GreenshotImgurPlugin/ImgurPlugin.cs +++ b/GreenshotImgurPlugin/ImgurPlugin.cs @@ -61,9 +61,6 @@ namespace GreenshotImgurPlugin { } } - public ImgurPlugin() { - } - public IEnumerable Destinations() { yield return new ImgurDestination(this); } diff --git a/GreenshotJiraPlugin/JiraDestination.cs b/GreenshotJiraPlugin/JiraDestination.cs index f45859841..1b35e6fde 100644 --- a/GreenshotJiraPlugin/JiraDestination.cs +++ b/GreenshotJiraPlugin/JiraDestination.cs @@ -65,9 +65,9 @@ namespace GreenshotJiraPlugin { } } - public override bool isActive => base.isActive && !string.IsNullOrEmpty(Config.Url); + public override bool IsActive => base.IsActive && !string.IsNullOrEmpty(Config.Url); - public override bool isDynamic => true; + public override bool IsDynamic => true; public override Image DisplayIcon { get diff --git a/GreenshotJiraPlugin/JiraPlugin.cs b/GreenshotJiraPlugin/JiraPlugin.cs index b61bbe907..cf888d5d8 100644 --- a/GreenshotJiraPlugin/JiraPlugin.cs +++ b/GreenshotJiraPlugin/JiraPlugin.cs @@ -23,13 +23,10 @@ using System.Windows.Forms; using Greenshot.IniFile; using Greenshot.Plugin; using System; -using System.Drawing; -using System.Drawing.Imaging; using System.Threading.Tasks; using Dapplo.Log.Facade; using GreenshotJiraPlugin.Forms; using GreenshotPlugin.Core; -using Svg; namespace GreenshotJiraPlugin { /// diff --git a/GreenshotOCRCommand/COMWrapper.cs b/GreenshotOCRCommand/COMWrapper.cs index 5b3624460..67ef5fad9 100644 --- a/GreenshotOCRCommand/COMWrapper.cs +++ b/GreenshotOCRCommand/COMWrapper.cs @@ -316,13 +316,9 @@ namespace Greenshot.Interop { /// public override IMessage Invoke(IMessage myMessage) { IMethodCallMessage callMessage = myMessage as IMethodCallMessage; - if (null == callMessage) { - //LOG.DebugFormat("Message type not implemented: {0}", myMessage.GetType().ToString()); - return null; - } - MethodInfo method = callMessage.MethodBase as MethodInfo; - if (null == method) { + MethodInfo method = callMessage?.MethodBase as MethodInfo; + if (method == null) { //LOG.DebugFormat("Unrecognized Invoke call: {0}", callMessage.MethodBase.ToString()); return null; } @@ -336,18 +332,8 @@ namespace Greenshot.Interop { BindingFlags flags = BindingFlags.InvokeMethod; int argCount = callMessage.ArgCount; - object invokeObject; - Type invokeType; - Type byValType; - - object[] args; - object arg; - COMWrapper[] originalArgs; - COMWrapper wrapper; - ParameterModifier[] argModifiers = null; ParameterInfo[] parameters = null; - ParameterInfo parameter; if ("Dispose" == methodName && 0 == argCount && typeof(void) == returnType) { Dispose(); @@ -365,9 +351,11 @@ namespace Greenshot.Interop { return new ReturnMessage(new ArgumentNullException(nameof(handler)), callMessage); } } else { - invokeObject = _comObject; - invokeType = _comType; + var invokeObject = _comObject; + var invokeType = _comType; + ParameterInfo parameter; + object[] args; if (methodName.StartsWith("get_")) { // Property Get methodName = methodName.Substring(4); @@ -401,6 +389,9 @@ namespace Greenshot.Interop { } // Un-wrap wrapped COM objects before passing to the method + COMWrapper[] originalArgs; + COMWrapper wrapper; + Type byValType; if (null == args || 0 == args.Length) { originalArgs = null; } else { @@ -412,7 +403,7 @@ namespace Greenshot.Interop { originalArgs[i] = wrapper; args[i] = wrapper._comObject; } - } else if (0 != outArgsCount && argModifiers[0][i]) { + } else if (argModifiers != null && (0 != outArgsCount && argModifiers[0][i])) { byValType = GetByValType(parameters[i].ParameterType); if (byValType.IsInterface) { // If we're passing a COM object by reference, and @@ -453,42 +444,48 @@ namespace Greenshot.Interop { // Handle out args if (0 != outArgsCount) { - outArgs = new object[args.Length]; - for (int i = 0; i < parameters.Length; i++) { - if (!argModifiers[0][i]) { - continue; - } - - arg = args[i]; - if (null == arg) { - continue; - } - - parameter = parameters[i]; - wrapper = null; - - byValType = GetByValType(parameter.ParameterType); - if (typeof(decimal) == byValType) { - if (arg is CurrencyWrapper) { - arg = ((CurrencyWrapper)arg).WrappedObject; + if (args != null && parameters != null) + { + outArgs = new object[args.Length]; + for (int i = 0; i < parameters.Length; i++) { + if (argModifiers != null && !argModifiers[0][i]) { + continue; } - } else if (byValType.IsEnum) { - arg = Enum.Parse(byValType, arg.ToString()); - } else if (byValType.IsInterface) { - if (Marshal.IsComObject(arg)) { - wrapper = originalArgs[i]; - if (null != wrapper && wrapper._comObject != arg) { - wrapper.Dispose(); - wrapper = null; - } - if (null == wrapper) { - wrapper = new COMWrapper(arg, byValType); - } - arg = wrapper.GetTransparentProxy(); + var arg = args[i]; + if (null == arg) { + continue; } + + parameter = parameters[i]; + wrapper = null; + + byValType = GetByValType(parameter.ParameterType); + if (typeof(decimal) == byValType) { + if (arg is CurrencyWrapper) { + arg = ((CurrencyWrapper)arg).WrappedObject; + } + } else if (byValType.IsEnum) { + arg = Enum.Parse(byValType, arg.ToString()); + } else if (byValType.IsInterface) { + if (Marshal.IsComObject(arg)) { + if (originalArgs != null) + { + wrapper = originalArgs[i]; + } + if (null != wrapper && wrapper._comObject != arg) { + wrapper.Dispose(); + wrapper = null; + } + + if (null == wrapper) { + wrapper = new COMWrapper(arg, byValType); + } + arg = wrapper.GetTransparentProxy(); + } + } + outArgs[i] = arg; } - outArgs[i] = arg; } } } diff --git a/GreenshotOCRCommand/ComProgIdAttribute.cs b/GreenshotOCRCommand/ComProgIdAttribute.cs index 9f806c679..893db2fcb 100644 --- a/GreenshotOCRCommand/ComProgIdAttribute.cs +++ b/GreenshotOCRCommand/ComProgIdAttribute.cs @@ -24,10 +24,8 @@ namespace Greenshot.Interop { /// /// An attribute to specifiy the ProgID of the COM class to create. (As suggested by Kristen Wegner) /// - [AttributeUsage(AttributeTargets.Interface, Inherited = false, AllowMultiple = false)] + [AttributeUsage(AttributeTargets.Interface)] public sealed class ComProgIdAttribute : Attribute { - private readonly string _value; - /// /// Extracts the attribute from the specified type. /// @@ -42,24 +40,24 @@ namespace Greenshot.Interop { /// public static ComProgIdAttribute GetAttribute(Type interfaceType) { if (null == interfaceType) { - throw new ArgumentNullException("interfaceType"); + throw new ArgumentNullException(nameof(interfaceType)); } Type attributeType = typeof(ComProgIdAttribute); object[] attributes = interfaceType.GetCustomAttributes(attributeType, false); - if (null == attributes || 0 == attributes.Length) { + if (0 == attributes.Length) { Type[] interfaces = interfaceType.GetInterfaces(); for (int i = 0; i < interfaces.Length; i++) { interfaceType = interfaces[i]; attributes = interfaceType.GetCustomAttributes(attributeType, false); - if (null != attributes && 0 != attributes.Length) { + if (0 != attributes.Length) { break; } } } - if (null == attributes || 0 == attributes.Length) { + if (0 == attributes.Length) { return null; } return (ComProgIdAttribute)attributes[0]; @@ -68,16 +66,12 @@ namespace Greenshot.Interop { /// Constructor /// The COM ProgID. public ComProgIdAttribute(string value) { - _value = value; + Value = value; } /// /// Returns the COM ProgID /// - public string Value { - get { - return _value; - } - } + public string Value { get; } } } diff --git a/GreenshotOCRPlugin/OCRDestination.cs b/GreenshotOCRPlugin/OCRDestination.cs index d5388ee84..69503cc3b 100644 --- a/GreenshotOCRPlugin/OCRDestination.cs +++ b/GreenshotOCRPlugin/OCRDestination.cs @@ -20,7 +20,6 @@ */ using System.Drawing; using System.IO; -using Greenshot.IniFile; using Greenshot.Plugin; using GreenshotPlugin.Core; @@ -29,23 +28,11 @@ namespace GreenshotOCR { /// Description of OCRDestination. /// public class OCRDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(OCRDestination)); - private static OCRConfiguration config = IniConfig.GetIniSection(); - private const int MIN_WIDTH = 130; - private const int MIN_HEIGHT = 130; - private readonly OcrPlugin plugin; + private readonly OcrPlugin _plugin; - public override string Designation { - get { - return "OCR"; - } - } + public override string Designation => "OCR"; - public override string Description { - get { - return "OCR"; - } - } + public override string Description => "OCR"; public override Image DisplayIcon { get { @@ -58,12 +45,14 @@ namespace GreenshotOCR { } public OCRDestination(OcrPlugin plugin) { - this.plugin = plugin; + _plugin = plugin; } public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { - ExportInformation exportInformation = new ExportInformation(Designation, Description); - exportInformation.ExportMade = plugin.DoOCR(surface) != null; + ExportInformation exportInformation = new ExportInformation(Designation, Description) + { + ExportMade = _plugin.DoOcr(surface) != null + }; return exportInformation; } } diff --git a/GreenshotOCRPlugin/OCRForm.cs b/GreenshotOCRPlugin/OCRForm.cs index 9be31a48e..468b31bac 100644 --- a/GreenshotOCRPlugin/OCRForm.cs +++ b/GreenshotOCRPlugin/OCRForm.cs @@ -25,8 +25,6 @@ namespace GreenshotOCR { /// /// This class is needed for design-time resolving of the language files /// - public class OCRForm : GreenshotForm { - public OCRForm() : base() { - } + public class OcrForm : GreenshotForm { } } diff --git a/GreenshotOCRPlugin/OCRPlugin.cs b/GreenshotOCRPlugin/OCRPlugin.cs index 745003da4..65ae39723 100644 --- a/GreenshotOCRPlugin/OCRPlugin.cs +++ b/GreenshotOCRPlugin/OCRPlugin.cs @@ -27,6 +27,7 @@ using Greenshot.IniFile; using Greenshot.Plugin; using GreenshotPlugin.Core; using Greenshot.Core; +using GreenshotPlugin.Effects; //using Microsoft.Win32; @@ -60,13 +61,11 @@ namespace GreenshotOCR { /// OCR Plugin Greenshot /// public class OcrPlugin : IGreenshotPlugin { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(OcrPlugin)); - private const string CONFIG_FILENAME = "ocr-config.properties"; - private string OCR_COMMAND; - private static IGreenshotHost host; + private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(OcrPlugin)); + private string _ocrCommand; private static OCRConfiguration config; - private PluginAttribute myAttributes; - private ToolStripMenuItem ocrMenuItem = new ToolStripMenuItem(); + private PluginAttribute _myAttributes; + private ToolStripMenuItem _ocrMenuItem = new ToolStripMenuItem(); public void Dispose() { Dispose(true); @@ -75,15 +74,13 @@ namespace GreenshotOCR { protected virtual void Dispose(bool disposing) { if (disposing) { - if (ocrMenuItem != null) { - ocrMenuItem.Dispose(); - ocrMenuItem = null; + if (_ocrMenuItem != null) { + _ocrMenuItem.Dispose(); + _ocrMenuItem = null; } } } - public OcrPlugin() { } - public IEnumerable Destinations() { yield return new OCRDestination(this); } @@ -98,14 +95,18 @@ namespace GreenshotOCR { /// My own attributes /// true if plugin is initialized, false if not (doesn't show) public virtual bool Initialize(IGreenshotHost greenshotHost, PluginAttribute myAttributes) { - LOG.Debug("Initialize called of " + myAttributes.Name); - host = greenshotHost; - this.myAttributes = myAttributes; - - OCR_COMMAND = Path.Combine(Path.GetDirectoryName(myAttributes.DllFile), "greenshotocrcommand.exe"); + Log.Debug("Initialize called of " + myAttributes.Name); + _myAttributes = myAttributes; - if (!HasMODI()) { - LOG.Warn("No MODI found!"); + var ocrDirectory = Path.GetDirectoryName(myAttributes.DllFile); + if (ocrDirectory == null) + { + return false; + } + _ocrCommand = Path.Combine(ocrDirectory, "greenshotocrcommand.exe"); + + if (!HasModi()) { + Log.Warn("No MODI found!"); return false; } // Load configuration @@ -121,14 +122,14 @@ namespace GreenshotOCR { /// Implementation of the IGreenshotPlugin.Shutdown /// public void Shutdown() { - LOG.Debug("Shutdown of " + myAttributes.Name); + Log.Debug("Shutdown of " + _myAttributes.Name); } /// /// Implementation of the IPlugin.Configure /// public virtual void Configure() { - if (!HasMODI()) { + if (!HasModi()) { MessageBox.Show("Sorry, is seems that Microsoft Office Document Imaging (MODI) is not installed, therefor the OCR Plugin cannot work."); return; } @@ -141,62 +142,68 @@ namespace GreenshotOCR { } + private const int MinWidth = 130; + private const int MinHeight = 130; /// /// Handling of the CaptureTaken "event" from the ICaptureHost /// We do the OCR here! /// - /// Has the Image and the capture details - private const int MIN_WIDTH = 130; - private const int MIN_HEIGHT = 130; - public string DoOCR(ISurface surface) { - string filePath = null; - SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(OutputFormat.bmp, 0, true); - outputSettings.ReduceColors = true; + /// Has the Image and the capture details + public string DoOcr(ISurface surface) { + SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(OutputFormat.bmp, 0, true) + { + ReduceColors = true, + SaveBackgroundOnly = true + }; // We only want the background - outputSettings.SaveBackgroundOnly = true; // Force Grayscale output outputSettings.Effects.Add(new GrayscaleEffect()); // Also we need to check the size, resize if needed to 130x130 this is the minimum - if (surface.Image.Width < MIN_WIDTH || surface.Image.Height < MIN_HEIGHT) { - int addedWidth = MIN_WIDTH - surface.Image.Width; + if (surface.Image.Width < MinWidth || surface.Image.Height < MinHeight) { + int addedWidth = MinWidth - surface.Image.Width; if (addedWidth < 0) { addedWidth = 0; } - int addedHeight = MIN_HEIGHT - surface.Image.Height; + int addedHeight = MinHeight - surface.Image.Height; if (addedHeight < 0) { addedHeight = 0; } IEffect effect = new ResizeCanvasEffect(addedWidth / 2, addedWidth / 2, addedHeight / 2, addedHeight / 2); outputSettings.Effects.Add(effect); } - filePath = ImageOutput.SaveToTmpFile(surface, outputSettings, null); + var filePath = ImageOutput.SaveToTmpFile(surface, outputSettings, null); - LOG.Debug("Saved tmp file to: " + filePath); + Log.Debug("Saved tmp file to: " + filePath); string text = ""; try { - ProcessStartInfo processStartInfo = new ProcessStartInfo(OCR_COMMAND, "\"" + filePath + "\" " + config.Language + " " + config.Orientimage + " " + config.StraightenImage); - processStartInfo.CreateNoWindow = true; - processStartInfo.RedirectStandardOutput = true; - processStartInfo.UseShellExecute = false; + ProcessStartInfo processStartInfo = new ProcessStartInfo(_ocrCommand, "\"" + filePath + "\" " + config.Language + " " + config.Orientimage + " " + config.StraightenImage) + { + CreateNoWindow = true, + RedirectStandardOutput = true, + UseShellExecute = false + }; using (Process process = Process.Start(processStartInfo)) { - process.WaitForExit(30 * 1000); - if (process.ExitCode == 0) { - text = process.StandardOutput.ReadToEnd(); + if (process != null) + { + process.WaitForExit(30 * 1000); + if (process.ExitCode == 0) { + text = process.StandardOutput.ReadToEnd(); + } } } } catch (Exception e) { - LOG.Error("Error while calling Microsoft Office Document Imaging (MODI) to OCR: ", e); + Log.Error("Error while calling Microsoft Office Document Imaging (MODI) to OCR: ", e); } finally { if (File.Exists(filePath)) { - LOG.Debug("Cleaning up tmp file: " + filePath); + Log.Debug("Cleaning up tmp file: " + filePath); File.Delete(filePath); } } - if (text == null || text.Trim().Length == 0) { - LOG.Info("No text returned"); + if (string.IsNullOrEmpty(text)) { + Log.Info("No text returned"); return null; } @@ -204,27 +211,30 @@ namespace GreenshotOCR { text = text.Trim(); try { - LOG.DebugFormat("Pasting OCR Text to Clipboard: {0}", text); + Log.DebugFormat("Pasting OCR Text to Clipboard: {0}", text); // Paste to Clipboard (the Plugin currently doesn't have access to the ClipboardHelper from Greenshot IDataObject ido = new DataObject(); ido.SetData(DataFormats.Text, true, text); Clipboard.SetDataObject(ido, true); } catch (Exception e) { - LOG.Error("Problem pasting text to clipboard: ", e); + Log.Error("Problem pasting text to clipboard: ", e); } return text; } - private bool HasMODI() { + private bool HasModi() { try { - using (Process process = Process.Start(OCR_COMMAND, "-c")) { - process.WaitForExit(); - return process.ExitCode == 0; + using (Process process = Process.Start(_ocrCommand, "-c")) { + if (process != null) + { + process.WaitForExit(); + return process.ExitCode == 0; + } } } catch(Exception e) { - LOG.DebugFormat("Error trying to initiate MODI: {0}", e.Message); + Log.DebugFormat("Error trying to initiate MODI: {0}", e.Message); } - LOG.InfoFormat("No Microsoft Office Document Imaging (MODI) found, disabling OCR"); + Log.InfoFormat("No Microsoft Office Document Imaging (MODI) found, disabling OCR"); return false; } } diff --git a/GreenshotOCRPlugin/SettingsForm.cs b/GreenshotOCRPlugin/SettingsForm.cs index 871da209e..e63ca4eb2 100644 --- a/GreenshotOCRPlugin/SettingsForm.cs +++ b/GreenshotOCRPlugin/SettingsForm.cs @@ -24,7 +24,7 @@ namespace GreenshotOCR { /// /// Description of SettingsForm. /// - public partial class SettingsForm : OCRForm { + public partial class SettingsForm : OcrForm { private readonly OCRConfiguration config; public SettingsForm(string [] languages, OCRConfiguration config) { diff --git a/GreenshotOfficePlugin/Destinations/ExcelDestination.cs b/GreenshotOfficePlugin/Destinations/ExcelDestination.cs index 2da9e79fc..caa0bc37a 100644 --- a/GreenshotOfficePlugin/Destinations/ExcelDestination.cs +++ b/GreenshotOfficePlugin/Destinations/ExcelDestination.cs @@ -32,18 +32,17 @@ namespace GreenshotOfficePlugin { /// Description of PowerpointDestination. /// public class ExcelDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ExcelDestination)); - private const int ICON_APPLICATION = 0; - private const int ICON_WORKBOOK = 1; - private static readonly string exePath = null; - private readonly string workbookName = null; + private const int IconApplication = 0; + private const int IconWorkbook = 1; + private static readonly string ExePath; + private readonly string _workbookName; static ExcelDestination() { - exePath = PluginUtils.GetExePath("EXCEL.EXE"); - if (exePath != null && File.Exists(exePath)) { + ExePath = PluginUtils.GetExePath("EXCEL.EXE"); + if (ExePath != null && File.Exists(ExePath)) { WindowDetails.AddProcessToExcludeFromFreeze("excel"); } else { - exePath = null; + ExePath = null; } } @@ -51,51 +50,20 @@ namespace GreenshotOfficePlugin { } public ExcelDestination(string workbookName) { - this.workbookName = workbookName; + _workbookName = workbookName; } - public override string Designation { - get { - return "Excel"; - } - } + public override string Designation => "Excel"; - public override string Description { - get { - if (workbookName == null) { - return "Microsoft Excel"; - } else { - return workbookName; - } - } - } + public override string Description => _workbookName ?? "Microsoft Excel"; - public override int Priority { - get { - return 5; - } - } - - public override bool isDynamic { - get { - return true; - } - } + public override int Priority => 5; - public override bool isActive { - get { - return base.isActive && exePath != null; - } - } + public override bool IsDynamic => true; - public override Image DisplayIcon { - get { - if (!string.IsNullOrEmpty(workbookName)) { - return PluginUtils.GetCachedExeIcon(exePath, ICON_WORKBOOK); - } - return PluginUtils.GetCachedExeIcon(exePath, ICON_APPLICATION); - } - } + public override bool IsActive => base.IsActive && ExePath != null; + + public override Image DisplayIcon => PluginUtils.GetCachedExeIcon(ExePath, !string.IsNullOrEmpty(_workbookName) ? IconWorkbook : IconApplication); public override IEnumerable DynamicDestinations() { foreach (string workbookName in ExcelExporter.GetWorkbooks()) { @@ -111,8 +79,8 @@ namespace GreenshotOfficePlugin { imageFile = ImageOutput.SaveNamedTmpFile(surface, captureDetails, new SurfaceOutputSettings().PreventGreenshotFormat()); createdFile = true; } - if (workbookName != null) { - ExcelExporter.InsertIntoExistingWorkbook(workbookName, imageFile, surface.Image.Size); + if (_workbookName != null) { + ExcelExporter.InsertIntoExistingWorkbook(_workbookName, imageFile, surface.Image.Size); } else { ExcelExporter.InsertIntoNewWorkbook(imageFile, surface.Image.Size); } diff --git a/GreenshotOfficePlugin/Destinations/OneNoteDestination.cs b/GreenshotOfficePlugin/Destinations/OneNoteDestination.cs index a6656c3f3..e6b677596 100644 --- a/GreenshotOfficePlugin/Destinations/OneNoteDestination.cs +++ b/GreenshotOfficePlugin/Destinations/OneNoteDestination.cs @@ -32,8 +32,8 @@ namespace GreenshotOfficePlugin { private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(WordDestination)); private const int ICON_APPLICATION = 0; public const string DESIGNATION = "OneNote"; - private static readonly string exePath = null; - private readonly OneNotePage page = null; + private static readonly string exePath; + private readonly OneNotePage page; static OneNoteDestination() { exePath = PluginUtils.GetExePath("ONENOTE.EXE"); @@ -74,15 +74,15 @@ namespace GreenshotOfficePlugin { } } - public override bool isDynamic { + public override bool IsDynamic { get { return true; } } - public override bool isActive { + public override bool IsActive { get { - return base.isActive && exePath != null; + return base.IsActive && exePath != null; } } diff --git a/GreenshotOfficePlugin/Destinations/OutlookDestination.cs b/GreenshotOfficePlugin/Destinations/OutlookDestination.cs index 6c8c81848..6474eb844 100644 --- a/GreenshotOfficePlugin/Destinations/OutlookDestination.cs +++ b/GreenshotOfficePlugin/Destinations/OutlookDestination.cs @@ -34,31 +34,30 @@ namespace GreenshotOfficePlugin { /// Description of OutlookDestination. /// public class OutlookDestination : AbstractDestination { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(OutlookDestination)); - private const int ICON_APPLICATION = 0; - private const int ICON_MEETING = 2; + private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(OutlookDestination)); + private const int IconApplication = 0; + private const int IconMeeting = 2; - private static readonly Image mailIcon = GreenshotResources.getImage("Email.Image"); - private static readonly OfficeConfiguration conf = IniConfig.GetIniSection(); - private static readonly string exePath = null; - private static readonly bool isActiveFlag = false; - private static readonly string mapiClient = "Microsoft Outlook"; - public const string DESIGNATION = "Outlook"; - private readonly string outlookInspectorCaption; - private readonly OlObjectClass outlookInspectorType; + private static readonly Image MailIcon = GreenshotResources.getImage("Email.Image"); + private static readonly OfficeConfiguration OfficeConfig = IniConfig.GetIniSection(); + private static readonly string ExePath; + private static readonly bool IsActiveFlag; + private const string MapiClient = "Microsoft Outlook"; + private readonly string _outlookInspectorCaption; + private readonly OlObjectClass _outlookInspectorType; static OutlookDestination() { if (EmailConfigHelper.HasOutlook()) { - isActiveFlag = true; + IsActiveFlag = true; } - exePath = PluginUtils.GetExePath("OUTLOOK.EXE"); - if (exePath != null && File.Exists(exePath)) { + ExePath = PluginUtils.GetExePath("OUTLOOK.EXE"); + if (ExePath != null && File.Exists(ExePath)) { WindowDetails.AddProcessToExcludeFromFreeze("outlook"); } else { - exePath = null; + ExePath = null; } - if (exePath == null) { - isActiveFlag = false; + if (ExePath == null) { + IsActiveFlag = false; } } @@ -66,62 +65,34 @@ namespace GreenshotOfficePlugin { } public OutlookDestination(string outlookInspectorCaption, OlObjectClass outlookInspectorType) { - this.outlookInspectorCaption = outlookInspectorCaption; - this.outlookInspectorType = outlookInspectorType; + _outlookInspectorCaption = outlookInspectorCaption; + _outlookInspectorType = outlookInspectorType; } - public override string Designation { - get { - return DESIGNATION; - } - } + public override string Designation => "Outlook"; - public override string Description { - get { - if (outlookInspectorCaption == null) { - return mapiClient; - } else { - return outlookInspectorCaption; - } - } - } + public override string Description => _outlookInspectorCaption ?? MapiClient; - public override int Priority { - get { - return 3; - } - } + public override int Priority => 3; - public override bool isActive { - get { - return base.isActive && isActiveFlag; - } - } + public override bool IsActive => base.IsActive && IsActiveFlag; - public override bool isDynamic { - get { - return true; - } - } + public override bool IsDynamic => true; - public override Keys EditorShortcutKeys { - get { - return Keys.Control | Keys.E; - } - } + public override Keys EditorShortcutKeys => Keys.Control | Keys.E; public override Image DisplayIcon { - get { - if (outlookInspectorCaption != null) { - if (OlObjectClass.olAppointment.Equals(outlookInspectorType)) { - // Make sure we loaded the icon, maybe the configuration has been changed! - return PluginUtils.GetCachedExeIcon(exePath, ICON_MEETING); - } else { - return mailIcon; - } - } else { - return PluginUtils.GetCachedExeIcon(exePath, ICON_APPLICATION); + get + { + if (_outlookInspectorCaption == null) + { + return PluginUtils.GetCachedExeIcon(ExePath, IconApplication); } + if (OlObjectClass.olAppointment.Equals(_outlookInspectorType)) { + // Make sure we loaded the icon, maybe the configuration has been changed! + return PluginUtils.GetCachedExeIcon(ExePath, IconMeeting); + } + return MailIcon; } } @@ -148,7 +119,7 @@ namespace GreenshotOfficePlugin { if (tmpFile == null || surface.Modified || !Regex.IsMatch(tmpFile, @".*(\.png|\.gif|\.jpg|\.jpeg|\.tiff|\.bmp)$")) { tmpFile = ImageOutput.SaveNamedTmpFile(surface, captureDetails, new SurfaceOutputSettings().PreventGreenshotFormat()); } else { - LOG.InfoFormat("Using already available file: {0}", tmpFile); + Log.InfoFormat("Using already available file: {0}", tmpFile); } // Create a attachment name for the image @@ -163,15 +134,17 @@ namespace GreenshotOfficePlugin { // Make sure it's "clean" so it doesn't corrupt the header attachmentName = Regex.Replace(attachmentName, @"[^\x20\d\w]", ""); - if (outlookInspectorCaption != null) { - OutlookEmailExporter.ExportToInspector(outlookInspectorCaption, tmpFile, attachmentName); + if (_outlookInspectorCaption != null) { + OutlookEmailExporter.ExportToInspector(_outlookInspectorCaption, tmpFile, attachmentName); exportInformation.ExportMade = true; } else { if (!manuallyInitiated) { - IDictionary inspectorCaptions = OutlookEmailExporter.RetrievePossibleTargets(); + var inspectorCaptions = OutlookEmailExporter.RetrievePossibleTargets(); if (inspectorCaptions != null && inspectorCaptions.Count > 0) { - List destinations = new List(); - destinations.Add(new OutlookDestination()); + var destinations = new List + { + new OutlookDestination() + }; foreach (string inspectorCaption in inspectorCaptions.Keys) { destinations.Add(new OutlookDestination(inspectorCaption, inspectorCaptions[inspectorCaption])); } @@ -179,7 +152,7 @@ namespace GreenshotOfficePlugin { return ShowPickerMenu(false, surface, captureDetails, destinations); } } else { - exportInformation.ExportMade = OutlookEmailExporter.ExportToOutlook(conf.OutlookEmailFormat, tmpFile, FilenameHelper.FillPattern(conf.EmailSubjectPattern, captureDetails, false), attachmentName, conf.EmailTo, conf.EmailCC, conf.EmailBCC, null); + exportInformation.ExportMade = OutlookEmailExporter.ExportToOutlook(OfficeConfig.OutlookEmailFormat, tmpFile, FilenameHelper.FillPattern(OfficeConfig.EmailSubjectPattern, captureDetails, false), attachmentName, OfficeConfig.EmailTo, OfficeConfig.EmailCC, OfficeConfig.EmailBCC, null); } } ProcessExport(exportInformation, surface); diff --git a/GreenshotOfficePlugin/Destinations/PowerpointDestination.cs b/GreenshotOfficePlugin/Destinations/PowerpointDestination.cs index 9adeb0a2c..6ab1e1a54 100644 --- a/GreenshotOfficePlugin/Destinations/PowerpointDestination.cs +++ b/GreenshotOfficePlugin/Destinations/PowerpointDestination.cs @@ -32,19 +32,18 @@ namespace GreenshotOfficePlugin { /// Description of PowerpointDestination. /// public class PowerpointDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(PowerpointDestination)); - private const int ICON_APPLICATION = 0; - private const int ICON_PRESENTATION = 1; + private const int IconApplication = 0; + private const int IconPresentation = 1; - private static readonly string exePath = null; - private readonly string presentationName = null; + private static readonly string ExePath; + private readonly string _presentationName; static PowerpointDestination() { - exePath = PluginUtils.GetExePath("POWERPNT.EXE"); - if (exePath != null && File.Exists(exePath)) { + ExePath = PluginUtils.GetExePath("POWERPNT.EXE"); + if (ExePath != null && File.Exists(ExePath)) { WindowDetails.AddProcessToExcludeFromFreeze("powerpnt"); } else { - exePath = null; + ExePath = null; } } @@ -52,50 +51,34 @@ namespace GreenshotOfficePlugin { } public PowerpointDestination(string presentationName) { - this.presentationName = presentationName; + _presentationName = presentationName; } - public override string Designation { - get { - return "Powerpoint"; - } - } + public override string Designation => "Powerpoint"; public override string Description { - get { - if (presentationName == null) { + get + { + if (_presentationName == null) { return "Microsoft Powerpoint"; - } else { - return presentationName; } + return _presentationName; } } - public override int Priority { - get { - return 4; - } - } - - public override bool isDynamic { - get { - return true; - } - } + public override int Priority => 4; - public override bool isActive { - get { - return base.isActive && exePath != null; - } - } + public override bool IsDynamic => true; + + public override bool IsActive => base.IsActive && ExePath != null; public override Image DisplayIcon { get { - if (!string.IsNullOrEmpty(presentationName)) { - return PluginUtils.GetCachedExeIcon(exePath, ICON_PRESENTATION); + if (!string.IsNullOrEmpty(_presentationName)) { + return PluginUtils.GetCachedExeIcon(ExePath, IconPresentation); } - return PluginUtils.GetCachedExeIcon(exePath, ICON_APPLICATION); + return PluginUtils.GetCachedExeIcon(ExePath, IconApplication); } } @@ -113,14 +96,13 @@ namespace GreenshotOfficePlugin { tmpFile = ImageOutput.SaveNamedTmpFile(surface, captureDetails, new SurfaceOutputSettings().PreventGreenshotFormat()); imageSize = surface.Image.Size; } - if (presentationName != null) { - exportInformation.ExportMade = PowerpointExporter.ExportToPresentation(presentationName, tmpFile, imageSize, captureDetails.Title); + if (_presentationName != null) { + exportInformation.ExportMade = PowerpointExporter.ExportToPresentation(_presentationName, tmpFile, imageSize, captureDetails.Title); } else { if (!manuallyInitiated) { - List presentations = PowerpointExporter.GetPowerpointPresentations(); + var presentations = PowerpointExporter.GetPowerpointPresentations(); if (presentations != null && presentations.Count > 0) { - List destinations = new List(); - destinations.Add(new PowerpointDestination()); + var destinations = new List {new PowerpointDestination()}; foreach (string presentation in presentations) { destinations.Add(new PowerpointDestination(presentation)); } diff --git a/GreenshotOfficePlugin/Destinations/WordDestination.cs b/GreenshotOfficePlugin/Destinations/WordDestination.cs index 68cbacf79..989dd0626 100644 --- a/GreenshotOfficePlugin/Destinations/WordDestination.cs +++ b/GreenshotOfficePlugin/Destinations/WordDestination.cs @@ -33,16 +33,16 @@ namespace GreenshotOfficePlugin { /// Description of EmailDestination. /// public class WordDestination : AbstractDestination { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(WordDestination)); - private const int ICON_APPLICATION = 0; - private const int ICON_DOCUMENT = 1; - private static readonly string exePath = null; - private readonly string documentCaption = null; + private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(WordDestination)); + private const int IconApplication = 0; + private const int IconDocument = 1; + private static readonly string ExePath; + private readonly string _documentCaption; static WordDestination() { - exePath = PluginUtils.GetExePath("WINWORD.EXE"); - if (exePath != null && !File.Exists(exePath)) { - exePath = null; + ExePath = PluginUtils.GetExePath("WINWORD.EXE"); + if (ExePath != null && !File.Exists(ExePath)) { + ExePath = null; } } @@ -51,51 +51,20 @@ namespace GreenshotOfficePlugin { } public WordDestination(string wordCaption) { - documentCaption = wordCaption; + _documentCaption = wordCaption; } - public override string Designation { - get { - return "Word"; - } - } + public override string Designation => "Word"; - public override string Description { - get { - if (documentCaption == null) { - return "Microsoft Word"; - } else { - return documentCaption; - } - } - } + public override string Description => _documentCaption ?? "Microsoft Word"; - public override int Priority { - get { - return 4; - } - } - - public override bool isDynamic { - get { - return true; - } - } + public override int Priority => 4; - public override bool isActive { - get { - return base.isActive && exePath != null; - } - } + public override bool IsDynamic => true; - public override Image DisplayIcon { - get { - if (!string.IsNullOrEmpty(documentCaption)) { - return PluginUtils.GetCachedExeIcon(exePath, ICON_DOCUMENT); - } - return PluginUtils.GetCachedExeIcon(exePath, ICON_APPLICATION); - } - } + public override bool IsActive => base.IsActive && ExePath != null; + + public override Image DisplayIcon => PluginUtils.GetCachedExeIcon(ExePath, !string.IsNullOrEmpty(_documentCaption) ? IconDocument : IconApplication); public override IEnumerable DynamicDestinations() { foreach (string wordCaption in WordExporter.GetWordDocuments()) { @@ -109,26 +78,28 @@ namespace GreenshotOfficePlugin { if (tmpFile == null || surface.Modified || !Regex.IsMatch(tmpFile, @".*(\.png|\.gif|\.jpg|\.jpeg|\.tiff|\.bmp)$")) { tmpFile = ImageOutput.SaveNamedTmpFile(surface, captureDetails, new SurfaceOutputSettings().PreventGreenshotFormat()); } - if (documentCaption != null) { + if (_documentCaption != null) { try { - WordExporter.InsertIntoExistingDocument(documentCaption, tmpFile); + WordExporter.InsertIntoExistingDocument(_documentCaption, tmpFile); exportInformation.ExportMade = true; } catch (Exception) { try { - WordExporter.InsertIntoExistingDocument(documentCaption, tmpFile); + WordExporter.InsertIntoExistingDocument(_documentCaption, tmpFile); exportInformation.ExportMade = true; } catch (Exception ex) { - LOG.Error(ex); + Log.Error(ex); // TODO: Change to general logic in ProcessExport surface.SendMessageEvent(this, SurfaceMessageTyp.Error, Language.GetFormattedString("destination_exportfailed", Description)); } } } else { if (!manuallyInitiated) { - List documents = WordExporter.GetWordDocuments(); + var documents = WordExporter.GetWordDocuments(); if (documents != null && documents.Count > 0) { - List destinations = new List(); - destinations.Add(new WordDestination()); + var destinations = new List + { + new WordDestination() + }; foreach (string document in documents) { destinations.Add(new WordDestination(document)); } @@ -145,7 +116,7 @@ namespace GreenshotOfficePlugin { WordExporter.InsertIntoNewDocument(tmpFile, null, null); exportInformation.ExportMade = true; } catch (Exception ex) { - LOG.Error(ex); + Log.Error(ex); // TODO: Change to general logic in ProcessExport surface.SendMessageEvent(this, SurfaceMessageTyp.Error, Language.GetFormattedString("destination_exportfailed", Description)); } diff --git a/GreenshotOfficePlugin/OfficeExport/ExcelExporter.cs b/GreenshotOfficePlugin/OfficeExport/ExcelExporter.cs index 7bcd88497..74fc732a0 100644 --- a/GreenshotOfficePlugin/OfficeExport/ExcelExporter.cs +++ b/GreenshotOfficePlugin/OfficeExport/ExcelExporter.cs @@ -22,14 +22,11 @@ using System; using System.Collections.Generic; using System.Reflection; using System.Drawing; -using GreenshotOfficePlugin; -using Greenshot.IniFile; namespace Greenshot.Interop.Office { public class ExcelExporter { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ExcelExporter)); - private static readonly OfficeConfiguration officeConfiguration = IniConfig.GetIniSection(); - private static Version excelVersion; + private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ExcelExporter)); + private static Version _excelVersion; /// /// Get all currently opened workbooks @@ -60,6 +57,7 @@ namespace Greenshot.Interop.Office { /// /// /// + /// public static void InsertIntoExistingWorkbook(string workbookName, string tmpFile, Size imageSize) { using (IExcelApplication excelApplication = GetExcelApplication()) { if (excelApplication == null) { @@ -147,16 +145,16 @@ namespace Greenshot.Interop.Office { /// /// private static void InitializeVariables(IExcelApplication excelApplication) { - if (excelApplication == null || excelVersion != null) { + if (excelApplication == null || _excelVersion != null) { return; } try { - excelVersion = new Version(excelApplication.Version); - LOG.InfoFormat("Using Excel {0}", excelVersion); + _excelVersion = new Version(excelApplication.Version); + Log.InfoFormat("Using Excel {0}", _excelVersion); } catch (Exception exVersion) { - LOG.Error(exVersion); - LOG.Warn("Assuming Excel version 1997."); - excelVersion = new Version((int)OfficeVersion.OFFICE_97, 0, 0, 0); + Log.Error(exVersion); + Log.Warn("Assuming Excel version 1997."); + _excelVersion = new Version((int)OfficeVersion.OFFICE_97, 0, 0, 0); } } } diff --git a/GreenshotOfficePlugin/OfficeExport/OneNoteExporter.cs b/GreenshotOfficePlugin/OfficeExport/OneNoteExporter.cs index aed3eea01..68619db38 100644 --- a/GreenshotOfficePlugin/OfficeExport/OneNoteExporter.cs +++ b/GreenshotOfficePlugin/OfficeExport/OneNoteExporter.cs @@ -30,11 +30,10 @@ using System.Xml; namespace Greenshot.Interop.Office { public class OneNoteExporter { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(OneNoteExporter)); - private const string XML_IMAGE_CONTENT = "{0}"; - private const string XML_OUTLINE = "{0}"; - private const string ONENOTE_NAMESPACE_2007 = "http://schemas.microsoft.com/office/onenote/2007/onenote"; - private const string ONENOTE_NAMESPACE_2010 = "http://schemas.microsoft.com/office/onenote/2010/onenote"; + private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(OneNoteExporter)); + private const string XmlImageContent = "{0}"; + private const string XmlOutline = "{0}"; + private const string OnenoteNamespace2010 = "http://schemas.microsoft.com/office/onenote/2010/onenote"; /// /// Create a new page in the "unfiled notes section", with the title of the capture, and export the capture there. @@ -44,10 +43,10 @@ namespace Greenshot.Interop.Office { public static bool ExportToNewPage(ISurface surfaceToUpload) { using(IOneNoteApplication oneNoteApplication = COMWrapper.GetOrCreateInstance()) { OneNotePage newPage = new OneNotePage(); - string unfiledNotesSectionID = GetSectionID(oneNoteApplication, SpecialLocation.slUnfiledNotesSection); - if(unfiledNotesSectionID != null) { - string pageId = ""; - oneNoteApplication.CreateNewPage(unfiledNotesSectionID, out pageId, NewPageStyle.npsDefault); + string unfiledNotesSectionId = GetSectionId(oneNoteApplication, SpecialLocation.slUnfiledNotesSection); + if(unfiledNotesSectionId != null) { + string pageId; + oneNoteApplication.CreateNewPage(unfiledNotesSectionId, out pageId, NewPageStyle.npsDefault); newPage.ID = pageId; // Set the new name, this is automatically done in the export to page newPage.Name = surfaceToUpload.CaptureDetails.Title; @@ -57,30 +56,6 @@ namespace Greenshot.Interop.Office { return false; } - /// - /// Can be used to change the title of a page - /// - /// - /// - /// - private static void UpdatePageTitle(IOneNoteApplication oneNoteApplication, string pageId, string title) { - try { - string pageXML = ""; - oneNoteApplication.GetPageContent(pageId, out pageXML, PageInfo.piAll, XMLSchema.xsCurrent); - XmlDocument doc = new XmlDocument(); - doc.LoadXml(pageXML); - XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable); - namespaceManager.AddNamespace("one", ONENOTE_NAMESPACE_2010); - - doc.SelectSingleNode("//one:T", namespaceManager).InnerText = title; - // Update the page - oneNoteApplication.UpdatePageContent(doc.OuterXml, DateTime.MinValue, XMLSchema.xs2010, true); - - } catch(Exception ex) { - LOG.Warn("Couldn't set page title.", ex); - } - } - /// /// Export the capture to the specified page /// @@ -108,14 +83,14 @@ namespace Greenshot.Interop.Office { SurfaceOutputSettings pngOutputSettings = new SurfaceOutputSettings(OutputFormat.png, 100, false); ImageOutput.SaveToStream(surfaceToUpload, pngStream, pngOutputSettings); string base64String = Convert.ToBase64String(pngStream.GetBuffer()); - string imageXmlStr = string.Format(XML_IMAGE_CONTENT, base64String, surfaceToUpload.Image.Width, surfaceToUpload.Image.Height); - string pageChangesXml = string.Format(XML_OUTLINE, new object[] { imageXmlStr, page.ID, ONENOTE_NAMESPACE_2010, page.Name }); - LOG.InfoFormat("Sending XML: {0}", pageChangesXml); + string imageXmlStr = string.Format(XmlImageContent, base64String, surfaceToUpload.Image.Width, surfaceToUpload.Image.Height); + string pageChangesXml = string.Format(XmlOutline, imageXmlStr, page.ID, OnenoteNamespace2010, page.Name); + Log.InfoFormat("Sending XML: {0}", pageChangesXml); oneNoteApplication.UpdatePageContent(pageChangesXml, DateTime.MinValue, XMLSchema.xs2010, false); try { oneNoteApplication.NavigateTo(page.ID, null, false); } catch(Exception ex) { - LOG.Warn("Unable to navigate to the target page", ex); + Log.Warn("Unable to navigate to the target page", ex); } return true; } @@ -127,17 +102,17 @@ namespace Greenshot.Interop.Office { /// /// SpecialLocation /// string with section ID - private static string GetSectionID(IOneNoteApplication oneNoteApplication, SpecialLocation specialLocation) { + private static string GetSectionId(IOneNoteApplication oneNoteApplication, SpecialLocation specialLocation) { if(oneNoteApplication == null) { return null; } - string unfiledNotesPath = ""; + string unfiledNotesPath; oneNoteApplication.GetSpecialLocation(specialLocation, out unfiledNotesPath); - string notebookXml = ""; + string notebookXml; oneNoteApplication.GetHierarchy("", HierarchyScope.hsPages, out notebookXml, XMLSchema.xs2010); if(!string.IsNullOrEmpty(notebookXml)) { - LOG.Debug(notebookXml); + Log.Debug(notebookXml); StringReader reader = null; try { reader = new StringReader(notebookXml); @@ -152,10 +127,9 @@ namespace Greenshot.Interop.Office { } } } - } finally { - if(reader != null) { - reader.Dispose(); - } + } finally + { + reader?.Dispose(); } } return null; @@ -170,10 +144,10 @@ namespace Greenshot.Interop.Office { try { using (IOneNoteApplication oneNoteApplication = COMWrapper.GetOrCreateInstance()) { if (oneNoteApplication != null) { - string notebookXml = ""; + string notebookXml; oneNoteApplication.GetHierarchy("", HierarchyScope.hsPages, out notebookXml, XMLSchema.xs2010); if (!string.IsNullOrEmpty(notebookXml)) { - LOG.Debug(notebookXml); + Log.Debug(notebookXml); StringReader reader = null; try { reader = new StringReader(notebookXml); @@ -185,18 +159,22 @@ namespace Greenshot.Interop.Office { if ("one:Notebook".Equals(xmlReader.Name)) { string id = xmlReader.GetAttribute("ID"); if (id != null && (currentNotebook == null || !id.Equals(currentNotebook.ID))) { - currentNotebook = new OneNoteNotebook(); - currentNotebook.ID = xmlReader.GetAttribute("ID"); - currentNotebook.Name = xmlReader.GetAttribute("name"); + currentNotebook = new OneNoteNotebook + { + ID = xmlReader.GetAttribute("ID"), + Name = xmlReader.GetAttribute("name") + }; } } if ("one:Section".Equals(xmlReader.Name)) { string id = xmlReader.GetAttribute("ID"); if (id != null && (currentSection == null || !id.Equals(currentSection.ID))) { - currentSection = new OneNoteSection(); - currentSection.ID = xmlReader.GetAttribute("ID"); - currentSection.Name = xmlReader.GetAttribute("name"); - currentSection.Parent = currentNotebook; + currentSection = new OneNoteSection + { + ID = xmlReader.GetAttribute("ID"), + Name = xmlReader.GetAttribute("name"), + Parent = currentNotebook + }; } } if ("one:Page".Equals(xmlReader.Name)) { @@ -204,10 +182,12 @@ namespace Greenshot.Interop.Office { if ("true".Equals(xmlReader.GetAttribute("isInRecycleBin"))) { continue; } - OneNotePage page = new OneNotePage(); - page.Parent = currentSection; - page.Name = xmlReader.GetAttribute("name"); - page.ID = xmlReader.GetAttribute("ID"); + OneNotePage page = new OneNotePage + { + Parent = currentSection, + Name = xmlReader.GetAttribute("name"), + ID = xmlReader.GetAttribute("ID") + }; if (page.ID == null || page.Name == null) { continue; } @@ -216,27 +196,26 @@ namespace Greenshot.Interop.Office { } } } - } finally { - if (reader != null) { - reader.Dispose(); - } + } finally + { + reader?.Dispose(); } } } } } catch (COMException cEx) { if (cEx.ErrorCode == unchecked((int)0x8002801D)) { - LOG.Warn("Wrong registry keys, to solve this remove the OneNote key as described here: http://microsoftmercenary.com/wp/outlook-excel-interop-calls-breaking-solved/"); + Log.Warn("Wrong registry keys, to solve this remove the OneNote key as described here: http://microsoftmercenary.com/wp/outlook-excel-interop-calls-breaking-solved/"); } - LOG.Warn("Problem retrieving onenote destinations, ignoring: ", cEx); + Log.Warn("Problem retrieving onenote destinations, ignoring: ", cEx); } catch (Exception ex) { - LOG.Warn("Problem retrieving onenote destinations, ignoring: ", ex); + Log.Warn("Problem retrieving onenote destinations, ignoring: ", ex); } pages.Sort(delegate(OneNotePage p1, OneNotePage p2) { if(p1.IsCurrentlyViewed || p2.IsCurrentlyViewed) { return p2.IsCurrentlyViewed.CompareTo(p1.IsCurrentlyViewed); } - return p1.DisplayName.CompareTo(p2.DisplayName); + return String.Compare(p1.DisplayName, p2.DisplayName, StringComparison.Ordinal); }); return pages; } diff --git a/GreenshotOfficePlugin/OfficeExport/OutlookEmailExporter.cs b/GreenshotOfficePlugin/OfficeExport/OutlookEmailExporter.cs index 11768666b..4d0d724f2 100644 --- a/GreenshotOfficePlugin/OfficeExport/OutlookEmailExporter.cs +++ b/GreenshotOfficePlugin/OfficeExport/OutlookEmailExporter.cs @@ -33,18 +33,18 @@ namespace Greenshot.Interop.Office { /// Outlook exporter has all the functionality to export to outlook /// public class OutlookEmailExporter { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(OutlookEmailExporter)); - private static readonly OfficeConfiguration conf = IniConfig.GetIniSection(); - private static readonly string SIGNATURE_PATH = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Microsoft\Signatures"); - private static Version outlookVersion = null; - private static string currentUser = null; + private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(OutlookEmailExporter)); + private static readonly OfficeConfiguration OfficeConfig = IniConfig.GetIniSection(); + private static readonly string SignaturePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Microsoft\Signatures"); + private static Version _outlookVersion; + private static string _currentUser; // The signature key can be found at: // HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\\9375CFF0413111d3B88A00104B2A6676\ [New Signature] - private const string PROFILES_KEY = @"Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\"; - private const string ACCOUNT_KEY = "9375CFF0413111d3B88A00104B2A6676"; - private const string NEW_SIGNATURE_VALUE = "New Signature"; - private const string DEFAULT_PROFILE_VALUE = "DefaultProfile"; + private const string ProfilesKey = @"Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\"; + private const string AccountKey = "9375CFF0413111d3B88A00104B2A6676"; + private const string NewSignatureValue = "New Signature"; + private const string DefaultProfileValue = "DefaultProfile"; /// /// A method to retrieve all inspectors which can act as an export target @@ -58,12 +58,12 @@ namespace Greenshot.Interop.Office { return null; } - if (outlookVersion.Major >= (int)OfficeVersion.OFFICE_2013) { + if (_outlookVersion.Major >= (int)OfficeVersion.OFFICE_2013) { // Check inline "panel" for Outlook 2013 using (var activeExplorer = outlookApplication.ActiveExplorer()) { if (activeExplorer != null) { using (var inlineResponse = activeExplorer.ActiveInlineResponse) { - if (canExportToInspector(inlineResponse)) { + if (CanExportToInspector(inlineResponse)) { OlObjectClass currentItemClass = inlineResponse.Class; inspectorCaptions.Add(activeExplorer.Caption, currentItemClass); } @@ -77,7 +77,7 @@ namespace Greenshot.Interop.Office { for (int i = 1; i <= inspectors.Count; i++) { using (IInspector inspector = outlookApplication.Inspectors[i]) { using (IItem currentItem = inspector.CurrentItem) { - if (canExportToInspector(currentItem)) { + if (CanExportToInspector(currentItem)) { OlObjectClass currentItemClass = currentItem.Class; inspectorCaptions.Add(inspector.Caption, currentItemClass); } @@ -88,7 +88,7 @@ namespace Greenshot.Interop.Office { } } } catch (Exception ex) { - LOG.Warn("Problem retrieving word destinations, ignoring: ", ex); + Log.Warn("Problem retrieving word destinations, ignoring: ", ex); } return inspectorCaptions; } @@ -98,29 +98,28 @@ namespace Greenshot.Interop.Office { /// /// the Item to check /// - private static bool canExportToInspector(IItem currentItem) { + private static bool CanExportToInspector(IItem currentItem) { try { if (currentItem != null) { OlObjectClass currentItemClass = currentItem.Class; if (OlObjectClass.olMail.Equals(currentItemClass)) { MailItem mailItem = (MailItem)currentItem; //MailItem mailItem = COMWrapper.Cast(currentItem); - LOG.DebugFormat("Mail sent: {0}", mailItem.Sent); + Log.DebugFormat("Mail sent: {0}", mailItem.Sent); if (!mailItem.Sent) { return true; } - } else if (outlookVersion.Major >= (int)OfficeVersion.OFFICE_2010 && conf.OutlookAllowExportInMeetings && OlObjectClass.olAppointment.Equals(currentItemClass)) { + } else if (_outlookVersion.Major >= (int)OfficeVersion.OFFICE_2010 && OfficeConfig.OutlookAllowExportInMeetings && OlObjectClass.olAppointment.Equals(currentItemClass)) { //AppointmentItem appointmentItem = COMWrapper.Cast(currentItem); AppointmentItem appointmentItem = (AppointmentItem)currentItem; - if (string.IsNullOrEmpty(appointmentItem.Organizer) || (currentUser != null && currentUser.Equals(appointmentItem.Organizer))) { + if (string.IsNullOrEmpty(appointmentItem.Organizer) || (_currentUser != null && _currentUser.Equals(appointmentItem.Organizer))) { return true; - } else { - LOG.DebugFormat("Not exporting, as organizer is {1} and currentuser {2}", appointmentItem.Organizer, currentUser); } + Log.DebugFormat("Not exporting, as organizer is {0} and currentuser {1}", appointmentItem.Organizer, _currentUser); } } } catch (Exception ex) { - LOG.WarnFormat("Couldn't process item due to: {0}", ex.Message); + Log.WarnFormat("Couldn't process item due to: {0}", ex.Message); } return false; } @@ -138,7 +137,7 @@ namespace Greenshot.Interop.Office { if (outlookApplication == null) { return false; } - if (outlookVersion.Major >= (int)OfficeVersion.OFFICE_2013) { + if (_outlookVersion.Major >= (int)OfficeVersion.OFFICE_2013) { // Check inline "panel" for Outlook 2013 using (var activeExplorer = outlookApplication.ActiveExplorer()) { if (activeExplorer == null) { @@ -148,11 +147,11 @@ namespace Greenshot.Interop.Office { if (currentCaption.StartsWith(inspectorCaption)) { using (var inlineResponse = activeExplorer.ActiveInlineResponse) { using (IItem currentItem = activeExplorer.ActiveInlineResponse) { - if (canExportToInspector(inlineResponse)) { + if (CanExportToInspector(inlineResponse)) { try { return ExportToInspector(activeExplorer, currentItem, tmpFile, attachmentName); } catch (Exception exExport) { - LOG.Error("Export to " + currentCaption + " failed.", exExport); + Log.Error("Export to " + currentCaption + " failed.", exExport); } } } @@ -165,17 +164,17 @@ namespace Greenshot.Interop.Office { if (inspectors == null || inspectors.Count == 0) { return false; } - LOG.DebugFormat("Got {0} inspectors to check", inspectors.Count); + Log.DebugFormat("Got {0} inspectors to check", inspectors.Count); for (int i = 1; i <= inspectors.Count; i++) { using (IInspector inspector = outlookApplication.Inspectors[i]) { string currentCaption = inspector.Caption; if (currentCaption.StartsWith(inspectorCaption)) { using (IItem currentItem = inspector.CurrentItem) { - if (canExportToInspector(currentItem)) { + if (CanExportToInspector(currentItem)) { try { return ExportToInspector(inspector, currentItem, tmpFile, attachmentName); } catch (Exception exExport) { - LOG.Error("Export to " + currentCaption + " failed.", exExport); + Log.Error("Export to " + currentCaption + " failed.", exExport); } } } @@ -190,21 +189,21 @@ namespace Greenshot.Interop.Office { /// /// Export the file to the supplied inspector /// - /// Inspector + /// ICommonExplorer /// Item /// /// /// private static bool ExportToInspector(ICommonExplorer inspectorOrExplorer, IItem currentItem, string tmpFile, string attachmentName) { if (currentItem == null) { - LOG.Warn("No current item."); + Log.Warn("No current item."); return false; } OlObjectClass itemClass = currentItem.Class; bool isMail = OlObjectClass.olMail.Equals(itemClass); bool isAppointment = OlObjectClass.olAppointment.Equals(itemClass); if (!isMail && !isAppointment) { - LOG.Warn("Item is no mail or appointment."); + Log.Warn("Item is no mail or appointment."); return false; } MailItem mailItem = null; @@ -213,7 +212,7 @@ namespace Greenshot.Interop.Office { //mailItem = COMWrapper.Cast(currentItem); mailItem = (MailItem)currentItem; if (mailItem.Sent) { - LOG.WarnFormat("Item already sent, can't export to {0}", currentItem.Subject); + Log.WarnFormat("Item already sent, can't export to {0}", currentItem.Subject); return false; } } @@ -230,41 +229,46 @@ namespace Greenshot.Interop.Office { // http://msdn.microsoft.com/en-us/library/dd492012%28v=office.12%29.aspx // Earlier versions of Outlook also supported an Inspector.HTMLEditor object property, but since Internet Explorer is no longer the rendering engine for HTML messages and posts, HTMLEditor is no longer supported. IWordDocument wordDocument = null; - if (inspectorOrExplorer is IExplorer) { - var explorer = inspectorOrExplorer as IExplorer; + var explorer = inspectorOrExplorer as IExplorer; + if (explorer != null) { wordDocument = explorer.ActiveInlineResponseWordEditor; - } else if (inspectorOrExplorer is IInspector) { - var inspector = inspectorOrExplorer as IInspector; - if (inspector.IsWordMail()) { - wordDocument = inspector.WordEditor; + } + else + { + var inspector1 = inspectorOrExplorer as IInspector; + if (inspector1 != null) { + var inspector = inspector1; + if (inspector.IsWordMail()) { + wordDocument = inspector.WordEditor; + } } } if (wordDocument != null) { try { if (WordExporter.InsertIntoExistingDocument(wordDocument.Application, wordDocument, tmpFile, null, null)) { - LOG.Info("Inserted into Wordmail"); + Log.Info("Inserted into Wordmail"); wordDocument.Dispose(); return true; } } catch (Exception exportException) { - LOG.Error("Error exporting to the word editor, trying to do it via another method", exportException); + Log.Error("Error exporting to the word editor, trying to do it via another method", exportException); } } else if (isAppointment) { - LOG.Info("Can't export to an appointment if no word editor is used"); + Log.Info("Can't export to an appointment if no word editor is used"); return false; } else { - LOG.Info("Trying export for outlook < 2007."); + Log.Info("Trying export for outlook < 2007."); } } // Only use mailitem as it should be filled!! - LOG.InfoFormat("Item '{0}' has format: {1}", mailItem.Subject, mailItem.BodyFormat); + Log.InfoFormat("Item '{0}' has format: {1}", mailItem?.Subject, mailItem?.BodyFormat); - string contentID; - if (outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) { - contentID = Guid.NewGuid().ToString(); + string contentId; + if (_outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) { + contentId = Guid.NewGuid().ToString(); } else { - LOG.Info("Older Outlook (<2007) found, using filename as contentid."); - contentID = Path.GetFileName(tmpFile); + Log.Info("Older Outlook (<2007) found, using filename as contentid."); + contentId = Path.GetFileName(tmpFile); } // Use this to change the format, it will probably lose the current selection. @@ -274,7 +278,7 @@ namespace Greenshot.Interop.Office { //} bool inlinePossible = false; - if (inspectorOrExplorer is IInspector && OlBodyFormat.olFormatHTML.Equals(mailItem.BodyFormat)) { + if (inspectorOrExplorer is IInspector && OlBodyFormat.olFormatHTML.Equals(mailItem?.BodyFormat)) { // if html we can try to inline it // The following might cause a security popup... can't ignore it. try { @@ -285,46 +289,46 @@ namespace Greenshot.Interop.Office { IHTMLTxtRange range = selection.createRange(); if (range != null) { // First paste, than attach (otherwise the range is wrong!) - range.pasteHTML("
\""
"); + range.pasteHTML("
\""
"); inlinePossible = true; } else { - LOG.DebugFormat("No range for '{0}'", inspectorOrExplorer.Caption); + Log.DebugFormat("No range for '{0}'", inspectorOrExplorer.Caption); } } else { - LOG.DebugFormat("No selection for '{0}'", inspectorOrExplorer.Caption); + Log.DebugFormat("No selection for '{0}'", inspectorOrExplorer.Caption); } } else { - LOG.DebugFormat("No HTML editor for '{0}'", inspectorOrExplorer.Caption); + Log.DebugFormat("No HTML editor for '{0}'", inspectorOrExplorer.Caption); } } catch (Exception e) { // Continue with non inline image - LOG.Warn("Error pasting HTML, most likely due to an ACCESS_DENIED as the user clicked no.", e); + Log.Warn("Error pasting HTML, most likely due to an ACCESS_DENIED as the user clicked no.", e); } } // Create the attachment (if inlined the attachment isn't visible as attachment!) using (IAttachment attachment = mailItem.Attachments.Add(tmpFile, OlAttachmentType.olByValue, inlinePossible ? 0 : 1, attachmentName)) { - if (outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) { + if (_outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) { // Add the content id to the attachment, this only works for Outlook >= 2007 try { IPropertyAccessor propertyAccessor = attachment.PropertyAccessor; - propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentID); + propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentId); } catch { // Ignore } } } } catch (Exception ex) { - LOG.WarnFormat("Problem while trying to add attachment to Item '{0}' : {1}", inspectorOrExplorer.Caption, ex); + Log.WarnFormat("Problem while trying to add attachment to Item '{0}' : {1}", inspectorOrExplorer.Caption, ex); return false; } try { inspectorOrExplorer.Activate(); } catch (Exception ex) { - LOG.Warn("Problem activating inspector/explorer: ", ex); + Log.Warn("Problem activating inspector/explorer: ", ex); return false; } - LOG.Debug("Finished!"); + Log.Debug("Finished!"); return true; } @@ -363,7 +367,7 @@ namespace Greenshot.Interop.Office { try { bodyString = GetOutlookSignature(format); } catch (Exception e) { - LOG.Error("Problem reading signature!", e); + Log.Error("Problem reading signature!", e); } switch (format) { case EmailFormat.Text: @@ -377,20 +381,19 @@ namespace Greenshot.Interop.Office { newMail.Body = bodyString; } break; - case EmailFormat.HTML: default: - string contentID = Path.GetFileName(tmpFile); + string contentId = Path.GetFileName(tmpFile); // Create the attachment (and dispose the COM object after using) using (IAttachment attachment = newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 0, attachmentName)) { // add content ID to the attachment - if (outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) { + if (_outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) { try { - contentID = Guid.NewGuid().ToString(); + contentId = Guid.NewGuid().ToString(); IPropertyAccessor propertyAccessor = attachment.PropertyAccessor; - propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentID); + propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentId); } catch { - LOG.Info("Error working with the PropertyAccessor, using filename as contentid"); - contentID = Path.GetFileName(tmpFile); + Log.Info("Error working with the PropertyAccessor, using filename as contentid"); + contentId = Path.GetFileName(tmpFile); } } } @@ -399,22 +402,19 @@ namespace Greenshot.Interop.Office { string href = ""; string hrefEnd = ""; if (!string.IsNullOrEmpty(url)) { - href = string.Format("", url); + href = $""; hrefEnd = ""; } - string htmlImgEmbedded = string.Format("
{0}\"{1}\"{3}
", href, attachmentName, contentID, hrefEnd); - string fallbackBody = string.Format("{0}", htmlImgEmbedded); + string htmlImgEmbedded = $"
{href}\"{attachmentName}\"{hrefEnd}
"; + string fallbackBody = $"{htmlImgEmbedded}"; if (bodyString == null) { bodyString = fallbackBody; } else { int bodyIndex = bodyString.IndexOf("= 0) { - bodyIndex = bodyString.IndexOf(">", bodyIndex) + 1; - if (bodyIndex >= 0) { - bodyString = bodyString.Insert(bodyIndex, htmlImgEmbedded); - } else { - bodyString = fallbackBody; - } + if (bodyIndex >= 0) + { + bodyIndex = bodyString.IndexOf(">", bodyIndex, StringComparison.Ordinal) + 1; + bodyString = bodyIndex >= 0 ? bodyString.Insert(bodyIndex, htmlImgEmbedded) : fallbackBody; } else { bodyString = fallbackBody; } @@ -460,7 +460,7 @@ namespace Greenshot.Interop.Office { } return exported; } catch (Exception e) { - LOG.Error("Error while creating an outlook mail item: ", e); + Log.Error("Error while creating an outlook mail item: ", e); } return exported; } @@ -470,46 +470,48 @@ namespace Greenshot.Interop.Office { /// /// private static string GetOutlookSignature(EmailFormat format) { - using (RegistryKey profilesKey = Registry.CurrentUser.OpenSubKey(PROFILES_KEY, false)) { + using (RegistryKey profilesKey = Registry.CurrentUser.OpenSubKey(ProfilesKey, false)) { if (profilesKey == null) { return null; } - string defaultProfile = (string)profilesKey.GetValue(DEFAULT_PROFILE_VALUE); - LOG.DebugFormat("defaultProfile={0}", defaultProfile); - using (RegistryKey profileKey = profilesKey.OpenSubKey(defaultProfile + @"\" + ACCOUNT_KEY, false)) { - if (profilesKey == null) { - return null; - } - string[] numbers = profileKey.GetSubKeyNames(); - foreach (string number in numbers) { - LOG.DebugFormat("Found subkey {0}", number); - using (RegistryKey numberKey = profileKey.OpenSubKey(number, false)) { - byte[] val = (byte[])numberKey.GetValue(NEW_SIGNATURE_VALUE); - if (val == null) { - continue; - } - string signatureName = ""; - foreach (byte b in val) { - if (b != 0) { - signatureName += (char)b; + string defaultProfile = (string)profilesKey.GetValue(DefaultProfileValue); + Log.DebugFormat("defaultProfile={0}", defaultProfile); + using (RegistryKey profileKey = profilesKey.OpenSubKey(defaultProfile + @"\" + AccountKey, false)) { + if (profileKey != null) + { + string[] numbers = profileKey.GetSubKeyNames(); + foreach (string number in numbers) { + Log.DebugFormat("Found subkey {0}", number); + using (RegistryKey numberKey = profileKey.OpenSubKey(number, false)) { + if (numberKey != null) + { + byte[] val = (byte[])numberKey.GetValue(NewSignatureValue); + if (val == null) { + continue; + } + string signatureName = ""; + foreach (byte b in val) { + if (b != 0) { + signatureName += (char)b; + } + } + Log.DebugFormat("Found email signature: {0}", signatureName); + string extension; + switch (format) { + case EmailFormat.Text: + extension = ".txt"; + break; + default: + extension = ".htm"; + break; + } + string signatureFile = Path.Combine(SignaturePath, signatureName + extension); + if (File.Exists(signatureFile)) { + Log.DebugFormat("Found email signature file: {0}", signatureFile); + return File.ReadAllText(signatureFile, Encoding.Default); + } } } - LOG.DebugFormat("Found email signature: {0}", signatureName); - string extension; - switch (format) { - case EmailFormat.Text: - extension = ".txt"; - break; - case EmailFormat.HTML: - default: - extension = ".htm"; - break; - } - string signatureFile = Path.Combine(SIGNATURE_PATH, signatureName + extension); - if (File.Exists(signatureFile)) { - LOG.DebugFormat("Found email signature file: {0}", signatureFile); - return File.ReadAllText(signatureFile, Encoding.Default); - } } } } @@ -522,25 +524,25 @@ namespace Greenshot.Interop.Office { /// /// private static void InitializeVariables(IOutlookApplication outlookApplication) { - if (outlookApplication == null || outlookVersion != null) { + if (outlookApplication == null || _outlookVersion != null) { return; } try { - outlookVersion = new Version(outlookApplication.Version); - LOG.InfoFormat("Using Outlook {0}", outlookVersion); + _outlookVersion = new Version(outlookApplication.Version); + Log.InfoFormat("Using Outlook {0}", _outlookVersion); } catch (Exception exVersion) { - LOG.Error(exVersion); - LOG.Warn("Assuming outlook version 1997."); - outlookVersion = new Version((int)OfficeVersion.OFFICE_97, 0, 0, 0); + Log.Error(exVersion); + Log.Warn("Assuming outlook version 1997."); + _outlookVersion = new Version((int)OfficeVersion.OFFICE_97, 0, 0, 0); } // Preventing retrieval of currentUser if Outlook is older than 2007 - if (outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) { + if (_outlookVersion.Major >= (int)OfficeVersion.OFFICE_2007) { try { INameSpace mapiNamespace = outlookApplication.GetNameSpace("MAPI"); - currentUser = mapiNamespace.CurrentUser.Name; - LOG.InfoFormat("Current user: {0}", currentUser); - } catch (Exception exNS) { - LOG.Error(exNS); + _currentUser = mapiNamespace.CurrentUser.Name; + Log.InfoFormat("Current user: {0}", _currentUser); + } catch (Exception exNs) { + Log.Error(exNs); } } } diff --git a/GreenshotOfficePlugin/OfficeExport/WordExporter.cs b/GreenshotOfficePlugin/OfficeExport/WordExporter.cs index ba362f3cd..548914287 100644 --- a/GreenshotOfficePlugin/OfficeExport/WordExporter.cs +++ b/GreenshotOfficePlugin/OfficeExport/WordExporter.cs @@ -25,16 +25,16 @@ using Greenshot.IniFile; namespace Greenshot.Interop.Office { public class WordExporter { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(WordExporter)); - private static Version wordVersion = null; - private static readonly OfficeConfiguration config = IniConfig.GetIniSection(); + private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(WordExporter)); + private static Version _wordVersion; + private static readonly OfficeConfiguration OfficeConfig = IniConfig.GetIniSection(); /// /// Check if the used version is higher than Office 2003 /// /// - private static bool isAfter2003() { - return wordVersion.Major > (int)OfficeVersion.OFFICE_2003; + private static bool IsAfter2003() { + return _wordVersion.Major > (int)OfficeVersion.OFFICE_2003; } /// @@ -77,11 +77,14 @@ namespace Greenshot.Interop.Office { // Solution: Make sure the selected document is active, otherwise the insert will be made in a different document! try { wordDocument.Activate(); - } catch { + } + catch + { + // ignored } using (ISelection selection = wordApplication.Selection) { if (selection == null) { - LOG.InfoFormat("No selection to insert {0} into found.", tmpFile); + Log.InfoFormat("No selection to insert {0} into found.", tmpFile); return false; } // Add Picture @@ -96,7 +99,7 @@ namespace Greenshot.Interop.Office { hyperlinks.Add(shape, screentip, Type.Missing, screentip, Type.Missing, Type.Missing); } } catch (Exception e) { - LOG.WarnFormat("Couldn't add hyperlink for image: {0}", e.Message); + Log.WarnFormat("Couldn't add hyperlink for image: {0}", e.Message); } } } @@ -110,19 +113,21 @@ namespace Greenshot.Interop.Office { } } } catch (Exception e) { - if (e.InnerException != null) { - LOG.WarnFormat("Couldn't set zoom to 100, error: {0}", e.InnerException.Message); - } else { - LOG.WarnFormat("Couldn't set zoom to 100, error: {0}", e.Message); - } + Log.WarnFormat("Couldn't set zoom to 100, error: {0}", e.InnerException?.Message ?? e.Message); } try { wordApplication.Activate(); - } catch { + } + catch + { + // ignored } try { wordDocument.Activate(); - } catch { + } + catch + { + // ignored } return true; } @@ -138,7 +143,7 @@ namespace Greenshot.Interop.Office { using (IInlineShapes shapes = selection.InlineShapes) { IInlineShape shape = shapes.AddPicture(tmpFile, false, true, Type.Missing); // Lock aspect ratio - if (config.WordLockAspectRatio) { + if (OfficeConfig.WordLockAspectRatio) { shape.LockAspectRatio = MsoTriState.msoTrue; } selection.InsertAfter("\r\n"); @@ -174,18 +179,24 @@ namespace Greenshot.Interop.Office { hyperlinks.Add(shape, screentip, Type.Missing, screentip, Type.Missing, Type.Missing); } } catch (Exception e) { - LOG.WarnFormat("Couldn't add hyperlink for image: {0}", e.Message); + Log.WarnFormat("Couldn't add hyperlink for image: {0}", e.Message); } } } } try { wordDocument.Activate(); - } catch { + } + catch + { + // ignored } try { wordDocument.ActiveWindow.Activate(); - } catch { + } + catch + { + // ignored } } } @@ -209,7 +220,7 @@ namespace Greenshot.Interop.Office { if (document.ReadOnly) { continue; } - if (isAfter2003()) { + if (IsAfter2003()) { if (document.Final) { continue; } @@ -222,7 +233,7 @@ namespace Greenshot.Interop.Office { } } } catch (Exception ex) { - LOG.Warn("Problem retrieving word destinations, ignoring: ", ex); + Log.Warn("Problem retrieving word destinations, ignoring: ", ex); } openDocuments.Sort(); return openDocuments; @@ -253,16 +264,16 @@ namespace Greenshot.Interop.Office { /// /// private static void InitializeVariables(IWordApplication wordApplication) { - if (wordApplication == null || wordVersion != null) { + if (wordApplication == null || _wordVersion != null) { return; } try { - wordVersion = new Version(wordApplication.Version); - LOG.InfoFormat("Using Word {0}", wordVersion); + _wordVersion = new Version(wordApplication.Version); + Log.InfoFormat("Using Word {0}", _wordVersion); } catch (Exception exVersion) { - LOG.Error(exVersion); - LOG.Warn("Assuming Word version 1997."); - wordVersion = new Version((int)OfficeVersion.OFFICE_97, 0, 0, 0); + Log.Error(exVersion); + Log.Warn("Assuming Word version 1997."); + _wordVersion = new Version((int)OfficeVersion.OFFICE_97, 0, 0, 0); } } } diff --git a/GreenshotOfficePlugin/OfficeInterop/OutlookInterop.cs b/GreenshotOfficePlugin/OfficeInterop/OutlookInterop.cs index ee22eb68c..f91390271 100644 --- a/GreenshotOfficePlugin/OfficeInterop/OutlookInterop.cs +++ b/GreenshotOfficePlugin/OfficeInterop/OutlookInterop.cs @@ -253,8 +253,8 @@ namespace Greenshot.Interop.Office { // See: http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.propertyaccessor_members.aspx public interface IPropertyAccessor : ICommon { - void SetProperty(string SchemaName, Object Value); - Object GetProperty(string SchemaName); + void SetProperty(string SchemaName, object Value); + object GetProperty(string SchemaName); } // Schema definitions for the MAPI properties @@ -363,7 +363,7 @@ namespace Greenshot.Interop.Office { // See: http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook._application.inspectors.aspx public interface IInspectors : ICommon, ICollection, IEnumerable { // Use index + 1!! - IInspector this[Object Index] { + IInspector this[object Index] { get; } } @@ -374,7 +374,7 @@ namespace Greenshot.Interop.Office { /// public interface IExplorers : ICommon, ICollection, IEnumerable { // Use index + 1!! - IExplorer this[Object Index] { + IExplorer this[object Index] { get; } } diff --git a/GreenshotPhotobucketPlugin/Forms/PhotobucketForm.cs b/GreenshotPhotobucketPlugin/Forms/PhotobucketForm.cs index 9997c273c..49b237289 100644 --- a/GreenshotPhotobucketPlugin/Forms/PhotobucketForm.cs +++ b/GreenshotPhotobucketPlugin/Forms/PhotobucketForm.cs @@ -24,7 +24,5 @@ namespace GreenshotPhotobucketPlugin { /// This class is needed for design-time resolving of the language files /// public class PhotobucketForm : GreenshotPlugin.Controls.GreenshotForm { - public PhotobucketForm() : base() { - } } } diff --git a/GreenshotPhotobucketPlugin/Forms/SettingsForm.cs b/GreenshotPhotobucketPlugin/Forms/SettingsForm.cs index d2a59e4e4..4fc578463 100644 --- a/GreenshotPhotobucketPlugin/Forms/SettingsForm.cs +++ b/GreenshotPhotobucketPlugin/Forms/SettingsForm.cs @@ -24,7 +24,8 @@ namespace GreenshotPhotobucketPlugin { /// Description of PasswordRequestForm. /// public partial class SettingsForm : PhotobucketForm { - public SettingsForm(PhotobucketConfiguration config) : base() { + public SettingsForm() + { // // The InitializeComponent() call is required for Windows Forms designer support. // diff --git a/GreenshotPhotobucketPlugin/PhotobucketConfiguration.cs b/GreenshotPhotobucketPlugin/PhotobucketConfiguration.cs index 5b284689b..4eed1bcdd 100644 --- a/GreenshotPhotobucketPlugin/PhotobucketConfiguration.cs +++ b/GreenshotPhotobucketPlugin/PhotobucketConfiguration.cs @@ -59,8 +59,8 @@ namespace GreenshotPhotobucketPlugin { SettingsForm settingsForm = null; new PleaseWaitForm().ShowAndWait(PhotobucketPlugin.Attributes.Name, Language.GetString("photobucket", LangKey.communication_wait), - delegate() { - settingsForm = new SettingsForm(this); + delegate { + settingsForm = new SettingsForm(); } ); DialogResult result = settingsForm.ShowDialog(); diff --git a/GreenshotPhotobucketPlugin/PhotobucketDestination.cs b/GreenshotPhotobucketPlugin/PhotobucketDestination.cs index fd35a3fca..d2b484342 100644 --- a/GreenshotPhotobucketPlugin/PhotobucketDestination.cs +++ b/GreenshotPhotobucketPlugin/PhotobucketDestination.cs @@ -21,8 +21,6 @@ using System.ComponentModel; using System.Collections.Generic; using System.Drawing; - -using Greenshot.IniFile; using Greenshot.Plugin; using GreenshotPlugin.Core; @@ -31,10 +29,8 @@ namespace GreenshotPhotobucketPlugin { /// Description of PhotobucketDestination. /// public class PhotobucketDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(PhotobucketDestination)); - private static PhotobucketConfiguration config = IniConfig.GetIniSection(); - private readonly PhotobucketPlugin plugin = null; - private readonly string albumPath = null; + private readonly PhotobucketPlugin _plugin; + private readonly string _albumPath; /// /// Create a Photobucket destination, which also has the path to the album in it @@ -42,20 +38,16 @@ namespace GreenshotPhotobucketPlugin { /// /// path to the album, null for default public PhotobucketDestination(PhotobucketPlugin plugin, string albumPath) { - this.plugin = plugin; - this.albumPath = albumPath; + _plugin = plugin; + _albumPath = albumPath; } - public override string Designation { - get { - return "Photobucket"; - } - } + public override string Designation => "Photobucket"; public override string Description { get { - if (albumPath != null) { - return albumPath; + if (_albumPath != null) { + return _albumPath; } return Language.GetString("photobucket", LangKey.upload_menu_item); } @@ -68,24 +60,23 @@ namespace GreenshotPhotobucketPlugin { } } - public override bool isDynamic { - get { - return true; - } - } + public override bool IsDynamic => true; public override IEnumerable DynamicDestinations() { - List albums = null; + IList albums = null; try { albums = PhotobucketUtils.RetrievePhotobucketAlbums(); - } catch { + } + catch + { + // ignored } if (albums == null || albums.Count == 0) { yield break; } foreach (string album in albums) { - yield return new PhotobucketDestination(plugin, album); + yield return new PhotobucketDestination(_plugin, album); } } @@ -98,11 +89,11 @@ namespace GreenshotPhotobucketPlugin { /// public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { ExportInformation exportInformation = new ExportInformation(Designation, Description); - string uploadURL = null; - bool uploaded = plugin.Upload(captureDetails, surface, albumPath, out uploadURL); + string uploadUrl; + bool uploaded = _plugin.Upload(captureDetails, surface, _albumPath, out uploadUrl); if (uploaded) { exportInformation.ExportMade = true; - exportInformation.Uri = uploadURL; + exportInformation.Uri = uploadUrl; } ProcessExport(exportInformation, surface); return exportInformation; diff --git a/GreenshotPhotobucketPlugin/PhotobucketInfo.cs b/GreenshotPhotobucketPlugin/PhotobucketInfo.cs index 2fa2883a2..cd66992fb 100644 --- a/GreenshotPhotobucketPlugin/PhotobucketInfo.cs +++ b/GreenshotPhotobucketPlugin/PhotobucketInfo.cs @@ -27,28 +27,13 @@ namespace GreenshotPhotobucketPlugin /// Description of PhotobucketInfo. /// public class PhotobucketInfo { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(PhotobucketInfo)); + private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(PhotobucketInfo)); - private string original; - public string Original { - get {return original;} - set {original = value;} - } + public string Original { get; set; } - private string page; - public string Page { - get {return page;} - set {page = value;} - } + public string Page { get; set; } - private string thumbnail; - public string Thumbnail { - get {return thumbnail;} - set {thumbnail = value;} - } - - public PhotobucketInfo() { - } + public string Thumbnail { get; set; } /// /// Parse the upload response @@ -56,28 +41,27 @@ namespace GreenshotPhotobucketPlugin /// XML /// PhotobucketInfo object public static PhotobucketInfo FromUploadResponse(string response) { - LOG.Debug(response); - PhotobucketInfo PhotobucketInfo = new PhotobucketInfo(); + Log.Debug(response); + PhotobucketInfo photobucketInfo = new PhotobucketInfo(); try { XmlDocument doc = new XmlDocument(); doc.LoadXml(response); - XmlNodeList nodes; - nodes = doc.GetElementsByTagName("url"); + var nodes = doc.GetElementsByTagName("url"); if(nodes.Count > 0) { - PhotobucketInfo.Original = nodes.Item(0).InnerText; + photobucketInfo.Original = nodes.Item(0)?.InnerText; } nodes = doc.GetElementsByTagName("browseurl"); if(nodes.Count > 0) { - PhotobucketInfo.Page = nodes.Item(0).InnerText; + photobucketInfo.Page = nodes.Item(0)?.InnerText; } nodes = doc.GetElementsByTagName("thumb"); if(nodes.Count > 0) { - PhotobucketInfo.Thumbnail = nodes.Item(0).InnerText; + photobucketInfo.Thumbnail = nodes.Item(0)?.InnerText; } } catch(Exception e) { - LOG.ErrorFormat("Could not parse Photobucket response due to error {0}, response was: {1}", e.Message, response); + Log.ErrorFormat("Could not parse Photobucket response due to error {0}, response was: {1}", e.Message, response); } - return PhotobucketInfo; + return photobucketInfo; } } } diff --git a/GreenshotPhotobucketPlugin/PhotobucketPlugin.cs b/GreenshotPhotobucketPlugin/PhotobucketPlugin.cs index 531681a35..6d7402319 100644 --- a/GreenshotPhotobucketPlugin/PhotobucketPlugin.cs +++ b/GreenshotPhotobucketPlugin/PhotobucketPlugin.cs @@ -55,9 +55,6 @@ namespace GreenshotPhotobucketPlugin { } } - public PhotobucketPlugin() { - } - public IEnumerable Destinations() { yield return new PhotobucketDestination(this, null); } diff --git a/GreenshotPhotobucketPlugin/PhotobucketUtils.cs b/GreenshotPhotobucketPlugin/PhotobucketUtils.cs index 69613eb3d..6738c0086 100644 --- a/GreenshotPhotobucketPlugin/PhotobucketUtils.cs +++ b/GreenshotPhotobucketPlugin/PhotobucketUtils.cs @@ -19,6 +19,7 @@ * along with this program. If not, see . */ using System; +using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Xml; @@ -31,9 +32,9 @@ namespace GreenshotPhotobucketPlugin { /// Description of PhotobucketUtils. /// public static class PhotobucketUtils { - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(PhotobucketUtils)); - private static readonly PhotobucketConfiguration config = IniConfig.GetIniSection(); - private static List albumsCache = null; + private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(PhotobucketUtils)); + private static readonly PhotobucketConfiguration PhotobucketConfig = IniConfig.GetIniSection(); + private static List _albumsCache; /// /// Do the actual upload to Photobucket @@ -43,18 +44,15 @@ namespace GreenshotPhotobucketPlugin { public static PhotobucketInfo UploadToPhotobucket(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string albumPath, string title, string filename) { string responseString; - if (string.IsNullOrEmpty(albumPath)) { - albumPath = "!"; - } - - OAuthSession oAuth = createSession(true); + var oAuth = CreateSession(true); if (oAuth == null) { return null; } IDictionary signedParameters = new Dictionary(); // add album - if (albumPath == null) { - signedParameters.Add("id", config.Username); + if (string.IsNullOrEmpty(albumPath)) + { + signedParameters.Add("id", string.IsNullOrEmpty(PhotobucketConfig.Username) ? "!" : PhotobucketConfig.Username); } else { signedParameters.Add("id", albumPath); } @@ -73,47 +71,49 @@ namespace GreenshotPhotobucketPlugin { unsignedParameters.Add("uploadfile", new SurfaceContainer(surfaceToUpload, outputSettings, filename)); try { string apiUrl = "http://api.photobucket.com/album/!/upload"; - responseString = oAuth.MakeOAuthRequest(HTTPMethod.POST, apiUrl, apiUrl.Replace("api.photobucket.com", config.SubDomain), signedParameters, unsignedParameters, null); + responseString = oAuth.MakeOAuthRequest(HTTPMethod.POST, apiUrl, apiUrl.Replace("api.photobucket.com", PhotobucketConfig.SubDomain), signedParameters, unsignedParameters, null); } catch (Exception ex) { - LOG.Error("Error uploading to Photobucket.", ex); + Log.Error("Error uploading to Photobucket.", ex); throw; } finally { if (!string.IsNullOrEmpty(oAuth.Token)) { - config.Token = oAuth.Token; + PhotobucketConfig.Token = oAuth.Token; } if (!string.IsNullOrEmpty(oAuth.TokenSecret)) { - config.TokenSecret = oAuth.TokenSecret; + PhotobucketConfig.TokenSecret = oAuth.TokenSecret; } } if (responseString == null) { return null; } - LOG.Info(responseString); - PhotobucketInfo PhotobucketInfo = PhotobucketInfo.FromUploadResponse(responseString); - LOG.Debug("Upload to Photobucket was finished"); - return PhotobucketInfo; + Log.Info(responseString); + var photobucketInfo = PhotobucketInfo.FromUploadResponse(responseString); + Log.Debug("Upload to Photobucket was finished"); + return photobucketInfo; } /// /// Helper method to create an OAuth session object for contacting the Photobucket API /// /// OAuthSession - private static OAuthSession createSession(bool autoLogin) { - OAuthSession oAuth = new OAuthSession(PhotobucketCredentials.ConsumerKey, PhotobucketCredentials.ConsumerSecret); - oAuth.AutoLogin = autoLogin; - oAuth.CheckVerifier = false; + private static OAuthSession CreateSession(bool autoLogin) { + var oAuth = new OAuthSession(PhotobucketCredentials.ConsumerKey, PhotobucketCredentials.ConsumerSecret) + { + AutoLogin = autoLogin, + CheckVerifier = false, + CallbackUrl = "http://getgreenshot.org", + AccessTokenUrl = "http://api.photobucket.com/login/access", + AuthorizeUrl = "http://photobucket.com/apilogin/login", + RequestTokenUrl = "http://api.photobucket.com/login/request", + BrowserSize = new Size(1010, 400), + RequestTokenMethod = HTTPMethod.POST, + AccessTokenMethod = HTTPMethod.POST, + LoginTitle = "Photobucket authorization" + }; // This url is configured in the Photobucket API settings in the Photobucket site!! - oAuth.CallbackUrl = "http://getgreenshot.org"; - oAuth.AccessTokenUrl = "http://api.photobucket.com/login/access"; - oAuth.AuthorizeUrl = "http://photobucket.com/apilogin/login"; - oAuth.RequestTokenUrl = "http://api.photobucket.com/login/request"; - oAuth.BrowserSize = new Size(1010, 400); // Photobucket is very particular about the used methods! - oAuth.RequestTokenMethod = HTTPMethod.POST; - oAuth.AccessTokenMethod = HTTPMethod.POST; - oAuth.LoginTitle = "Photobucket authorization"; - if (string.IsNullOrEmpty(config.SubDomain) || string.IsNullOrEmpty(config.Token) || string.IsNullOrEmpty(config.Username)) { + if (string.IsNullOrEmpty(PhotobucketConfig.SubDomain) || string.IsNullOrEmpty(PhotobucketConfig.Token) || string.IsNullOrEmpty(PhotobucketConfig.Username)) { if (!autoLogin) { return null; } @@ -121,21 +121,21 @@ namespace GreenshotPhotobucketPlugin { return null; } if (!string.IsNullOrEmpty(oAuth.Token)) { - config.Token = oAuth.Token; + PhotobucketConfig.Token = oAuth.Token; } if (!string.IsNullOrEmpty(oAuth.TokenSecret)) { - config.TokenSecret = oAuth.TokenSecret; + PhotobucketConfig.TokenSecret = oAuth.TokenSecret; } - if (oAuth.AccessTokenResponseParameters != null && oAuth.AccessTokenResponseParameters["subdomain"] != null) { - config.SubDomain = oAuth.AccessTokenResponseParameters["subdomain"]; + if (oAuth.AccessTokenResponseParameters?["subdomain"] != null) { + PhotobucketConfig.SubDomain = oAuth.AccessTokenResponseParameters["subdomain"]; } - if (oAuth.AccessTokenResponseParameters != null && oAuth.AccessTokenResponseParameters["username"] != null) { - config.Username = oAuth.AccessTokenResponseParameters["username"]; + if (oAuth.AccessTokenResponseParameters?["username"] != null) { + PhotobucketConfig.Username = oAuth.AccessTokenResponseParameters["username"]; } IniConfig.Save(); } - oAuth.Token = config.Token; - oAuth.TokenSecret = config.TokenSecret; + oAuth.Token = PhotobucketConfig.Token; + oAuth.TokenSecret = PhotobucketConfig.TokenSecret; return oAuth; } @@ -143,29 +143,29 @@ namespace GreenshotPhotobucketPlugin { /// Get list of photobucket albums /// /// List of string - public static List RetrievePhotobucketAlbums() { - if (albumsCache != null) { - return albumsCache; + public static IList RetrievePhotobucketAlbums() { + if (_albumsCache != null) { + return _albumsCache; } string responseString; - OAuthSession oAuth = createSession(false); + OAuthSession oAuth = CreateSession(false); if (oAuth == null) { return null; } IDictionary signedParameters = new Dictionary(); try { - string apiUrl = string.Format("http://api.photobucket.com/album/{0}", config.Username); - responseString = oAuth.MakeOAuthRequest(HTTPMethod.GET, apiUrl, apiUrl.Replace("api.photobucket.com", config.SubDomain), signedParameters, null, null); + string apiUrl = $"http://api.photobucket.com/album/{PhotobucketConfig.Username}"; + responseString = oAuth.MakeOAuthRequest(HTTPMethod.GET, apiUrl, apiUrl.Replace("api.photobucket.com", PhotobucketConfig.SubDomain), signedParameters, null, null); } catch (Exception ex) { - LOG.Error("Error uploading to Photobucket.", ex); + Log.Error("Error uploading to Photobucket.", ex); throw; } finally { if (!string.IsNullOrEmpty(oAuth.Token)) { - config.Token = oAuth.Token; + PhotobucketConfig.Token = oAuth.Token; } if (!string.IsNullOrEmpty(oAuth.TokenSecret)) { - config.TokenSecret = oAuth.TokenSecret; + PhotobucketConfig.TokenSecret = oAuth.TokenSecret; } } if (responseString == null) { @@ -175,15 +175,19 @@ namespace GreenshotPhotobucketPlugin { XmlDocument doc = new XmlDocument(); doc.LoadXml(responseString); List albums = new List(); - recurseAlbums(albums, null, doc.GetElementsByTagName("content").Item(0).ChildNodes); - LOG.DebugFormat("Albums: {0}", string.Join(",", albums.ToArray())); - albumsCache = albums; + var xmlNode = doc.GetElementsByTagName("content").Item(0); + if (xmlNode != null) + { + RecurseAlbums(albums, null, xmlNode.ChildNodes); + } + Log.DebugFormat("Albums: {0}", string.Join(",", albums.ToArray())); + _albumsCache = albums; return albums; } catch(Exception e) { - LOG.Error("Error while Reading albums: ", e); + Log.Error("Error while Reading albums: ", e); } - LOG.Debug("Upload to Photobucket was finished"); + Log.Debug("Upload to Photobucket was finished"); return null; } @@ -193,20 +197,23 @@ namespace GreenshotPhotobucketPlugin { /// /// /// - private static void recurseAlbums(Listalbums, string path, XmlNodeList nodes) { + private static void RecurseAlbums(ICollection albums, string path, IEnumerable nodes) { foreach(XmlNode node in nodes) { if (node.Name != "album") { continue; } - string currentAlbum = node.Attributes["name"].Value; - string currentPath = currentAlbum; - if (path != null && path.Length > 0) { - currentPath = string.Format("{0}/{1}", path, currentAlbum); - } + if (node.Attributes != null) + { + string currentAlbum = node.Attributes["name"].Value; + string currentPath = currentAlbum; + if (!string.IsNullOrEmpty(path)) { + currentPath = $"{path}/{currentAlbum}"; + } - albums.Add(currentPath); - if (node.Attributes["subalbum_count"] != null && node.Attributes["subalbum_count"].Value != "0") { - recurseAlbums(albums, currentPath, node.ChildNodes); + albums.Add(currentPath); + if (node.Attributes["subalbum_count"] != null && node.Attributes["subalbum_count"].Value != "0") { + RecurseAlbums(albums, currentPath, node.ChildNodes); + } } } } diff --git a/GreenshotPicasaPlugin/Forms/SettingsForm.cs b/GreenshotPicasaPlugin/Forms/SettingsForm.cs index 1ee8f5594..734559762 100644 --- a/GreenshotPicasaPlugin/Forms/SettingsForm.cs +++ b/GreenshotPicasaPlugin/Forms/SettingsForm.cs @@ -24,7 +24,8 @@ namespace GreenshotPicasaPlugin { /// public partial class SettingsForm : PicasaForm { - public SettingsForm(PicasaConfiguration config) : base() { + public SettingsForm() + { // // The InitializeComponent() call is required for Windows Forms designer support. // diff --git a/GreenshotPicasaPlugin/PicasaConfiguration.cs b/GreenshotPicasaPlugin/PicasaConfiguration.cs index dc906d8c9..17e44efee 100644 --- a/GreenshotPicasaPlugin/PicasaConfiguration.cs +++ b/GreenshotPicasaPlugin/PicasaConfiguration.cs @@ -81,7 +81,7 @@ namespace GreenshotPicasaPlugin { /// /// bool true if OK was pressed, false if cancel public bool ShowConfigDialog() { - DialogResult result = new SettingsForm(this).ShowDialog(); + DialogResult result = new SettingsForm().ShowDialog(); if (result == DialogResult.OK) { return true; } diff --git a/GreenshotPicasaPlugin/PicasaDestination.cs b/GreenshotPicasaPlugin/PicasaDestination.cs index aaced6491..cb2206f13 100644 --- a/GreenshotPicasaPlugin/PicasaDestination.cs +++ b/GreenshotPicasaPlugin/PicasaDestination.cs @@ -19,31 +19,19 @@ */ using System.ComponentModel; using System.Drawing; -using Greenshot.IniFile; using Greenshot.Plugin; using GreenshotPlugin.Core; namespace GreenshotPicasaPlugin { public class PicasaDestination : AbstractDestination { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(PicasaDestination)); - private static PicasaConfiguration config = IniConfig.GetIniSection(); - - private readonly PicasaPlugin plugin = null; + private readonly PicasaPlugin _plugin; public PicasaDestination(PicasaPlugin plugin) { - this.plugin = plugin; + _plugin = plugin; } - public override string Designation { - get { - return "Picasa"; - } - } + public override string Designation => "Picasa"; - public override string Description { - get { - return Language.GetString("picasa", LangKey.upload_menu_item); - } - } + public override string Description => Language.GetString("picasa", LangKey.upload_menu_item); public override Image DisplayIcon { get { @@ -55,7 +43,7 @@ namespace GreenshotPicasaPlugin { public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { ExportInformation exportInformation = new ExportInformation(Designation, Description); string uploadUrl; - bool uploaded = plugin.Upload(captureDetails, surface, out uploadUrl); + bool uploaded = _plugin.Upload(captureDetails, surface, out uploadUrl); if (uploaded) { exportInformation.ExportMade = true; exportInformation.Uri = uploadUrl; diff --git a/GreenshotPicasaPlugin/PicasaPlugin.cs b/GreenshotPicasaPlugin/PicasaPlugin.cs index 84ba7547e..76bd80250 100644 --- a/GreenshotPicasaPlugin/PicasaPlugin.cs +++ b/GreenshotPicasaPlugin/PicasaPlugin.cs @@ -54,9 +54,6 @@ namespace GreenshotPicasaPlugin { } } - public PicasaPlugin() { - } - public IEnumerable Destinations() { yield return new PicasaDestination(this); } @@ -79,10 +76,12 @@ namespace GreenshotPicasaPlugin { _config = IniConfig.GetIniSection(); _resources = new ComponentResourceManager(typeof(PicasaPlugin)); - _itemPlugInRoot = new ToolStripMenuItem(); - _itemPlugInRoot.Text = Language.GetString("picasa", LangKey.Configure); - _itemPlugInRoot.Tag = _host; - _itemPlugInRoot.Image = (Image)_resources.GetObject("Picasa"); + _itemPlugInRoot = new ToolStripMenuItem + { + Text = Language.GetString("picasa", LangKey.Configure), + Tag = _host, + Image = (Image) _resources.GetObject("Picasa") + }; _itemPlugInRoot.Click += ConfigMenuClick; PluginUtils.AddToContextMenu(_host, _itemPlugInRoot); Language.LanguageChanged += OnLanguageChanged; diff --git a/GreenshotPicasaPlugin/PicasaUtils.cs b/GreenshotPicasaPlugin/PicasaUtils.cs index 4aef53b5c..39519915c 100644 --- a/GreenshotPicasaPlugin/PicasaUtils.cs +++ b/GreenshotPicasaPlugin/PicasaUtils.cs @@ -30,7 +30,7 @@ namespace GreenshotPicasaPlugin { /// public static class PicasaUtils { private const string PicasaScope = "https://picasaweb.google.com/data/"; - private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(PicasaUtils)); + private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(PicasaUtils)); private static readonly PicasaConfiguration Config = IniConfig.GetIniSection(); private const string AuthUrl = "https://accounts.google.com/o/oauth2/auth?response_type=code&client_id={ClientId}&redirect_uri={RedirectUrl}&state={State}&scope=" + PicasaScope; private const string TokenUrl = "https://www.googleapis.com/oauth2/v3/token"; @@ -46,18 +46,20 @@ namespace GreenshotPicasaPlugin { /// PicasaResponse public static string UploadToPicasa(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string title, string filename) { // Fill the OAuth2Settings - OAuth2Settings settings = new OAuth2Settings(); - settings.AuthUrlPattern = AuthUrl; - settings.TokenUrl = TokenUrl; - settings.CloudServiceName = "Picasa"; - settings.ClientId = PicasaCredentials.ClientId; - settings.ClientSecret = PicasaCredentials.ClientSecret; - settings.AuthorizeMode = OAuth2AuthorizeMode.LocalServer; + var settings = new OAuth2Settings + { + AuthUrlPattern = AuthUrl, + TokenUrl = TokenUrl, + CloudServiceName = "Picasa", + ClientId = PicasaCredentials.ClientId, + ClientSecret = PicasaCredentials.ClientSecret, + AuthorizeMode = OAuth2AuthorizeMode.LocalServer, + RefreshToken = Config.RefreshToken, + AccessToken = Config.AccessToken, + AccessTokenExpires = Config.AccessTokenExpires + }; // Copy the settings from the config, which is kept in memory and on the disk - settings.RefreshToken = Config.RefreshToken; - settings.AccessToken = Config.AccessToken; - settings.AccessTokenExpires = Config.AccessTokenExpires; try { var webRequest = OAuth2Helper.CreateOAuth2WebRequest(HTTPMethod.POST, string.Format(UploadUrl, Config.UploadUser, Config.UploadAlbum), settings); @@ -108,7 +110,7 @@ namespace GreenshotPicasaPlugin { return url; } } catch(Exception e) { - LOG.ErrorFormat("Could not parse Picasa response due to error {0}, response was: {1}", e.Message, response); + Log.ErrorFormat("Could not parse Picasa response due to error {0}, response was: {1}", e.Message, response); } return null; } diff --git a/GreenshotPlugin/Controls/AnimatingForm.cs b/GreenshotPlugin/Controls/AnimatingForm.cs index c1e6bedc3..db6fc8c59 100644 --- a/GreenshotPlugin/Controls/AnimatingForm.cs +++ b/GreenshotPlugin/Controls/AnimatingForm.cs @@ -29,7 +29,7 @@ namespace GreenshotPlugin.Controls { /// Extend this Form to have the possibility for animations on your form /// public class AnimatingForm : GreenshotForm { - private static readonly ILog LOG = LogManager.GetLogger(typeof(AnimatingForm)); + private static readonly ILog Log = LogManager.GetLogger(typeof(AnimatingForm)); private const int DEFAULT_VREFRESH = 60; private int _vRefresh; private Timer _timer; @@ -49,7 +49,7 @@ namespace GreenshotPlugin.Controls { get { if (_vRefresh == 0) { // get te hDC of the desktop to get the VREFRESH - using (SafeWindowDCHandle desktopHandle = SafeWindowDCHandle.FromDesktop()) { + using (SafeWindowDcHandle desktopHandle = SafeWindowDcHandle.FromDesktop()) { _vRefresh = GDI32.GetDeviceCaps(desktopHandle, DeviceCaps.VREFRESH); } } @@ -65,11 +65,7 @@ namespace GreenshotPlugin.Controls { /// /// Check if we are in a Terminal Server session OR need to optimize for RDP / remote desktop connections /// - protected bool IsTerminalServerSession { - get { - return !coreConfiguration.DisableRDPOptimizing && (coreConfiguration.OptimizeForRDP || SystemInformation.TerminalServerSession); - } - } + protected bool IsTerminalServerSession => !coreConfiguration.DisableRDPOptimizing && (coreConfiguration.OptimizeForRDP || SystemInformation.TerminalServerSession); /// /// Calculate the amount of frames that an animation takes @@ -89,19 +85,22 @@ namespace GreenshotPlugin.Controls { /// protected AnimatingForm() { Load += delegate { - if (EnableAnimation) { - _timer = new Timer(); - _timer.Interval = 1000 / VRefresh; - _timer.Tick += timer_Tick; - _timer.Start(); + if (!EnableAnimation) + { + return; } + _timer = new Timer + { + Interval = 1000/VRefresh + }; + _timer.Tick += timer_Tick; + _timer.Start(); }; // Unregister at close - FormClosing += delegate { - if (_timer != null) { - _timer.Stop(); - } + FormClosing += delegate + { + _timer?.Stop(); }; } @@ -114,7 +113,7 @@ namespace GreenshotPlugin.Controls { try { Animate(); } catch (Exception ex) { - LOG.Warn("An exception occured while animating:", ex); + Log.Warn("An exception occured while animating:", ex); } } diff --git a/GreenshotPlugin/Controls/ExtendedWebBrowser.cs b/GreenshotPlugin/Controls/ExtendedWebBrowser.cs index 5fae94edd..6a0d52418 100644 --- a/GreenshotPlugin/Controls/ExtendedWebBrowser.cs +++ b/GreenshotPlugin/Controls/ExtendedWebBrowser.cs @@ -59,8 +59,5 @@ namespace GreenshotPlugin.Controls { protected override WebBrowserSiteBase CreateWebBrowserSiteBase() { return new ExtendedWebBrowserSite(this); } - - public ExtendedWebBrowser() { - } } } \ No newline at end of file diff --git a/GreenshotPlugin/Controls/GreenshotComboBox.cs b/GreenshotPlugin/Controls/GreenshotComboBox.cs index 139ecac5e..262309410 100644 --- a/GreenshotPlugin/Controls/GreenshotComboBox.cs +++ b/GreenshotPlugin/Controls/GreenshotComboBox.cs @@ -83,7 +83,7 @@ namespace GreenshotPlugin.Controls { foreach (Enum enumValue in availableValues) { string enumKey = enumTypeName + "." + enumValue; - if (Language.hasKey(enumKey)) { + if (Language.HasKey(enumKey)) { string translation = Language.GetString(enumTypeName + "." + enumValue); if (translation.Equals(selectedValue)) { returnValue = enumValue; diff --git a/GreenshotPlugin/Controls/GreenshotForm.cs b/GreenshotPlugin/Controls/GreenshotForm.cs index f26605e83..e30f7e674 100644 --- a/GreenshotPlugin/Controls/GreenshotForm.cs +++ b/GreenshotPlugin/Controls/GreenshotForm.cs @@ -107,13 +107,16 @@ namespace GreenshotPlugin.Controls { // this "type" Assembly currentAssembly = GetType().Assembly; - string assemblyPath = typeResService.GetPathOfAssembly(currentAssembly.GetName()); - string assemblyDirectory = Path.GetDirectoryName(assemblyPath); - if (!Language.AddLanguageFilePath(Path.Combine(assemblyDirectory, @"..\..\Greenshot\Languages\"))) { - Language.AddLanguageFilePath(Path.Combine(assemblyDirectory, @"..\..\..\Greenshot\Languages\")); - } - if (!Language.AddLanguageFilePath(Path.Combine(assemblyDirectory, @"..\..\Languages\"))) { - Language.AddLanguageFilePath(Path.Combine(assemblyDirectory, @"..\..\..\Languages\")); + if (typeResService != null) + { + string assemblyPath = typeResService.GetPathOfAssembly(currentAssembly.GetName()); + string assemblyDirectory = Path.GetDirectoryName(assemblyPath); + if (assemblyDirectory != null && !Language.AddLanguageFilePath(Path.Combine(assemblyDirectory, @"..\..\Greenshot\Languages\"))) { + Language.AddLanguageFilePath(Path.Combine(assemblyDirectory, @"..\..\..\Greenshot\Languages\")); + } + if (assemblyDirectory != null && !Language.AddLanguageFilePath(Path.Combine(assemblyDirectory, @"..\..\Languages\"))) { + Language.AddLanguageFilePath(Path.Combine(assemblyDirectory, @"..\..\..\Languages\")); + } } } catch (Exception ex) { MessageBox.Show(ex.Message); @@ -131,7 +134,10 @@ namespace GreenshotPlugin.Controls { _isDesignModeLanguageSet = true; try { ApplyLanguage(); - } catch (Exception) { + } + catch (Exception) + { + // ignored } } } @@ -229,7 +235,7 @@ namespace GreenshotPlugin.Controls { /// /// private void OnComponentChanged(object sender, ComponentChangedEventArgs ce) { - if (ce.Component != null && ((IComponent)ce.Component).Site != null && ce.Member != null) { + if (((IComponent) ce.Component)?.Site != null && ce.Member != null) { if ("LanguageKey".Equals(ce.Member.Name)) { Control control = ce.Component as Control; if (control != null) { @@ -249,7 +255,7 @@ namespace GreenshotPlugin.Controls { } private void OnComponentAdded(object sender, ComponentEventArgs ce) { - if (ce.Component != null && ((IComponent)ce.Component).Site != null) { + if (ce.Component?.Site != null) { Control control = ce.Component as Control; if (control != null) { if (!_designTimeControls.ContainsKey(control.Name)) { @@ -257,12 +263,17 @@ namespace GreenshotPlugin.Controls { } else { _designTimeControls[control.Name] = control; } - } else if (ce.Component is ToolStripItem) { - ToolStripItem item = ce.Component as ToolStripItem; - if (!_designTimeControls.ContainsKey(item.Name)) { - _designTimeToolStripItems.Add(item.Name, item); - } else { - _designTimeToolStripItems[item.Name] = item; + } + else + { + var stripItem = ce.Component as ToolStripItem; + if (stripItem != null) { + ToolStripItem item = stripItem; + if (!_designTimeControls.ContainsKey(item.Name)) { + _designTimeToolStripItems.Add(item.Name, item); + } else { + _designTimeToolStripItems[item.Name] = item; + } } } } @@ -308,10 +319,12 @@ namespace GreenshotPlugin.Controls { if (languageBindable == null) { // check if it's a menu! ToolStrip toolStrip = applyTo as ToolStrip; - if (toolStrip != null) { - foreach (ToolStripItem item in toolStrip.Items) { - ApplyLanguage(item); - } + if (toolStrip == null) + { + return; + } + foreach (ToolStripItem item in toolStrip.Items) { + ApplyLanguage(item); } return; } @@ -327,7 +340,7 @@ namespace GreenshotPlugin.Controls { IniSection section = IniConfig.GetIniSection(configBindable.SectionName); if (section != null) { // Only update the language, so get the actual value and than repopulate - Enum currentValue = (Enum)comboxBox.GetSelectedEnum(); + Enum currentValue = comboxBox.GetSelectedEnum(); comboxBox.Populate(section.Values[configBindable.PropertyName].ValueType); comboxBox.SetValue(currentValue); } @@ -341,7 +354,7 @@ namespace GreenshotPlugin.Controls { /// /// private static FieldInfo[] GetCachedFields(Type typeToGetFieldsFor) { - FieldInfo[] fields = null; + FieldInfo[] fields; if (!reflectionCache.TryGetValue(typeToGetFieldsFor, out fields)) { fields = typeToGetFieldsFor.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); reflectionCache.Add(typeToGetFieldsFor, fields); @@ -353,17 +366,17 @@ namespace GreenshotPlugin.Controls { /// Apply all the language settings to the "Greenshot" Controls on this form /// protected void ApplyLanguage() { - string langString = null; SuspendLayout(); try { // Set title of the form + string langString; if (!string.IsNullOrEmpty(LanguageKey) && Language.TryGetString(LanguageKey, out langString)) { Text = langString; } // Reset the text values for all GreenshotControls foreach (FieldInfo field in GetCachedFields(GetType())) { - Object controlObject = field.GetValue(this); + object controlObject = field.GetValue(this); if (controlObject == null) { LOG.DebugFormat("No value: {0}", field.Name); continue; @@ -398,7 +411,7 @@ namespace GreenshotPlugin.Controls { /// Apply the language text to supplied control /// protected void ApplyLanguage(Control applyTo, string languageKey) { - string langString = null; + string langString; if (!string.IsNullOrEmpty(languageKey)) { if (!Language.TryGetString(languageKey, out langString)) { LOG.WarnFormat("Wrong language key '{0}' configured for control '{1}'", languageKey, applyTo.Name); @@ -422,18 +435,12 @@ namespace GreenshotPlugin.Controls { /// protected void FillFields() { foreach (FieldInfo field in GetCachedFields(GetType())) { - Object controlObject = field.GetValue(this); - if (controlObject == null) { - continue; - } + var controlObject = field.GetValue(this); IGreenshotConfigBindable configBindable = controlObject as IGreenshotConfigBindable; - if (configBindable == null) { - continue; - } - if (!string.IsNullOrEmpty(configBindable.SectionName) && !string.IsNullOrEmpty(configBindable.PropertyName)) { + if (!string.IsNullOrEmpty(configBindable?.SectionName) && !string.IsNullOrEmpty(configBindable.PropertyName)) { IniSection section = IniConfig.GetIniSection(configBindable.SectionName); if (section != null) { - IniValue iniValue = null; + IniValue iniValue; if (!section.Values.TryGetValue(configBindable.PropertyName, out iniValue)) { LOG.DebugFormat("Wrong property '{0}' configured for field '{1}'",configBindable.PropertyName,field.Name); continue; @@ -445,7 +452,7 @@ namespace GreenshotPlugin.Controls { checkBox.Enabled = !iniValue.IsFixed; continue; } - RadioButton radíoButton = controlObject as RadioButton; + RadioButton radíoButton = controlObject as RadioButton; if (radíoButton != null) { radíoButton.Checked = (bool)iniValue.Value; radíoButton.Enabled = !iniValue.IsFixed; @@ -477,11 +484,11 @@ namespace GreenshotPlugin.Controls { } } } - OnFieldsFilled(); + OnFieldsFilled(); } - protected virtual void OnFieldsFilled() { - } + protected virtual void OnFieldsFilled() { + } /// /// Store all GreenshotControl values to the configuration @@ -489,19 +496,13 @@ namespace GreenshotPlugin.Controls { protected void StoreFields() { bool iniDirty = false; foreach (FieldInfo field in GetCachedFields(GetType())) { - Object controlObject = field.GetValue(this); - if (controlObject == null) { - continue; - } + var controlObject = field.GetValue(this); IGreenshotConfigBindable configBindable = controlObject as IGreenshotConfigBindable; - if (configBindable == null) { - continue; - } - if (!string.IsNullOrEmpty(configBindable.SectionName) && !string.IsNullOrEmpty(configBindable.PropertyName)) { + if (!string.IsNullOrEmpty(configBindable?.SectionName) && !string.IsNullOrEmpty(configBindable.PropertyName)) { IniSection section = IniConfig.GetIniSection(configBindable.SectionName); if (section != null) { - IniValue iniValue = null; + IniValue iniValue; if (!section.Values.TryGetValue(configBindable.PropertyName, out iniValue)) { continue; } @@ -511,7 +512,7 @@ namespace GreenshotPlugin.Controls { iniDirty = true; continue; } - RadioButton radioButton = controlObject as RadioButton; + RadioButton radioButton = controlObject as RadioButton; if (radioButton != null) { iniValue.Value = radioButton.Checked; iniDirty = true; @@ -519,12 +520,12 @@ namespace GreenshotPlugin.Controls { } TextBox textBox = controlObject as TextBox; if (textBox != null) { - HotkeyControl hotkeyControl = controlObject as HotkeyControl; - if (hotkeyControl != null) { - iniValue.Value = hotkeyControl.ToString(); - iniDirty = true; - continue; - } + HotkeyControl hotkeyControl = controlObject as HotkeyControl; + if (hotkeyControl != null) { + iniValue.Value = hotkeyControl.ToString(); + iniDirty = true; + continue; + } iniValue.UseValueOrDefault(textBox.Text); iniDirty = true; continue; @@ -533,7 +534,6 @@ namespace GreenshotPlugin.Controls { if (comboxBox != null) { iniValue.Value = comboxBox.GetSelectedEnum(); iniDirty = true; - continue; } } diff --git a/GreenshotPlugin/Controls/GreenshotRadioButton.cs b/GreenshotPlugin/Controls/GreenshotRadioButton.cs index 90ca3a531..010378da2 100644 --- a/GreenshotPlugin/Controls/GreenshotRadioButton.cs +++ b/GreenshotPlugin/Controls/GreenshotRadioButton.cs @@ -33,16 +33,8 @@ namespace GreenshotPlugin.Controls { set; } - private string sectionName = "Core"; [Category("Greenshot"), DefaultValue("Core"), Description("Specifies the Ini-Section to map this control with.")] - public string SectionName { - get { - return sectionName; - } - set { - sectionName = value; - } - } + public string SectionName { get; set; } = "Core"; [Category("Greenshot"), DefaultValue(null), Description("Specifies the property name to map the configuration.")] public string PropertyName { diff --git a/GreenshotPlugin/Controls/HotkeyControl.cs b/GreenshotPlugin/Controls/HotkeyControl.cs index fb9674ec8..0e40a9cbc 100644 --- a/GreenshotPlugin/Controls/HotkeyControl.cs +++ b/GreenshotPlugin/Controls/HotkeyControl.cs @@ -37,17 +37,17 @@ namespace GreenshotPlugin.Controls { /// See: http://www.codeproject.com/KB/buttons/hotkeycontrol.aspx /// But is modified to fit in Greenshot, and have localized support /// - public class HotkeyControl : GreenshotTextBox { - private static readonly ILog LOG = LogManager.GetLogger(typeof(HotkeyControl)); + public sealed class HotkeyControl : GreenshotTextBox { + private static readonly ILog Log = LogManager.GetLogger(typeof(HotkeyControl)); - 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; + 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 readonly IDictionary keyHandlers = new Dictionary(); - private static int hotKeyCounter = 1; + private static readonly IDictionary KeyHandlers = new Dictionary(); + private static int _hotKeyCounter = 1; private const uint WM_HOTKEY = 0x312; - private static IntPtr hotkeyHWND; + private static IntPtr _hotkeyHwnd; // static HotkeyControl() { // StringBuilder keyName = new StringBuilder(); @@ -96,20 +96,20 @@ 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 readonly ArrayList needNonShiftModifier; - private readonly ArrayList needNonAltGrModifier; + private readonly ArrayList _needNonShiftModifier; + private readonly ArrayList _needNonAltGrModifier; - private readonly ContextMenu dummy = new ContextMenu(); + private readonly ContextMenu _dummy = new ContextMenu(); /// /// Used to make sure that there is no right-click menu available /// public override ContextMenu ContextMenu { get { - return dummy; + return _dummy; } set { - base.ContextMenu = dummy; + base.ContextMenu = _dummy; } } @@ -130,7 +130,7 @@ namespace GreenshotPlugin.Controls { /// Creates a new HotkeyControl /// public HotkeyControl() { - ContextMenu = dummy; // Disable right-clicking + ContextMenu = _dummy; // Disable right-clicking Text = "None"; // Handle events that occurs when keys are pressed @@ -139,8 +139,8 @@ namespace GreenshotPlugin.Controls { KeyDown += HotkeyControl_KeyDown; // Fill the ArrayLists that contain all invalid hotkey combinations - needNonShiftModifier = new ArrayList(); - needNonAltGrModifier = new ArrayList(); + _needNonShiftModifier = new ArrayList(); + _needNonAltGrModifier = new ArrayList(); PopulateModifierLists(); } @@ -151,41 +151,41 @@ namespace GreenshotPlugin.Controls { private void PopulateModifierLists() { // Shift + 0 - 9, A - Z for (Keys k = Keys.D0; k <= Keys.Z; k++) { - needNonShiftModifier.Add((int)k); + _needNonShiftModifier.Add((int)k); } // Shift + Numpad keys for (Keys k = Keys.NumPad0; k <= Keys.NumPad9; k++) { - needNonShiftModifier.Add((int)k); + _needNonShiftModifier.Add((int)k); } // Shift + Misc (,;<./ etc) for (Keys k = Keys.Oem1; k <= Keys.OemBackslash; k++) { - needNonShiftModifier.Add((int)k); + _needNonShiftModifier.Add((int)k); } // Shift + Space, PgUp, PgDn, End, Home for (Keys k = Keys.Space; k <= Keys.Home; k++) { - needNonShiftModifier.Add((int)k); + _needNonShiftModifier.Add((int)k); } // Misc keys that we can't loop through - needNonShiftModifier.Add((int)Keys.Insert); - needNonShiftModifier.Add((int)Keys.Help); - needNonShiftModifier.Add((int)Keys.Multiply); - needNonShiftModifier.Add((int)Keys.Add); - needNonShiftModifier.Add((int)Keys.Subtract); - needNonShiftModifier.Add((int)Keys.Divide); - needNonShiftModifier.Add((int)Keys.Decimal); - needNonShiftModifier.Add((int)Keys.Return); - needNonShiftModifier.Add((int)Keys.Escape); - needNonShiftModifier.Add((int)Keys.NumLock); - needNonShiftModifier.Add((int)Keys.Scroll); - needNonShiftModifier.Add((int)Keys.Pause); + _needNonShiftModifier.Add((int)Keys.Insert); + _needNonShiftModifier.Add((int)Keys.Help); + _needNonShiftModifier.Add((int)Keys.Multiply); + _needNonShiftModifier.Add((int)Keys.Add); + _needNonShiftModifier.Add((int)Keys.Subtract); + _needNonShiftModifier.Add((int)Keys.Divide); + _needNonShiftModifier.Add((int)Keys.Decimal); + _needNonShiftModifier.Add((int)Keys.Return); + _needNonShiftModifier.Add((int)Keys.Escape); + _needNonShiftModifier.Add((int)Keys.NumLock); + _needNonShiftModifier.Add((int)Keys.Scroll); + _needNonShiftModifier.Add((int)Keys.Pause); // Ctrl+Alt + 0 - 9 for (Keys k = Keys.D0; k <= Keys.D9; k++) { - needNonAltGrModifier.Add((int)k); + _needNonAltGrModifier.Add((int)k); } } @@ -205,7 +205,6 @@ namespace GreenshotPlugin.Controls { // Clear the current hotkey if (e.KeyCode == Keys.Back || e.KeyCode == Keys.Delete) { ResetHotkey(); - return; } else { _modifiers = e.Modifiers; _hotkey = e.KeyCode; @@ -227,7 +226,6 @@ namespace GreenshotPlugin.Controls { if (_hotkey == Keys.None && ModifierKeys == Keys.None) { ResetHotkey(); - return; } } @@ -301,18 +299,11 @@ namespace GreenshotPlugin.Controls { } } - /// - /// Helper function - /// - private void Redraw() { - Redraw(false); - } - /// /// Redraws the TextBox when necessary. /// /// Specifies whether this function was called by the Hotkey/HotkeyModifiers properties or by the user. - private void Redraw(bool bCalledProgramatically) { + private void Redraw(bool bCalledProgramatically = false) { // No hotkey set if (_hotkey == Keys.None) { Text = ""; @@ -328,10 +319,10 @@ namespace GreenshotPlugin.Controls { // Only validate input if it comes from the user if (bCalledProgramatically == false) { // No modifier or shift only, AND a hotkey that needs another modifier - if ((_modifiers == Keys.Shift || _modifiers == Keys.None) && needNonShiftModifier.Contains((int)_hotkey)) { + if ((_modifiers == Keys.Shift || _modifiers == Keys.None) && _needNonShiftModifier.Contains((int)_hotkey)) { if (_modifiers == Keys.None) { // Set Ctrl+Alt as the modifier unless Ctrl+Alt+ won't work... - if (needNonAltGrModifier.Contains((int)_hotkey) == false) { + if (_needNonAltGrModifier.Contains((int)_hotkey) == false) { _modifiers = Keys.Alt | Keys.Control; } else { // ... in that case, use Shift+Alt instead. @@ -346,7 +337,7 @@ namespace GreenshotPlugin.Controls { } } // Check all Ctrl+Alt keys - if ((_modifiers == (Keys.Alt | Keys.Control)) && needNonAltGrModifier.Contains((int)_hotkey)) { + if ((_modifiers == (Keys.Alt | Keys.Control)) && _needNonAltGrModifier.Contains((int)_hotkey)) { // Ctrl+Alt+4 etc won't work; reset hotkey and tell the user _hotkey = Keys.None; Text = ""; @@ -373,7 +364,7 @@ namespace GreenshotPlugin.Controls { } public static string HotkeyToString(Keys modifierKeyCode, Keys virtualKeyCode) { - return HotkeyModifiersToString(modifierKeyCode) + virtualKeyCode.ToString(); + return HotkeyModifiersToString(modifierKeyCode) + virtualKeyCode; } public static string HotkeyModifiersToString(Keys modifierKeyCode) { @@ -446,8 +437,8 @@ namespace GreenshotPlugin.Controls { return key; } - public static void RegisterHotkeyHWND(IntPtr hWnd) { - hotkeyHWND = hWnd; + public static void RegisterHotkeyHwnd(IntPtr hWnd) { + _hotkeyHwnd = hWnd; } public static int RegisterHotKey(string hotkey, HotKeyHandler handler) { @@ -463,7 +454,7 @@ namespace GreenshotPlugin.Controls { /// the hotkey number, -1 if failed public static int RegisterHotKey(Keys modifierKeyCode, Keys virtualKeyCode, HotKeyHandler handler) { if (virtualKeyCode == Keys.None) { - LOG.Warn("Trying to register a Keys.none hotkey, ignoring"); + Log.Warn("Trying to register a Keys.none hotkey, ignoring"); return 0; } // Convert Modifiers to fit HKM_SETHOTKEY @@ -481,37 +472,37 @@ namespace GreenshotPlugin.Controls { modifiers |= (uint)Modifiers.WIN; } // Disable repeating hotkey for Windows 7 and beyond, as described in #1559 - if (isWindows7OrOlder) { + if (IsWindows7OrOlder) { modifiers |= (uint)Modifiers.NO_REPEAT; } - if (RegisterHotKey(hotkeyHWND, hotKeyCounter, modifiers, (uint)virtualKeyCode)) { - keyHandlers.Add(hotKeyCounter, handler); - return hotKeyCounter++; + if (RegisterHotKey(_hotkeyHwnd, _hotKeyCounter, modifiers, (uint)virtualKeyCode)) { + KeyHandlers.Add(_hotKeyCounter, handler); + return _hotKeyCounter++; } else { - LOG.Warn(String.Format("Couldn't register hotkey modifier {0} virtualKeyCode {1}", modifierKeyCode, virtualKeyCode)); + Log.Warn($"Couldn't register hotkey modifier {modifierKeyCode} virtualKeyCode {virtualKeyCode}"); return -1; } } public static void UnregisterHotkeys() { - foreach(int hotkey in keyHandlers.Keys) { - UnregisterHotKey(hotkeyHWND, hotkey); + foreach(int hotkey in KeyHandlers.Keys) { + UnregisterHotKey(_hotkeyHwnd, hotkey); } // Remove all key handlers - keyHandlers.Clear(); + KeyHandlers.Clear(); } public static void UnregisterHotkey(int hotkey) { bool removeHotkey = false; - foreach(int availableHotkey in keyHandlers.Keys) { + foreach(int availableHotkey in KeyHandlers.Keys) { if (availableHotkey == hotkey) { - UnregisterHotKey(hotkeyHWND, hotkey); + UnregisterHotKey(_hotkeyHwnd, hotkey); removeHotkey = true; } } if (removeHotkey) { // Remove key handler - keyHandlers.Remove(hotkey); + KeyHandlers.Remove(hotkey); } } @@ -523,11 +514,11 @@ namespace GreenshotPlugin.Controls { public static bool HandleMessages(ref Message m) { if (m.Msg == WM_HOTKEY) { // Call handler - if (isWindows7OrOlder) { - keyHandlers[(int)m.WParam](); + if (IsWindows7OrOlder) { + KeyHandlers[(int)m.WParam](); } else { - if (eventDelay.Check()) { - keyHandlers[(int)m.WParam](); + if (EventDelay.Check()) { + KeyHandlers[(int)m.WParam](); } } return true; @@ -537,10 +528,10 @@ namespace GreenshotPlugin.Controls { public static string GetKeyName(Keys givenKey) { StringBuilder keyName = new StringBuilder(); - const uint NUMPAD = 55; + const uint numpad = 55; Keys virtualKey = givenKey; - string keyString = ""; + string keyString; // Make VC's to real keys switch(virtualKey) { case Keys.Alt: @@ -553,17 +544,17 @@ namespace GreenshotPlugin.Controls { virtualKey = Keys.LShiftKey; break; case Keys.Multiply: - GetKeyNameText(NUMPAD << 16, keyName, 100); + GetKeyNameText(numpad << 16, keyName, 100); keyString = keyName.ToString().Replace("*","").Trim().ToLower(); - if (keyString.IndexOf("(") >= 0) { + if (keyString.IndexOf("(", StringComparison.Ordinal) >= 0) { return "* " + keyString; } keyString = keyString.Substring(0,1).ToUpper() + keyString.Substring(1).ToLower(); return keyString + " *"; case Keys.Divide: - GetKeyNameText(NUMPAD << 16, keyName, 100); + GetKeyNameText(numpad << 16, keyName, 100); keyString = keyName.ToString().Replace("*","").Trim().ToLower(); - if (keyString.IndexOf("(") >= 0) { + if (keyString.IndexOf("(", StringComparison.Ordinal) >= 0) { return "/ " + keyString; } keyString = keyString.Substring(0,1).ToUpper() + keyString.Substring(1).ToLower(); @@ -578,7 +569,7 @@ namespace GreenshotPlugin.Controls { case Keys.End: case Keys.Home: case Keys.Insert: case Keys.Delete: case Keys.NumLock: - LOG.Debug("Modifying Extended bit"); + Log.Debug("Modifying Extended bit"); scanCode |= 0x100; // set extended bit break; case Keys.PrintScreen: // PrintScreen diff --git a/GreenshotPlugin/Controls/ThumbnailForm.cs b/GreenshotPlugin/Controls/ThumbnailForm.cs index 72152185a..c0ca8435b 100644 --- a/GreenshotPlugin/Controls/ThumbnailForm.cs +++ b/GreenshotPlugin/Controls/ThumbnailForm.cs @@ -77,10 +77,10 @@ namespace GreenshotPlugin.Controls { SIZE sourceSize; DWM.DwmQueryThumbnailSourceSize(_thumbnailHandle, out sourceSize); int thumbnailHeight = 200; - int thumbnailWidth = (int)(thumbnailHeight * ((float)sourceSize.Width / (float)sourceSize.Height)); + int thumbnailWidth = (int)(thumbnailHeight * (sourceSize.Width / (float)sourceSize.Height)); if (parentControl != null && thumbnailWidth > parentControl.Width) { thumbnailWidth = parentControl.Width; - thumbnailHeight = (int)(thumbnailWidth * ((float)sourceSize.Height / (float)sourceSize.Width)); + thumbnailHeight = (int)(thumbnailWidth * (sourceSize.Height / (float)sourceSize.Width)); } Width = thumbnailWidth; Height = thumbnailHeight; diff --git a/GreenshotPlugin/Core/AbstractDestination.cs b/GreenshotPlugin/Core/AbstractDestination.cs index b0a0bd965..1980e2614 100644 --- a/GreenshotPlugin/Core/AbstractDestination.cs +++ b/GreenshotPlugin/Core/AbstractDestination.cs @@ -33,8 +33,8 @@ namespace GreenshotPlugin.Core { /// Description of AbstractDestination. /// public abstract class AbstractDestination : IDestination { - private static readonly ILog LOG = LogManager.GetLogger(typeof(AbstractDestination)); - private static readonly CoreConfiguration configuration = IniConfig.GetIniSection(); + private static readonly ILog Log = LogManager.GetLogger(typeof(AbstractDestination)); + private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); public virtual int CompareTo(object obj) { IDestination other = obj as IDestination; @@ -42,7 +42,7 @@ namespace GreenshotPlugin.Core { return 1; } if (Priority == other.Priority) { - return Description.CompareTo(other.Description); + return String.Compare(Description, other.Description, StringComparison.Ordinal); } return Priority - other.Priority; } @@ -55,23 +55,11 @@ namespace GreenshotPlugin.Core { get; } - public virtual int Priority { - get { - return 10; - } - } - - public virtual Image DisplayIcon { - get { - return null; - } - } + public virtual int Priority => 10; - public virtual Keys EditorShortcutKeys { - get { - return Keys.None; - } - } + public virtual Image DisplayIcon => null; + + public virtual Keys EditorShortcutKeys => Keys.None; public virtual IEnumerable DynamicDestinations() { yield break; @@ -86,27 +74,15 @@ namespace GreenshotPlugin.Core { //if (disposing) {} } - public virtual bool isDynamic { - get { - return false; - } - } + public virtual bool IsDynamic => false; - public virtual bool useDynamicsOnly { - get { - return false; - } - } + public virtual bool UseDynamicsOnly => false; - public virtual bool isLinkable { - get { - return false; - } - } + public virtual bool IsLinkable => false; - public virtual bool isActive { + public virtual bool IsActive { get { - if (configuration.ExcludeDestinations != null && configuration.ExcludeDestinations.Contains(Designation)) { + if (CoreConfig.ExcludeDestinations != null && CoreConfig.ExcludeDestinations.Contains(Designation)) { return false; } return true; @@ -132,7 +108,7 @@ namespace GreenshotPlugin.Core { surface.SendMessageEvent(this, SurfaceMessageTyp.Info, Language.GetFormattedString("exported_to", exportInformation.DestinationDescription)); } surface.Modified = false; - } else if (exportInformation != null && !string.IsNullOrEmpty(exportInformation.ErrorMessage)) { + } else if (!string.IsNullOrEmpty(exportInformation?.ErrorMessage)) { surface.SendMessageEvent(this, SurfaceMessageTyp.Error, Language.GetFormattedString("exported_to_error", exportInformation.DestinationDescription) + " " + exportInformation.ErrorMessage); } } @@ -149,12 +125,14 @@ namespace GreenshotPlugin.Core { /// Value for the tag private void AddTagEvents(ToolStripMenuItem menuItem, ContextMenuStrip menu, string tagValue) { if (menuItem != null && menu != null) { - menuItem.MouseDown += delegate(object source, MouseEventArgs eventArgs) { - LOG.DebugFormat("Setting tag to '{0}'", tagValue); + menuItem.MouseDown += delegate + { + Log.DebugFormat("Setting tag to '{0}'", tagValue); menu.Tag = tagValue; }; - menuItem.MouseUp += delegate(object source, MouseEventArgs eventArgs) { - LOG.Debug("Deleting tag"); + menuItem.MouseUp += delegate + { + Log.Debug("Deleting tag"); menu.Tag = null; }; } @@ -171,19 +149,21 @@ namespace GreenshotPlugin.Core { public ExportInformation ShowPickerMenu(bool addDynamics, ISurface surface, ICaptureDetails captureDetails, IEnumerable destinations) { // Generate an empty ExportInformation object, for when nothing was selected. ExportInformation exportInformation = new ExportInformation(Designation, Language.GetString("settings_destination_picker")); - ContextMenuStrip menu = new ContextMenuStrip(); - menu.ImageScalingSize = configuration.IconSize; - menu.Tag = null; + var menu = new ContextMenuStrip + { + ImageScalingSize = CoreConfig.IconSize, + Tag = null + }; menu.Closing += delegate(object source, ToolStripDropDownClosingEventArgs eventArgs) { - LOG.DebugFormat("Close reason: {0}", eventArgs.CloseReason); + Log.DebugFormat("Close reason: {0}", eventArgs.CloseReason); switch (eventArgs.CloseReason) { case ToolStripDropDownCloseReason.AppFocusChange: if (menu.Tag == null) { // Do not allow the close if the tag is not set, this means the user clicked somewhere else. eventArgs.Cancel = true; } else { - LOG.DebugFormat("Letting the menu 'close' as the tag is set to '{0}'", menu.Tag); + Log.DebugFormat("Letting the menu 'close' as the tag is set to '{0}'", menu.Tag); } break; case ToolStripDropDownCloseReason.ItemClicked: @@ -202,7 +182,8 @@ namespace GreenshotPlugin.Core { break; } }; - menu.MouseEnter += delegate(object source, EventArgs eventArgs) { + menu.MouseEnter += delegate + { // in case the menu has been unfocused, focus again so that dropdown menus will still open on mouseenter if(!menu.ContainsFocus) menu.Focus(); }; @@ -211,10 +192,7 @@ namespace GreenshotPlugin.Core { ToolStripMenuItem item = destination.GetMenuItem(addDynamics, menu, delegate(object sender, EventArgs e) { ToolStripMenuItem toolStripMenuItem = sender as ToolStripMenuItem; - if (toolStripMenuItem == null) { - return; - } - IDestination clickedDestination = (IDestination)toolStripMenuItem.Tag; + IDestination clickedDestination = (IDestination) toolStripMenuItem?.Tag; if (clickedDestination == null) { return; } @@ -222,7 +200,7 @@ namespace GreenshotPlugin.Core { // Export exportInformation = clickedDestination.ExportCapture(true, surface, captureDetails); if (exportInformation != null && exportInformation.ExportMade) { - LOG.InfoFormat("Export to {0} success, closing menu", exportInformation.DestinationDescription); + Log.InfoFormat("Export to {0} success, closing menu", exportInformation.DestinationDescription); // close menu if the destination wasn't the editor menu.Close(); @@ -232,7 +210,7 @@ namespace GreenshotPlugin.Core { surface = null; } } else { - LOG.Info("Export cancelled or failed, showing menu again"); + Log.Info("Export cancelled or failed, showing menu again"); // Make sure a click besides the menu don't close it. menu.Tag = null; @@ -248,8 +226,10 @@ namespace GreenshotPlugin.Core { } // Close menu.Items.Add(new ToolStripSeparator()); - ToolStripMenuItem closeItem = new ToolStripMenuItem(Language.GetString("editor_close")); - closeItem.Image = GreenshotResources.getImage("Close.Image"); + ToolStripMenuItem closeItem = new ToolStripMenuItem(Language.GetString("editor_close")) + { + Image = GreenshotResources.getImage("Close.Image") + }; closeItem.Click += delegate { // This menu entry is the close itself, we can dispose the surface menu.Close(); @@ -314,7 +294,7 @@ namespace GreenshotPlugin.Core { basisMenuItem.Click -= destinationClickHandler; basisMenuItem.Click += destinationClickHandler; - if (isDynamic && addDynamics) { + if (IsDynamic && addDynamics) { basisMenuItem.DropDownOpening += delegate { if (basisMenuItem.DropDownItems.Count == 0) { @@ -323,21 +303,21 @@ namespace GreenshotPlugin.Core { try { subDestinations.AddRange(DynamicDestinations()); } catch (Exception ex) { - LOG.ErrorFormat("Skipping {0}, due to the following error: {1}", Description, ex.Message); + Log.ErrorFormat("Skipping {0}, due to the following error: {1}", Description, ex.Message); } if (subDestinations.Count > 0) { - ToolStripMenuItem destinationMenuItem = null; - - if (useDynamicsOnly && subDestinations.Count == 1) { + if (UseDynamicsOnly && subDestinations.Count == 1) { basisMenuItem.Tag = subDestinations[0]; basisMenuItem.Text = subDestinations[0].Description; basisMenuItem.Click -= destinationClickHandler; basisMenuItem.Click += destinationClickHandler; } else { foreach (IDestination subDestination in subDestinations) { - destinationMenuItem = new ToolStripMenuItem(subDestination.Description); - destinationMenuItem.Tag = subDestination; - destinationMenuItem.Image = subDestination.DisplayIcon; + var destinationMenuItem = new ToolStripMenuItem(subDestination.Description) + { + Tag = subDestination, + Image = subDestination.DisplayIcon + }; destinationMenuItem.Click += destinationClickHandler; AddTagEvents(destinationMenuItem, menu, subDestination.Description); basisMenuItem.DropDownItems.Add(destinationMenuItem); diff --git a/GreenshotPlugin/Core/AccessibleHelper.cs b/GreenshotPlugin/Core/AccessibleHelper.cs index 704ecd60e..9b6064f30 100644 --- a/GreenshotPlugin/Core/AccessibleHelper.cs +++ b/GreenshotPlugin/Core/AccessibleHelper.cs @@ -33,11 +33,11 @@ namespace GreenshotPlugin.Core { /// Maybe move the basic Accessible functions to WindowDetails!? /// public class Accessible { - private static ILog LOG = LogManager.GetLogger(typeof(Accessible)); + private static readonly ILog Log = LogManager.GetLogger(typeof(Accessible)); #region Interop private static int AccessibleObjectFromWindow(IntPtr hWnd, OBJID idObject, ref IAccessible acc) { - Guid guid = new Guid("{618736e0-3c3d-11cf-810c-00aa00389b71}"); // IAccessible + var guid = new Guid("{618736e0-3c3d-11cf-810c-00aa00389b71}"); // IAccessible object obj = null; int num = AccessibleObjectFromWindow(hWnd, (uint)idObject, ref guid, ref obj); acc = (IAccessible)obj; diff --git a/GreenshotPlugin/Core/Cache.cs b/GreenshotPlugin/Core/Cache.cs index 0c5c09a78..61604c23b 100644 --- a/GreenshotPlugin/Core/Cache.cs +++ b/GreenshotPlugin/Core/Cache.cs @@ -30,11 +30,11 @@ namespace GreenshotPlugin.Core { /// Type of key /// Type of value public class Cache { - private static readonly ILog LOG = LogManager.GetLogger(typeof(Cache)); - private readonly IDictionary internalCache = new Dictionary(); - private readonly object lockObject = new object(); - private readonly int secondsToExpire = 10; - private readonly CacheObjectExpired expiredCallback; + private static readonly ILog Log = LogManager.GetLogger(typeof(Cache)); + private readonly IDictionary _internalCache = new Dictionary(); + private readonly object _lockObject = new object(); + private readonly int _secondsToExpire = 10; + private readonly CacheObjectExpired _expiredCallback; public delegate void CacheObjectExpired(TK key, TV cacheValue); /// @@ -47,7 +47,7 @@ namespace GreenshotPlugin.Core { /// /// public Cache(CacheObjectExpired expiredCallback) : this() { - this.expiredCallback = expiredCallback; + _expiredCallback = expiredCallback; } /// @@ -55,7 +55,7 @@ namespace GreenshotPlugin.Core { /// /// public Cache(int secondsToExpire) : this() { - this.secondsToExpire = secondsToExpire; + _secondsToExpire = secondsToExpire; } /// @@ -64,7 +64,7 @@ namespace GreenshotPlugin.Core { /// /// public Cache(int secondsToExpire, CacheObjectExpired expiredCallback) : this(expiredCallback) { - this.secondsToExpire = secondsToExpire; + _secondsToExpire = secondsToExpire; } /// @@ -74,9 +74,9 @@ namespace GreenshotPlugin.Core { get { List elements = new List(); - lock (lockObject) + lock (_lockObject) { - foreach (TV element in internalCache.Values) { + foreach (TV element in _internalCache.Values) { elements.Add(element); } } @@ -94,9 +94,9 @@ namespace GreenshotPlugin.Core { public TV this[TK key] { get { TV result = default(TV); - lock (lockObject) { - if (internalCache.ContainsKey(key)) { - result = internalCache[key]; + lock (_lockObject) { + if (_internalCache.ContainsKey(key)) { + result = _internalCache[key]; } } return result; @@ -110,9 +110,9 @@ namespace GreenshotPlugin.Core { /// true if the cache contains the key public bool Contains(TK key) { - lock (lockObject) + lock (_lockObject) { - return internalCache.ContainsKey(key); + return _internalCache.ContainsKey(key); } } @@ -130,28 +130,26 @@ namespace GreenshotPlugin.Core { /// /// /// - /// optional value for the seconds to expire + /// optional value for the seconds to expire public void Add(TK key, TV value, int? secondsToExpire) { - lock (lockObject) { - var cachedItem = new CachedItem(key, value, secondsToExpire.HasValue ? secondsToExpire.Value : this.secondsToExpire); + lock (_lockObject) { + var cachedItem = new CachedItem(key, value, secondsToExpire ?? _secondsToExpire); cachedItem.Expired += delegate(TK cacheKey, TV cacheValue) { - if (internalCache.ContainsKey(cacheKey)) { - LOG.DebugFormat("Expiring object with Key: {0}", cacheKey); - if (expiredCallback != null) { - expiredCallback(cacheKey, cacheValue); - } + if (_internalCache.ContainsKey(cacheKey)) { + Log.DebugFormat("Expiring object with Key: {0}", cacheKey); + _expiredCallback?.Invoke(cacheKey, cacheValue); Remove(cacheKey); } else { - LOG.DebugFormat("Expired old object with Key: {0}", cacheKey); + Log.DebugFormat("Expired old object with Key: {0}", cacheKey); } }; - if (internalCache.ContainsKey(key)) { - internalCache[key] = value; - LOG.DebugFormat("Updated item with Key: {0}", key); + if (_internalCache.ContainsKey(key)) { + _internalCache[key] = value; + Log.DebugFormat("Updated item with Key: {0}", key); } else { - internalCache.Add(key, cachedItem); - LOG.DebugFormat("Added item with Key: {0}", key); + _internalCache.Add(key, cachedItem); + Log.DebugFormat("Added item with Key: {0}", key); } } } @@ -161,12 +159,12 @@ namespace GreenshotPlugin.Core { /// /// public void Remove(TK key) { - lock (lockObject) { - if (!internalCache.ContainsKey(key)) { - throw new ApplicationException(String.Format("An object with key ‘{0}’ does not exists in cache", key)); + lock (_lockObject) { + if (!_internalCache.ContainsKey(key)) { + throw new ApplicationException($"An object with key ‘{key}’ does not exists in cache"); } - internalCache.Remove(key); - LOG.DebugFormat("Removed item with Key: {0}", key); + _internalCache.Remove(key); + Log.DebugFormat("Removed item with Key: {0}", key); } } @@ -175,27 +173,29 @@ namespace GreenshotPlugin.Core { /// private class CachedItem { public event CacheObjectExpired Expired; - private readonly int secondsToExpire; + private readonly int _secondsToExpire; private readonly Timer _timerEvent; public CachedItem(TK key, TV item, int secondsToExpire) { if (key == null) { - throw new ArgumentNullException("key is not valid"); + throw new ArgumentNullException(nameof(key)); } Key = key; Item = item; - this.secondsToExpire = secondsToExpire; - if (secondsToExpire > 0) { - _timerEvent = new Timer(secondsToExpire * 1000) { AutoReset = false }; - _timerEvent.Elapsed += timerEvent_Elapsed; - _timerEvent.Start(); + _secondsToExpire = secondsToExpire; + if (secondsToExpire <= 0) + { + return; } + _timerEvent = new Timer(secondsToExpire * 1000) { AutoReset = false }; + _timerEvent.Elapsed += timerEvent_Elapsed; + _timerEvent.Start(); } private void ExpireNow() { _timerEvent.Stop(); - if (secondsToExpire > 0 && Expired != null) { - Expired(Key, Item); + if (_secondsToExpire > 0) { + Expired?.Invoke(Key, Item); } } diff --git a/GreenshotPlugin/Core/ClipboardHelper.cs b/GreenshotPlugin/Core/ClipboardHelper.cs index 93984853c..6e9162f19 100644 --- a/GreenshotPlugin/Core/ClipboardHelper.cs +++ b/GreenshotPlugin/Core/ClipboardHelper.cs @@ -352,7 +352,7 @@ EndSelection:<<<<<<<4 retrieveFormats = new[] { FORMAT_PNG_OFFICEART, FORMAT_PNG, FORMAT_17, FORMAT_JFIF_OFFICEART, FORMAT_JPG, FORMAT_JFIF, DataFormats.Tiff, DataFormats.Dib, FORMAT_BITMAP, FORMAT_FILECONTENTS, FORMAT_GIF }; } foreach (string currentFormat in retrieveFormats) { - if (formats.Contains(currentFormat)) { + if (formats != null && formats.Contains(currentFormat)) { Log.InfoFormat("Found {0}, trying to retrieve.", currentFormat); returnImage = GetImageForFormat(currentFormat, dataObject); } else { @@ -385,54 +385,57 @@ EndSelection:<<<<<<<4 if (format == FORMAT_17 || format == DataFormats.Dib) { Log.Info("Found DIB stream, trying to process it."); try { - byte[] dibBuffer = new byte[imageStream.Length]; - imageStream.Read(dibBuffer, 0, dibBuffer.Length); - BITMAPINFOHEADER infoHeader = BinaryStructHelper.FromByteArray(dibBuffer); - if (!infoHeader.IsDibV5) { - Log.InfoFormat("Using special DIB (dibBuffer); + if (!infoHeader.IsDibV5) { + Log.InfoFormat("Using special DIB ") + "".Length).ToString("D8")); - sb.Replace("<<<<<<<2", (utf8EncodedHtmlString.IndexOf("")).ToString("D8")); - sb.Replace("<<<<<<<3", (utf8EncodedHtmlString.IndexOf("")+"".Length).ToString("D8")); - sb.Replace("<<<<<<<4", (utf8EncodedHtmlString.IndexOf("")).ToString("D8")); + sb.Replace("<<<<<<<1", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal) + "".Length).ToString("D8")); + sb.Replace("<<<<<<<2", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal)).ToString("D8")); + sb.Replace("<<<<<<<3", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal)+"".Length).ToString("D8")); + sb.Replace("<<<<<<<4", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal)).ToString("D8")); return sb.ToString(); } @@ -510,13 +513,14 @@ EndSelection:<<<<<<<4 utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${data}", Convert.ToBase64String(pngStream.GetBuffer(),0, (int)pngStream.Length)); StringBuilder sb=new StringBuilder(); sb.Append(utf8EncodedHtmlString); - sb.Replace("<<<<<<<1", (utf8EncodedHtmlString.IndexOf("") + "".Length).ToString("D8")); - sb.Replace("<<<<<<<2", (utf8EncodedHtmlString.IndexOf("")).ToString("D8")); - sb.Replace("<<<<<<<3", (utf8EncodedHtmlString.IndexOf("")+"".Length).ToString("D8")); - sb.Replace("<<<<<<<4", (utf8EncodedHtmlString.IndexOf("")).ToString("D8")); + sb.Replace("<<<<<<<1", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal) + "".Length).ToString("D8")); + sb.Replace("<<<<<<<2", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal)).ToString("D8")); + sb.Replace("<<<<<<<3", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal)+"".Length).ToString("D8")); + sb.Replace("<<<<<<<4", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal)).ToString("D8")); return sb.ToString(); } + private const int BITMAPFILEHEADER_LENGTH = 14; /// /// Set an Image to the clipboard /// This method will place images to the clipboard depending on the ClipboardFormats setting. @@ -526,7 +530,6 @@ EndSelection:<<<<<<<4 /// When pasting a Dib in PP 2003 the Bitmap is somehow shifted left! /// For this problem the user should not use the direct paste (=Dib), but select Bitmap /// - private const int BITMAPFILEHEADER_LENGTH = 14; public static void SetClipboardData(ISurface surface) { DataObject dataObject = new DataObject(); @@ -553,8 +556,8 @@ EndSelection:<<<<<<<4 // Set the PNG stream dataObject.SetData(FORMAT_PNG, false, pngStream); } - } catch (Exception pngEX) { - Log.Error("Error creating PNG for the Clipboard.", pngEX); + } catch (Exception pngEx) { + Log.Error("Error creating PNG for the Clipboard.", pngEx); } try { @@ -650,20 +653,10 @@ EndSelection:<<<<<<<4 // Place the DataObject to the clipboard SetDataObject(dataObject, true); } - - if (pngStream != null) { - pngStream.Dispose(); - pngStream = null; - } - if (dibStream != null) { - dibStream.Dispose(); - dibStream = null; - } - if (dibV5Stream != null) { - dibV5Stream.Dispose(); - dibV5Stream = null; - } + pngStream?.Dispose(); + dibStream?.Dispose(); + dibV5Stream?.Dispose(); // cleanup if needed if (disposeImage) { imageToSave?.Dispose(); diff --git a/GreenshotPlugin/Core/CoreConfiguration.cs b/GreenshotPlugin/Core/CoreConfiguration.cs index a667fa349..57de57088 100644 --- a/GreenshotPlugin/Core/CoreConfiguration.cs +++ b/GreenshotPlugin/Core/CoreConfiguration.cs @@ -287,9 +287,7 @@ namespace GreenshotPlugin.Core { } if (_iconSize != newSize) { _iconSize = value; - if (PropertyChanged != null) { - PropertyChanged(this, new PropertyChangedEventArgs("IconSize")); - } + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IconSize")); } } } @@ -317,18 +315,14 @@ namespace GreenshotPlugin.Core { } } - public bool UseLargeIcons { - get { - return IconSize.Width >= 32 || IconSize.Height >= 32; - } - } + public bool UseLargeIcons => IconSize.Width >= 32 || IconSize.Height >= 32; /// /// A helper method which returns true if the supplied experimental feature is enabled /// /// /// - public bool isExperimentalFeatureEnabled(string experimentalFeature) { + public bool IsExperimentalFeatureEnabled(string experimentalFeature) { return (ExperimentalFeatures != null && ExperimentalFeatures.Contains(experimentalFeature)); } @@ -367,23 +361,11 @@ namespace GreenshotPlugin.Core { case "DWMBackgroundColor": return Color.Transparent; case "ActiveTitleFixes": - List activeDefaults = new List(); - activeDefaults.Add("Firefox"); - activeDefaults.Add("IE"); - activeDefaults.Add("Chrome"); - return activeDefaults; + return new List {"Firefox", "IE", "Chrome"}; case "TitleFixMatcher": - Dictionary matcherDefaults = new Dictionary(); - matcherDefaults.Add("Firefox", " - Mozilla Firefox.*"); - matcherDefaults.Add("IE", " - (Microsoft|Windows) Internet Explorer.*"); - matcherDefaults.Add("Chrome", " - Google Chrome.*"); - return matcherDefaults; + return new Dictionary {{"Firefox", " - Mozilla Firefox.*"}, {"IE", " - (Microsoft|Windows) Internet Explorer.*"}, {"Chrome", " - Google Chrome.*"}}; case "TitleFixReplacer": - Dictionary replacerDefaults = new Dictionary(); - replacerDefaults.Add("Firefox", ""); - replacerDefaults.Add("IE", ""); - replacerDefaults.Add("Chrome", ""); - return replacerDefaults; + return new Dictionary {{"Firefox", ""}, {"IE", ""}, {"Chrome", ""}}; } return null; } @@ -417,7 +399,10 @@ namespace GreenshotPlugin.Core { try { // Store version, this can be used later to fix settings after an update LastSaveWithVersion = Assembly.GetEntryAssembly().GetName().Version.ToString(); - } catch { + } + catch + { + // ignored } } @@ -432,8 +417,10 @@ namespace GreenshotPlugin.Core { try { // Store version, this can be used later to fix settings after an update LastSaveWithVersion = Assembly.GetEntryAssembly().GetName().Version.ToString(); - } catch { - + } + catch + { + // ignored } // Disable the AutoReduceColors as it causes issues with Mozzila applications and some others OutputFileAutoReduceColors = false; @@ -465,10 +452,7 @@ namespace GreenshotPlugin.Core { // Make sure we have clipboard formats, otherwise a paste doesn't make sense! if (ClipboardFormats == null || ClipboardFormats.Count == 0) { - ClipboardFormats = new List(); - ClipboardFormats.Add(ClipboardFormat.PNG); - ClipboardFormats.Add(ClipboardFormat.HTML); - ClipboardFormats.Add(ClipboardFormat.DIB); + ClipboardFormats = new List {ClipboardFormat.PNG, ClipboardFormat.HTML, ClipboardFormat.DIB}; } // Make sure the lists are lowercase, to speedup the check diff --git a/GreenshotPlugin/Core/CredentialsHelper.cs b/GreenshotPlugin/Core/CredentialsHelper.cs index 6aa8d2bff..bffce88e5 100644 --- a/GreenshotPlugin/Core/CredentialsHelper.cs +++ b/GreenshotPlugin/Core/CredentialsHelper.cs @@ -114,7 +114,7 @@ namespace GreenshotPlugin.Core { /// Gets or sets if the credentials are to be persisted in the credential manager. public bool Persist { get; set; } = true; - /// Gets or sets if the incorrect password balloontip needs to be shown. Introduced AFTER Windows XPGets> + /// Gets or sets if the incorrect password balloontip needs to be shown. Introduced AFTER Windows XP public bool IncorrectPassword { get; set; } /// Gets or sets if the name is read-only. @@ -127,14 +127,12 @@ namespace GreenshotPlugin.Core { return _name; } set { - if (value != null) { - if (value.Length > CREDUI.MAX_USERNAME_LENGTH) { - string message = string.Format( - Thread.CurrentThread.CurrentUICulture, - "The name has a maximum length of {0} characters.", - CREDUI.MAX_USERNAME_LENGTH); - throw new ArgumentException(message, nameof(Name)); - } + if (value?.Length > CredUi.MAX_USERNAME_LENGTH) { + string message = string.Format( + Thread.CurrentThread.CurrentUICulture, + "The name has a maximum length of {0} characters.", + CredUi.MAX_USERNAME_LENGTH); + throw new ArgumentException(message, nameof(Name)); } _name = value; } @@ -147,14 +145,12 @@ namespace GreenshotPlugin.Core { return _password; } set { - if (value != null) { - if (value.Length > CREDUI.MAX_PASSWORD_LENGTH) { - string message = string.Format( - Thread.CurrentThread.CurrentUICulture, - "The password has a maximum length of {0} characters.", - CREDUI.MAX_PASSWORD_LENGTH); - throw new ArgumentException(message, nameof(Password)); - } + if (value?.Length > CredUi.MAX_PASSWORD_LENGTH) { + string message = string.Format( + Thread.CurrentThread.CurrentUICulture, + "The password has a maximum length of {0} characters.", + CredUi.MAX_PASSWORD_LENGTH); + throw new ArgumentException(message, nameof(Password)); } _password = value; } @@ -175,13 +171,13 @@ namespace GreenshotPlugin.Core { } set { if (value == null) { - throw new ArgumentException("The target cannot be a null value.", "Target"); + throw new ArgumentException("The target cannot be a null value.", nameof(Target)); } - if (value.Length > CREDUI.MAX_GENERIC_TARGET_LENGTH) { + if (value.Length > CredUi.MAX_GENERIC_TARGET_LENGTH) { string message = string.Format( Thread.CurrentThread.CurrentUICulture, "The target has a maximum length of {0} characters.", - CREDUI.MAX_GENERIC_TARGET_LENGTH); + CredUi.MAX_GENERIC_TARGET_LENGTH); throw new ArgumentException(message, nameof(Target)); } _target = value; @@ -196,14 +192,12 @@ namespace GreenshotPlugin.Core { return _caption; } set { - if (value != null) { - if (value.Length > CREDUI.MAX_CAPTION_LENGTH) { - string message = string.Format( - Thread.CurrentThread.CurrentUICulture, - "The caption has a maximum length of {0} characters.", - CREDUI.MAX_CAPTION_LENGTH); - throw new ArgumentException(message, nameof(Caption)); - } + if (value?.Length > CredUi.MAX_CAPTION_LENGTH) { + string message = string.Format( + Thread.CurrentThread.CurrentUICulture, + "The caption has a maximum length of {0} characters.", + CredUi.MAX_CAPTION_LENGTH); + throw new ArgumentException(message, nameof(Caption)); } _caption = value; } @@ -217,14 +211,12 @@ namespace GreenshotPlugin.Core { return _message; } set { - if (value != null) { - if (value.Length > CREDUI.MAX_MESSAGE_LENGTH) { - string message = string.Format( - Thread.CurrentThread.CurrentUICulture, - "The message has a maximum length of {0} characters.", - CREDUI.MAX_MESSAGE_LENGTH); - throw new ArgumentException(message, nameof(Message)); - } + if (value?.Length > CredUi.MAX_MESSAGE_LENGTH) { + string message = string.Format( + Thread.CurrentThread.CurrentUICulture, + "The message has a maximum length of {0} characters.", + CredUi.MAX_MESSAGE_LENGTH); + throw new ArgumentException(message, nameof(Message)); } _message = value; } @@ -331,11 +323,11 @@ namespace GreenshotPlugin.Core { /// Confirmation action to be applied. /// True if the credentials should be persisted. public void Confirm(bool value) { - switch (CREDUI.CredUIConfirmCredentials(Target, value)) { - case CREDUI.ReturnCodes.NO_ERROR: + switch (CredUi.CredUIConfirmCredentials(Target, value)) { + case CredUi.ReturnCodes.NO_ERROR: break; - case CREDUI.ReturnCodes.ERROR_INVALID_PARAMETER: + case CredUi.ReturnCodes.ERROR_INVALID_PARAMETER: // for some reason, this is encountered when credentials are overwritten break; @@ -351,26 +343,26 @@ namespace GreenshotPlugin.Core { /// private DialogResult ShowDialog(IWin32Window owner) { // set the api call parameters - StringBuilder name = new StringBuilder(CREDUI.MAX_USERNAME_LENGTH); + StringBuilder name = new StringBuilder(CredUi.MAX_USERNAME_LENGTH); name.Append(Name); - StringBuilder password = new StringBuilder(CREDUI.MAX_PASSWORD_LENGTH); + StringBuilder password = new StringBuilder(CredUi.MAX_PASSWORD_LENGTH); password.Append(Password); int saveChecked = Convert.ToInt32(SaveChecked); - CREDUI.INFO info = GetInfo(owner); - CREDUI.FLAGS flags = GetFlags(); + CredUi.INFO info = GetInfo(owner); + CredUi.CredFlags credFlags = GetFlags(); // make the api call - CREDUI.ReturnCodes code = CREDUI.CredUIPromptForCredentials( + CredUi.ReturnCodes code = CredUi.CredUIPromptForCredentials( ref info, Target, IntPtr.Zero, 0, - name, CREDUI.MAX_USERNAME_LENGTH, - password, CREDUI.MAX_PASSWORD_LENGTH, + name, CredUi.MAX_USERNAME_LENGTH, + password, CredUi.MAX_PASSWORD_LENGTH, ref saveChecked, - flags + credFlags ); // clean up resources @@ -388,8 +380,8 @@ namespace GreenshotPlugin.Core { /// Returns the info structure for dialog display settings. /// The System.Windows.Forms.IWin32Window the dialog will display in front of. - private CREDUI.INFO GetInfo(IWin32Window owner) { - CREDUI.INFO info = new CREDUI.INFO(); + private CredUi.INFO GetInfo(IWin32Window owner) { + CredUi.INFO info = new CredUi.INFO(); if (owner != null) info.hwndParent = owner.Handle; info.pszCaptionText = Caption; info.pszMessageText = Message; @@ -401,61 +393,61 @@ namespace GreenshotPlugin.Core { } /// Returns the flags for dialog display options. - private CREDUI.FLAGS GetFlags() { - CREDUI.FLAGS flags = CREDUI.FLAGS.GENERIC_CREDENTIALS; + private CredUi.CredFlags GetFlags() { + CredUi.CredFlags credFlags = CredUi.CredFlags.GENERIC_CREDENTIALS; if (IncorrectPassword) { - flags = flags | CREDUI.FLAGS.INCORRECT_PASSWORD; + credFlags = credFlags | CredUi.CredFlags.INCORRECT_PASSWORD; } if (AlwaysDisplay) { - flags = flags | CREDUI.FLAGS.ALWAYS_SHOW_UI; + credFlags = credFlags | CredUi.CredFlags.ALWAYS_SHOW_UI; } if (ExcludeCertificates) { - flags = flags | CREDUI.FLAGS.EXCLUDE_CERTIFICATES; + credFlags = credFlags | CredUi.CredFlags.EXCLUDE_CERTIFICATES; } if (Persist) { - flags = flags | CREDUI.FLAGS.EXPECT_CONFIRMATION; + credFlags = credFlags | CredUi.CredFlags.EXPECT_CONFIRMATION; if (SaveDisplayed) { - flags = flags | CREDUI.FLAGS.SHOW_SAVE_CHECK_BOX; + credFlags = credFlags | CredUi.CredFlags.SHOW_SAVE_CHECK_BOX; } else { - flags = flags | CREDUI.FLAGS.PERSIST; + credFlags = credFlags | CredUi.CredFlags.PERSIST; } } else { - flags = flags | CREDUI.FLAGS.DO_NOT_PERSIST; + credFlags = credFlags | CredUi.CredFlags.DO_NOT_PERSIST; } if (KeepName) { - flags = flags | CREDUI.FLAGS.KEEP_USERNAME; + credFlags = credFlags | CredUi.CredFlags.KEEP_USERNAME; } - return flags; + return credFlags; } /// Returns a DialogResult from the specified code. /// The credential return code. - private DialogResult GetDialogResult(CREDUI.ReturnCodes code) { + private DialogResult GetDialogResult(CredUi.ReturnCodes code) { DialogResult result; switch (code) { - case CREDUI.ReturnCodes.NO_ERROR: + case CredUi.ReturnCodes.NO_ERROR: result = DialogResult.OK; break; - case CREDUI.ReturnCodes.ERROR_CANCELLED: + case CredUi.ReturnCodes.ERROR_CANCELLED: result = DialogResult.Cancel; break; - case CREDUI.ReturnCodes.ERROR_NO_SUCH_LOGON_SESSION: + case CredUi.ReturnCodes.ERROR_NO_SUCH_LOGON_SESSION: throw new ApplicationException("No such logon session."); - case CREDUI.ReturnCodes.ERROR_NOT_FOUND: + case CredUi.ReturnCodes.ERROR_NOT_FOUND: throw new ApplicationException("Not found."); - case CREDUI.ReturnCodes.ERROR_INVALID_ACCOUNT_NAME: + case CredUi.ReturnCodes.ERROR_INVALID_ACCOUNT_NAME: throw new ApplicationException("Invalid account name."); - case CREDUI.ReturnCodes.ERROR_INSUFFICIENT_BUFFER: + case CredUi.ReturnCodes.ERROR_INSUFFICIENT_BUFFER: throw new ApplicationException("Insufficient buffer."); - case CREDUI.ReturnCodes.ERROR_INVALID_PARAMETER: + case CredUi.ReturnCodes.ERROR_INVALID_PARAMETER: throw new ApplicationException("Invalid parameter."); - case CREDUI.ReturnCodes.ERROR_INVALID_FLAGS: + case CredUi.ReturnCodes.ERROR_INVALID_FLAGS: throw new ApplicationException("Invalid flags."); default: throw new ApplicationException("Unknown credential result encountered."); @@ -464,10 +456,7 @@ namespace GreenshotPlugin.Core { } } - internal sealed class CREDUI { - private CREDUI() { - } - + internal static class CredUi { /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/secauthn/security/authentication_constants.asp public const int MAX_MESSAGE_LENGTH = 100; public const int MAX_CAPTION_LENGTH = 100; @@ -481,7 +470,8 @@ namespace GreenshotPlugin.Core { /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/dpapiusercredentials.asp /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/secauthn/security/creduipromptforcredentials.asp /// - [Flags] public enum FLAGS { + [Flags] + public enum CredFlags { INCORRECT_PASSWORD = 0x1, DO_NOT_PERSIST = 0x2, REQUEST_ADMINISTRATOR = 0x4, @@ -540,7 +530,7 @@ namespace GreenshotPlugin.Core { StringBuilder password, int maxPassword, ref int iSave, - FLAGS flags + CredFlags credFlags ); /// diff --git a/GreenshotPlugin/Core/DisplayKeyAttribute.cs b/GreenshotPlugin/Core/DisplayKeyAttribute.cs index fffd72c36..f8b1c4408 100644 --- a/GreenshotPlugin/Core/DisplayKeyAttribute.cs +++ b/GreenshotPlugin/Core/DisplayKeyAttribute.cs @@ -23,13 +23,10 @@ using System; namespace GreenshotPlugin.Core { [AttributeUsage(AttributeTargets.Field)] public sealed class DisplayKeyAttribute : Attribute { - private readonly string value; - public string Value { - get { return value; } - } - + public string Value { get; } + public DisplayKeyAttribute(string v) { - value = v; + Value = v; } public DisplayKeyAttribute() { diff --git a/GreenshotPlugin/Core/EffectConverter.cs b/GreenshotPlugin/Core/EffectConverter.cs new file mode 100644 index 000000000..1d41b8086 --- /dev/null +++ b/GreenshotPlugin/Core/EffectConverter.cs @@ -0,0 +1,180 @@ +using System; +using System.ComponentModel; +using System.Drawing; +using System.Globalization; +using System.Text; +using GreenshotPlugin.Effects; + +namespace Greenshot.Core +{ + public class EffectConverter : TypeConverter { + // Fix to prevent BUG-1753 + private readonly NumberFormatInfo _numberFormatInfo = new NumberFormatInfo(); + + public EffectConverter() + { + _numberFormatInfo.NumberDecimalSeparator = "."; + _numberFormatInfo.NumberGroupSeparator = ","; + } + + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { + if (sourceType == typeof(string)) { + return true; + } + return base.CanConvertFrom(context, sourceType); + } + + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { + if (destinationType == typeof(string)) { + return true; + } + if (destinationType == typeof(DropShadowEffect)) { + return true; + } + if (destinationType == typeof(TornEdgeEffect)) { + return true; + } + return base.CanConvertTo(context, destinationType); + } + + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { + // to string + if (destinationType == typeof(string)) { + StringBuilder sb = new StringBuilder(); + if (value.GetType() == typeof(DropShadowEffect)) { + DropShadowEffect effect = value as DropShadowEffect; + RetrieveDropShadowEffectValues(effect, sb); + return sb.ToString(); + } + if (value.GetType() == typeof(TornEdgeEffect)) { + TornEdgeEffect effect = value as TornEdgeEffect; + RetrieveDropShadowEffectValues(effect, sb); + sb.Append("|"); + RetrieveTornEdgeEffectValues(effect, sb); + return sb.ToString(); + } + } + // from string + if (value is string) { + string settings = value as string; + if (destinationType == typeof(DropShadowEffect)) { + DropShadowEffect effect = new DropShadowEffect(); + ApplyDropShadowEffectValues(settings, effect); + return effect; + } + if (destinationType == typeof(TornEdgeEffect)) { + TornEdgeEffect effect = new TornEdgeEffect(); + ApplyDropShadowEffectValues(settings, effect); + ApplyTornEdgeEffectValues(settings, effect); + return effect; + } + } + return base.ConvertTo(context, culture, value, destinationType); + } + + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { + var settings = value as string; + if (settings != null) { + if (settings.Contains("ToothHeight")) { + return ConvertTo(context, culture, settings, typeof(TornEdgeEffect)); + } + return ConvertTo(context, culture, settings, typeof(DropShadowEffect)); + } + return base.ConvertFrom(context, culture, value); + } + + private void ApplyDropShadowEffectValues(string valuesString, DropShadowEffect effect) { + string[] values = valuesString.Split('|'); + foreach(string nameValuePair in values) { + string[] pair = nameValuePair.Split(':'); + switch (pair[0]) { + case "Darkness" : + float darkness; + // Fix to prevent BUG-1753 + if (pair[1] != null && float.TryParse(pair[1], NumberStyles.Float, _numberFormatInfo, out darkness)) { + if (darkness <= 1.0) { + effect.Darkness = darkness; + } + } + break; + case "ShadowSize": + int shadowSize; + if (int.TryParse(pair[1], out shadowSize)) { + effect.ShadowSize = shadowSize; + } + break; + case "ShadowOffset": + Point shadowOffset = new Point(); + int shadowOffsetX; + int shadowOffsetY; + string[] coordinates = pair[1].Split(','); + if (int.TryParse(coordinates[0], out shadowOffsetX)) { + shadowOffset.X = shadowOffsetX; + } + if (int.TryParse(coordinates[1], out shadowOffsetY)) { + shadowOffset.Y = shadowOffsetY; + } + effect.ShadowOffset = shadowOffset; + break; + } + } + } + + private void ApplyTornEdgeEffectValues(string valuesString, TornEdgeEffect effect) { + string[] values = valuesString.Split('|'); + foreach (string nameValuePair in values) { + string[] pair = nameValuePair.Split(':'); + switch (pair[0]) { + case "GenerateShadow": + bool generateShadow; + if (bool.TryParse(pair[1], out generateShadow)) { + effect.GenerateShadow = generateShadow; + } + break; + case "ToothHeight": + int toothHeight; + if (int.TryParse(pair[1], out toothHeight)) { + effect.ToothHeight = toothHeight; + } + break; + case "HorizontalToothRange": + int horizontalToothRange; + if (int.TryParse(pair[1], out horizontalToothRange)) { + effect.HorizontalToothRange = horizontalToothRange; + } + break; + case "VerticalToothRange": + int verticalToothRange; + if (int.TryParse(pair[1], out verticalToothRange)) { + effect.VerticalToothRange = verticalToothRange; + } + break; + case "Edges": + string[] edges = pair[1].Split(','); + bool edge; + if (bool.TryParse(edges[0], out edge)) { + effect.Edges[0] = edge; + } + if (bool.TryParse(edges[1], out edge)) { + effect.Edges[1] = edge; + } + if (bool.TryParse(edges[2], out edge)) { + effect.Edges[2] = edge; + } + if (bool.TryParse(edges[3], out edge)) { + effect.Edges[3] = edge; + } + break; + } + } + } + + private void RetrieveDropShadowEffectValues(DropShadowEffect effect, StringBuilder sb) { + // Fix to prevent BUG-1753 is to use the numberFormatInfo + sb.AppendFormat("Darkness:{0}|ShadowSize:{1}|ShadowOffset:{2},{3}", effect.Darkness.ToString("F2", _numberFormatInfo), effect.ShadowSize, effect.ShadowOffset.X, effect.ShadowOffset.Y); + } + private void RetrieveTornEdgeEffectValues(TornEdgeEffect effect, StringBuilder sb) { + sb.AppendFormat("GenerateShadow:{0}|ToothHeight:{1}|HorizontalToothRange:{2}|VerticalToothRange:{3}|Edges:{4},{5},{6},{7}", effect.GenerateShadow, effect.ToothHeight, effect.HorizontalToothRange, effect.VerticalToothRange, effect.Edges[0], effect.Edges[1], effect.Edges[2], effect.Edges[3]); + } + } +} \ No newline at end of file diff --git a/GreenshotPlugin/Core/Effects.cs b/GreenshotPlugin/Core/Effects.cs deleted file mode 100644 index 30924a9a2..000000000 --- a/GreenshotPlugin/Core/Effects.cs +++ /dev/null @@ -1,529 +0,0 @@ -/* - * Greenshot - a free and open source screenshot tool - * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom - * - * For more information see: http://getgreenshot.org/ - * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 1 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -using GreenshotPlugin.Core; -using log4net; -using System; -using System.ComponentModel; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Drawing.Imaging; -using System.Globalization; -using System.Text; - -namespace Greenshot.Core { - /// - /// Interface to describe an effect - /// - public interface IEffect { - /// - /// Apply this IEffect to the supplied sourceImage. - /// In the process of applying the supplied matrix will be modified to represent the changes. - /// - /// Image to apply the effect to - /// Matrix with the modifications like rotate, translate etc. this can be used to calculate the new location of elements on a canvas - /// new image with applied effect - Image Apply(Image sourceImage, Matrix matrix); - - /// - /// Reset all values to their defaults - /// - void Reset(); - } - - /// - /// DropShadowEffect - /// - [TypeConverter(typeof(EffectConverter))] - public class DropShadowEffect : IEffect { - public DropShadowEffect() { - Reset(); - } - public float Darkness { - get; - set; - } - public int ShadowSize { - get; - set; - } - public Point ShadowOffset { - get; - set; - } - - public virtual void Reset() { - Darkness = 0.6f; - ShadowSize = 7; - ShadowOffset = new Point(-1, -1); - } - - public virtual Image Apply(Image sourceImage, Matrix matrix) { - return ImageHelper.CreateShadow(sourceImage, Darkness, ShadowSize, ShadowOffset, matrix, PixelFormat.Format32bppArgb); - } - } - - /// - /// TornEdgeEffect extends on DropShadowEffect - /// - [TypeConverter(typeof(EffectConverter))] - public class TornEdgeEffect : DropShadowEffect { - public TornEdgeEffect() - { - Reset(); - } - public int ToothHeight { - get; - set; - } - public int HorizontalToothRange { - get; - set; - } - public int VerticalToothRange { - get; - set; - } - public bool[] Edges { - get; - set; - } - public bool GenerateShadow { - get; - set; - } - - public override void Reset() { - base.Reset(); - ShadowSize = 7; - ToothHeight = 12; - HorizontalToothRange = 20; - VerticalToothRange = 20; - Edges = new[] { true, true, true, true }; - GenerateShadow = true; - } - public override Image Apply(Image sourceImage, Matrix matrix) { - Image tmpTornImage = ImageHelper.CreateTornEdge(sourceImage, ToothHeight, HorizontalToothRange, VerticalToothRange, Edges); - if (GenerateShadow) { - using (tmpTornImage) { - return ImageHelper.CreateShadow(tmpTornImage, Darkness, ShadowSize, ShadowOffset, matrix, PixelFormat.Format32bppArgb); - } - } - return tmpTornImage; - } - } - - /// - /// GrayscaleEffect - /// - public class GrayscaleEffect : IEffect { - public Image Apply(Image sourceImage, Matrix matrix) { - return ImageHelper.CreateGrayscale(sourceImage); - } - public void Reset() { - // No settings to reset - } - } - - /// - /// MonochromeEffect - /// - public class MonochromeEffect : IEffect { - private readonly byte _threshold; - /// Threshold for monochrome filter (0 - 255), lower value means less black - public MonochromeEffect(byte threshold) { - _threshold = threshold; - } - public void Reset() { - // TODO: Modify the threshold to have a default, which is reset here - } - public Image Apply(Image sourceImage, Matrix matrix) { - return ImageHelper.CreateMonochrome(sourceImage, _threshold); - } - } - - /// - /// AdjustEffect - /// - public class AdjustEffect : IEffect { - public AdjustEffect() - { - Reset(); - } - public float Contrast { - get; - set; - } - public float Brightness { - get; - set; - } - public float Gamma { - get; - set; - } - public void Reset() { - Contrast = 1f; - Brightness = 1f; - Gamma = 1f; - } - public Image Apply(Image sourceImage, Matrix matrix) { - return ImageHelper.Adjust(sourceImage, Brightness, Contrast, Gamma); - } - } - - /// - /// ReduceColorsEffect - /// - public class ReduceColorsEffect : IEffect { - private static readonly ILog LOG = LogManager.GetLogger(typeof(ReduceColorsEffect)); - public ReduceColorsEffect() - { - Reset(); - } - public int Colors { - get; - set; - } - public void Reset() { - Colors = 256; - } - public Image Apply(Image sourceImage, Matrix matrix) { - using (WuQuantizer quantizer = new WuQuantizer((Bitmap)sourceImage)) { - int colorCount = quantizer.GetColorCount(); - if (colorCount > Colors) { - try { - return quantizer.GetQuantizedImage(Colors); - } catch (Exception e) { - LOG.Warn("Error occurred while Quantizing the image, ignoring and using original. Error: ", e); - } - } - } - return null; - } - } - - /// - /// InvertEffect - /// - public class InvertEffect : IEffect { - public Image Apply(Image sourceImage, Matrix matrix) { - return ImageHelper.CreateNegative(sourceImage); - } - public void Reset() { - // No settings to reset - } - } - - /// - /// BorderEffect - /// - public class BorderEffect : IEffect { - public BorderEffect() { - Reset(); - } - public Color Color { - get; - set; - } - public int Width { - get; - set; - } - public void Reset() { - Width = 2; - Color = Color.Black; - } - public Image Apply(Image sourceImage, Matrix matrix) { - return ImageHelper.CreateBorder(sourceImage, Width, Color, sourceImage.PixelFormat, matrix); - } - } - - /// - /// RotateEffect - /// - public class RotateEffect : IEffect { - public RotateEffect(int angle) { - Angle = angle; - } - public int Angle { - get; - set; - } - public void Reset() { - // Angle doesn't have a default value - } - public Image Apply(Image sourceImage, Matrix matrix) { - RotateFlipType flipType; - if (Angle == 90) { - matrix.Rotate(90, MatrixOrder.Append); - matrix.Translate(sourceImage.Height, 0, MatrixOrder.Append); - flipType = RotateFlipType.Rotate90FlipNone; - } else if (Angle == -90 || Angle == 270) { - flipType = RotateFlipType.Rotate270FlipNone; - matrix.Rotate(-90, MatrixOrder.Append); - matrix.Translate(0, sourceImage.Width, MatrixOrder.Append); - } else { - throw new NotSupportedException("Currently only an angle of 90 or -90 (270) is supported."); - } - return ImageHelper.RotateFlip(sourceImage, flipType); - } - } - - /// - /// ResizeEffect - /// - public class ResizeEffect : IEffect { - public ResizeEffect(int width, int height, bool maintainAspectRatio) { - Width = width; - Height = height; - MaintainAspectRatio = maintainAspectRatio; - } - public int Width { - get; - set; - } - public int Height { - get; - set; - } - public bool MaintainAspectRatio { - get; - set; - } - public void Reset() { - // values don't have a default value - } - public Image Apply(Image sourceImage, Matrix matrix) { - return ImageHelper.ResizeImage(sourceImage, MaintainAspectRatio, Width, Height, matrix); - } - } - - /// - /// ResizeCanvasEffect - /// - public class ResizeCanvasEffect : IEffect { - public ResizeCanvasEffect(int left, int right, int top, int bottom) { - Left = left; - Right = right; - Top = top; - Bottom = bottom; - BackgroundColor = Color.Empty; // Uses the default background color depending on the format - } - public int Left { - get; - set; - } - public int Right { - get; - set; - } - public int Top { - get; - set; - } - public int Bottom { - get; - set; - } - public Color BackgroundColor { - get; - set; - } - public void Reset() { - // values don't have a default value - } - public Image Apply(Image sourceImage, Matrix matrix) { - return ImageHelper.ResizeCanvas(sourceImage, BackgroundColor, Left, Right, Top, Bottom, matrix); - } - } - - public class EffectConverter : TypeConverter { - // Fix to prevent BUG-1753 - private readonly NumberFormatInfo numberFormatInfo = new NumberFormatInfo(); - - public EffectConverter() - { - numberFormatInfo.NumberDecimalSeparator = "."; - numberFormatInfo.NumberGroupSeparator = ","; - } - - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { - if (sourceType == typeof(string)) { - return true; - } - return base.CanConvertFrom(context, sourceType); - } - - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { - if (destinationType == typeof(string)) { - return true; - } - if (destinationType == typeof(DropShadowEffect)) { - return true; - } - if (destinationType == typeof(TornEdgeEffect)) { - return true; - } - return base.CanConvertTo(context, destinationType); - } - - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { - // to string - if (destinationType == typeof(string)) { - StringBuilder sb = new StringBuilder(); - if (value.GetType() == typeof(DropShadowEffect)) { - DropShadowEffect effect = value as DropShadowEffect; - RetrieveDropShadowEffectValues(effect, sb); - return sb.ToString(); - } - if (value.GetType() == typeof(TornEdgeEffect)) { - TornEdgeEffect effect = value as TornEdgeEffect; - RetrieveDropShadowEffectValues(effect, sb); - sb.Append("|"); - RetrieveTornEdgeEffectValues(effect, sb); - return sb.ToString(); - } - } - // from string - if (value is string) { - string settings = value as string; - if (destinationType == typeof(DropShadowEffect)) { - DropShadowEffect effect = new DropShadowEffect(); - ApplyDropShadowEffectValues(settings, effect); - return effect; - } - if (destinationType == typeof(TornEdgeEffect)) { - TornEdgeEffect effect = new TornEdgeEffect(); - ApplyDropShadowEffectValues(settings, effect); - ApplyTornEdgeEffectValues(settings, effect); - return effect; - } - } - return base.ConvertTo(context, culture, value, destinationType); - } - - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - if (value != null && value is string) { - string settings = value as string; - if (settings.Contains("ToothHeight")) { - return ConvertTo(context, culture, value, typeof(TornEdgeEffect)); - } - return ConvertTo(context, culture, value, typeof(DropShadowEffect)); - } - return base.ConvertFrom(context, culture, value); - } - - private void ApplyDropShadowEffectValues(string valuesString, DropShadowEffect effect) { - string[] values = valuesString.Split('|'); - foreach(string nameValuePair in values) { - string[] pair = nameValuePair.Split(':'); - switch (pair[0]) { - case "Darkness" : - float darkness; - // Fix to prevent BUG-1753 - if (pair[1] != null && float.TryParse(pair[1], NumberStyles.Float, numberFormatInfo, out darkness)) { - if (darkness <= 1.0) { - effect.Darkness = darkness; - } - } - break; - case "ShadowSize": - int shadowSize; - if (int.TryParse(pair[1], out shadowSize)) { - effect.ShadowSize = shadowSize; - } - break; - case "ShadowOffset": - Point shadowOffset = new Point(); - int shadowOffsetX; - int shadowOffsetY; - string[] coordinates = pair[1].Split(','); - if (int.TryParse(coordinates[0], out shadowOffsetX)) { - shadowOffset.X = shadowOffsetX; - } - if (int.TryParse(coordinates[1], out shadowOffsetY)) { - shadowOffset.Y = shadowOffsetY; - } - effect.ShadowOffset = shadowOffset; - break; - } - } - } - - private void ApplyTornEdgeEffectValues(string valuesString, TornEdgeEffect effect) { - string[] values = valuesString.Split('|'); - foreach (string nameValuePair in values) { - string[] pair = nameValuePair.Split(':'); - switch (pair[0]) { - case "GenerateShadow": - bool generateShadow; - if (bool.TryParse(pair[1], out generateShadow)) { - effect.GenerateShadow = generateShadow; - } - break; - case "ToothHeight": - int toothHeight; - if (int.TryParse(pair[1], out toothHeight)) { - effect.ToothHeight = toothHeight; - } - break; - case "HorizontalToothRange": - int horizontalToothRange; - if (int.TryParse(pair[1], out horizontalToothRange)) { - effect.HorizontalToothRange = horizontalToothRange; - } - break; - case "VerticalToothRange": - int verticalToothRange; - if (int.TryParse(pair[1], out verticalToothRange)) { - effect.VerticalToothRange = verticalToothRange; - } - break; - case "Edges": - string[] edges = pair[1].Split(','); - bool edge; - if (bool.TryParse(edges[0], out edge)) { - effect.Edges[0] = edge; - } - if (bool.TryParse(edges[1], out edge)) { - effect.Edges[1] = edge; - } - if (bool.TryParse(edges[2], out edge)) { - effect.Edges[2] = edge; - } - if (bool.TryParse(edges[3], out edge)) { - effect.Edges[3] = edge; - } - break; - } - } - } - - private void RetrieveDropShadowEffectValues(DropShadowEffect effect, StringBuilder sb) { - // Fix to prevent BUG-1753 is to use the numberFormatInfo - sb.AppendFormat("Darkness:{0}|ShadowSize:{1}|ShadowOffset:{2},{3}", effect.Darkness.ToString("F2", numberFormatInfo), effect.ShadowSize, effect.ShadowOffset.X, effect.ShadowOffset.Y); - } - private void RetrieveTornEdgeEffectValues(TornEdgeEffect effect, StringBuilder sb) { - sb.AppendFormat("GenerateShadow:{0}|ToothHeight:{1}|HorizontalToothRange:{2}|VerticalToothRange:{3}|Edges:{4},{5},{6},{7}", effect.GenerateShadow, effect.ToothHeight, effect.HorizontalToothRange, effect.VerticalToothRange, effect.Edges[0], effect.Edges[1], effect.Edges[2], effect.Edges[3]); - } - } -} \ No newline at end of file diff --git a/GreenshotPlugin/Core/EmailConfigHelper.cs b/GreenshotPlugin/Core/EmailConfigHelper.cs index c5ce92d0b..14ae354f2 100644 --- a/GreenshotPlugin/Core/EmailConfigHelper.cs +++ b/GreenshotPlugin/Core/EmailConfigHelper.cs @@ -26,38 +26,32 @@ namespace GreenshotPlugin.Core { /// Description of EmailConfigHelper. /// public static class EmailConfigHelper { - private const string OUTLOOK_PATH_KEY = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\OUTLOOK.EXE"; - private const string MAPI_CLIENT_KEY = @"SOFTWARE\Clients\Mail"; - private const string MAPI_LOCATION_KEY = @"SOFTWARE\Microsoft\Windows Messaging Subsystem"; - private const string MAPI_KEY = @"MAPI"; + private const string OutlookPathKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\OUTLOOK.EXE"; + private const string MapiClientKey = @"SOFTWARE\Clients\Mail"; + private const string MapiLocationKey = @"SOFTWARE\Microsoft\Windows Messaging Subsystem"; + private const string MapiKey = @"MAPI"; public static string GetMapiClient() { - using (RegistryKey key = Registry.CurrentUser.OpenSubKey(MAPI_CLIENT_KEY, false)) { + using (RegistryKey key = Registry.CurrentUser.OpenSubKey(MapiClientKey, false)) { if (key != null) { return (string)key.GetValue(""); } } - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(MAPI_CLIENT_KEY, false)) { - if (key != null) { - return (string)key.GetValue(""); - } else { - return null; - } + using (RegistryKey key = Registry.LocalMachine.OpenSubKey(MapiClientKey, false)) + { + return (string) key?.GetValue(""); } } - public static bool HasMAPI() { - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(MAPI_LOCATION_KEY, false)) { - if (key != null) { - return "1".Equals(key.GetValue(MAPI_KEY, "0")); - } else { - return false; - } + public static bool HasMapi() { + using (RegistryKey key = Registry.LocalMachine.OpenSubKey(MapiLocationKey, false)) + { + return key != null && "1".Equals(key.GetValue(MapiKey, "0")); } } public static string GetOutlookExePath() { - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(OUTLOOK_PATH_KEY, false)) { + using (RegistryKey key = Registry.LocalMachine.OpenSubKey(OutlookPathKey, false)) { if (key != null) { // "" is the default key, which should point to the outlook location return (string)key.GetValue(""); diff --git a/GreenshotPlugin/Core/EnumExtensions.cs b/GreenshotPlugin/Core/EnumExtensions.cs index 26d8e0c16..1201f28f9 100644 --- a/GreenshotPlugin/Core/EnumExtensions.cs +++ b/GreenshotPlugin/Core/EnumExtensions.cs @@ -20,8 +20,8 @@ */ using System; namespace GreenshotPlugin.Core { - public static class EnumerationExtensions { - public static bool Has(this Enum type, T value) { + public static class EnumerationExtensions { + public static bool Has(this Enum type, T value) { Type underlyingType = Enum.GetUnderlyingType(value.GetType()); try { if (underlyingType == typeof(int)) { @@ -29,23 +29,31 @@ namespace GreenshotPlugin.Core { } else if (underlyingType == typeof(uint)) { return (((uint)(object)type & (uint)(object)value) == (uint)(object)value); } - } catch { - } + } + catch + { + // ignored + } return false; - } + } - public static bool Is(this Enum type, T value) { + public static bool Is(this Enum type, T value) { Type underlyingType = Enum.GetUnderlyingType(value.GetType()); - try { + try + { if (underlyingType == typeof(int)) { return (int)(object)type == (int)(object)value; - } else if (underlyingType == typeof(uint)) { + } + if (underlyingType == typeof(uint)) { return (uint)(object)type == (uint)(object)value; } - } catch { - } + } + catch + { + // ignored + } return false; - } + } /// /// Add a flag to an enum @@ -53,19 +61,21 @@ namespace GreenshotPlugin.Core { /// /// /// - public static T Add(this Enum type, T value) { + public static T Add(this Enum type, T value) { Type underlyingType = Enum.GetUnderlyingType(value.GetType()); - try { + try + { if (underlyingType == typeof(int)) { return (T)(object)(((int)(object)type | (int)(object)value)); - } else if (underlyingType == typeof(uint)) { + } + if (underlyingType == typeof(uint)) { return (T)(object)(((uint)(object)type | (uint)(object)value)); } } catch(Exception ex) { - throw new ArgumentException(string.Format("Could not append value '{0}' to enumerated type '{1}'.", value, typeof(T).Name), ex); + throw new ArgumentException($"Could not append value '{value}' to enumerated type '{typeof(T).Name}'.", ex); } - throw new ArgumentException(string.Format("Could not append value '{0}' to enumerated type '{1}'.", value, typeof(T).Name)); - } + throw new ArgumentException($"Could not append value '{value}' to enumerated type '{typeof(T).Name}'."); + } /// /// Remove a flag from an enum type @@ -73,18 +83,20 @@ namespace GreenshotPlugin.Core { /// /// /// - public static T Remove(this Enum type, T value) { + public static T Remove(this Enum type, T value) { Type underlyingType = Enum.GetUnderlyingType(value.GetType()); - try { + try + { if (underlyingType == typeof(int)) { return (T)(object)(((int)(object)type & ~(int)(object)value)); - } else if (underlyingType == typeof(uint)) { + } + if (underlyingType == typeof(uint)) { return (T)(object)(((uint)(object)type & ~(uint)(object)value)); } } catch(Exception ex) { - throw new ArgumentException(string.Format("Could not remove value '{0}' from enumerated type '{1}'.", value, typeof(T).Name), ex); + throw new ArgumentException($"Could not remove value '{value}' from enumerated type '{typeof(T).Name}'.", ex); } - throw new ArgumentException(string.Format("Could not remove value '{0}' from enumerated type '{1}'.", value, typeof(T).Name)); - } - } + throw new ArgumentException($"Could not remove value '{value}' from enumerated type '{typeof(T).Name}'."); + } + } } diff --git a/GreenshotPlugin/Core/FastBitmap.cs b/GreenshotPlugin/Core/FastBitmap.cs index 564a4e4d4..8bc3b3313 100644 --- a/GreenshotPlugin/Core/FastBitmap.cs +++ b/GreenshotPlugin/Core/FastBitmap.cs @@ -22,7 +22,6 @@ using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; -using log4net; namespace GreenshotPlugin.Core { @@ -285,9 +284,7 @@ namespace GreenshotPlugin.Core { /// /// The base class for the fast bitmap implementation /// - public abstract unsafe class FastBitmap : IFastBitmap, IFastBitmapWithClip, IFastBitmapWithOffset { - private static ILog _log = LogManager.GetLogger(typeof(FastBitmap)); - + public abstract unsafe class FastBitmap : IFastBitmapWithClip, IFastBitmapWithOffset { protected const int PixelformatIndexA = 3; protected const int PixelformatIndexR = 2; protected const int PixelformatIndexG = 1; @@ -298,7 +295,7 @@ namespace GreenshotPlugin.Core { public const int ColorIndexB = 2; public const int ColorIndexA = 3; - protected Rectangle Area = Rectangle.Empty; + protected Rectangle Area; /// /// If this is set to true, the bitmap will be disposed when disposing the IFastBitmap /// @@ -354,7 +351,7 @@ namespace GreenshotPlugin.Core { case PixelFormat.Format32bppPArgb: return new Fast32ArgbBitmap(source, area); default: - throw new NotSupportedException(string.Format("Not supported Pixelformat {0}", source.PixelFormat)); + throw new NotSupportedException($"Not supported Pixelformat {source.PixelFormat}"); } } @@ -396,9 +393,12 @@ namespace GreenshotPlugin.Core { public static IFastBitmap CreateCloneOf(Image source, PixelFormat pixelFormat, Rectangle area) { Bitmap destination = ImageHelper.CloneArea(source, area, pixelFormat); FastBitmap fastBitmap = Create(destination) as FastBitmap; - fastBitmap.NeedsDispose = true; - fastBitmap.Left = area.Left; - fastBitmap.Top = area.Top; + if (fastBitmap != null) + { + fastBitmap.NeedsDispose = true; + fastBitmap.Left = area.Left; + fastBitmap.Top = area.Top; + } return fastBitmap; } @@ -529,20 +529,12 @@ namespace GreenshotPlugin.Core { /// /// Return the right of the fastbitmap /// - public int Right { - get { - return Left + Width; - } - } + public int Right => Left + Width; /// /// Return the bottom of the fastbitmap /// - public int Bottom { - get { - return Top + Height; - } - } + public int Bottom => Top + Height; /// /// Returns the underlying bitmap, unlocks it and prevents that it will be disposed @@ -555,11 +547,7 @@ namespace GreenshotPlugin.Core { return Bitmap; } - public virtual bool HasAlphaChannel { - get { - return false; - } - } + public virtual bool HasAlphaChannel => false; /// /// Destructor @@ -600,14 +588,16 @@ namespace GreenshotPlugin.Core { /// Lock the bitmap so we have direct access to the memory /// public void Lock() { - if (Width > 0 && Height > 0 && !BitsLocked) { - BmData = Bitmap.LockBits(Area, ImageLockMode.ReadWrite, Bitmap.PixelFormat); - BitsLocked = true; - - IntPtr scan0 = BmData.Scan0; - Pointer = (byte*)(void*)scan0; - Stride = BmData.Stride; + if (Width <= 0 || Height <= 0 || BitsLocked) + { + return; } + BmData = Bitmap.LockBits(Area, ImageLockMode.ReadWrite, Bitmap.PixelFormat); + BitsLocked = true; + + IntPtr scan0 = BmData.Scan0; + Pointer = (byte*)(void*)scan0; + Stride = BmData.Stride; } /// @@ -635,7 +625,6 @@ namespace GreenshotPlugin.Core { /// /// /// - /// public void DrawTo(Graphics graphics, Rectangle destinationRect) { // Make sure this.bitmap is unlocked, if it was locked bool isLocked = BitsLocked; @@ -944,11 +933,7 @@ namespace GreenshotPlugin.Core { /// This is the implementation of the IFastBitmap for 32 bit images with Alpha /// public unsafe class Fast32ArgbBitmap : FastBitmap, IFastBitmapWithBlend { - public override bool HasAlphaChannel { - get { - return true; - } - } + public override bool HasAlphaChannel => true; public Color BackgroundBlendColor { get; diff --git a/GreenshotPlugin/Core/FilenameHelper.cs b/GreenshotPlugin/Core/FilenameHelper.cs index 9e890ce76..b3ed50181 100644 --- a/GreenshotPlugin/Core/FilenameHelper.cs +++ b/GreenshotPlugin/Core/FilenameHelper.cs @@ -30,27 +30,27 @@ using System.Collections.Generic; namespace GreenshotPlugin.Core { public static class FilenameHelper { - private static readonly ILog LOG = LogManager.GetLogger(typeof(FilenameHelper)); + private static readonly ILog Log = LogManager.GetLogger(typeof(FilenameHelper)); // Specify the regular expression for the filename formatting: // Starting with ${ // than the varname, which ends with a : or } // If a parameters needs to be supplied, than a ":" should follow the name... everything from the : until the } is considered to be part of the parameters. // The parameter format is a single alpha followed by the value belonging to the parameter, e.g. : // ${capturetime:d"yyyy-MM-dd HH_mm_ss"} - private static readonly Regex VAR_REGEXP = new Regex(@"\${(?[^:}]+)[:]?(?[^}]*)}", RegexOptions.Compiled); - private static readonly Regex CMD_VAR_REGEXP = new Regex(@"%(?[^%]+)%", RegexOptions.Compiled); + private static readonly Regex VarRegexp = new Regex(@"\${(?[^:}]+)[:]?(?[^}]*)}", RegexOptions.Compiled); + private static readonly Regex CmdVarRegexp = new Regex(@"%(?[^%]+)%", RegexOptions.Compiled); - private static readonly Regex SPLIT_REGEXP = new Regex(";(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", RegexOptions.Compiled); - private const int MAX_TITLE_LENGTH = 80; - private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); - private const string UNSAFE_REPLACEMENT = "_"; + private static readonly Regex SplitRegexp = new Regex(";(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", RegexOptions.Compiled); + private const int MaxTitleLength = 80; + private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); + private const string UnsafeReplacement = "_"; /// /// Remove invalid characters from the fully qualified filename /// /// string with the full path to a file /// string with the full path to a file, without invalid characters - public static string MakeFQFilenameSafe(string fullPath) { + public static string MakeFqFilenameSafe(string fullPath) { string path = MakePathSafe(Path.GetDirectoryName(fullPath)); string filename = MakeFilenameSafe(Path.GetFileName(fullPath)); // Make the fullpath again and return @@ -66,7 +66,7 @@ namespace GreenshotPlugin.Core { // Make the filename save! if (filename != null) { foreach (char disallowed in Path.GetInvalidFileNameChars()) { - filename = filename.Replace(disallowed.ToString(), UNSAFE_REPLACEMENT); + filename = filename.Replace(disallowed.ToString(), UnsafeReplacement); } } return filename; @@ -81,7 +81,7 @@ namespace GreenshotPlugin.Core { // Make the path save! if (path != null) { foreach (char disallowed in Path.GetInvalidPathChars()) { - path = path.Replace(disallowed.ToString(), UNSAFE_REPLACEMENT); + path = path.Replace(disallowed.ToString(), UnsafeReplacement); } } return path; @@ -108,15 +108,16 @@ namespace GreenshotPlugin.Core { /// that is specified in the configuration /// /// A string with the format + /// /// The filename which should be used to save the image public static string GetFilename(OutputFormat format, ICaptureDetails captureDetails) { - string pattern = conf.OutputFileFilenamePattern; - if (pattern == null || string.IsNullOrEmpty(pattern.Trim())) { + string pattern = CoreConfig.OutputFileFilenamePattern; + if (string.IsNullOrEmpty(pattern?.Trim())) { pattern = "greenshot ${capturetime}"; } return GetFilenameFromPattern(pattern, format, captureDetails); } - + /// /// This method will be called by the regexp.replace as a MatchEvaluator delegate! @@ -127,14 +128,15 @@ namespace GreenshotPlugin.Core { /// Variables from the process /// Variables from the user /// Variables from the machine + /// /// string with the match replacement private static string MatchVarEvaluator(Match match, ICaptureDetails captureDetails, IDictionary processVars, IDictionary userVars, IDictionary machineVars, bool filenameSafeMode) { try { return MatchVarEvaluatorInternal(match, captureDetails, processVars, userVars, machineVars, filenameSafeMode); } catch (Exception e) { - LOG.Error("Error in MatchVarEvaluatorInternal", e); + Log.Error("Error in MatchVarEvaluatorInternal", e); } - return ""; + return string.Empty; } /// @@ -159,17 +161,20 @@ namespace GreenshotPlugin.Core { string variable = match.Groups["variable"].Value; string parameters = match.Groups["parameters"].Value; - if (parameters != null && parameters.Length > 0) { - string[] parms = SPLIT_REGEXP.Split(parameters); + if (parameters.Length > 0) { + string[] parms = SplitRegexp.Split(parameters); foreach (string parameter in parms) { switch (parameter.Substring(0, 1)) { // Padding p[,pad-character] case "p": - string[] padParams = parameter.Substring(1).Split(new[] { ',' }); + string[] padParams = parameter.Substring(1).Split(','); try { padWidth = int.Parse(padParams[0]); - } catch { - }; + } + catch + { + // ignored + } if (padParams.Length > 1) { padChar = padParams[1][0]; } @@ -177,7 +182,7 @@ namespace GreenshotPlugin.Core { // replace // r, case "r": - string[] replaceParameters = parameter.Substring(1).Split(new[] { ',' }); + string[] replaceParameters = parameter.Substring(1).Split(','); if (replaceParameters != null && replaceParameters.Length == 2) { replacements.Add(replaceParameters[0], replaceParameters[1]); } @@ -197,7 +202,7 @@ namespace GreenshotPlugin.Core { // s[,length] case "s": string range = parameter.Substring(1); - string[] rangelist = range.Split(new[] { ',' }); + string[] rangelist = range.Split(','); if (rangelist.Length > 0) { try { startIndex = int.Parse(rangelist[0]); @@ -231,7 +236,7 @@ namespace GreenshotPlugin.Core { if (filenameSafeMode) { replaceValue = MakePathSafe(replaceValue); } - } else if (captureDetails != null && captureDetails.MetaData != null && captureDetails.MetaData.ContainsKey(variable)) { + } else if (captureDetails?.MetaData != null && captureDetails.MetaData.ContainsKey(variable)) { replaceValue = captureDetails.MetaData[variable]; if (filenameSafeMode) { replaceValue = MakePathSafe(replaceValue); @@ -248,8 +253,8 @@ namespace GreenshotPlugin.Core { capturetime = captureDetails.DateTime; if (captureDetails.Title != null) { title = captureDetails.Title; - if (title.Length > MAX_TITLE_LENGTH) { - title = title.Substring(0, MAX_TITLE_LENGTH); + if (title.Length > MaxTitleLength) { + title = title.Substring(0, MaxTitleLength); } } } @@ -318,9 +323,9 @@ namespace GreenshotPlugin.Core { } break; case "NUM": - conf.OutputFileIncrementingNumber++; + CoreConfig.OutputFileIncrementingNumber++; IniConfig.Save(); - replaceValue = conf.OutputFileIncrementingNumber.ToString(); + replaceValue = CoreConfig.OutputFileIncrementingNumber.ToString(); if (padWidth == 0) { padWidth = -6; padChar = '0'; @@ -412,7 +417,7 @@ namespace GreenshotPlugin.Core { } catch (Exception e) { - LOG.Error("Error retrieving EnvironmentVariableTarget.Process", e); + Log.Error("Error retrieving EnvironmentVariableTarget.Process", e); } try @@ -421,7 +426,7 @@ namespace GreenshotPlugin.Core { } catch (Exception e) { - LOG.Error("Error retrieving EnvironmentVariableTarget.User", e); + Log.Error("Error retrieving EnvironmentVariableTarget.User", e); } try @@ -430,13 +435,11 @@ namespace GreenshotPlugin.Core { } catch (Exception e) { - LOG.Error("Error retrieving EnvironmentVariableTarget.Machine", e); + Log.Error("Error retrieving EnvironmentVariableTarget.Machine", e); } - return CMD_VAR_REGEXP.Replace(pattern, - delegate (Match m) { - return MatchVarEvaluator(m, null, processVars, userVars, machineVars, filenameSafeMode); - } + return CmdVarRegexp.Replace(pattern, + m => MatchVarEvaluator(m, null, processVars, userVars, machineVars, filenameSafeMode) ); } @@ -453,25 +456,23 @@ namespace GreenshotPlugin.Core { try { processVars = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Process); } catch (Exception e) { - LOG.Error("Error retrieving EnvironmentVariableTarget.Process", e); + Log.Error("Error retrieving EnvironmentVariableTarget.Process", e); } try { userVars = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User); } catch (Exception e) { - LOG.Error("Error retrieving EnvironmentVariableTarget.User", e); + Log.Error("Error retrieving EnvironmentVariableTarget.User", e); } try { machineVars = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine); } catch (Exception e) { - LOG.Error("Error retrieving EnvironmentVariableTarget.Machine", e); + Log.Error("Error retrieving EnvironmentVariableTarget.Machine", e); } - return VAR_REGEXP.Replace(pattern, - delegate(Match m) { - return MatchVarEvaluator(m, null, processVars, userVars, machineVars, filenameSafeMode); - } + return VarRegexp.Replace(pattern, + m => MatchVarEvaluator(m, null, processVars, userVars, machineVars, filenameSafeMode) ); } @@ -489,26 +490,24 @@ namespace GreenshotPlugin.Core { try { processVars = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Process); } catch (Exception e) { - LOG.Error("Error retrieving EnvironmentVariableTarget.Process", e); + Log.Error("Error retrieving EnvironmentVariableTarget.Process", e); } try { userVars = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User); } catch (Exception e) { - LOG.Error("Error retrieving EnvironmentVariableTarget.User", e); + Log.Error("Error retrieving EnvironmentVariableTarget.User", e); } try { machineVars = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine); } catch (Exception e) { - LOG.Error("Error retrieving EnvironmentVariableTarget.Machine", e); + Log.Error("Error retrieving EnvironmentVariableTarget.Machine", e); } try { - return VAR_REGEXP.Replace(pattern, - delegate(Match m) { - return MatchVarEvaluator(m, captureDetails, processVars, userVars, machineVars, filenameSafeMode); - } + return VarRegexp.Replace(pattern, + m => MatchVarEvaluator(m, captureDetails, processVars, userVars, machineVars, filenameSafeMode) ); } catch (Exception e) { // adding additional data for bug tracking diff --git a/GreenshotPlugin/Core/ImageHelper.cs b/GreenshotPlugin/Core/ImageHelper.cs index 44e0fd7b6..a9169d097 100644 --- a/GreenshotPlugin/Core/ImageHelper.cs +++ b/GreenshotPlugin/Core/ImageHelper.cs @@ -29,6 +29,7 @@ using Greenshot.IniFile; using GreenshotPlugin.UnmanagedHelpers; using Greenshot.Core; using Greenshot.Plugin; +using GreenshotPlugin.Effects; using log4net; namespace GreenshotPlugin.Core { diff --git a/GreenshotPlugin/Core/ImageOutput.cs b/GreenshotPlugin/Core/ImageOutput.cs index 3b1803e95..7a2e40f37 100644 --- a/GreenshotPlugin/Core/ImageOutput.cs +++ b/GreenshotPlugin/Core/ImageOutput.cs @@ -167,7 +167,6 @@ namespace GreenshotPlugin.Core { AddTag(nonAlphaImage); nonAlphaImage.Save(targetStream, imageCodec, parameters); nonAlphaImage.Dispose(); - nonAlphaImage = null; } else { @@ -205,7 +204,6 @@ namespace GreenshotPlugin.Core { } if (needsDispose) { imageToSave.Dispose(); - imageToSave = null; } } @@ -221,7 +219,7 @@ namespace GreenshotPlugin.Core { using (BinaryWriter writer = new BinaryWriter(tmpStream)) { writer.Write(bytesWritten); Version v = Assembly.GetExecutingAssembly().GetName().Version; - byte[] marker = Encoding.ASCII.GetBytes(String.Format("Greenshot{0:00}.{1:00}", v.Major, v.Minor)); + byte[] marker = Encoding.ASCII.GetBytes($"Greenshot{v.Major:00}.{v.Minor:00}"); writer.Write(marker); tmpStream.WriteTo(stream); } @@ -407,7 +405,7 @@ namespace GreenshotPlugin.Core { /// Saves image to specific path with specified quality /// public static void Save(ISurface surface, string fullPath, bool allowOverwrite, SurfaceOutputSettings outputSettings, bool copyPathToClipboard) { - fullPath = FilenameHelper.MakeFQFilenameSafe(fullPath); + fullPath = FilenameHelper.MakeFqFilenameSafe(fullPath); string path = Path.GetDirectoryName(fullPath); // check whether path exists - if not create it @@ -549,7 +547,7 @@ namespace GreenshotPlugin.Core { /// /// public static string SaveToTmpFile(ISurface surface, SurfaceOutputSettings outputSettings, string destinationPath) { - string tmpFile = Path.GetRandomFileName() + "." + outputSettings.Format.ToString(); + string tmpFile = Path.GetRandomFileName() + "." + outputSettings.Format; // Prevent problems with "other characters", which could cause problems tmpFile = Regex.Replace(tmpFile, @"[^\d\w\.]", ""); if (destinationPath == null) { diff --git a/GreenshotPlugin/Core/JSONHelper.cs b/GreenshotPlugin/Core/JSONHelper.cs index 5e44585b7..57293726c 100644 --- a/GreenshotPlugin/Core/JSONHelper.cs +++ b/GreenshotPlugin/Core/JSONHelper.cs @@ -7,7 +7,7 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -using System; + using System.Collections.Generic; using System.Globalization; using System.Text; @@ -173,12 +173,11 @@ namespace GreenshotPlugin.Core { protected static string ParseString(char[] json, ref int index, ref bool success) { StringBuilder s = new StringBuilder(BUILDER_CAPACITY); - char c; EatWhitespace(json, ref index); // " - c = json[index++]; + var c = json[index++]; bool complete = false; while (!complete) { @@ -218,11 +217,11 @@ namespace GreenshotPlugin.Core { if (remainingLength >= 4) { // parse the 32 bit hex into an integer codepoint uint codePoint; - if (!(success = UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint))) { + if (!(success = uint.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint))) { return ""; } // convert the integer codepoint to a unicode char and add to string - s.Append(Char.ConvertFromUtf32((int)codePoint)); + s.Append(char.ConvertFromUtf32((int)codePoint)); // skip 4 chars index += 4; } else { @@ -251,7 +250,7 @@ namespace GreenshotPlugin.Core { int charLength = (lastIndex - index) + 1; double number; - success = Double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number); + success = double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number); index = lastIndex + 1; return number; diff --git a/GreenshotPlugin/Core/Language.cs b/GreenshotPlugin/Core/Language.cs index 1f174260b..79c32c19c 100644 --- a/GreenshotPlugin/Core/Language.cs +++ b/GreenshotPlugin/Core/Language.cs @@ -35,21 +35,20 @@ namespace GreenshotPlugin.Core { /// The language resources are loaded from the language files found on fixed or supplied paths /// public class Language { - private static readonly ILog LOG = LogManager.GetLogger(typeof(Language)); - private static readonly List languagePaths = new List(); - private static readonly IDictionary> languageFiles = new Dictionary>(); - private static readonly IDictionary helpFiles = new Dictionary(); - private const string DEFAULT_LANGUAGE = "en-US"; - private const string HELP_FILENAME_PATTERN = @"help-*.html"; - private const string LANGUAGE_FILENAME_PATTERN = @"language*.xml"; - private static readonly Regex PREFIX_REGEXP = new Regex(@"language_([a-zA-Z0-9]+).*"); - private static readonly Regex IETF_CLEAN_REGEXP = new Regex(@"[^a-zA-Z]+"); - private static readonly Regex IETF_REGEXP = new Regex(@"^.*([a-zA-Z]{2}-[a-zA-Z]{2})\.xml$"); - private const string LANGUAGE_GROUPS_KEY = @"SYSTEM\CurrentControlSet\Control\Nls\Language Groups"; - private static readonly List unsupportedLanguageGroups = new List(); - private static readonly IDictionary resources = new Dictionary(); - private static string currentLanguage; - private static readonly CoreConfiguration coreConfig; + private static readonly ILog Log = LogManager.GetLogger(typeof(Language)); + private static readonly IList LanguagePaths = new List(); + private static readonly IDictionary> LanguageFiles = new Dictionary>(); + private static readonly IDictionary HelpFiles = new Dictionary(); + private const string DefaultLanguage = "en-US"; + private const string HelpFilenamePattern = @"help-*.html"; + private const string LanguageFilenamePattern = @"language*.xml"; + private static readonly Regex PrefixRegexp = new Regex(@"language_([a-zA-Z0-9]+).*"); + private static readonly Regex IetfCleanRegexp = new Regex(@"[^a-zA-Z]+"); + private static readonly Regex IetfRegexp = new Regex(@"^.*([a-zA-Z]{2}-[a-zA-Z]{2})\.xml$"); + private const string LanguageGroupsKey = @"SYSTEM\CurrentControlSet\Control\Nls\Language Groups"; + private static readonly IList UnsupportedLanguageGroups = new List(); + private static readonly IDictionary Resources = new Dictionary(); + private static string _currentLanguage; public static event LanguageChangedHandler LanguageChanged; @@ -57,49 +56,55 @@ namespace GreenshotPlugin.Core { /// Static initializer for the language code /// static Language() { - if (!IniConfig.isInitialized) { - LOG.Warn("IniConfig hasn't been initialized yet! (Design mode?)"); + if (!IniConfig.IsInitialized) { + Log.Warn("IniConfig hasn't been initialized yet! (Design mode?)"); IniConfig.Init("greenshot", "greenshot"); } if (!LogHelper.IsInitialized) { - LOG.Warn("Log4net hasn't been initialized yet! (Design mode?)"); - LogHelper.InitializeLog4NET(); + Log.Warn("Log4net hasn't been initialized yet! (Design mode?)"); + LogHelper.InitializeLog4Net(); } try { - string applicationDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); string applicationFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); // PAF Path - AddPath(Path.Combine(applicationFolder, @"App\Greenshot\Languages")); - + if (applicationFolder != null) + { + AddPath(Path.Combine(applicationFolder, @"App\Greenshot\Languages")); + } // Application data path + string applicationDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); AddPath(Path.Combine(applicationDataFolder, @"Greenshot\Languages\")); - + // Startup path - AddPath(Path.Combine(applicationFolder, @"Languages")); - } catch (Exception pathException) { - LOG.Error(pathException); + if (applicationFolder != null) + { + AddPath(Path.Combine(applicationFolder, @"Languages")); + } + } + catch (Exception pathException) { + Log.Error(pathException); } try { - using (RegistryKey languageGroupsKey = Registry.LocalMachine.OpenSubKey(LANGUAGE_GROUPS_KEY, false)) { + using (RegistryKey languageGroupsKey = Registry.LocalMachine.OpenSubKey(LanguageGroupsKey, false)) { if (languageGroupsKey != null) { string [] groups = languageGroupsKey.GetValueNames(); foreach(string group in groups) { string groupValue = (string)languageGroupsKey.GetValue(group); bool isGroupNotInstalled = "0".Equals(groupValue); if (isGroupNotInstalled) { - unsupportedLanguageGroups.Add(group.ToLower()); + UnsupportedLanguageGroups.Add(group.ToLower()); } } } } } catch(Exception e) { - LOG.Warn("Couldn't read the installed language groups.", e); + Log.Warn("Couldn't read the installed language groups.", e); } - coreConfig = IniConfig.GetIniSection(); + var coreConfig = IniConfig.GetIniSection(); ScanFiles(); if (!string.IsNullOrEmpty(coreConfig.Language)) { CurrentLanguage = coreConfig.Language; @@ -109,15 +114,15 @@ namespace GreenshotPlugin.Core { } if (CurrentLanguage == null) { - LOG.Warn("Couldn't set language from configuration, changing to default. Installation problem?"); - CurrentLanguage = DEFAULT_LANGUAGE; + Log.Warn("Couldn't set language from configuration, changing to default. Installation problem?"); + CurrentLanguage = DefaultLanguage; if (CurrentLanguage != null) { coreConfig.Language = CurrentLanguage; } } if (CurrentLanguage == null) { - LOG.Error("Couldn't set language, installation problem?"); + Log.Error("Couldn't set language, installation problem?"); } } @@ -127,13 +132,13 @@ namespace GreenshotPlugin.Core { /// /// true if the path exists and is added private static bool AddPath(string path) { - if (!languagePaths.Contains(path)) { + if (!LanguagePaths.Contains(path)) { if (Directory.Exists(path)) { - LOG.DebugFormat("Adding language path {0}", path); - languagePaths.Add(path); + Log.DebugFormat("Adding language path {0}", path); + LanguagePaths.Add(path); return true; } else { - LOG.InfoFormat("Not adding non existing language path {0}", path); + Log.InfoFormat("Not adding non existing language path {0}", path); } } return false; @@ -145,8 +150,8 @@ namespace GreenshotPlugin.Core { /// /// true if the path exists and is added public static bool AddLanguageFilePath(string path) { - if (!languagePaths.Contains(path)) { - LOG.DebugFormat("New language path {0}", path); + if (!LanguagePaths.Contains(path)) { + Log.DebugFormat("New language path {0}", path); if (AddPath(path)) { ScanFiles(); Reload(); @@ -163,11 +168,11 @@ namespace GreenshotPlugin.Core { /// private static void LoadFiles(string ietf) { ietf = ReformatIETF(ietf); - if (!languageFiles.ContainsKey(ietf)) { - LOG.ErrorFormat("No language {0} available.", ietf); + if (!LanguageFiles.ContainsKey(ietf)) { + Log.ErrorFormat("No language {0} available.", ietf); return; } - List filesToLoad = languageFiles[ietf]; + List filesToLoad = LanguageFiles[ietf]; foreach (LanguageFile fileToLoad in filesToLoad) { LoadResources(fileToLoad); } @@ -177,10 +182,10 @@ namespace GreenshotPlugin.Core { /// Load the language resources from the scanned files /// private static void Reload() { - resources.Clear(); - LoadFiles(DEFAULT_LANGUAGE); - if (currentLanguage != null && !currentLanguage.Equals(DEFAULT_LANGUAGE)) { - LoadFiles(currentLanguage); + Resources.Clear(); + LoadFiles(DefaultLanguage); + if (_currentLanguage != null && !_currentLanguage.Equals(DefaultLanguage)) { + LoadFiles(_currentLanguage); } } @@ -189,26 +194,31 @@ namespace GreenshotPlugin.Core { /// public static string CurrentLanguage { get { - return currentLanguage; + return _currentLanguage; } set { string ietf = FindBestIETFMatch(value); - if (!languageFiles.ContainsKey(ietf)) { - LOG.WarnFormat("No match for language {0} found!", ietf); + if (!LanguageFiles.ContainsKey(ietf)) { + Log.WarnFormat("No match for language {0} found!", ietf); } else { - if (currentLanguage == null || !currentLanguage.Equals(ietf)) { - currentLanguage = ietf; + if (_currentLanguage == null || !_currentLanguage.Equals(ietf)) { + _currentLanguage = ietf; Reload(); - if (LanguageChanged != null) { - try { - LanguageChanged(null, null); - } catch { - } + if (LanguageChanged == null) + { + return; + } + try { + LanguageChanged(null, null); + } + catch + { + // ignored } return; } } - LOG.Debug("CurrentLanguage not changed!"); + Log.Debug("CurrentLanguage not changed!"); } } @@ -220,17 +230,17 @@ namespace GreenshotPlugin.Core { private static string FindBestIETFMatch(string inputIETF) { string returnIETF = inputIETF; if (string.IsNullOrEmpty(returnIETF)) { - returnIETF = DEFAULT_LANGUAGE; + returnIETF = DefaultLanguage; } returnIETF = ReformatIETF(returnIETF); - if (!languageFiles.ContainsKey(returnIETF)) { - LOG.WarnFormat("Unknown language {0}, trying best match!", returnIETF); + if (!LanguageFiles.ContainsKey(returnIETF)) { + Log.WarnFormat("Unknown language {0}, trying best match!", returnIETF); if (returnIETF.Length == 5) { returnIETF = returnIETF.Substring(0, 2); } - foreach (string availableIETF in languageFiles.Keys) { + foreach (string availableIETF in LanguageFiles.Keys) { if (availableIETF.StartsWith(returnIETF)) { - LOG.InfoFormat("Found language {0}, best match for {1}!", availableIETF, returnIETF); + Log.InfoFormat("Found language {0}, best match for {1}!", availableIETF, returnIETF); returnIETF = availableIETF; break; } @@ -249,7 +259,7 @@ namespace GreenshotPlugin.Core { string returnIETF = null; if (!string.IsNullOrEmpty(inputIETF)) { returnIETF = inputIETF.ToLower(); - returnIETF = IETF_CLEAN_REGEXP.Replace(returnIETF, ""); + returnIETF = IetfCleanRegexp.Replace(returnIETF, ""); if (returnIETF.Length == 4) { returnIETF = returnIETF.Substring(0, 2) + "-" + returnIETF.Substring(2, 2).ToUpper(); } @@ -264,7 +274,7 @@ namespace GreenshotPlugin.Core { get { IList languages = new List(); // Loop over all languages with all the files in there - foreach (List langs in languageFiles.Values) { + foreach (List langs in LanguageFiles.Values) { // Loop over all the files for a language foreach (LanguageFile langFile in langs) { // Only take the ones without prefix, these are the "base" language files @@ -283,10 +293,10 @@ namespace GreenshotPlugin.Core { /// public static string HelpFilePath { get { - if (helpFiles.ContainsKey(currentLanguage)) { - return helpFiles[currentLanguage]; + if (HelpFiles.ContainsKey(_currentLanguage)) { + return HelpFiles[_currentLanguage]; } - return helpFiles[DEFAULT_LANGUAGE]; + return HelpFiles[DefaultLanguage]; } } @@ -295,7 +305,7 @@ namespace GreenshotPlugin.Core { /// /// File to load from private static void LoadResources(LanguageFile languageFile) { - LOG.InfoFormat("Loading language file {0}", languageFile.Filepath); + Log.InfoFormat("Loading language file {0}", languageFile.Filepath); try { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(languageFile.Filepath); @@ -309,14 +319,14 @@ namespace GreenshotPlugin.Core { if (!string.IsNullOrEmpty(text)) { text = text.Trim(); } - if (!resources.ContainsKey(key)) { - resources.Add(key, text); + if (!Resources.ContainsKey(key)) { + Resources.Add(key, text); } else { - resources[key] = text; + Resources[key] = text; } } } catch (Exception e) { - LOG.Error("Could not load language file " + languageFile.Filepath, e); + Log.Error("Could not load language file " + languageFile.Filepath, e); } } @@ -334,26 +344,28 @@ namespace GreenshotPlugin.Core { LanguageFile languageFile = new LanguageFile(); languageFile.Filepath = languageFilePath; XmlNode node = nodes.Item(0); - languageFile.Description = node.Attributes["description"].Value; - if (node.Attributes["ietf"] != null) { - languageFile.Ietf = ReformatIETF(node.Attributes["ietf"].Value); - } - if (node.Attributes["version"] != null) { - languageFile.Version = new Version(node.Attributes["version"].Value); - } - if (node.Attributes["prefix"] != null) { - languageFile.Prefix = node.Attributes["prefix"].Value.ToLower(); - } - if (node.Attributes["languagegroup"] != null) { - string languageGroup = node.Attributes["languagegroup"].Value; - languageFile.LanguageGroup = languageGroup.ToLower(); + if (node?.Attributes != null) + { + languageFile.Description = node.Attributes["description"].Value; + if (node.Attributes["ietf"] != null) { + languageFile.Ietf = ReformatIETF(node.Attributes["ietf"].Value); + } + if (node.Attributes["version"] != null) { + languageFile.Version = new Version(node.Attributes["version"].Value); + } + if (node.Attributes["prefix"] != null) { + languageFile.Prefix = node.Attributes["prefix"].Value.ToLower(); + } + if (node.Attributes["languagegroup"] != null) { + string languageGroup = node.Attributes["languagegroup"].Value; + languageFile.LanguageGroup = languageGroup.ToLower(); + } } return languageFile; - } else { - throw new XmlException("Root element is missing"); } + throw new XmlException("Root element is missing"); } catch (Exception e) { - LOG.Error("Could not load language file " + languageFilePath, e); + Log.Error("Could not load language file " + languageFilePath, e); } return null; } @@ -362,63 +374,63 @@ namespace GreenshotPlugin.Core { /// Scan the files in all directories /// private static void ScanFiles() { - languageFiles.Clear(); - helpFiles.Clear(); - foreach (string languagePath in languagePaths) { + LanguageFiles.Clear(); + HelpFiles.Clear(); + foreach (string languagePath in LanguagePaths) { if (!Directory.Exists(languagePath)) { - LOG.InfoFormat("Skipping non existing language path {0}", languagePath); + Log.InfoFormat("Skipping non existing language path {0}", languagePath); continue; } - LOG.InfoFormat("Searching language directory '{0}' for language files with pattern '{1}'", languagePath, LANGUAGE_FILENAME_PATTERN); + Log.InfoFormat("Searching language directory '{0}' for language files with pattern '{1}'", languagePath, LanguageFilenamePattern); try { - foreach (string languageFilepath in Directory.GetFiles(languagePath, LANGUAGE_FILENAME_PATTERN, SearchOption.AllDirectories)) { + foreach (string languageFilepath in Directory.GetFiles(languagePath, LanguageFilenamePattern, SearchOption.AllDirectories)) { //LOG.DebugFormat("Found language file: {0}", languageFilepath); LanguageFile languageFile = LoadFileInfo(languageFilepath); if (languageFile == null) { continue; } if (string.IsNullOrEmpty(languageFile.Ietf)) { - LOG.WarnFormat("Fixing missing ietf in language-file {0}", languageFilepath); + Log.WarnFormat("Fixing missing ietf in language-file {0}", languageFilepath); string languageFilename = Path.GetFileName(languageFilepath); - if (IETF_REGEXP.IsMatch(languageFilename)) { - string replacementIETF = IETF_REGEXP.Replace(languageFilename, "$1"); + if (IetfRegexp.IsMatch(languageFilename)) { + string replacementIETF = IetfRegexp.Replace(languageFilename, "$1"); languageFile.Ietf = ReformatIETF(replacementIETF); - LOG.InfoFormat("Fixed IETF to {0}", languageFile.Ietf); + Log.InfoFormat("Fixed IETF to {0}", languageFile.Ietf); } else { - LOG.ErrorFormat("Missing ietf , no recover possible... skipping language-file {0}!", languageFilepath); + Log.ErrorFormat("Missing ietf , no recover possible... skipping language-file {0}!", languageFilepath); continue; } } // Check if we can display the file - if (!string.IsNullOrEmpty(languageFile.LanguageGroup) && unsupportedLanguageGroups.Contains(languageFile.LanguageGroup)) { - LOG.InfoFormat("Skipping unsuported (not able to display) language {0} from file {1}", languageFile.Description, languageFilepath); + if (!string.IsNullOrEmpty(languageFile.LanguageGroup) && UnsupportedLanguageGroups.Contains(languageFile.LanguageGroup)) { + Log.InfoFormat("Skipping unsuported (not able to display) language {0} from file {1}", languageFile.Description, languageFilepath); continue; } // build prefix, based on the filename, but only if it's not set in the file itself. if (string.IsNullOrEmpty(languageFile.Prefix)) { string languageFilename = Path.GetFileNameWithoutExtension(languageFilepath); - if (PREFIX_REGEXP.IsMatch(languageFilename)) { - languageFile.Prefix = PREFIX_REGEXP.Replace(languageFilename, "$1"); + if (PrefixRegexp.IsMatch(languageFilename)) { + languageFile.Prefix = PrefixRegexp.Replace(languageFilename, "$1"); if (!string.IsNullOrEmpty(languageFile.Prefix)) { languageFile.Prefix = languageFile.Prefix.Replace("plugin", "").ToLower(); } } } List currentFiles = null; - if (languageFiles.ContainsKey(languageFile.Ietf)) { - currentFiles = languageFiles[languageFile.Ietf]; + if (LanguageFiles.ContainsKey(languageFile.Ietf)) { + currentFiles = LanguageFiles[languageFile.Ietf]; bool needToAdd = true; List deleteList = new List(); foreach (LanguageFile compareWithLangfile in currentFiles) { if ((languageFile.Prefix == null && compareWithLangfile.Prefix == null) || (languageFile.Prefix != null && languageFile.Prefix.Equals(compareWithLangfile.Prefix))) { if (compareWithLangfile.Version > languageFile.Version) { - LOG.WarnFormat("Skipping {0}:{1}:{2} as {3}:{4}:{5} is newer", languageFile.Filepath, languageFile.Prefix, languageFile.Version, compareWithLangfile.Filepath, compareWithLangfile.Prefix, compareWithLangfile.Version); + Log.WarnFormat("Skipping {0}:{1}:{2} as {3}:{4}:{5} is newer", languageFile.Filepath, languageFile.Prefix, languageFile.Version, compareWithLangfile.Filepath, compareWithLangfile.Prefix, compareWithLangfile.Version); needToAdd = false; break; } else { - LOG.WarnFormat("Found {0}:{1}:{2} and deleting {3}:{4}:{5}", languageFile.Filepath, languageFile.Prefix, languageFile.Version, compareWithLangfile.Filepath, compareWithLangfile.Prefix, compareWithLangfile.Version); + Log.WarnFormat("Found {0}:{1}:{2} and deleting {3}:{4}:{5}", languageFile.Filepath, languageFile.Prefix, languageFile.Version, compareWithLangfile.Filepath, compareWithLangfile.Prefix, compareWithLangfile.Version); deleteList.Add(compareWithLangfile); } } @@ -427,39 +439,38 @@ namespace GreenshotPlugin.Core { foreach (LanguageFile deleteFile in deleteList) { currentFiles.Remove(deleteFile); } - LOG.InfoFormat("Added language definition {0} from: {1}", languageFile.Description, languageFile.Filepath); + Log.InfoFormat("Added language definition {0} from: {1}", languageFile.Description, languageFile.Filepath); currentFiles.Add(languageFile); } } else { - currentFiles = new List(); - currentFiles.Add(languageFile); - languageFiles.Add(languageFile.Ietf, currentFiles); - LOG.InfoFormat("Added language definition {0} from: {1}", languageFile.Description, languageFile.Filepath); + currentFiles = new List {languageFile}; + LanguageFiles.Add(languageFile.Ietf, currentFiles); + Log.InfoFormat("Added language definition {0} from: {1}", languageFile.Description, languageFile.Filepath); } } } catch (DirectoryNotFoundException) { - LOG.InfoFormat("Non existing language directory: {0}", languagePath); + Log.InfoFormat("Non existing language directory: {0}", languagePath); } catch (Exception e) { - LOG.Error("Error trying for read directory " + languagePath, e); + Log.Error("Error trying for read directory " + languagePath, e); } // Now find the help files - LOG.InfoFormat("Searching language directory '{0}' for help files with pattern '{1}'", languagePath, HELP_FILENAME_PATTERN); + Log.InfoFormat("Searching language directory '{0}' for help files with pattern '{1}'", languagePath, HelpFilenamePattern); try { - foreach (string helpFilepath in Directory.GetFiles(languagePath, HELP_FILENAME_PATTERN, SearchOption.AllDirectories)) { - LOG.DebugFormat("Found help file: {0}", helpFilepath); + foreach (string helpFilepath in Directory.GetFiles(languagePath, HelpFilenamePattern, SearchOption.AllDirectories)) { + Log.DebugFormat("Found help file: {0}", helpFilepath); string helpFilename = Path.GetFileName(helpFilepath); string ietf = ReformatIETF(helpFilename.Replace(".html", "").Replace("help-", "")); - if (!helpFiles.ContainsKey(ietf)) { - helpFiles.Add(ietf, helpFilepath); + if (!HelpFiles.ContainsKey(ietf)) { + HelpFiles.Add(ietf, helpFilepath); } else { - LOG.WarnFormat("skipping help file {0}, already a file with the same IETF {1} found!", helpFilepath, ietf); + Log.WarnFormat("skipping help file {0}, already a file with the same IETF {1} found!", helpFilepath, ietf); } } } catch (DirectoryNotFoundException) { - LOG.InfoFormat("Non existing language directory: {0}", languagePath); + Log.InfoFormat("Non existing language directory: {0}", languagePath); } catch (Exception e) { - LOG.Error("Error trying for read directory " + languagePath, e); + Log.Error("Error trying for read directory " + languagePath, e); } } } @@ -470,11 +481,11 @@ namespace GreenshotPlugin.Core { /// /// /// true if available - public static bool hasKey(string prefix, Enum key) { + public static bool HasKey(string prefix, Enum key) { if (key == null) { return false; } - return hasKey(prefix + "." + key); + return HasKey(prefix + "." + key); } /// @@ -482,11 +493,11 @@ namespace GreenshotPlugin.Core { /// /// /// true if available - public static bool hasKey(Enum key) { + public static bool HasKey(Enum key) { if (key == null) { return false; } - return hasKey(key.ToString()); + return HasKey(key.ToString()); } /// @@ -495,8 +506,8 @@ namespace GreenshotPlugin.Core { /// /// /// true if available - public static bool hasKey(string prefix, string key) { - return hasKey(prefix + "." + key); + public static bool HasKey(string prefix, string key) { + return HasKey(prefix + "." + key); } /// @@ -504,36 +515,36 @@ namespace GreenshotPlugin.Core { /// /// /// true if available - public static bool hasKey(string key) { + public static bool HasKey(string key) { if (key == null) { return false; } - return resources.ContainsKey(key); + return Resources.ContainsKey(key); } /// - /// TryGet method which combines hasKey & GetString + /// TryGet method which combines HasKey & GetString /// /// /// out string /// public static bool TryGetString(string key, out string languageString) { - return resources.TryGetValue(key, out languageString); + return Resources.TryGetValue(key, out languageString); } /// - /// TryGet method which combines hasKey & GetString + /// TryGet method which combines HasKey & GetString /// /// string with prefix /// string with key /// out string /// public static bool TryGetString(string prefix, string key, out string languageString) { - return resources.TryGetValue(prefix + "." + key, out languageString); + return Resources.TryGetValue(prefix + "." + key, out languageString); } /// - /// TryGet method which combines hasKey & GetString + /// TryGet method which combines HasKey & GetString /// /// string with prefix /// Enum with key @@ -541,14 +552,14 @@ namespace GreenshotPlugin.Core { /// public static bool TryGetString(string prefix, Enum key, out string languageString) { - return resources.TryGetValue(prefix + "." + key, out languageString); + return Resources.TryGetValue(prefix + "." + key, out languageString); } public static string Translate(object key) { string typename = key.GetType().Name; string enumKey = typename + "." + key; - if (hasKey(enumKey)) { + if (HasKey(enumKey)) { return GetString(enumKey); } return key.ToString(); @@ -599,7 +610,7 @@ namespace GreenshotPlugin.Core { return null; } string returnValue; - if (!resources.TryGetValue(key, out returnValue)) { + if (!Resources.TryGetValue(key, out returnValue)) { return "string ###" + key + "### not found"; } return returnValue; @@ -645,7 +656,7 @@ namespace GreenshotPlugin.Core { /// formatted resource or a "string ###key### not found" public static string GetFormattedString(string key, object param) { string returnValue; - if (!resources.TryGetValue(key, out returnValue)) { + if (!Resources.TryGetValue(key, out returnValue)) { return "string ###" + key + "### not found"; } return string.Format(returnValue, param); @@ -693,31 +704,31 @@ namespace GreenshotPlugin.Core { /// public bool Equals(LanguageFile other) { if (Prefix != null) { - if (!Prefix.Equals(other.Prefix)) { + if (other != null && !Prefix.Equals(other.Prefix)) { return false; } - } else if (other.Prefix != null) { + } else if (other?.Prefix != null) { return false; } if (Ietf != null) { - if (!Ietf.Equals(other.Ietf)) { + if (other != null && !Ietf.Equals(other.Ietf)) { return false; } - } else if (other.Ietf != null) { + } else if (other?.Ietf != null) { return false; } if (Version != null) { - if (!Version.Equals(other.Version)) { + if (other != null && !Version.Equals(other.Version)) { return false; } - } else if (other.Version != null) { + } else if (other != null && other.Version != null) { return false; } if (Filepath != null) { - if (!Filepath.Equals(other.Filepath)) { + if (other != null && !Filepath.Equals(other.Filepath)) { return false; } - } else if (other.Filepath != null) { + } else if (other?.Filepath != null) { return false; } return true; diff --git a/GreenshotPlugin/Core/LogHelper.cs b/GreenshotPlugin/Core/LogHelper.cs index 306d4cbf0..8d7ab2368 100644 --- a/GreenshotPlugin/Core/LogHelper.cs +++ b/GreenshotPlugin/Core/LogHelper.cs @@ -37,16 +37,12 @@ namespace GreenshotPlugin.Core { /// public class LogHelper { private static bool _isLog4NetConfigured; - private const string INIT_MESSAGE = "Greenshot initialization of log system failed"; + private const string InitMessage = "Greenshot initialization of log system failed"; - public static bool IsInitialized { - get { - return _isLog4NetConfigured; - } - } + public static bool IsInitialized => _isLog4NetConfigured; // Initialize Log4J - public static string InitializeLog4NET() { + public static string InitializeLog4Net() { // Setup log4j, currently the file is called log4net.xml foreach (var logName in new[] { "log4net.xml" , @"App\Greenshot\log4net-portable.xml"}) { @@ -60,7 +56,7 @@ namespace GreenshotPlugin.Core { } catch (Exception ex) { - MessageBox.Show(ex.Message, INIT_MESSAGE, MessageBoxButtons.OK, MessageBoxIcon.Warning); + MessageBox.Show(ex.Message, InitMessage, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } @@ -74,7 +70,7 @@ namespace GreenshotPlugin.Core { IniConfig.ForceIniInStartupPath(); } } catch (Exception ex){ - MessageBox.Show(ex.Message, INIT_MESSAGE, MessageBoxButtons.OK, MessageBoxIcon.Warning); + MessageBox.Show(ex.Message, InitMessage, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } @@ -82,13 +78,19 @@ namespace GreenshotPlugin.Core { // Get the logfile name try { if (((Hierarchy)LogManager.GetRepository()).Root.Appenders.Count > 0) { - foreach (IAppender appender in ((Hierarchy)LogManager.GetRepository()).Root.Appenders) { - if (appender is FileAppender) { - return ((FileAppender)appender).File; + foreach (IAppender appender in ((Hierarchy)LogManager.GetRepository()).Root.Appenders) + { + var fileAppender = appender as FileAppender; + if (fileAppender != null) { + return fileAppender.File; } } } - } catch {} + } + catch + { + // ignored + } } return null; } diff --git a/GreenshotPlugin/Core/NetworkHelper.cs b/GreenshotPlugin/Core/NetworkHelper.cs index 65f54baf6..d8874cc65 100644 --- a/GreenshotPlugin/Core/NetworkHelper.cs +++ b/GreenshotPlugin/Core/NetworkHelper.cs @@ -47,7 +47,7 @@ namespace GreenshotPlugin.Core { /// Description of NetworkHelper. /// public static class NetworkHelper { - private static readonly ILog LOG = LogManager.GetLogger(typeof(NetworkHelper)); + private static readonly ILog Log = LogManager.GetLogger(typeof(NetworkHelper)); private static readonly CoreConfiguration Config = IniConfig.GetIniSection(); static NetworkHelper() { @@ -60,7 +60,7 @@ namespace GreenshotPlugin.Core { } catch (Exception ex) { - LOG.Warn("An error has occured while allowing self-signed certificates:", ex); + Log.Warn("An error has occured while allowing self-signed certificates:", ex); } } @@ -99,7 +99,7 @@ namespace GreenshotPlugin.Core { } } } catch (Exception e) { - LOG.Error("Problem downloading the FavIcon from: " + baseUri, e); + Log.Error("Problem downloading the FavIcon from: " + baseUri, e); } return null; } @@ -114,9 +114,7 @@ namespace GreenshotPlugin.Core { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { MemoryStream memoryStream = new MemoryStream(); using (Stream responseStream = response.GetResponseStream()) { - if (responseStream != null) { - responseStream.CopyTo(memoryStream); - } + responseStream?.CopyTo(memoryStream); // Make sure it can be used directly memoryStream.Seek(0, SeekOrigin.Begin); } @@ -178,7 +176,7 @@ namespace GreenshotPlugin.Core { } catch (Exception e) { - LOG.Error("Problem downloading the image from: " + url, e); + Log.Error("Problem downloading the image from: " + url, e); } return null; } @@ -246,21 +244,21 @@ namespace GreenshotPlugin.Core { proxyToUse = WebRequest.DefaultWebProxy; if (proxyToUse != null) { proxyToUse.Credentials = CredentialCache.DefaultCredentials; - if (LOG.IsDebugEnabled) { + if (Log.IsDebugEnabled) { // check the proxy for the Uri if (!proxyToUse.IsBypassed(uri)) { Uri proxyUri = proxyToUse.GetProxy(uri); if (proxyUri != null) { - LOG.Debug("Using proxy: " + proxyUri + " for " + uri); + Log.Debug("Using proxy: " + proxyUri + " for " + uri); } else { - LOG.Debug("No proxy found!"); + Log.Debug("No proxy found!"); } } else { - LOG.Debug("Proxy bypass for: " + uri); + Log.Debug("Proxy bypass for: " + uri); } } } else { - LOG.Debug("No proxy found!"); + Log.Debug("No proxy found!"); } } return proxyToUse; @@ -350,7 +348,7 @@ namespace GreenshotPlugin.Core { StringBuilder sb = new StringBuilder(); foreach(string key in queryParameters.Keys) { - sb.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", key, UrlEncode(string.Format("{0}",queryParameters[key]))); + sb.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", key, UrlEncode($"{queryParameters[key]}")); } sb.Remove(sb.Length-1,1); @@ -363,7 +361,7 @@ namespace GreenshotPlugin.Core { /// HttpWebRequest to write the multipart form data to /// Parameters to include in the multipart form data public static void WriteMultipartFormData(HttpWebRequest webRequest, IDictionary postParameters) { - string boundary = string.Format("----------{0:N}", Guid.NewGuid()); + string boundary = $"----------{Guid.NewGuid():N}"; webRequest.ContentType = "multipart/form-data; boundary=" + boundary; using (Stream formDataStream = webRequest.GetRequestStream()) { WriteMultipartFormData(formDataStream, boundary, postParameters); @@ -376,7 +374,7 @@ namespace GreenshotPlugin.Core { /// HttpListenerResponse /// Parameters to include in the multipart form data public static void WriteMultipartFormData(HttpListenerResponse response, IDictionary postParameters) { - string boundary = string.Format("----------{0:N}", Guid.NewGuid()); + string boundary = $"----------{Guid.NewGuid():N}"; response.ContentType = "multipart/form-data; boundary=" + boundary; WriteMultipartFormData(response.OutputStream, boundary, postParameters); } @@ -398,14 +396,11 @@ namespace GreenshotPlugin.Core { needsClrf = true; - if (param.Value is IBinaryContainer) { - IBinaryContainer binaryParameter = (IBinaryContainer)param.Value; - binaryParameter.WriteFormDataToStream(boundary, param.Key, formDataStream); + var binaryContainer = param.Value as IBinaryContainer; + if (binaryContainer != null) { + binaryContainer.WriteFormDataToStream(boundary, param.Key, formDataStream); } else { - string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", - boundary, - param.Key, - param.Value); + string postData = $"--{boundary}\r\nContent-Disposition: form-data; name=\"{param.Key}\"\r\n\r\n{param.Value}"; formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); } } @@ -435,12 +430,12 @@ namespace GreenshotPlugin.Core { /// /// WebResponse private static void DebugHeaders(WebResponse response) { - if (!LOG.IsDebugEnabled) { + if (!Log.IsDebugEnabled) { return; } - LOG.DebugFormat("Debug information on the response from {0} :", response.ResponseUri); + Log.DebugFormat("Debug information on the response from {0} :", response.ResponseUri); foreach (string key in response.Headers.AllKeys) { - LOG.DebugFormat("Reponse-header: {0}={1}", key, response.Headers[key]); + Log.DebugFormat("Reponse-header: {0}={1}", key, response.Headers[key]); } } @@ -492,17 +487,17 @@ namespace GreenshotPlugin.Core { bool isHttpError = false; try { response = (HttpWebResponse)webRequest.GetResponse(); - LOG.InfoFormat("Response status: {0}", response.StatusCode); + Log.InfoFormat("Response status: {0}", response.StatusCode); isHttpError = (int)response.StatusCode >= 300; if (isHttpError) { - LOG.ErrorFormat("HTTP error {0}", response.StatusCode); + Log.ErrorFormat("HTTP error {0}", response.StatusCode); } DebugHeaders(response); responseData = GetResponseAsString(response); if (isHttpError) { - LOG.ErrorFormat("HTTP response {0}", responseData); + Log.ErrorFormat("HTTP response {0}", responseData); } } catch (WebException e) { @@ -510,15 +505,15 @@ namespace GreenshotPlugin.Core { HttpStatusCode statusCode = HttpStatusCode.Unused; if (response != null) { statusCode = response.StatusCode; - LOG.ErrorFormat("HTTP error {0}", statusCode); + Log.ErrorFormat("HTTP error {0}", statusCode); string errorContent = GetResponseAsString(response); if (alsoReturnContentOnError) { return errorContent; } - LOG.ErrorFormat("Content: {0}", errorContent); + Log.ErrorFormat("Content: {0}", errorContent); } - LOG.Error("WebException: ", e); + Log.Error("WebException: ", e); if (statusCode == HttpStatusCode.Unauthorized) { throw new UnauthorizedAccessException(e.Message); @@ -531,7 +526,7 @@ namespace GreenshotPlugin.Core { { if (isHttpError) { - LOG.ErrorFormat("HTTP error {0} with content: {1}", response.StatusCode, responseData); + Log.ErrorFormat("HTTP error {0} with content: {1}", response.StatusCode, responseData); } response.Close(); } @@ -550,12 +545,12 @@ namespace GreenshotPlugin.Core { webRequest.Method = HTTPMethod.HEAD.ToString(); using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse()) { - LOG.DebugFormat("RSS feed was updated at {0}", webResponse.LastModified); + Log.DebugFormat("RSS feed was updated at {0}", webResponse.LastModified); return webResponse.LastModified; } } catch (Exception wE) { - LOG.WarnFormat("Problem requesting HTTP - HEAD on uri {0}", uri); - LOG.Warn(wE.Message); + Log.WarnFormat("Problem requesting HTTP - HEAD on uri {0}", uri); + Log.Warn(wE.Message); // Pretend it is old return DateTime.MinValue; } @@ -620,11 +615,7 @@ namespace GreenshotPlugin.Core { /// Stream to write to public void WriteFormDataToStream(string boundary, string name, Stream formDataStream) { // Add just the first part of this param, since we will write the file data directly to the Stream - string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n", - boundary, - name, - Filename ?? name, - _contentType ?? "application/octet-stream"); + string header = $"--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"; filename=\"{Filename ?? name}\";\r\nContent-Type: {_contentType ?? "application/octet-stream"}\r\n\r\n"; formDataStream.Write(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header)); @@ -702,11 +693,7 @@ namespace GreenshotPlugin.Core { /// Stream to write to public void WriteFormDataToStream(string boundary, string name, Stream formDataStream) { // Add just the first part of this param, since we will write the file data directly to the Stream - string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n", - boundary, - name, - Filename ?? name, - ContentType); + string header = $"--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"; filename=\"{Filename ?? name}\";\r\nContent-Type: {ContentType}\r\n\r\n"; formDataStream.Write(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header)); ImageOutput.SaveToStream(_bitmap, null, formDataStream, _outputSettings); @@ -782,11 +769,7 @@ namespace GreenshotPlugin.Core { /// Stream to write to public void WriteFormDataToStream(string boundary, string name, Stream formDataStream) { // Add just the first part of this param, since we will write the file data directly to the Stream - string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n", - boundary, - name, - Filename ?? name, - ContentType); + string header = $"--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"; filename=\"{Filename ?? name}\";\r\nContent-Type: {ContentType}\r\n\r\n"; formDataStream.Write(Encoding.UTF8.GetBytes(header), 0, Encoding.UTF8.GetByteCount(header)); ImageOutput.SaveToStream(_surface, formDataStream, _outputSettings); diff --git a/GreenshotPlugin/Core/OAuthHelper.cs b/GreenshotPlugin/Core/OAuthHelper.cs index 9cf5d8876..6a34c58d9 100644 --- a/GreenshotPlugin/Core/OAuthHelper.cs +++ b/GreenshotPlugin/Core/OAuthHelper.cs @@ -30,7 +30,6 @@ using System.Globalization; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; -using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; @@ -41,7 +40,6 @@ namespace GreenshotPlugin.Core { public enum OAuthSignatureTypes { HMACSHA1, PLAINTEXT, - RSASHA1 } /// @@ -124,11 +122,7 @@ namespace GreenshotPlugin.Core { /// /// Get formatted Auth url (this will call a FormatWith(this) on the AuthUrlPattern /// - public string FormattedAuthUrl { - get { - return AuthUrlPattern.FormatWith(this); - } - } + public string FormattedAuthUrl => AuthUrlPattern.FormatWith(this); /// /// The URL to get a Token @@ -170,7 +164,7 @@ namespace GreenshotPlugin.Core { public bool IsAccessTokenExpired { get { bool expired = true; - if (!string.IsNullOrEmpty(AccessToken) && AccessTokenExpires != null) { + if (!string.IsNullOrEmpty(AccessToken)) { expired = DateTimeOffset.Now.AddSeconds(60) > AccessTokenExpires; } // Make sure the token is not usable @@ -211,7 +205,7 @@ namespace GreenshotPlugin.Core { /// An OAuth 1 session object /// public class OAuthSession { - private static readonly ILog LOG = LogManager.GetLogger(typeof(OAuthSession)); + private static readonly ILog Log = LogManager.GetLogger(typeof(OAuthSession)); protected const string OAUTH_VERSION = "1.0"; protected const string OAUTH_PARAMETER_PREFIX = "oauth_"; @@ -231,47 +225,30 @@ namespace GreenshotPlugin.Core { protected const string HMACSHA1SignatureType = "HMAC-SHA1"; protected const string PlainTextSignatureType = "PLAINTEXT"; - protected const string RSASHA1SignatureType = "RSA-SHA1"; - protected static Random random = new Random(); - protected const string UNRESERVED_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"; + protected const string UnreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"; private string _userAgent = "Greenshot"; - private string _callbackUrl = "http://getgreenshot.org"; - private bool _checkVerifier = true; - private bool _useHttpHeadersForAuthorization = true; - private IDictionary _accessTokenResponseParameters; private IDictionary _requestTokenResponseParameters; - private readonly IDictionary _requestTokenParameters = new Dictionary(); - - public IDictionary RequestTokenParameters { - get { return _requestTokenParameters; } - } + + public IDictionary RequestTokenParameters { get; } = new Dictionary(); /// /// Parameters of the last called getAccessToken /// - public IDictionary AccessTokenResponseParameters { - get { - return _accessTokenResponseParameters; - } - } + public IDictionary AccessTokenResponseParameters { get; private set; } + /// /// Parameters of the last called getRequestToken /// - public IDictionary RequestTokenResponseParameters { - get { - return _requestTokenResponseParameters; - } - } + public IDictionary RequestTokenResponseParameters => _requestTokenResponseParameters; + private readonly string _consumerKey; private readonly string _consumerSecret; // default _browser size - private Size _browserSize = new Size(864, 587); - private string _loginTitle = "Authorize Greenshot access"; #region PublicProperties public HTTPMethod RequestTokenMethod { @@ -320,48 +297,15 @@ namespace GreenshotPlugin.Core { _userAgent = value; } } - public string CallbackUrl { - get { - return _callbackUrl; - } - set { - _callbackUrl = value; - } - } - public bool CheckVerifier { - get { - return _checkVerifier; - } - set { - _checkVerifier = value; - } - } + public string CallbackUrl { get; set; } = "http://getgreenshot.org"; - public Size BrowserSize { - get { - return _browserSize; - } - set { - _browserSize = value; - } - } + public bool CheckVerifier { get; set; } = true; - public string LoginTitle { - get { - return _loginTitle; - } - set { - _loginTitle = value; - } - } - public bool UseHTTPHeadersForAuthorization { - get { - return _useHttpHeadersForAuthorization; - } - set { - _useHttpHeadersForAuthorization = value; - } - } + public Size BrowserSize { get; set; } = new Size(864, 587); + + public string LoginTitle { get; set; } = "Authorize Greenshot access"; + + public bool UseHttpHeadersForAuthorization { get; set; } = true; public bool AutoLogin { get; @@ -393,11 +337,11 @@ namespace GreenshotPlugin.Core { /// a Base64 string of the hash value private static string ComputeHash(HashAlgorithm hashAlgorithm, string data) { if (hashAlgorithm == null) { - throw new ArgumentNullException("hashAlgorithm"); + throw new ArgumentNullException(nameof(hashAlgorithm)); } if (string.IsNullOrEmpty(data)) { - throw new ArgumentNullException("data"); + throw new ArgumentNullException(nameof(data)); } byte[] dataBuffer = Encoding.UTF8.GetBytes(data); @@ -421,7 +365,7 @@ namespace GreenshotPlugin.Core { StringBuilder sb = new StringBuilder(); foreach (string key in queryParameters.Keys) { if (queryParameters[key] is string) { - sb.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", key, UrlEncode3986(string.Format("{0}",queryParameters[key]))); + sb.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", key, UrlEncode3986($"{queryParameters[key]}")); } } sb.Remove(sb.Length - 1, 1); @@ -440,7 +384,7 @@ namespace GreenshotPlugin.Core { StringBuilder result = new StringBuilder(); foreach (char symbol in value) { - if (UNRESERVED_CHARS.IndexOf(symbol) != -1) { + if (UnreservedChars.IndexOf(symbol) != -1) { result.Append(symbol); } else { byte[] utf8Bytes = Encoding.UTF8.GetBytes(symbol.ToString()); @@ -478,14 +422,14 @@ namespace GreenshotPlugin.Core { /// response, this doesn't need to be used!! private string GetRequestToken() { IDictionary parameters = new Dictionary(); - foreach(var value in _requestTokenParameters) { + foreach(var value in RequestTokenParameters) { parameters.Add(value); } Sign(RequestTokenMethod, RequestTokenUrl, parameters); string response = MakeRequest(RequestTokenMethod, RequestTokenUrl, null, parameters, null); if (!string.IsNullOrEmpty(response)) { response = NetworkHelper.UrlDecode(response); - LOG.DebugFormat("Request token response: {0}", response); + Log.DebugFormat("Request token response: {0}", response); _requestTokenResponseParameters = NetworkHelper.ParseQueryString(response); string value; if (_requestTokenResponseParameters.TryGetValue(OAUTH_TOKEN_KEY, out value)) { @@ -506,7 +450,7 @@ namespace GreenshotPlugin.Core { Exception e = new Exception("The request token is not set, service responded with: " + requestTokenResponse); throw e; } - LOG.DebugFormat("Opening AuthorizationLink: {0}", AuthorizationLink); + Log.DebugFormat("Opening AuthorizationLink: {0}", AuthorizationLink); OAuthLoginForm oAuthLoginForm = new OAuthLoginForm(LoginTitle, BrowserSize, AuthorizationLink, CallbackUrl); oAuthLoginForm.ShowDialog(); if (oAuthLoginForm.IsOk) { @@ -545,14 +489,14 @@ namespace GreenshotPlugin.Core { string response = MakeRequest(AccessTokenMethod, AccessTokenUrl, null, parameters, null); if (!string.IsNullOrEmpty(response)) { response = NetworkHelper.UrlDecode(response); - LOG.DebugFormat("Access token response: {0}", response); - _accessTokenResponseParameters = NetworkHelper.ParseQueryString(response); + Log.DebugFormat("Access token response: {0}", response); + AccessTokenResponseParameters = NetworkHelper.ParseQueryString(response); string tokenValue; - if (_accessTokenResponseParameters.TryGetValue(OAUTH_TOKEN_KEY, out tokenValue) && tokenValue != null) { + if (AccessTokenResponseParameters.TryGetValue(OAUTH_TOKEN_KEY, out tokenValue) && tokenValue != null) { Token = tokenValue; } string secretValue; - if (_accessTokenResponseParameters.TryGetValue(OAUTH_TOKEN_SECRET_KEY, out secretValue) && secretValue != null) { + if (AccessTokenResponseParameters.TryGetValue(OAUTH_TOKEN_SECRET_KEY, out secretValue) && secretValue != null) { TokenSecret = secretValue; } } @@ -568,23 +512,23 @@ namespace GreenshotPlugin.Core { Token = null; TokenSecret = null; Verifier = null; - LOG.Debug("Creating Token"); + Log.Debug("Creating Token"); string requestTokenResponse; - try { + try { requestTokenResponse = GetRequestToken(); } catch (Exception ex) { - LOG.Error(ex); + Log.Error(ex); throw new NotSupportedException("Service is not available: " + ex.Message); } if (string.IsNullOrEmpty(GetAuthorizeToken(requestTokenResponse))) { - LOG.Debug("User didn't authenticate!"); + Log.Debug("User didn't authenticate!"); return false; } try { Thread.Sleep(1000); return GetAccessToken() != null; } catch (Exception ex) { - LOG.Error(ex); + Log.Error(ex); throw; } } @@ -593,37 +537,33 @@ namespace GreenshotPlugin.Core { /// Get the link to the authorization page for this application. /// /// The url with a valid request token, or a null string. - private string AuthorizationLink { - get { - return AuthorizeUrl + "?" + OAUTH_TOKEN_KEY + "=" + Token + "&" + OAUTH_CALLBACK_KEY + "=" + UrlEncode3986(CallbackUrl); - } - } + private string AuthorizationLink => AuthorizeUrl + "?" + OAUTH_TOKEN_KEY + "=" + Token + "&" + OAUTH_CALLBACK_KEY + "=" + UrlEncode3986(CallbackUrl); /// /// Submit a web request using oAuth. /// /// GET or POST - /// The full url, including the querystring for the signing/request + /// The full url, including the querystring for the signing/request /// Parameters for the request, which need to be signed /// Parameters for the request, which do not need to be signed /// Data to post (MemoryStream) /// The web server response. - public string MakeOAuthRequest(HTTPMethod method, string requestURL, IDictionary parametersToSign, IDictionary additionalParameters, IBinaryContainer postData) { - return MakeOAuthRequest(method, requestURL, requestURL, null, parametersToSign, additionalParameters, postData); + public string MakeOAuthRequest(HTTPMethod method, string requestUrl, IDictionary parametersToSign, IDictionary additionalParameters, IBinaryContainer postData) { + return MakeOAuthRequest(method, requestUrl, requestUrl, null, parametersToSign, additionalParameters, postData); } /// /// Submit a web request using oAuth. /// /// GET or POST - /// The full url, including the querystring for the signing/request + /// The full url, including the querystring for the signing/request /// Header values /// Parameters for the request, which need to be signed /// Parameters for the request, which do not need to be signed /// Data to post (MemoryStream) /// The web server response. - public string MakeOAuthRequest(HTTPMethod method, string requestURL, IDictionary headers, IDictionary parametersToSign, IDictionary additionalParameters, IBinaryContainer postData) { - return MakeOAuthRequest(method, requestURL, requestURL, headers, parametersToSign, additionalParameters, postData); + public string MakeOAuthRequest(HTTPMethod method, string requestUrl, IDictionary headers, IDictionary parametersToSign, IDictionary additionalParameters, IBinaryContainer postData) { + return MakeOAuthRequest(method, requestUrl, requestUrl, headers, parametersToSign, additionalParameters, postData); } /// @@ -631,13 +571,13 @@ namespace GreenshotPlugin.Core { /// /// GET or POST /// The full url, including the querystring for the signing - /// The full url, including the querystring for the request + /// The full url, including the querystring for the request /// Parameters for the request, which need to be signed /// Parameters for the request, which do not need to be signed /// Data to post (MemoryStream) /// The web server response. - public string MakeOAuthRequest(HTTPMethod method, string signUrl, string requestURL, IDictionary parametersToSign, IDictionary additionalParameters, IBinaryContainer postData) { - return MakeOAuthRequest(method, signUrl, requestURL, null, parametersToSign, additionalParameters, postData); + public string MakeOAuthRequest(HTTPMethod method, string signUrl, string requestUrl, IDictionary parametersToSign, IDictionary additionalParameters, IBinaryContainer postData) { + return MakeOAuthRequest(method, signUrl, requestUrl, null, parametersToSign, additionalParameters, postData); } /// @@ -645,13 +585,13 @@ namespace GreenshotPlugin.Core { /// /// GET or POST /// The full url, including the querystring for the signing - /// The full url, including the querystring for the request + /// The full url, including the querystring for the request /// Headers for the request /// Parameters for the request, which need to be signed /// Parameters for the request, which do not need to be signed /// Data to post (MemoryStream) /// The web server response. - public string MakeOAuthRequest(HTTPMethod method, string signUrl, string requestURL, IDictionary headers, IDictionary parametersToSign, IDictionary additionalParameters, IBinaryContainer postData) { + public string MakeOAuthRequest(HTTPMethod method, string signUrl, string requestUrl, IDictionary headers, IDictionary parametersToSign, IDictionary additionalParameters, IBinaryContainer postData) { if (parametersToSign == null) { parametersToSign = new Dictionary(); } @@ -677,7 +617,7 @@ namespace GreenshotPlugin.Core { newParameters.Add(parameter); } } - return MakeRequest(method, requestURL, headers, newParameters, postData); + return MakeRequest(method, requestUrl, headers, newParameters, postData); } catch (UnauthorizedAccessException uaEx) { lastException = uaEx; Token = null; @@ -695,7 +635,6 @@ namespace GreenshotPlugin.Core { { parametersToSign.Remove(keyToDelete); } - continue; } } if (lastException != null) { @@ -735,13 +674,9 @@ namespace GreenshotPlugin.Core { parameters.Add(OAUTH_NONCE_KEY, GenerateNonce()); parameters.Add(OAUTH_TIMESTAMP_KEY, GenerateTimeStamp()); switch(SignatureType) { - case OAuthSignatureTypes.RSASHA1: - parameters.Add(OAUTH_SIGNATURE_METHOD_KEY, RSASHA1SignatureType); - break; case OAuthSignatureTypes.PLAINTEXT: parameters.Add(OAUTH_SIGNATURE_METHOD_KEY, PlainTextSignatureType); break; - case OAuthSignatureTypes.HMACSHA1: default: parameters.Add(OAUTH_SIGNATURE_METHOD_KEY, HMACSHA1SignatureType); break; @@ -757,41 +692,15 @@ namespace GreenshotPlugin.Core { parameters.Add(OAUTH_TOKEN_KEY, Token); } signatureBase.Append(UrlEncode3986(GenerateNormalizedParametersString(parameters))); - LOG.DebugFormat("Signature base: {0}", signatureBase); + Log.DebugFormat("Signature base: {0}", signatureBase); string key = string.Format(CultureInfo.InvariantCulture, "{0}&{1}", UrlEncode3986(_consumerSecret), string.IsNullOrEmpty(TokenSecret) ? string.Empty : UrlEncode3986(TokenSecret)); switch (SignatureType) { - case OAuthSignatureTypes.RSASHA1: - // Code comes from here: http://www.dotnetfunda.com/articles/article1932-rest-service-call-using-oauth-10-authorization-with-rsa-sha1.aspx - // Read the .P12 file to read Private/Public key Certificate - string certFilePath = _consumerKey; // The .P12 certificate file path Example: "C:/mycertificate/MCOpenAPI.p12 - string password = _consumerSecret; // password to read certificate .p12 file - // Read the Certification from .P12 file. - X509Certificate2 cert = new X509Certificate2(certFilePath.ToString(), password); - // Retrieve the Private key from Certificate. - RSACryptoServiceProvider RSAcrypt = (RSACryptoServiceProvider)cert.PrivateKey; - // Create a RSA-SHA1 Hash object - using (SHA1Managed shaHASHObject = new SHA1Managed()) { - // Create Byte Array of Signature base string - byte[] data = Encoding.ASCII.GetBytes(signatureBase.ToString()); - // Create Hashmap of Signature base string - byte[] hash = shaHASHObject.ComputeHash(data); - // Create Sign Hash of base string - // NOTE - 'SignHash' gives correct data. Don't use SignData method - byte[] rsaSignature = RSAcrypt.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")); - // Convert to Base64 string - string base64string = Convert.ToBase64String(rsaSignature); - // Return the Encoded UTF8 string - parameters.Add(OAUTH_SIGNATURE_KEY, UrlEncode3986(base64string)); - } - break; case OAuthSignatureTypes.PLAINTEXT: parameters.Add(OAUTH_SIGNATURE_KEY, key); break; - case OAuthSignatureTypes.HMACSHA1: default: // Generate Signature and add it to the parameters - HMACSHA1 hmacsha1 = new HMACSHA1(); - hmacsha1.Key = Encoding.UTF8.GetBytes(key); + HMACSHA1 hmacsha1 = new HMACSHA1 {Key = Encoding.UTF8.GetBytes(key)}; string signature = ComputeHash(hmacsha1, signatureBase.ToString()); parameters.Add(OAUTH_SIGNATURE_KEY, signature); break; @@ -803,24 +712,24 @@ namespace GreenshotPlugin.Core { /// Any additional parameters added after the Sign call are not in the signature, this could be by design! /// /// - /// + /// /// /// /// IBinaryParameter /// Response from server - private string MakeRequest(HTTPMethod method, string requestURL, IDictionary headers, IDictionary parameters, IBinaryContainer postData) { + private string MakeRequest(HTTPMethod method, string requestUrl, IDictionary headers, IDictionary parameters, IBinaryContainer postData) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } IDictionary requestParameters; // Add oAuth values as HTTP headers, if this is allowed StringBuilder authHeader = null; - if (UseHTTPHeadersForAuthorization) { + if (UseHttpHeadersForAuthorization) { authHeader = new StringBuilder(); requestParameters = new Dictionary(); foreach (string parameterKey in parameters.Keys) { if (parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX)) { - authHeader.AppendFormat(CultureInfo.InvariantCulture, "{0}=\"{1}\", ", parameterKey, UrlEncode3986(string.Format("{0}",parameters[parameterKey]))); + authHeader.AppendFormat(CultureInfo.InvariantCulture, "{0}=\"{1}\", ", parameterKey, UrlEncode3986($"{parameters[parameterKey]}")); } else if (!requestParameters.ContainsKey(parameterKey)) { requestParameters.Add(parameterKey, parameters[parameterKey]); } @@ -836,16 +745,16 @@ namespace GreenshotPlugin.Core { if (HTTPMethod.GET == method || postData != null) { if (requestParameters.Count > 0) { // Add the parameters to the request - requestURL += "?" + NetworkHelper.GenerateQueryParameters(requestParameters); + requestUrl += "?" + NetworkHelper.GenerateQueryParameters(requestParameters); } } // Create webrequest - HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(requestURL, method); + HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(requestUrl, method); webRequest.ServicePoint.Expect100Continue = false; webRequest.UserAgent = _userAgent; - if (UseHTTPHeadersForAuthorization && authHeader != null) { - LOG.DebugFormat("Authorization: OAuth {0}", authHeader); + if (UseHttpHeadersForAuthorization && authHeader != null) { + Log.DebugFormat("Authorization: OAuth {0}", authHeader); webRequest.Headers.Add("Authorization: OAuth " + authHeader); } @@ -860,13 +769,10 @@ namespace GreenshotPlugin.Core { NetworkHelper.WriteMultipartFormData(webRequest, requestParameters); } else { StringBuilder form = new StringBuilder(); - foreach (string parameterKey in requestParameters.Keys) { - if (parameters[parameterKey] is IBinaryContainer) { - IBinaryContainer binaryParameter = parameters[parameterKey] as IBinaryContainer; - form.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey), UrlEncode3986(binaryParameter.ToBase64String(Base64FormattingOptions.None))); - } else { - form.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey), UrlEncode3986(string.Format("{0}",parameters[parameterKey]))); - } + foreach (string parameterKey in requestParameters.Keys) + { + var binaryParameter = parameters[parameterKey] as IBinaryContainer; + form.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey), binaryParameter != null ? UrlEncode3986(binaryParameter.ToBase64String(Base64FormattingOptions.None)) : UrlEncode3986($"{parameters[parameterKey]}")); } // Remove trailing & if (form.Length > 0) { @@ -887,12 +793,10 @@ namespace GreenshotPlugin.Core { string responseData; try { responseData = NetworkHelper.GetResponseAsString(webRequest); - LOG.DebugFormat("Response: {0}", responseData); + Log.DebugFormat("Response: {0}", responseData); } catch (Exception ex) { - LOG.Error("Couldn't retrieve response: ", ex); + Log.Error("Couldn't retrieve response: ", ex); throw; - } finally { - webRequest = null; } return responseData; @@ -904,52 +808,34 @@ namespace GreenshotPlugin.Core { /// and waits for a call with the authorization verification code. /// public class LocalServerCodeReceiver { - private static readonly ILog LOG = LogManager.GetLogger(typeof(LocalServerCodeReceiver)); + private static readonly ILog Log = LogManager.GetLogger(typeof(LocalServerCodeReceiver)); private readonly ManualResetEvent _ready = new ManualResetEvent(true); - private string _loopbackCallback = "http://localhost:{0}/authorize/"; /// /// The call back format. Expects one port parameter. /// Default: http://localhost:{0}/authorize/ /// - public string LoopbackCallbackUrl { - get { - return _loopbackCallback; - } - set { - _loopbackCallback = value; - } - } - - private string _closePageResponse = -@" -OAuth 2.0 Authentication CloudServiceName - -Greenshot received information from CloudServiceName. You can close this browser / tab if it is not closed itself... - - -"; + public string LoopbackCallbackUrl { get; set; } = "http://localhost:{0}/authorize/"; /// /// HTML code to to return the _browser, default it will try to close the _browser / tab, this won't always work. /// You can use CloudServiceName where you want to show the CloudServiceName from your OAuth2 settings /// - public string ClosePageResponse { - get { - return _closePageResponse; - } - set { - _closePageResponse = value; - } - } + public string ClosePageResponse { get; set; } = @" +OAuth 2.0 Authentication CloudServiceName + +Greenshot received information from CloudServiceName. You can close this browser / tab if it is not closed itself... + + +"; private string _redirectUri; /// @@ -961,7 +847,7 @@ Greenshot received information from CloudServiceName. You can close this browser return _redirectUri; } - return _redirectUri = string.Format(_loopbackCallback, GetRandomUnusedPort()); + return _redirectUri = string.Format(LoopbackCallbackUrl, GetRandomUnusedPort()); } } @@ -973,7 +859,7 @@ Greenshot received information from CloudServiceName. You can close this browser /// /// The OAuth code receiver /// - /// + /// /// Dictionary with values public IDictionary ReceiveCode(OAuth2Settings oauth2Settings) { // Set the redirect URL on the settings @@ -986,7 +872,7 @@ Greenshot received information from CloudServiceName. You can close this browser // Get the formatted FormattedAuthUrl string authorizationUrl = oauth2Settings.FormattedAuthUrl; - LOG.DebugFormat("Open a browser with: {0}", authorizationUrl); + Log.DebugFormat("Open a browser with: {0}", authorizationUrl); Process.Start(authorizationUrl); // Wait to get the authorization code response. @@ -994,7 +880,7 @@ Greenshot received information from CloudServiceName. You can close this browser _ready.Reset(); while (!context.AsyncWaitHandle.WaitOne(1000, true)) { - LOG.Debug("Waiting for response"); + Log.Debug("Waiting for response"); } } catch (Exception) { // Make sure we can clean up, also if the thead is aborted @@ -1072,15 +958,15 @@ Greenshot received information from CloudServiceName. You can close this browser /// Code to simplify OAuth 2 /// public static class OAuth2Helper { - private const string REFRESH_TOKEN = "refresh_token"; - private const string ACCESS_TOKEN = "access_token"; - private const string CODE = "code"; - private const string CLIENT_ID = "client_id"; - private const string CLIENT_SECRET = "client_secret"; - private const string GRANT_TYPE = "grant_type"; - private const string AUTHORIZATION_CODE = "authorization_code"; - private const string REDIRECT_URI = "redirect_uri"; - private const string EXPIRES_IN = "expires_in"; + private const string RefreshToken = "refresh_token"; + private const string AccessToken = "access_token"; + private const string Code = "code"; + private const string ClientId = "client_id"; + private const string ClientSecret = "client_secret"; + private const string GrantType = "grant_type"; + private const string AuthorizationCode = "authorization_code"; + private const string RedirectUri = "redirect_uri"; + private const string ExpiresIn = "expires_in"; /// /// Generate an OAuth 2 Token by using the supplied code @@ -1089,11 +975,11 @@ Greenshot received information from CloudServiceName. You can close this browser public static void GenerateRefreshToken(OAuth2Settings settings) { IDictionary data = new Dictionary(); // Use the returned code to get a refresh code - data.Add(CODE, settings.Code); - data.Add(CLIENT_ID, settings.ClientId); - data.Add(REDIRECT_URI, settings.RedirectUrl); - data.Add(CLIENT_SECRET, settings.ClientSecret); - data.Add(GRANT_TYPE, AUTHORIZATION_CODE); + data.Add(Code, settings.Code); + data.Add(ClientId, settings.ClientId); + data.Add(RedirectUri, settings.RedirectUrl); + data.Add(ClientSecret, settings.ClientSecret); + data.Add(GrantType, AuthorizationCode); foreach (string key in settings.AdditionalAttributes.Keys) { data.Add(key, settings.AdditionalAttributes[key]); } @@ -1103,12 +989,12 @@ Greenshot received information from CloudServiceName. You can close this browser string accessTokenJsonResult = NetworkHelper.GetResponseAsString(webRequest, true); IDictionary refreshTokenResult = JSONHelper.JsonDecode(accessTokenJsonResult); - if (refreshTokenResult.ContainsKey("error")) { + if (refreshTokenResult.ContainsKey("error")) + { if (refreshTokenResult.ContainsKey("error_description")) { - throw new Exception(string.Format("{0} - {1}", refreshTokenResult["error"], refreshTokenResult["error_description"])); - } else { - throw new Exception((string)refreshTokenResult["error"]); + throw new Exception($"{refreshTokenResult["error"]} - {refreshTokenResult["error_description"]}"); } + throw new Exception((string)refreshTokenResult["error"]); } // gives as described here: https://developers.google.com/identity/protocols/OAuth2InstalledApp @@ -1116,10 +1002,10 @@ Greenshot received information from CloudServiceName. You can close this browser // "expires_in":3920, // "token_type":"Bearer", // "refresh_token":"1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI" - settings.AccessToken = (string)refreshTokenResult[ACCESS_TOKEN] as string; - settings.RefreshToken = (string)refreshTokenResult[REFRESH_TOKEN] as string; + settings.AccessToken = (string)refreshTokenResult[AccessToken]; + settings.RefreshToken = (string)refreshTokenResult[RefreshToken]; - object seconds = refreshTokenResult[EXPIRES_IN]; + object seconds = refreshTokenResult[ExpiresIn]; if (seconds != null) { settings.AccessTokenExpires = DateTimeOffset.Now.AddSeconds((double)seconds); } @@ -1133,10 +1019,10 @@ Greenshot received information from CloudServiceName. You can close this browser /// public static void GenerateAccessToken(OAuth2Settings settings) { IDictionary data = new Dictionary(); - data.Add(REFRESH_TOKEN, settings.RefreshToken); - data.Add(CLIENT_ID, settings.ClientId); - data.Add(CLIENT_SECRET, settings.ClientSecret); - data.Add(GRANT_TYPE, REFRESH_TOKEN); + data.Add(RefreshToken, settings.RefreshToken); + data.Add(ClientId, settings.ClientId); + data.Add(ClientSecret, settings.ClientSecret); + data.Add(GrantType, RefreshToken); foreach (string key in settings.AdditionalAttributes.Keys) { data.Add(key, settings.AdditionalAttributes[key]); } @@ -1161,19 +1047,19 @@ Greenshot received information from CloudServiceName. You can close this browser return; } else { if (accessTokenResult.ContainsKey("error_description")) { - throw new Exception(string.Format("{0} - {1}", accessTokenResult["error"], accessTokenResult["error_description"])); + throw new Exception($"{accessTokenResult["error"]} - {accessTokenResult["error_description"]}"); } else { throw new Exception((string)accessTokenResult["error"]); } } } - settings.AccessToken = (string)accessTokenResult[ACCESS_TOKEN] as string; - if (accessTokenResult.ContainsKey(REFRESH_TOKEN)) { + settings.AccessToken = (string)accessTokenResult[AccessToken]; + if (accessTokenResult.ContainsKey(RefreshToken)) { // Refresh the refresh token :) - settings.RefreshToken = (string)accessTokenResult[REFRESH_TOKEN] as string; + settings.RefreshToken = (string)accessTokenResult[RefreshToken]; } - object seconds = accessTokenResult[EXPIRES_IN]; + object seconds = accessTokenResult[ExpiresIn]; if (seconds != null) { settings.AccessTokenExpires = DateTimeOffset.Now.AddSeconds((double)seconds); } else { @@ -1187,7 +1073,7 @@ Greenshot received information from CloudServiceName. You can close this browser /// OAuth2Settings /// false if it was canceled, true if it worked, exception if not public static bool Authenticate(OAuth2Settings settings) { - bool completed = true; + bool completed; switch (settings.AuthorizeMode) { case OAuth2AuthorizeMode.LocalServer: completed = AuthenticateViaLocalServer(settings); @@ -1196,7 +1082,7 @@ Greenshot received information from CloudServiceName. You can close this browser completed = AuthenticateViaEmbeddedBrowser(settings); break; default: - throw new NotImplementedException(string.Format("Authorize mode '{0}' is not 'yet' implemented.", settings.AuthorizeMode)); + throw new NotImplementedException($"Authorize mode '{settings.AuthorizeMode}' is not 'yet' implemented."); } return completed; } @@ -1209,16 +1095,16 @@ Greenshot received information from CloudServiceName. You can close this browser /// true if completed, false if canceled private static bool AuthenticateViaEmbeddedBrowser(OAuth2Settings settings) { if (string.IsNullOrEmpty(settings.CloudServiceName)) { - throw new ArgumentNullException("CloudServiceName"); + throw new ArgumentNullException(nameof(settings.CloudServiceName)); } if (settings.BrowserSize == Size.Empty) { - throw new ArgumentNullException("BrowserSize"); + throw new ArgumentNullException(nameof(settings.BrowserSize)); } - OAuthLoginForm loginForm = new OAuthLoginForm(string.Format("Authorize {0}", settings.CloudServiceName), settings.BrowserSize, settings.FormattedAuthUrl, settings.RedirectUrl); + OAuthLoginForm loginForm = new OAuthLoginForm($"Authorize {settings.CloudServiceName}", settings.BrowserSize, settings.FormattedAuthUrl, settings.RedirectUrl); loginForm.ShowDialog(); if (loginForm.IsOk) { string code; - if (loginForm.CallbackParameters.TryGetValue(CODE, out code) && !string.IsNullOrEmpty(code)) { + if (loginForm.CallbackParameters.TryGetValue(Code, out code) && !string.IsNullOrEmpty(code)) { settings.Code = code; GenerateRefreshToken(settings); return true; @@ -1238,7 +1124,7 @@ Greenshot received information from CloudServiceName. You can close this browser IDictionary result = codeReceiver.ReceiveCode(settings); string code; - if (result.TryGetValue(CODE, out code) && !string.IsNullOrEmpty(code)) { + if (result.TryGetValue(Code, out code) && !string.IsNullOrEmpty(code)) { settings.Code = code; GenerateRefreshToken(settings); return true; @@ -1251,9 +1137,8 @@ Greenshot received information from CloudServiceName. You can close this browser } if ("access_denied" == error) { throw new UnauthorizedAccessException("Access denied"); - } else { - throw new Exception(error); } + throw new Exception(error); } return false; } diff --git a/GreenshotPlugin/Core/PluginUtils.cs b/GreenshotPlugin/Core/PluginUtils.cs index 0758215a8..78d0f1cd5 100644 --- a/GreenshotPlugin/Core/PluginUtils.cs +++ b/GreenshotPlugin/Core/PluginUtils.cs @@ -36,13 +36,13 @@ namespace GreenshotPlugin.Core { /// Description of PluginUtils. /// public static class PluginUtils { - private static readonly ILog LOG = LogManager.GetLogger(typeof(PluginUtils)); - private static readonly CoreConfiguration conf = IniConfig.GetIniSection(); - private const string PATH_KEY = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\"; - private static readonly IDictionary exeIconCache = new Dictionary(); + private static readonly ILog Log = LogManager.GetLogger(typeof(PluginUtils)); + private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); + private const string PathKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\"; + private static readonly IDictionary ExeIconCache = new Dictionary(); static PluginUtils() { - conf.PropertyChanged += OnIconSizeChanged; + CoreConfig.PropertyChanged += OnIconSizeChanged; } /// @@ -61,16 +61,15 @@ namespace GreenshotPlugin.Core { private static void OnIconSizeChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IconSize") { List cachedImages = new List(); - lock (exeIconCache) { - foreach (string key in exeIconCache.Keys) { - cachedImages.Add(exeIconCache[key]); + lock (ExeIconCache) { + foreach (string key in ExeIconCache.Keys) { + cachedImages.Add(ExeIconCache[key]); } - exeIconCache.Clear(); + ExeIconCache.Clear(); } - foreach (Image cachedImage in cachedImages) { - if (cachedImage != null) { - cachedImage.Dispose(); - } + foreach (Image cachedImage in cachedImages) + { + cachedImage?.Dispose(); } } @@ -82,7 +81,7 @@ namespace GreenshotPlugin.Core { /// e.g. cmd.exe /// Path to file public static string GetExePath(string exeName) { - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(PATH_KEY + exeName, false)) { + using (RegistryKey key = Registry.LocalMachine.OpenSubKey(PathKey + exeName, false)) { if (key != null) { // "" is the default key, which should point to the requested location return (string)key.GetValue(""); @@ -91,11 +90,11 @@ namespace GreenshotPlugin.Core { foreach (string pathEntry in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(';')) { try { string path = pathEntry.Trim(); - if (!String.IsNullOrEmpty(path) && File.Exists(path = Path.Combine(path, exeName))) { + if (!string.IsNullOrEmpty(path) && File.Exists(path = Path.Combine(path, exeName))) { return Path.GetFullPath(path); } } catch (Exception) { - LOG.WarnFormat("Problem with path entry '{0}'.", pathEntry); + Log.WarnFormat("Problem with path entry '{0}'.", pathEntry); } } return null; @@ -108,18 +107,22 @@ namespace GreenshotPlugin.Core { /// index of the icon /// Bitmap with the icon or null if something happended public static Image GetCachedExeIcon(string path, int index) { - string cacheKey = string.Format("{0}:{1}", path, index); + string cacheKey = $"{path}:{index}"; Image returnValue; - lock (exeIconCache) + lock (ExeIconCache) { - if (!exeIconCache.TryGetValue(cacheKey, out returnValue)) { - lock (exeIconCache) { - if (!exeIconCache.TryGetValue(cacheKey, out returnValue)) { - returnValue = GetExeIcon(path, index); - if (returnValue != null) { - exeIconCache.Add(cacheKey, returnValue); - } - } + if (ExeIconCache.TryGetValue(cacheKey, out returnValue)) + { + return returnValue; + } + lock (ExeIconCache) { + if (ExeIconCache.TryGetValue(cacheKey, out returnValue)) + { + return returnValue; + } + returnValue = GetExeIcon(path, index); + if (returnValue != null) { + ExeIconCache.Add(cacheKey, returnValue); } } } @@ -137,18 +140,18 @@ namespace GreenshotPlugin.Core { return null; } try { - using (Icon appIcon = ImageHelper.ExtractAssociatedIcon(path, index, conf.UseLargeIcons)) { + using (Icon appIcon = ImageHelper.ExtractAssociatedIcon(path, index, CoreConfig.UseLargeIcons)) { if (appIcon != null) { return appIcon.ToBitmap(); } } - using (Icon appIcon = Shell32.GetFileIcon(path, conf.UseLargeIcons ? Shell32.IconSize.Large : Shell32.IconSize.Small, false)) { + using (Icon appIcon = Shell32.GetFileIcon(path, CoreConfig.UseLargeIcons ? Shell32.IconSize.Large : Shell32.IconSize.Small, false)) { if (appIcon != null) { return appIcon.ToBitmap(); } } } catch (Exception exIcon) { - LOG.Error("error retrieving icon: ", exIcon); + Log.Error("error retrieving icon: ", exIcon); } return null; } @@ -163,10 +166,12 @@ namespace GreenshotPlugin.Core { /// Keys which can be used as shortcut /// The onclick handler public static void AddToFileMenu(IImageEditor imageEditor, Image image, string text, object tag, Keys? shortcutKeys, EventHandler handler) { - ToolStripMenuItem item = new ToolStripMenuItem(); - item.Image = image; - item.Text = text; - item.Tag = tag; + var item = new ToolStripMenuItem + { + Image = image, + Text = text, + Tag = tag + }; if (shortcutKeys.HasValue) { item.ShortcutKeys = shortcutKeys.Value; } @@ -228,9 +233,11 @@ namespace GreenshotPlugin.Core { if (contextMenu.Items[i].GetType() == typeof(ToolStripSeparator)) { // Check if we need to add a new separator, which is done if the first found has a Tag with the value "PluginsAreAddedBefore" if ("PluginsAreAddedBefore".Equals(contextMenu.Items[i].Tag)) { - ToolStripSeparator separator = new ToolStripSeparator(); - separator.Tag = "PluginsAreAddedAfter"; - separator.Size = new Size(305, 6); + var separator = new ToolStripSeparator + { + Tag = "PluginsAreAddedAfter", + Size = new Size(305, 6) + }; contextMenu.Items.Insert(i, separator); } else if (!"PluginsAreAddedAfter".Equals(contextMenu.Items[i].Tag)) { continue; diff --git a/GreenshotPlugin/Core/QuantizerHelper.cs b/GreenshotPlugin/Core/QuantizerHelper.cs index 09b1ee0d2..4b3267726 100644 --- a/GreenshotPlugin/Core/QuantizerHelper.cs +++ b/GreenshotPlugin/Core/QuantizerHelper.cs @@ -337,7 +337,6 @@ namespace GreenshotPlugin.Core { using (IFastBitmap src = FastBitmap.Create(sourceBitmap)) { IFastBitmapWithBlend srcBlend = src as IFastBitmapWithBlend; Dictionary lookup = new Dictionary(); - byte bestMatch; for (int y = 0; y < src.Height; y++) { for (int x = 0; x < src.Width; x++) { Color color; @@ -349,6 +348,7 @@ namespace GreenshotPlugin.Core { } // Check if we already matched the color + byte bestMatch; if (!lookup.ContainsKey(color)) { // If not we need to find the best match @@ -678,5 +678,5 @@ namespace GreenshotPlugin.Core { } } } - } + } } \ No newline at end of file diff --git a/GreenshotPlugin/Core/RssHelper.cs b/GreenshotPlugin/Core/RssHelper.cs index d4480b877..445f5fd53 100644 --- a/GreenshotPlugin/Core/RssHelper.cs +++ b/GreenshotPlugin/Core/RssHelper.cs @@ -29,65 +29,49 @@ using log4net; namespace GreenshotPlugin.Core { public class RssFile { - private readonly string _file; - public string File { - get {return _file;} - } + public string File { get; } private readonly DateTime _pubdate; - public DateTime Pubdate { - get {return _pubdate;} - } - private readonly string _link; - public string Link { - get {return _link;} - } - private Version _version; - public Version Version { - get {return _version;} - set { - _version = value; - } - } - private string _language; - public string Language { - get {return _language;} - set {_language = value;} - } + public DateTime Pubdate => _pubdate; - public bool isExe { + public string Link { get; } + public Version Version { get; set; } + + public string Language { get; set; } + + public bool IsExe { get { - if (_file != null) { - return _file.ToLower().EndsWith(".exe"); + if (File != null) { + return File.ToLower().EndsWith(".exe"); } return false; } } - public bool isUnstable { + public bool IsUnstable { get { - if (_file != null) { - return _file.ToLower().Contains("unstable"); + if (File != null) { + return File.ToLower().Contains("unstable"); } return false; } } - public bool isReleaseCandidate { + public bool IsReleaseCandidate { get { - if (_file != null) { - return Regex.IsMatch(_file.ToLower(), "rc[0-9]+"); + if (File != null) { + return Regex.IsMatch(File.ToLower(), "rc[0-9]+"); } return false; } } public RssFile(string file, string pubdate, string link) { - _file = file; + File = file; if (!DateTime.TryParse(pubdate, out _pubdate)) { DateTime.TryParseExact(pubdate.Replace(" UT", ""), "ddd, dd MMM yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out _pubdate); } - _link = link; + Link = link; } } @@ -95,16 +79,16 @@ namespace GreenshotPlugin.Core { /// Description of RssHelper. /// public class RssHelper { - private static ILog LOG = LogManager.GetLogger(typeof(RssHelper)); - private const string RSSFEED = "http://getgreenshot.org/project-feed/"; + private static readonly ILog Log = LogManager.GetLogger(typeof(RssHelper)); + private const string Rssfeed = "http://getgreenshot.org/project-feed/"; /// /// This is using the HTTP HEAD Method to check if the RSS Feed is modified after the supplied date /// /// DateTime /// true if the feed is newer - public static bool IsRSSModifiedAfter(DateTime updateTime) { - DateTime lastModified = NetworkHelper.GetLastModified(new Uri(RSSFEED)); + public static bool IsRssModifiedAfter(DateTime updateTime) { + DateTime lastModified = NetworkHelper.GetLastModified(new Uri(Rssfeed)); if (lastModified == DateTime.MinValue) { // Time could not be read, just take now and add one hour to it. @@ -118,17 +102,17 @@ namespace GreenshotPlugin.Core { /// Read the Greenshot RSS feed, so we can use this information to check for updates /// /// List with RssFile(s) - public static IList readRSS() { + public static IList ReadRss() { XmlDocument rssDoc = new XmlDocument(); try { - HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(RSSFEED); + HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(Rssfeed); XmlTextReader rssReader = new XmlTextReader(webRequest.GetResponse().GetResponseStream()); // Load the XML content into a XmlDocument rssDoc.Load(rssReader); } catch (Exception wE) { - LOG.WarnFormat("Problem reading RSS from {0}", RSSFEED); - LOG.Warn(wE.Message); + Log.WarnFormat("Problem reading RSS from {0}", Rssfeed); + Log.Warn(wE.Message); return null; } @@ -143,7 +127,7 @@ namespace GreenshotPlugin.Core { } if (nodeRss == null) { - LOG.Debug("No RSS Feed!"); + Log.Debug("No RSS Feed!"); return null; } @@ -158,7 +142,7 @@ namespace GreenshotPlugin.Core { } if (nodeChannel == null) { - LOG.Debug("No channel in RSS feed!"); + Log.Debug("No channel in RSS feed!"); return null; } @@ -168,41 +152,49 @@ namespace GreenshotPlugin.Core { for (int i = 0; i < nodeChannel.ChildNodes.Count; i++) { // If it is the item tag, then it has children tags which we will add as items to the ListView - if (nodeChannel.ChildNodes[i].Name == "item") { - XmlNode nodeItem = nodeChannel.ChildNodes[i]; - string link = nodeItem["link"].InnerText; - string pubdate = nodeItem["pubDate"].InnerText; - try { - Match match= Regex.Match(Uri.UnescapeDataString(link), @"^.*\/(Greenshot.+)\/download$"); - if (match.Success) { - string file = match.Groups[1].Value; + if (nodeChannel.ChildNodes[i].Name != "item") + { + continue; + } + XmlNode nodeItem = nodeChannel.ChildNodes[i]; + string link = nodeItem["link"]?.InnerText; + string pubdate = nodeItem["pubDate"]?.InnerText; + try { + if (link == null) + { + continue; + } + Match match = Regex.Match(Uri.UnescapeDataString(link), @"^.*\/(Greenshot.+)\/download$"); + if (!match.Success) + { + continue; + } + string file = match.Groups[1].Value; - RssFile rssFile = new RssFile(file, pubdate, link); - if (file.EndsWith(".exe") ||file.EndsWith(".zip")) { - string version = Regex.Replace(file, @".*[a-zA-Z_]\-", ""); - version = version.Replace(@"\-[a-zA-Z]+.*",""); - version = Regex.Replace(version, @"\.exe$", ""); - version = Regex.Replace(version, @"\.zip$", ""); - version = Regex.Replace(version, @"RC[0-9]+", ""); - if (version.Trim().Length > 0) { - version = version.Replace('-','.'); - version = version.Replace(',','.'); - version = Regex.Replace(version, @"^[a-zA-Z_]*\.", ""); - version = Regex.Replace(version, @"\.[a-zA-Z_]*$", ""); + RssFile rssFile = new RssFile(file, pubdate, link); + if (file.EndsWith(".exe") ||file.EndsWith(".zip")) { + string version = Regex.Replace(file, @".*[a-zA-Z_]\-", ""); + version = version.Replace(@"\-[a-zA-Z]+.*",""); + version = Regex.Replace(version, @"\.exe$", ""); + version = Regex.Replace(version, @"\.zip$", ""); + version = Regex.Replace(version, @"RC[0-9]+", ""); + if (version.Trim().Length > 0) { + version = version.Replace('-','.'); + version = version.Replace(',','.'); + version = Regex.Replace(version, @"^[a-zA-Z_]*\.", ""); + version = Regex.Replace(version, @"\.[a-zA-Z_]*$", ""); - try { - rssFile.Version = new Version(version); - } catch (Exception) { - LOG.DebugFormat("Found invalid version {0} in file {1}", version, file); - } - } - rssFiles.Add(rssFile); + try { + rssFile.Version = new Version(version); + } catch (Exception) { + Log.DebugFormat("Found invalid version {0} in file {1}", version, file); } } - } catch (Exception ex) { - LOG.WarnFormat("Couldn't read RSS entry for: {0}", nodeChannel["title"].InnerText); - LOG.Warn("Reason: ", ex); + rssFiles.Add(rssFile); } + } catch (Exception ex) { + Log.WarnFormat("Couldn't read RSS entry for: {0}", nodeChannel["title"]?.InnerText); + Log.Warn("Reason: ", ex); } } diff --git a/GreenshotPlugin/Core/StringExtensions.cs b/GreenshotPlugin/Core/StringExtensions.cs index 832acb07b..7483fc967 100644 --- a/GreenshotPlugin/Core/StringExtensions.cs +++ b/GreenshotPlugin/Core/StringExtensions.cs @@ -52,7 +52,7 @@ namespace GreenshotPlugin.Core { /// Formatted string public static string FormatWith(this string format, IFormatProvider provider, object source) { if (format == null) { - throw new ArgumentNullException("format"); + throw new ArgumentNullException(nameof(format)); } IDictionary properties = new Dictionary(); @@ -80,11 +80,7 @@ namespace GreenshotPlugin.Core { Group endGroup = m.Groups["end"]; object value; - if (properties.TryGetValue(propertyGroup.Value, out value)) { - values.Add(value); - } else { - values.Add(source); - } + values.Add(properties.TryGetValue(propertyGroup.Value, out value) ? value : source); return new string('{', startGroup.Captures.Count) + (values.Count - 1) + formatGroup.Value + new string('}', endGroup.Captures.Count); }); @@ -94,12 +90,12 @@ namespace GreenshotPlugin.Core { /// /// A simply rijndael aes encryption, can be used to store passwords /// - /// the string to call upon + /// the string to call upon /// an encryped string in base64 form - public static string Encrypt(this string ClearText) { - string returnValue = ClearText; + public static string Encrypt(this string clearText) { + string returnValue = clearText; try { - byte[] clearTextBytes = Encoding.ASCII.GetBytes(ClearText); + byte[] clearTextBytes = Encoding.ASCII.GetBytes(clearText); SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); using (MemoryStream ms = new MemoryStream()) { @@ -113,7 +109,7 @@ namespace GreenshotPlugin.Core { } } } catch (Exception ex) { - LOG.ErrorFormat("Error encrypting, error: ", ex.Message); + LOG.ErrorFormat("Error encrypting, error: {0}", ex.Message); } return returnValue; } @@ -121,12 +117,12 @@ namespace GreenshotPlugin.Core { /// /// A simply rijndael aes decryption, can be used to store passwords /// - /// a base64 encoded rijndael encrypted string + /// a base64 encoded rijndael encrypted string /// Decrypeted text - public static string Decrypt(this string EncryptedText) { - string returnValue = EncryptedText; + public static string Decrypt(this string encryptedText) { + string returnValue = encryptedText; try { - byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText); + byte[] encryptedTextBytes = Convert.FromBase64String(encryptedText); using (MemoryStream ms = new MemoryStream()) { SymmetricAlgorithm rijn = SymmetricAlgorithm.Create(); @@ -142,7 +138,7 @@ namespace GreenshotPlugin.Core { } } catch (Exception ex) { - LOG.ErrorFormat("Error decrypting {0}, error: ", EncryptedText, ex.Message); + LOG.ErrorFormat("Error decrypting {0}, error: {1}", encryptedText, ex.Message); } return returnValue; diff --git a/GreenshotPlugin/Core/WindowCapture.cs b/GreenshotPlugin/Core/WindowCapture.cs index eae9ba0ec..2fa0aded5 100644 --- a/GreenshotPlugin/Core/WindowCapture.cs +++ b/GreenshotPlugin/Core/WindowCapture.cs @@ -62,16 +62,13 @@ namespace GreenshotPlugin.Core { set; } - private readonly Dictionary metaData = new Dictionary(); - public Dictionary MetaData { - get {return metaData;} - } - + public Dictionary MetaData { get; } = new Dictionary(); + public void AddMetaData(string key, string value) { - if (metaData.ContainsKey(key)) { - metaData[key] = value; + if (MetaData.ContainsKey(key)) { + MetaData[key] = value; } else { - metaData.Add(key, value); + MetaData.Add(key, value); } } @@ -117,10 +114,10 @@ namespace GreenshotPlugin.Core { /// Having the Bitmap, eventually the Windows Title and cursor all together. /// public class Capture : ICapture { - private static readonly ILog LOG = LogManager.GetLogger(typeof(Capture)); + private static readonly ILog Log = LogManager.GetLogger(typeof(Capture)); private List _elements = new List(); - private Rectangle _screenBounds = Rectangle.Empty; + private Rectangle _screenBounds; /// /// Get/Set the Screenbounds /// @@ -141,13 +138,11 @@ namespace GreenshotPlugin.Core { public Image Image { get {return _image;} set { - if (_image != null) { - _image.Dispose(); - } + _image?.Dispose(); _image = value; if (value != null) { if (value.PixelFormat.Equals(PixelFormat.Format8bppIndexed) || value.PixelFormat.Equals(PixelFormat.Format1bppIndexed) || value.PixelFormat.Equals(PixelFormat.Format4bppIndexed)) { - LOG.Debug("Converting Bitmap to PixelFormat.Format32bppArgb as we don't support: " + value.PixelFormat); + Log.Debug("Converting Bitmap to PixelFormat.Format32bppArgb as we don't support: " + value.PixelFormat); try { // Default Bitmap PixelFormat is Format32bppArgb _image = new Bitmap(value); @@ -156,9 +151,9 @@ namespace GreenshotPlugin.Core { value.Dispose(); } } - LOG.DebugFormat("Image is set with the following specifications: {0} - {1}", _image.Size, _image.PixelFormat); + Log.DebugFormat("Image is set with the following specifications: {0} - {1}", _image.Size, _image.PixelFormat); } else { - LOG.Debug("Image is removed."); + Log.Debug("Image is removed."); } } } @@ -174,21 +169,15 @@ namespace GreenshotPlugin.Core { public Icon Cursor { get {return _cursor;} set { - if (_cursor != null) { - _cursor.Dispose(); - } + _cursor?.Dispose(); _cursor = (Icon)value.Clone(); } } - - private bool _cursorVisible; + /// /// Set if the cursor is visible /// - public bool CursorVisible { - get {return _cursorVisible;} - set {_cursorVisible = value;} - } + public bool CursorVisible { get; set; } private Point _cursorLocation = Point.Empty; /// @@ -257,12 +246,8 @@ namespace GreenshotPlugin.Core { /// protected virtual void Dispose(bool disposing) { if (disposing) { - if (_image != null) { - _image.Dispose(); - } - if (_cursor != null) { - _cursor.Dispose(); - } + _image?.Dispose(); + _cursor?.Dispose(); } _image = null; _cursor = null; @@ -273,27 +258,28 @@ namespace GreenshotPlugin.Core { /// /// Rectangle with bitmap coordinates public bool Crop(Rectangle cropRectangle) { - LOG.Debug("Cropping to: " + cropRectangle.ToString()); - if (ImageHelper.Crop(ref _image, ref cropRectangle)) { - _location = cropRectangle.Location; - // Change mouse location according to the cropRegtangle (including screenbounds) offset - MoveMouseLocation(-cropRectangle.Location.X, -cropRectangle.Location.Y); - // Move all the elements - // TODO: Enable when the elements are usable again. - // MoveElements(-cropRectangle.Location.X, -cropRectangle.Location.Y); - - // Remove invisible elements - List newElements = new List(); - foreach(ICaptureElement captureElement in _elements) { - if (captureElement.Bounds.IntersectsWith(cropRectangle)) { - newElements.Add(captureElement); - } - } - _elements = newElements; - - return true; + Log.Debug("Cropping to: " + cropRectangle); + if (!ImageHelper.Crop(ref _image, ref cropRectangle)) + { + return false; } - return false; + _location = cropRectangle.Location; + // Change mouse location according to the cropRegtangle (including screenbounds) offset + MoveMouseLocation(-cropRectangle.Location.X, -cropRectangle.Location.Y); + // Move all the elements + // TODO: Enable when the elements are usable again. + // MoveElements(-cropRectangle.Location.X, -cropRectangle.Location.Y); + + // Remove invisible elements + var newElements = new List(); + foreach(var captureElement in _elements) { + if (captureElement.Bounds.IntersectsWith(cropRectangle)) { + newElements.Add(captureElement); + } + } + _elements = newElements; + + return true; } /// @@ -370,17 +356,9 @@ namespace GreenshotPlugin.Core { Name = name; Bounds = bounds; } - - private List _children = new List(); - public List Children { - get { - return _children; - } - set { - _children = value; - } - } - + + public List Children { get; set; } = new List(); + public string Name { get; set; @@ -392,17 +370,16 @@ namespace GreenshotPlugin.Core { // CaptureElements are regarded equal if their bounds are equal. this should be sufficient. public override bool Equals(object obj) { - bool ret = false; - if (obj != null && GetType() == obj.GetType()) { - CaptureElement other = obj as CaptureElement; - if (other != null && Bounds.Equals(other.Bounds)) { - ret = true; - } + if (obj == null || GetType() != obj.GetType()) + { + return false; } - return ret; + CaptureElement other = obj as CaptureElement; + return other != null && Bounds.Equals(other.Bounds); } public override int GetHashCode() { + // TODO: Fix this, this is not right... return Bounds.GetHashCode(); } } @@ -410,7 +387,7 @@ namespace GreenshotPlugin.Core { /// The Window Capture code /// public class WindowCapture { - private static readonly ILog LOG = LogManager.GetLogger(typeof(WindowCapture)); + private static readonly ILog Log = LogManager.GetLogger(typeof(WindowCapture)); private static readonly CoreConfiguration Configuration = IniConfig.GetIniSection(); /// @@ -472,22 +449,22 @@ namespace GreenshotPlugin.Core { /// /// A Capture Object with the Mouse Cursor information in it. public static ICapture CaptureCursor(ICapture capture) { - LOG.Debug("Capturing the mouse cursor."); + Log.Debug("Capturing the mouse cursor."); if (capture == null) { capture = new Capture(); } - int x,y; - CursorInfo cursorInfo = new CursorInfo(); - IconInfo iconInfo; + CursorInfo cursorInfo = new CursorInfo(); cursorInfo.cbSize = Marshal.SizeOf(cursorInfo); if (User32.GetCursorInfo(out cursorInfo)) { if (cursorInfo.flags == User32.CURSOR_SHOWING) { - using (SafeIconHandle safeIcon = User32.CopyIcon(cursorInfo.hCursor)) { + using (SafeIconHandle safeIcon = User32.CopyIcon(cursorInfo.hCursor)) + { + IconInfo iconInfo; if (User32.GetIconInfo(safeIcon, out iconInfo)) { Point cursorLocation = User32.GetCursorLocation(); // Allign cursor location to Bitmap coordinates (instead of Screen coordinates) - x = cursorLocation.X - iconInfo.xHotspot - capture.ScreenBounds.X; - y = cursorLocation.Y - iconInfo.yHotspot - capture.ScreenBounds.Y; + var x = cursorLocation.X - iconInfo.xHotspot - capture.ScreenBounds.X; + var y = cursorLocation.Y - iconInfo.yHotspot - capture.ScreenBounds.Y; // Set the location capture.CursorLocation = new Point(x, y); @@ -548,7 +525,7 @@ namespace GreenshotPlugin.Core { return false; } } catch (Exception ex) { - LOG.Warn(ex.Message); + Log.Warn(ex.Message); } } } @@ -569,7 +546,7 @@ namespace GreenshotPlugin.Core { return false; } } catch (Exception ex) { - LOG.Warn(ex.Message); + Log.Warn(ex.Message); } } } @@ -591,7 +568,10 @@ namespace GreenshotPlugin.Core { if (CaptureHandler.CaptureScreenRectangle != null) { try { capturedImage = CaptureHandler.CaptureScreenRectangle(captureBounds); - } catch { + } + catch + { + // ignored } } // If no capture, use the normal screen capture @@ -626,10 +606,10 @@ namespace GreenshotPlugin.Core { public static Bitmap CaptureRectangle(Rectangle captureBounds) { Bitmap returnBitmap = null; if (captureBounds.Height <= 0 || captureBounds.Width <= 0) { - LOG.Warn("Nothing to capture, ignoring!"); + Log.Warn("Nothing to capture, ignoring!"); return null; } - LOG.Debug("CaptureRectangle Called!"); + Log.Debug("CaptureRectangle Called!"); // .NET GDI+ Solution, according to some post this has a GDI+ leak... // See http://connect.microsoft.com/VisualStudio/feedback/details/344752/gdi-object-leak-when-calling-graphics-copyfromscreen @@ -640,8 +620,8 @@ namespace GreenshotPlugin.Core { // capture.Image = capturedBitmap; // capture.Location = captureBounds.Location; - using (SafeWindowDCHandle desktopDCHandle = SafeWindowDCHandle.FromDesktop()) { - if (desktopDCHandle.IsInvalid) { + using (var desktopDcHandle = SafeWindowDcHandle.FromDesktop()) { + if (desktopDcHandle.IsInvalid) { // Get Exception before the error is lost Exception exceptionToThrow = CreateCaptureException("desktopDCHandle", captureBounds); // throw exception @@ -649,9 +629,9 @@ namespace GreenshotPlugin.Core { } // create a device context we can copy to - using (SafeCompatibleDCHandle safeCompatibleDCHandle = GDI32.CreateCompatibleDC(desktopDCHandle)) { + using (SafeCompatibleDCHandle safeCompatibleDcHandle = GDI32.CreateCompatibleDC(desktopDcHandle)) { // Check if the device context is there, if not throw an error with as much info as possible! - if (safeCompatibleDCHandle.IsInvalid) { + if (safeCompatibleDcHandle.IsInvalid) { // Get Exception before the error is lost Exception exceptionToThrow = CreateCaptureException("CreateCompatibleDC", captureBounds); // throw exception @@ -665,20 +645,21 @@ namespace GreenshotPlugin.Core { // create a bitmap we can copy it to, using GetDeviceCaps to get the width/height IntPtr bits0; // not used for our purposes. It returns a pointer to the raw bits that make up the bitmap. - using (SafeDibSectionHandle safeDibSectionHandle = GDI32.CreateDIBSection(desktopDCHandle, ref bmi, BITMAPINFOHEADER.DIB_RGB_COLORS, out bits0, IntPtr.Zero, 0)) { + using (SafeDibSectionHandle safeDibSectionHandle = GDI32.CreateDIBSection(desktopDcHandle, ref bmi, BITMAPINFOHEADER.DIB_RGB_COLORS, out bits0, IntPtr.Zero, 0)) { if (safeDibSectionHandle.IsInvalid) { // Get Exception before the error is lost Exception exceptionToThrow = CreateCaptureException("CreateDIBSection", captureBounds); - exceptionToThrow.Data.Add("hdcDest", safeCompatibleDCHandle.DangerousGetHandle().ToInt32()); - exceptionToThrow.Data.Add("hdcSrc", desktopDCHandle.DangerousGetHandle().ToInt32()); + exceptionToThrow.Data.Add("hdcDest", safeCompatibleDcHandle.DangerousGetHandle().ToInt32()); + exceptionToThrow.Data.Add("hdcSrc", desktopDcHandle.DangerousGetHandle().ToInt32()); // Throw so people can report the problem throw exceptionToThrow; } // select the bitmap object and store the old handle - using (safeCompatibleDCHandle.SelectObject(safeDibSectionHandle)) { + using (safeCompatibleDcHandle.SelectObject(safeDibSectionHandle)) { // bitblt over (make copy) - GDI32.BitBlt(safeCompatibleDCHandle, 0, 0, captureBounds.Width, captureBounds.Height, desktopDCHandle, captureBounds.X, captureBounds.Y, CopyPixelOperation.SourceCopy | CopyPixelOperation.CaptureBlt); + // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags + GDI32.BitBlt(safeCompatibleDcHandle, 0, 0, captureBounds.Width, captureBounds.Height, desktopDcHandle, captureBounds.X, captureBounds.Y, CopyPixelOperation.SourceCopy | CopyPixelOperation.CaptureBlt); } // get a .NET image object for it @@ -731,12 +712,12 @@ namespace GreenshotPlugin.Core { success = true; break; } catch (ExternalException ee) { - LOG.Warn("Problem getting bitmap at try " + i + " : ", ee); + Log.Warn("Problem getting bitmap at try " + i + " : ", ee); exception = ee; } } if (!success) { - LOG.Error("Still couldn't create Bitmap!"); + Log.Error("Still couldn't create Bitmap!"); if (exception != null) { throw exception; } diff --git a/GreenshotPlugin/Core/WindowsHelper.cs b/GreenshotPlugin/Core/WindowsHelper.cs index fb7624bbf..54ac58240 100644 --- a/GreenshotPlugin/Core/WindowsHelper.cs +++ b/GreenshotPlugin/Core/WindowsHelper.cs @@ -680,12 +680,10 @@ namespace GreenshotPlugin.Core { RECT rect = new RECT(screen.Bounds); IntPtr monitor = User32.MonitorFromRect(ref rect, User32.MONITOR_DEFAULTTONULL); if (monitor != IntPtr.Zero) { - if (AppVisibility != null) { - MONITOR_APP_VISIBILITY monitorAppVisibility = AppVisibility.GetAppVisibilityOnMonitor(monitor); - //LOG.DebugFormat("App {0} visible: {1} on {2}", Text, monitorAppVisibility, screen.Bounds); - if (monitorAppVisibility == MONITOR_APP_VISIBILITY.MAV_APP_VISIBLE) { - return true; - } + MONITOR_APP_VISIBILITY? monitorAppVisibility = AppVisibility?.GetAppVisibilityOnMonitor(monitor); + //LOG.DebugFormat("App {0} visible: {1} on {2}", Text, monitorAppVisibility, screen.Bounds); + if (monitorAppVisibility == MONITOR_APP_VISIBILITY.MAV_APP_VISIBLE) { + return true; } } } else { diff --git a/GreenshotPlugin/Effects/AdjustEffect.cs b/GreenshotPlugin/Effects/AdjustEffect.cs new file mode 100644 index 000000000..9dd4da68e --- /dev/null +++ b/GreenshotPlugin/Effects/AdjustEffect.cs @@ -0,0 +1,57 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 1 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +using System.Drawing; +using System.Drawing.Drawing2D; +using GreenshotPlugin.Core; + +namespace GreenshotPlugin.Effects +{ + /// + /// AdjustEffect + /// + public class AdjustEffect : IEffect { + public AdjustEffect() + { + Reset(); + } + public float Contrast { + get; + set; + } + public float Brightness { + get; + set; + } + public float Gamma { + get; + set; + } + public void Reset() { + Contrast = 1f; + Brightness = 1f; + Gamma = 1f; + } + public Image Apply(Image sourceImage, Matrix matrix) { + return ImageHelper.Adjust(sourceImage, Brightness, Contrast, Gamma); + } + } +} \ No newline at end of file diff --git a/GreenshotPlugin/Effects/BorderEffect.cs b/GreenshotPlugin/Effects/BorderEffect.cs new file mode 100644 index 000000000..cfc36ca44 --- /dev/null +++ b/GreenshotPlugin/Effects/BorderEffect.cs @@ -0,0 +1,51 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 1 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +using System.Drawing; +using System.Drawing.Drawing2D; +using GreenshotPlugin.Core; + +namespace GreenshotPlugin.Effects +{ + /// + /// BorderEffect + /// + public class BorderEffect : IEffect { + public BorderEffect() { + Reset(); + } + public Color Color { + get; + set; + } + public int Width { + get; + set; + } + public void Reset() { + Width = 2; + Color = Color.Black; + } + public Image Apply(Image sourceImage, Matrix matrix) { + return ImageHelper.CreateBorder(sourceImage, Width, Color, sourceImage.PixelFormat, matrix); + } + } +} \ No newline at end of file diff --git a/GreenshotPlugin/Effects/DropShadowEffect.cs b/GreenshotPlugin/Effects/DropShadowEffect.cs new file mode 100644 index 000000000..8d3516303 --- /dev/null +++ b/GreenshotPlugin/Effects/DropShadowEffect.cs @@ -0,0 +1,64 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 1 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using Greenshot.Core; +using GreenshotPlugin.Core; + +namespace GreenshotPlugin.Effects { + /// + /// DropShadowEffect + /// + [TypeConverter(typeof(EffectConverter))] + public class DropShadowEffect : IEffect { + public DropShadowEffect() { + Reset(); + } + + public float Darkness { + get; + set; + } + + public int ShadowSize { + get; + set; + } + + public Point ShadowOffset { + get; + set; + } + + public virtual void Reset() { + Darkness = 0.6f; + ShadowSize = 7; + ShadowOffset = new Point(-1, -1); + } + + public virtual Image Apply(Image sourceImage, Matrix matrix) { + return ImageHelper.CreateShadow(sourceImage, Darkness, ShadowSize, ShadowOffset, matrix, PixelFormat.Format32bppArgb); + } + } +} \ No newline at end of file diff --git a/GreenshotPlugin/Effects/GrayscaleEffect.cs b/GreenshotPlugin/Effects/GrayscaleEffect.cs new file mode 100644 index 000000000..9e3b8f9b6 --- /dev/null +++ b/GreenshotPlugin/Effects/GrayscaleEffect.cs @@ -0,0 +1,39 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 1 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +using System.Drawing; +using System.Drawing.Drawing2D; +using GreenshotPlugin.Core; + +namespace GreenshotPlugin.Effects +{ + /// + /// GrayscaleEffect + /// + public class GrayscaleEffect : IEffect { + public Image Apply(Image sourceImage, Matrix matrix) { + return ImageHelper.CreateGrayscale(sourceImage); + } + public void Reset() { + // No settings to reset + } + } +} \ No newline at end of file diff --git a/GreenshotPlugin/Effects/IEffect.cs b/GreenshotPlugin/Effects/IEffect.cs new file mode 100644 index 000000000..2226ff91b --- /dev/null +++ b/GreenshotPlugin/Effects/IEffect.cs @@ -0,0 +1,45 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 1 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +using System.Drawing; +using System.Drawing.Drawing2D; + +namespace GreenshotPlugin.Effects +{ + /// + /// Interface to describe an effect + /// + public interface IEffect { + /// + /// Apply this IEffect to the supplied sourceImage. + /// In the process of applying the supplied matrix will be modified to represent the changes. + /// + /// Image to apply the effect to + /// Matrix with the modifications like rotate, translate etc. this can be used to calculate the new location of elements on a canvas + /// new image with applied effect + Image Apply(Image sourceImage, Matrix matrix); + + /// + /// Reset all values to their defaults + /// + void Reset(); + } +} \ No newline at end of file diff --git a/GreenshotPlugin/Effects/InvertEffect.cs b/GreenshotPlugin/Effects/InvertEffect.cs new file mode 100644 index 000000000..4b2c6b395 --- /dev/null +++ b/GreenshotPlugin/Effects/InvertEffect.cs @@ -0,0 +1,39 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 1 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +using System.Drawing; +using System.Drawing.Drawing2D; +using GreenshotPlugin.Core; + +namespace GreenshotPlugin.Effects +{ + /// + /// InvertEffect + /// + public class InvertEffect : IEffect { + public Image Apply(Image sourceImage, Matrix matrix) { + return ImageHelper.CreateNegative(sourceImage); + } + public void Reset() { + // No settings to reset + } + } +} \ No newline at end of file diff --git a/GreenshotPlugin/Effects/MonochromeEffect.cs b/GreenshotPlugin/Effects/MonochromeEffect.cs new file mode 100644 index 000000000..568fe0dad --- /dev/null +++ b/GreenshotPlugin/Effects/MonochromeEffect.cs @@ -0,0 +1,44 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 1 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +using System.Drawing; +using System.Drawing.Drawing2D; +using GreenshotPlugin.Core; + +namespace GreenshotPlugin.Effects +{ + /// + /// MonochromeEffect + /// + public class MonochromeEffect : IEffect { + private readonly byte _threshold; + /// Threshold for monochrome filter (0 - 255), lower value means less black + public MonochromeEffect(byte threshold) { + _threshold = threshold; + } + public void Reset() { + // TODO: Modify the threshold to have a default, which is reset here + } + public Image Apply(Image sourceImage, Matrix matrix) { + return ImageHelper.CreateMonochrome(sourceImage, _threshold); + } + } +} \ No newline at end of file diff --git a/GreenshotPlugin/Effects/ReduceColorsEffect.cs b/GreenshotPlugin/Effects/ReduceColorsEffect.cs new file mode 100644 index 000000000..5c9ea936f --- /dev/null +++ b/GreenshotPlugin/Effects/ReduceColorsEffect.cs @@ -0,0 +1,60 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 1 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using GreenshotPlugin.Core; +using log4net; + +namespace GreenshotPlugin.Effects +{ + /// + /// ReduceColorsEffect + /// + public class ReduceColorsEffect : IEffect { + private static readonly ILog Log = LogManager.GetLogger(typeof(ReduceColorsEffect)); + public ReduceColorsEffect() + { + Reset(); + } + public int Colors { + get; + set; + } + public void Reset() { + Colors = 256; + } + public Image Apply(Image sourceImage, Matrix matrix) { + using (WuQuantizer quantizer = new WuQuantizer((Bitmap)sourceImage)) { + int colorCount = quantizer.GetColorCount(); + if (colorCount > Colors) { + try { + return quantizer.GetQuantizedImage(Colors); + } catch (Exception e) { + Log.Warn("Error occurred while Quantizing the image, ignoring and using original. Error: ", e); + } + } + } + return null; + } + } +} \ No newline at end of file diff --git a/GreenshotPlugin/Effects/ResizeCanvasEffect.cs b/GreenshotPlugin/Effects/ResizeCanvasEffect.cs new file mode 100644 index 000000000..7103508ca --- /dev/null +++ b/GreenshotPlugin/Effects/ResizeCanvasEffect.cs @@ -0,0 +1,66 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 1 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +using System.Drawing; +using System.Drawing.Drawing2D; +using GreenshotPlugin.Core; + +namespace GreenshotPlugin.Effects +{ + /// + /// ResizeCanvasEffect + /// + public class ResizeCanvasEffect : IEffect { + public ResizeCanvasEffect(int left, int right, int top, int bottom) { + Left = left; + Right = right; + Top = top; + Bottom = bottom; + BackgroundColor = Color.Empty; // Uses the default background color depending on the format + } + public int Left { + get; + set; + } + public int Right { + get; + set; + } + public int Top { + get; + set; + } + public int Bottom { + get; + set; + } + public Color BackgroundColor { + get; + set; + } + public void Reset() { + // values don't have a default value + } + public Image Apply(Image sourceImage, Matrix matrix) { + return ImageHelper.ResizeCanvas(sourceImage, BackgroundColor, Left, Right, Top, Bottom, matrix); + } + } +} \ No newline at end of file diff --git a/GreenshotPlugin/Effects/ResizeEffect.cs b/GreenshotPlugin/Effects/ResizeEffect.cs new file mode 100644 index 000000000..f6702db74 --- /dev/null +++ b/GreenshotPlugin/Effects/ResizeEffect.cs @@ -0,0 +1,56 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 1 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +using System.Drawing; +using System.Drawing.Drawing2D; +using GreenshotPlugin.Core; + +namespace GreenshotPlugin.Effects +{ + /// + /// ResizeEffect + /// + public class ResizeEffect : IEffect { + public ResizeEffect(int width, int height, bool maintainAspectRatio) { + Width = width; + Height = height; + MaintainAspectRatio = maintainAspectRatio; + } + public int Width { + get; + set; + } + public int Height { + get; + set; + } + public bool MaintainAspectRatio { + get; + set; + } + public void Reset() { + // values don't have a default value + } + public Image Apply(Image sourceImage, Matrix matrix) { + return ImageHelper.ResizeImage(sourceImage, MaintainAspectRatio, Width, Height, matrix); + } + } +} \ No newline at end of file diff --git a/GreenshotPlugin/Effects/RotateEffect.cs b/GreenshotPlugin/Effects/RotateEffect.cs new file mode 100644 index 000000000..bbf37e351 --- /dev/null +++ b/GreenshotPlugin/Effects/RotateEffect.cs @@ -0,0 +1,59 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 1 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using GreenshotPlugin.Core; + +namespace GreenshotPlugin.Effects +{ + /// + /// RotateEffect + /// + public class RotateEffect : IEffect { + public RotateEffect(int angle) { + Angle = angle; + } + public int Angle { + get; + set; + } + public void Reset() { + // Angle doesn't have a default value + } + public Image Apply(Image sourceImage, Matrix matrix) { + RotateFlipType flipType; + if (Angle == 90) { + matrix.Rotate(90, MatrixOrder.Append); + matrix.Translate(sourceImage.Height, 0, MatrixOrder.Append); + flipType = RotateFlipType.Rotate90FlipNone; + } else if (Angle == -90 || Angle == 270) { + flipType = RotateFlipType.Rotate270FlipNone; + matrix.Rotate(-90, MatrixOrder.Append); + matrix.Translate(0, sourceImage.Width, MatrixOrder.Append); + } else { + throw new NotSupportedException("Currently only an angle of 90 or -90 (270) is supported."); + } + return ImageHelper.RotateFlip(sourceImage, flipType); + } + } +} \ No newline at end of file diff --git a/GreenshotPlugin/Effects/TornEdgeEffect.cs b/GreenshotPlugin/Effects/TornEdgeEffect.cs new file mode 100644 index 000000000..aab04d619 --- /dev/null +++ b/GreenshotPlugin/Effects/TornEdgeEffect.cs @@ -0,0 +1,80 @@ +/* + * Greenshot - a free and open source screenshot tool + * Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom + * + * For more information see: http://getgreenshot.org/ + * The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 1 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using Greenshot.Core; +using GreenshotPlugin.Core; + +namespace GreenshotPlugin.Effects +{ + /// + /// TornEdgeEffect extends on DropShadowEffect + /// + [TypeConverter(typeof(EffectConverter))] + public sealed class TornEdgeEffect : DropShadowEffect { + public TornEdgeEffect() + { + Reset(); + } + public int ToothHeight { + get; + set; + } + public int HorizontalToothRange { + get; + set; + } + public int VerticalToothRange { + get; + set; + } + public bool[] Edges { + get; + set; + } + public bool GenerateShadow { + get; + set; + } + + public override void Reset() { + base.Reset(); + ShadowSize = 7; + ToothHeight = 12; + HorizontalToothRange = 20; + VerticalToothRange = 20; + Edges = new[] { true, true, true, true }; + GenerateShadow = true; + } + public override Image Apply(Image sourceImage, Matrix matrix) { + Image tmpTornImage = ImageHelper.CreateTornEdge(sourceImage, ToothHeight, HorizontalToothRange, VerticalToothRange, Edges); + if (GenerateShadow) { + using (tmpTornImage) { + return ImageHelper.CreateShadow(tmpTornImage, Darkness, ShadowSize, ShadowOffset, matrix, PixelFormat.Format32bppArgb); + } + } + return tmpTornImage; + } + } +} \ No newline at end of file diff --git a/GreenshotPlugin/GlobalSuppressions.cs b/GreenshotPlugin/GlobalSuppressions.cs index 691d5bdec..c050f5d98 100644 Binary files a/GreenshotPlugin/GlobalSuppressions.cs and b/GreenshotPlugin/GlobalSuppressions.cs differ diff --git a/GreenshotPlugin/GreenshotPlugin.csproj b/GreenshotPlugin/GreenshotPlugin.csproj index 608c8a10b..a854cd79f 100644 --- a/GreenshotPlugin/GreenshotPlugin.csproj +++ b/GreenshotPlugin/GreenshotPlugin.csproj @@ -43,13 +43,25 @@ Component + + + + + + + + + + + + @@ -172,7 +184,7 @@ - + diff --git a/GreenshotPlugin/IniFile/IniAttributes.cs b/GreenshotPlugin/IniFile/IniAttributes.cs index 801d42994..5243b0fe2 100644 --- a/GreenshotPlugin/IniFile/IniAttributes.cs +++ b/GreenshotPlugin/IniFile/IniAttributes.cs @@ -24,23 +24,19 @@ namespace Greenshot.IniFile { /// /// Attribute for telling that this class is linked to a section in the ini-configuration /// - [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] + [AttributeUsage(AttributeTargets.Class)] public class IniSectionAttribute : Attribute { - private string name; public IniSectionAttribute(string name) { - this.name = name; + Name = name; } public string Description; - public string Name { - get { return name; } - set { name = value; } - } + public string Name { get; set; } } /// /// Attribute for telling that a field is linked to a property in the ini-configuration selection /// - [AttributeUsage(AttributeTargets.Field|AttributeTargets.Property, AllowMultiple = false)] + [AttributeUsage(AttributeTargets.Field|AttributeTargets.Property)] public class IniPropertyAttribute : Attribute { public IniPropertyAttribute() { Separator = ","; diff --git a/GreenshotPlugin/IniFile/IniConfig.cs b/GreenshotPlugin/IniFile/IniConfig.cs index 2ada973d9..3869640f0 100644 --- a/GreenshotPlugin/IniFile/IniConfig.cs +++ b/GreenshotPlugin/IniFile/IniConfig.cs @@ -28,55 +28,50 @@ using log4net; namespace Greenshot.IniFile { public class IniConfig { - private static readonly ILog LOG = LogManager.GetLogger(typeof(IniConfig)); - private const string INI_EXTENSION = ".ini"; - private const string DEFAULTS_POSTFIX = "-defaults"; - private const string FIXED_POSTFIX = "-fixed"; + private static readonly ILog Log = LogManager.GetLogger(typeof(IniConfig)); + private const string IniExtension = ".ini"; + private const string DefaultsPostfix = "-defaults"; + private const string FixedPostfix = "-fixed"; /// /// A lock object for the ini file saving /// - private static readonly object iniLock = new object(); + private static readonly object IniLock = new object(); /// /// As the ini implementation is kept someone generic, for reusing, this holds the name of the application /// - private static string applicationName; + private static string _applicationName; /// /// As the ini implementation is kept someone generic, for reusing, this holds the name of the configuration /// - private static string configName; + private static string _configName; /// /// A Dictionary with all the sections stored by section name /// - private static readonly Dictionary sectionMap = new Dictionary(); + private static readonly Dictionary SectionMap = new Dictionary(); /// /// A Dictionary with the properties for a section stored by section name /// - private static Dictionary> sections = new Dictionary>(); + private static Dictionary> _sections = new Dictionary>(); /// /// A Dictionary with the fixed-properties for a section stored by section name /// - private static Dictionary> fixedProperties; + private static Dictionary> _fixedProperties; /// /// Stores if we checked for portable /// - private static bool portableCheckMade; + private static bool _portableCheckMade; /// /// Is the configuration portable (meaning we don't store it in the AppData directory) /// - private static bool portable; - public static bool IsPortable { - get { - return portable; - } - } + public static bool IsPortable { get; private set; } /// /// Config directory when set from external @@ -92,34 +87,34 @@ namespace Greenshot.IniFile { /// /// public static void Init(string appName, string configName) { - applicationName = appName; - IniConfig.configName = configName; + _applicationName = appName; + _configName = configName; Reload(); } /// /// Checks if we initialized the ini /// - public static bool isInitialized { - get { - return applicationName != null && configName != null && sectionMap.Count > 0; - } - } + public static bool IsInitialized => _applicationName != null && _configName != null && SectionMap.Count > 0; /// /// This forces the ini to be stored in the startup path, used for portable applications /// public static void ForceIniInStartupPath() { - if (portableCheckMade) { + if (_portableCheckMade) { throw new Exception("ForceLocal should be called before any file is read"); } - portable = false; - portableCheckMade = true; + IsPortable = false; + _portableCheckMade = true; string applicationStartupPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); - if (applicationName == null || configName == null) { + if (_applicationName == null || _configName == null) { Init(); } - string forcedIni = Path.Combine(applicationStartupPath, applicationName + INI_EXTENSION); + if (applicationStartupPath == null) + { + return; + } + string forcedIni = Path.Combine(applicationStartupPath, _applicationName + IniExtension); if (!File.Exists(forcedIni)) { using (File.Create(forcedIni)) {} } @@ -130,9 +125,9 @@ namespace Greenshot.IniFile { /// public static void Init() { AssemblyProductAttribute[] assemblyProductAttributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false) as AssemblyProductAttribute[]; - if (assemblyProductAttributes.Length > 0) { + if (assemblyProductAttributes != null && assemblyProductAttributes.Length > 0) { string productName = assemblyProductAttributes[0].Product; - LOG.InfoFormat("Using ProductName {0}", productName); + Log.InfoFormat("Using ProductName {0}", productName); Init(productName, productName); } else { throw new InvalidOperationException("Assembly ProductName not set."); @@ -144,8 +139,8 @@ namespace Greenshot.IniFile { /// public static string ConfigLocation { get { - if (isInitialized) { - return CreateIniLocation(configName + INI_EXTENSION, false); + if (IsInitialized) { + return CreateIniLocation(_configName + IniExtension, false); } throw new InvalidOperationException("Ini configuration was not initialized!"); } @@ -155,7 +150,7 @@ namespace Greenshot.IniFile { /// Create the location of the configuration file /// private static string CreateIniLocation(string configFilename, bool isReadOnly) { - if (applicationName == null || configName == null) { + if (_applicationName == null || _configName == null) { throw new InvalidOperationException("IniConfig.Init not called!"); } string iniFilePath = null; @@ -174,53 +169,60 @@ namespace Greenshot.IniFile { iniFilePath = null; } } catch (Exception exception) { - LOG.WarnFormat("The ini-directory {0} can't be used due to: {1}", IniDirectory, exception.Message); + Log.WarnFormat("The ini-directory {0} can't be used due to: {1}", IniDirectory, exception.Message); } - string applicationStartupPath = ""; + string applicationStartupPath; try { applicationStartupPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); } catch (Exception exception) { - LOG.WarnFormat("Problem retrieving the AssemblyLocation: {0} (Designer mode?)", exception.Message); + Log.WarnFormat("Problem retrieving the AssemblyLocation: {0} (Designer mode?)", exception.Message); applicationStartupPath = @"."; } - string pafPath = Path.Combine(applicationStartupPath, @"App\" + applicationName); + if (applicationStartupPath != null) + { + string pafPath = Path.Combine(applicationStartupPath, @"App\" + _applicationName); - if (portable || !portableCheckMade) { - if (!portable) { - LOG.Info("Checking for portable mode."); - portableCheckMade = true; - if (Directory.Exists(pafPath)) { - portable = true; - LOG.Info("Portable mode active!"); - } - } - if (portable) { - string pafConfigPath = Path.Combine(applicationStartupPath, @"Data\Settings"); - try { - if (!Directory.Exists(pafConfigPath)) { - Directory.CreateDirectory(pafConfigPath); + if (IsPortable || !_portableCheckMade) { + if (!IsPortable) { + Log.Info("Checking for portable mode."); + _portableCheckMade = true; + if (Directory.Exists(pafPath)) { + IsPortable = true; + Log.Info("Portable mode active!"); + } + } + if (IsPortable) { + string pafConfigPath = Path.Combine(applicationStartupPath, @"Data\Settings"); + try { + if (!Directory.Exists(pafConfigPath)) { + Directory.CreateDirectory(pafConfigPath); + } + iniFilePath = Path.Combine(pafConfigPath, configFilename); + } catch(Exception e) { + Log.InfoFormat("Portable mode NOT possible, couldn't create directory '{0}'! Reason: {1}", pafConfigPath, e.Message); } - iniFilePath = Path.Combine(pafConfigPath, configFilename); - } catch(Exception e) { - LOG.InfoFormat("Portable mode NOT possible, couldn't create directory '{0}'! Reason: {1}", pafConfigPath, e.Message); } } } - if (iniFilePath == null) { + if (iniFilePath == null) + { // check if file is in the same location as started from, if this is the case // we will use this file instead of the ApplicationData folder // Done for Feature Request #2741508 - iniFilePath = Path.Combine(applicationStartupPath, configFilename); + if (applicationStartupPath != null) + { + iniFilePath = Path.Combine(applicationStartupPath, configFilename); + } if (!File.Exists(iniFilePath)) { - string iniDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), applicationName); + string iniDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), _applicationName); if (!Directory.Exists(iniDirectory)) { Directory.CreateDirectory(iniDirectory); } iniFilePath = Path.Combine(iniDirectory, configFilename); } } - LOG.InfoFormat("Using ini file {0}", iniFilePath); + Log.InfoFormat("Using ini file {0}", iniFilePath); return iniFilePath; } @@ -229,25 +231,25 @@ namespace Greenshot.IniFile { /// public static void Reload() { // Clear the current properties - sections = new Dictionary>(); + _sections = new Dictionary>(); // Load the defaults - Read(CreateIniLocation(configName + DEFAULTS_POSTFIX + INI_EXTENSION, true)); + Read(CreateIniLocation(_configName + DefaultsPostfix + IniExtension, true)); // Load the normal - Read(CreateIniLocation(configName + INI_EXTENSION, false)); + Read(CreateIniLocation(_configName + IniExtension, false)); // Load the fixed settings - fixedProperties = Read(CreateIniLocation(configName + FIXED_POSTFIX + INI_EXTENSION, true)); + _fixedProperties = Read(CreateIniLocation(_configName + FixedPostfix + IniExtension, true)); - foreach (IniSection section in sectionMap.Values) { + foreach (IniSection section in SectionMap.Values) { try { section.Fill(PropertiesForSection(section)); FixProperties(section); } catch (Exception ex) { string sectionName = "unknown"; - if (section != null && section.IniSectionAttribute != null && section.IniSectionAttribute.Name != null) { + if (section?.IniSectionAttribute?.Name != null) { sectionName = section.IniSectionAttribute.Name; } - LOG.WarnFormat("Problem reading the ini section {0}", sectionName); - LOG.Warn("Exception", ex); + Log.WarnFormat("Problem reading the ini section {0}", sectionName); + Log.Warn("Exception", ex); } } } @@ -258,14 +260,18 @@ namespace Greenshot.IniFile { /// IniSection private static void FixProperties(IniSection section) { // Make properties unchangeable - if (fixedProperties != null) { - Dictionary fixedPropertiesForSection = null; - if (fixedProperties.TryGetValue(section.IniSectionAttribute.Name, out fixedPropertiesForSection)) { - foreach (string fixedPropertyKey in fixedPropertiesForSection.Keys) { - if (section.Values.ContainsKey(fixedPropertyKey)) { - section.Values[fixedPropertyKey].IsFixed = true; - } - } + if (_fixedProperties == null) + { + return; + } + Dictionary fixedPropertiesForSection; + if (!_fixedProperties.TryGetValue(section.IniSectionAttribute.Name, out fixedPropertiesForSection)) + { + return; + } + foreach (string fixedPropertyKey in fixedPropertiesForSection.Keys) { + if (section.Values.ContainsKey(fixedPropertyKey)) { + section.Values[fixedPropertyKey].IsFixed = true; } } } @@ -276,21 +282,21 @@ namespace Greenshot.IniFile { /// Path & Filename of ini file private static Dictionary> Read(string iniLocation) { if (!File.Exists(iniLocation)) { - LOG.Info("Can't find file: " + iniLocation); + Log.Info("Can't find file: " + iniLocation); return null; } - LOG.InfoFormat("Loading ini-file: {0}", iniLocation); + Log.InfoFormat("Loading ini-file: {0}", iniLocation); //LOG.Info("Reading ini-properties from file: " + iniLocation); Dictionary> newSections = IniReader.read(iniLocation, Encoding.UTF8); // Merge the newly loaded properties to the already available foreach(string section in newSections.Keys) { Dictionary newProperties = newSections[section]; - if (!sections.ContainsKey(section)) { + if (!_sections.ContainsKey(section)) { // This section is not yet loaded, simply add the complete section - sections.Add(section, newProperties); + _sections.Add(section, newProperties); } else { // Overwrite or add every property from the newly loaded section to the available one - Dictionary currentProperties = sections[section]; + Dictionary currentProperties = _sections[section]; foreach(string propertyName in newProperties.Keys) { string propertyValue = newProperties[propertyName]; if (currentProperties.ContainsKey(propertyName)) { @@ -308,7 +314,7 @@ namespace Greenshot.IniFile { public static IEnumerable IniSectionNames { get { - foreach (string sectionName in sectionMap.Keys) { + foreach (string sectionName in SectionMap.Keys) { yield return sectionName; } } @@ -321,7 +327,7 @@ namespace Greenshot.IniFile { /// public static IniSection GetIniSection(string sectionName) { IniSection returnValue; - sectionMap.TryGetValue(sectionName, out returnValue); + SectionMap.TryGetValue(sectionName, out returnValue); return returnValue; } @@ -345,20 +351,20 @@ namespace Greenshot.IniFile { Type iniSectionType = typeof(T); string sectionName = IniSection.GetIniSectionAttribute(iniSectionType).Name; - if (sectionMap.ContainsKey(sectionName)) { + if (SectionMap.ContainsKey(sectionName)) { //LOG.Debug("Returning pre-mapped section " + sectionName); - section = (T)sectionMap[sectionName]; + section = (T)SectionMap[sectionName]; } else { // Create instance of this type section = (T)Activator.CreateInstance(iniSectionType); // Store for later save & retrieval - sectionMap.Add(sectionName, section); + SectionMap.Add(sectionName, section); section.Fill(PropertiesForSection(section)); FixProperties(section); } if (allowSave && section.IsDirty) { - LOG.DebugFormat("Section {0} is marked dirty, saving!", sectionName); + Log.DebugFormat("Section {0} is marked dirty, saving!", sectionName); Save(); } return section; @@ -373,11 +379,11 @@ namespace Greenshot.IniFile { string sectionName = section.IniSectionAttribute.Name; // Get the properties for the section IDictionary properties; - if (sections.ContainsKey(sectionName)) { - properties = sections[sectionName]; + if (_sections.ContainsKey(sectionName)) { + properties = _sections[sectionName]; } else { - sections.Add(sectionName, new Dictionary()); - properties = sections[sectionName]; + _sections.Add(sectionName, new Dictionary()); + properties = _sections[sectionName]; } return properties; } @@ -388,23 +394,23 @@ namespace Greenshot.IniFile { public static void Save() { bool acquiredLock = false; try { - acquiredLock = Monitor.TryEnter(iniLock, TimeSpan.FromMilliseconds(200)); + acquiredLock = Monitor.TryEnter(IniLock, TimeSpan.FromMilliseconds(200)); if (acquiredLock) { // Code that accesses resources that are protected by the lock. - string iniLocation = CreateIniLocation(configName + INI_EXTENSION, false); + string iniLocation = CreateIniLocation(_configName + IniExtension, false); try { SaveInternally(iniLocation); } catch (Exception ex) { - LOG.Error("A problem occured while writing the configuration file to: " + iniLocation); - LOG.Error(ex); + Log.Error("A problem occured while writing the configuration file to: " + iniLocation); + Log.Error(ex); } } else { // Code to deal with the fact that the lock was not acquired. - LOG.Warn("A second thread tried to save the ini-file, we blocked as the first took too long."); + Log.Warn("A second thread tried to save the ini-file, we blocked as the first took too long."); } } finally { if (acquiredLock) { - Monitor.Exit(iniLock); + Monitor.Exit(IniLock); } } } @@ -414,13 +420,15 @@ namespace Greenshot.IniFile { /// /// private static void SaveInternally(string iniLocation) { - LOG.Info("Saving configuration to: " + iniLocation); - if (!Directory.Exists(Path.GetDirectoryName(iniLocation))) { - Directory.CreateDirectory(Path.GetDirectoryName(iniLocation)); + Log.Info("Saving configuration to: " + iniLocation); + var iniPath = Path.GetDirectoryName(iniLocation); + if (iniPath != null && !Directory.Exists(iniPath)) + { + Directory.CreateDirectory(iniPath); } - using (MemoryStream memoryStream = new MemoryStream()) { + using (var memoryStream = new MemoryStream()) { using (TextWriter writer = new StreamWriter(memoryStream, Encoding.UTF8)) { - foreach (IniSection section in sectionMap.Values) { + foreach (var section in SectionMap.Values) { section.Write(writer, false); // Add empty line after section writer.WriteLine(); @@ -428,20 +436,22 @@ namespace Greenshot.IniFile { } writer.WriteLine(); // Write left over properties - foreach (string sectionName in sections.Keys) { + foreach (string sectionName in _sections.Keys) { // Check if the section is one that is "registered", if so skip it! - if (!sectionMap.ContainsKey(sectionName)) { - writer.WriteLine("; The section {0} hasn't been 'claimed' since the last start of Greenshot, therefor it doesn't have additional information here!", sectionName); - writer.WriteLine("; The reason could be that the section {0} just hasn't been used, a plugin has an error and can't claim it or maybe the whole section {0} is obsolete.", sectionName); - // Write section name - writer.WriteLine("[{0}]", sectionName); - Dictionary properties = sections[sectionName]; - // Loop and write properties - foreach (string propertyName in properties.Keys) { - writer.WriteLine("{0}={1}", propertyName, properties[propertyName]); - } - writer.WriteLine(); + if (SectionMap.ContainsKey(sectionName)) + { + continue; } + writer.WriteLine("; The section {0} hasn't been 'claimed' since the last start of Greenshot, therefor it doesn't have additional information here!", sectionName); + writer.WriteLine("; The reason could be that the section {0} just hasn't been used, a plugin has an error and can't claim it or maybe the whole section {0} is obsolete.", sectionName); + // Write section name + writer.WriteLine("[{0}]", sectionName); + Dictionary properties = _sections[sectionName]; + // Loop and write properties + foreach (string propertyName in properties.Keys) { + writer.WriteLine("{0}={1}", propertyName, properties[propertyName]); + } + writer.WriteLine(); } // Don't forget to flush the buffer writer.Flush(); diff --git a/GreenshotPlugin/IniFile/IniValue.cs b/GreenshotPlugin/IniFile/IniValue.cs index 227ec0c3a..21d61644d 100644 --- a/GreenshotPlugin/IniFile/IniValue.cs +++ b/GreenshotPlugin/IniFile/IniValue.cs @@ -31,22 +31,22 @@ namespace Greenshot.IniFile { /// A container to be able to pass the value from a IniSection around. /// public class IniValue { - private static readonly ILog LOG = LogManager.GetLogger(typeof(IniValue)); - private readonly PropertyInfo propertyInfo; - private readonly FieldInfo fieldInfo; - private readonly IniSection containingIniSection; - private readonly IniPropertyAttribute attributes; + private static readonly ILog Log = LogManager.GetLogger(typeof(IniValue)); + private readonly PropertyInfo _propertyInfo; + private readonly FieldInfo _fieldInfo; + private readonly IniSection _containingIniSection; + private readonly IniPropertyAttribute _attributes; public IniValue(IniSection containingIniSection, PropertyInfo propertyInfo, IniPropertyAttribute iniPropertyAttribute) { - this.containingIniSection = containingIniSection; - this.propertyInfo = propertyInfo; - attributes = iniPropertyAttribute; + _containingIniSection = containingIniSection; + _propertyInfo = propertyInfo; + _attributes = iniPropertyAttribute; } public IniValue(IniSection containingIniSection, FieldInfo fieldInfo, IniPropertyAttribute iniPropertyAttribute) { - this.containingIniSection = containingIniSection; - this.fieldInfo = fieldInfo; - attributes = iniPropertyAttribute; + _containingIniSection = containingIniSection; + _fieldInfo = fieldInfo; + _attributes = iniPropertyAttribute; } /// @@ -54,14 +54,14 @@ namespace Greenshot.IniFile { /// public bool IsFixed { get { - if (attributes != null) { - return attributes.FixedValue; + if (_attributes != null) { + return _attributes.FixedValue; } return false; } set { - if (attributes != null) { - attributes.FixedValue = value; + if (_attributes != null) { + _attributes.FixedValue = value; } } } @@ -71,14 +71,14 @@ namespace Greenshot.IniFile { /// public bool IsExpert { get { - if (attributes != null) { - return attributes.Expert; + if (_attributes != null) { + return _attributes.Expert; } return false; } set { - if (attributes != null) { - attributes.Expert = value; + if (_attributes != null) { + _attributes.Expert = value; } } } @@ -87,65 +87,49 @@ namespace Greenshot.IniFile { /// /// Return true when the value is can be changed by the GUI /// - public bool IsEditable { - get { - return !IsFixed; - } - } + public bool IsEditable => !IsFixed; /// /// Return true when the value is visible in the GUI /// - public bool IsVisible { - get { - return !IsExpert; - } - } + public bool IsVisible => !IsExpert; public MemberInfo MemberInfo { - get { - if (propertyInfo == null) { - return fieldInfo; - } else { - return propertyInfo; + get + { + if (_propertyInfo == null) { + return _fieldInfo; } + return _propertyInfo; } } /// /// Returns the IniSection this value is contained in /// - public IniSection ContainingIniSection { - get { - return containingIniSection; - } - } - + public IniSection ContainingIniSection => _containingIniSection; + /// /// Get the in the ini file defined attributes /// - public IniPropertyAttribute Attributes { - get { - return attributes; - } - } - + public IniPropertyAttribute Attributes => _attributes; + /// /// Get the value for this IniValue /// public object Value { - get { - if (propertyInfo == null) { - return fieldInfo.GetValue(containingIniSection); - } else { - return propertyInfo.GetValue(containingIniSection, null); + get + { + if (_propertyInfo == null) { + return _fieldInfo.GetValue(_containingIniSection); } + return _propertyInfo.GetValue(_containingIniSection, null); } set { - if (propertyInfo == null) { - fieldInfo.SetValue(containingIniSection, value); + if (_propertyInfo == null) { + _fieldInfo.SetValue(_containingIniSection, value); } else { - propertyInfo.SetValue(containingIniSection, value, null); + _propertyInfo.SetValue(_containingIniSection, value, null); } } } @@ -155,13 +139,9 @@ namespace Greenshot.IniFile { /// public Type ValueType { get { - Type valueType = null; - if (propertyInfo == null) { - valueType = fieldInfo.FieldType; - } else { - valueType = propertyInfo.PropertyType; - } - if (valueType.IsGenericType && valueType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { + var valueType = _propertyInfo?.PropertyType ?? _fieldInfo.FieldType; + var genericTypeDefinition = valueType.GetGenericTypeDefinition(); + if (genericTypeDefinition != null && (valueType.IsGenericType && genericTypeDefinition == typeof(Nullable<>))) { // We are dealing with a generic type that is nullable valueType = Nullable.GetUnderlyingType(valueType); } @@ -178,29 +158,29 @@ namespace Greenshot.IniFile { object myValue = Value; Type valueType = ValueType; if (myValue == null) { - if (attributes.ExcludeIfNull) { + if (_attributes.ExcludeIfNull) { return; } - if (attributes.DefaultValue != null) { - myValue = attributes.DefaultValue; + if (_attributes.DefaultValue != null) { + myValue = _attributes.DefaultValue; valueType = typeof(string); } else { - myValue = containingIniSection.GetDefault(attributes.Name); + myValue = _containingIniSection.GetDefault(_attributes.Name); if (myValue != null) { valueType = myValue.GetType(); } } } if (myValue == null) { - if (attributes.ExcludeIfNull) { + if (_attributes.ExcludeIfNull) { return; } } if (!onlyProperties) { - writer.WriteLine("; {0}", attributes.Description); + writer.WriteLine("; {0}", _attributes.Description); } if (myValue == null) { - writer.WriteLine("{0}=", attributes.Name); + writer.WriteLine("{0}=", _attributes.Name); return; } if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(Dictionary<,>)) { @@ -218,10 +198,10 @@ namespace Greenshot.IniFile { var key = current.Invoke(enumerator, null); var valueObject = item.GetValue(myValue, new[] { key }); // Write to ini file! - writer.WriteLine("{0}.{1}={2}", attributes.Name, ConvertValueToString(valueType1, key, attributes.Separator), ConvertValueToString(valueType2, valueObject, attributes.Separator)); + writer.WriteLine("{0}.{1}={2}", _attributes.Name, ConvertValueToString(valueType1, key, _attributes.Separator), ConvertValueToString(valueType2, valueObject, _attributes.Separator)); } } else { - writer.WriteLine("{0}={1}", attributes.Name, ConvertValueToString(valueType, myValue, attributes.Separator)); + writer.WriteLine("{0}={1}", _attributes.Name, ConvertValueToString(valueType, myValue, _attributes.Separator)); } } @@ -230,10 +210,10 @@ namespace Greenshot.IniFile { /// /// public void SetValueFromProperties(IDictionary properties) { - string propertyName = attributes.Name; + string propertyName = _attributes.Name; string propertyValue = null; if (properties.ContainsKey(propertyName) && properties[propertyName] != null) { - propertyValue = containingIniSection.PreCheckValue(propertyName, properties[propertyName]); + propertyValue = _containingIniSection.PreCheckValue(propertyName, properties[propertyName]); } UseValueOrDefault(propertyValue); } @@ -244,23 +224,23 @@ namespace Greenshot.IniFile { /// public void UseValueOrDefault(string propertyValue) { Type valueType = ValueType; - string propertyName = attributes.Name; - string defaultValue = attributes.DefaultValue; + string propertyName = _attributes.Name; + string defaultValue = _attributes.DefaultValue; bool defaultUsed = false; - object defaultValueFromConfig = containingIniSection.GetDefault(propertyName); + object defaultValueFromConfig = _containingIniSection.GetDefault(propertyName); if (string.IsNullOrEmpty(propertyValue)) { if (defaultValue != null && defaultValue.Trim().Length != 0) { propertyValue = defaultValue; defaultUsed = true; } else if (defaultValueFromConfig != null) { - LOG.DebugFormat("Default for Property {0} implemented!", propertyName); + Log.DebugFormat("Default for Property {0} implemented!", propertyName); } else { - if (attributes.ExcludeIfNull) { + if (_attributes.ExcludeIfNull) { Value = null; return; } - LOG.DebugFormat("Property {0} has no value or default value!", propertyName); + Log.DebugFormat("Property {0} has no value or default value!", propertyName); } } // Now set the value @@ -272,7 +252,7 @@ namespace Greenshot.IniFile { object dictionary = Activator.CreateInstance(valueType); MethodInfo addMethodInfo = valueType.GetMethod("Add"); bool addedElements = false; - IDictionary properties = IniConfig.PropertiesForSection(containingIniSection); + IDictionary properties = IniConfig.PropertiesForSection(_containingIniSection); foreach (string key in properties.Keys) { if (key != null && key.StartsWith(propertyName + ".")) { // What "key" do we need to store it under? @@ -281,15 +261,15 @@ namespace Greenshot.IniFile { object newValue1 = null; object newValue2 = null; try { - newValue1 = ConvertStringToValueType(type1, subPropertyName, attributes.Separator); + newValue1 = ConvertStringToValueType(type1, subPropertyName, _attributes.Separator); } catch (Exception ex) { - LOG.Warn(ex); + Log.Warn(ex); //LOG.Error("Problem converting " + subPropertyName + " to type " + type1.FullName, e); } try { - newValue2 = ConvertStringToValueType(type2, stringValue, attributes.Separator); + newValue2 = ConvertStringToValueType(type2, stringValue, _attributes.Separator); } catch (Exception ex) { - LOG.Warn(ex); + Log.Warn(ex); //LOG.Error("Problem converting " + stringValue + " to type " + type2.FullName, e); } addMethodInfo.Invoke(dictionary, new[] { newValue1, newValue2 }); @@ -300,31 +280,33 @@ namespace Greenshot.IniFile { if (addedElements) { Value = dictionary; return; - } else if (defaultValueFromConfig != null) { + } + if (defaultValueFromConfig != null) { Value = defaultValueFromConfig; return; } } else if (!string.IsNullOrEmpty(propertyValue)) { - if (valueType.IsGenericType && valueType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { + var genericTypeDefinition = valueType.GetGenericTypeDefinition(); + if (genericTypeDefinition != null && (valueType.IsGenericType && genericTypeDefinition == typeof(Nullable<>))) { // We are dealing with a generic type that is nullable valueType = Nullable.GetUnderlyingType(valueType); } - object newValue = null; + object newValue; try { - newValue = ConvertStringToValueType(valueType, propertyValue, attributes.Separator); + newValue = ConvertStringToValueType(valueType, propertyValue, _attributes.Separator); } catch (Exception ex1) { newValue = null; if (!defaultUsed) { try { - LOG.WarnFormat("Problem '{0}' while converting {1} to type {2} trying fallback...", ex1.Message, propertyValue, valueType.FullName); - newValue = ConvertStringToValueType(valueType, defaultValue, attributes.Separator); + Log.WarnFormat("Problem '{0}' while converting {1} to type {2} trying fallback...", ex1.Message, propertyValue, valueType.FullName); + newValue = ConvertStringToValueType(valueType, defaultValue, _attributes.Separator); ContainingIniSection.IsDirty = true; - LOG.InfoFormat("Used default value {0} for property {1}", defaultValue, propertyName); + Log.InfoFormat("Used default value {0} for property {1}", defaultValue, propertyName); } catch (Exception ex2) { - LOG.Warn("Problem converting fallback value " + defaultValue + " to type " + valueType.FullName, ex2); + Log.Warn("Problem converting fallback value " + defaultValue + " to type " + valueType.FullName, ex2); } } else { - LOG.Warn("Problem converting " + propertyValue + " to type " + valueType.FullName, ex1); + Log.Warn("Problem converting " + propertyValue + " to type " + valueType.FullName, ex1); } } Value = newValue; @@ -340,7 +322,7 @@ namespace Greenshot.IniFile { try { Value = Activator.CreateInstance(ValueType); } catch (Exception) { - LOG.WarnFormat("Couldn't create instance of {0} for {1}, using default value.", ValueType.FullName, attributes.Name); + Log.WarnFormat("Couldn't create instance of {0} for {1}, using default value.", ValueType.FullName, _attributes.Name); Value = default(ValueType); } } else { @@ -371,18 +353,18 @@ namespace Greenshot.IniFile { object list = Activator.CreateInstance(valueType); // Logic for List<> string[] arrayValues = valueString.Split(new[] { arraySeparator }, StringSplitOptions.None); - if (arrayValues == null || arrayValues.Length == 0) { + if (arrayValues.Length == 0) { return list; } MethodInfo addMethodInfo = valueType.GetMethod("Add"); foreach (string arrayValue in arrayValues) { - if (arrayValue != null && arrayValue.Length > 0) { + if (!string.IsNullOrEmpty(arrayValue)) { object newValue = null; try { newValue = ConvertStringToValueType(valueType.GetGenericArguments()[0], arrayValue, separator); } catch (Exception ex) { - LOG.Warn("Problem converting " + arrayValue + " to type " + valueType.FullName, ex); + Log.Warn("Problem converting " + arrayValue + " to type " + valueType.FullName, ex); } if (newValue != null) { addMethodInfo.Invoke(list, new[] { newValue }); @@ -394,7 +376,7 @@ namespace Greenshot.IniFile { //LOG.Debug("No convertor for " + fieldType.ToString()); if (valueType == typeof(object) && valueString.Length > 0) { //LOG.Debug("Parsing: " + valueString); - string[] values = valueString.Split(new[] { ':' }); + string[] values = valueString.Split(':'); //LOG.Debug("Type: " + values[0]); //LOG.Debug("Value: " + values[1]); Type fieldTypeForValue = Type.GetType(values[0], true); @@ -402,25 +384,7 @@ namespace Greenshot.IniFile { return ConvertStringToValueType(fieldTypeForValue, values[1], separator); } TypeConverter converter = TypeDescriptor.GetConverter(valueType); - if (converter != null) { - return converter.ConvertFromInvariantString(valueString); - } else if (valueType.IsEnum) { - if (valueString.Length > 0) { - try { - return Enum.Parse(valueType, valueString); - } catch (ArgumentException) { - //LOG.InfoFormat("Couldn't match {0} to {1}, trying case-insentive match", valueString, fieldType); - foreach (Enum enumValue in Enum.GetValues(valueType)) { - if (enumValue.ToString().Equals(valueString, StringComparison.InvariantCultureIgnoreCase)) { - //LOG.Info("Match found..."); - return enumValue; - } - } - throw; - } - } - } - return null; + return converter.ConvertFromInvariantString(valueString); } /// @@ -428,7 +392,7 @@ namespace Greenshot.IniFile { /// /// string representation of this public override string ToString() { - return ConvertValueToString(ValueType, Value, attributes.Separator); + return ConvertValueToString(ValueType, Value, _attributes.Separator); } /// @@ -479,14 +443,10 @@ namespace Greenshot.IniFile { if (assemblyName.StartsWith("Green")) { assemblyName = assemblyName.Substring(0, assemblyName.IndexOf(',')); } - return string.Format("{0},{1}:{2}", valueTypeName, assemblyName, ourValue); + return $"{valueTypeName},{assemblyName}:{ourValue}"; } TypeConverter converter = TypeDescriptor.GetConverter(valueType); - if (converter != null) { - return converter.ConvertToInvariantString(valueObject); - } - // All other types - return valueObject.ToString(); + return converter.ConvertToInvariantString(valueObject); } } } \ No newline at end of file diff --git a/GreenshotPlugin/Interfaces/Generic.cs b/GreenshotPlugin/Interfaces/Generic.cs index 6f63972fb..afb835df2 100644 --- a/GreenshotPlugin/Interfaces/Generic.cs +++ b/GreenshotPlugin/Interfaces/Generic.cs @@ -25,6 +25,7 @@ using System; using System.Drawing; using System.IO; using System.Windows.Forms; +using GreenshotPlugin.Effects; namespace Greenshot.Plugin { diff --git a/GreenshotPlugin/Interfaces/IDestination.cs b/GreenshotPlugin/Interfaces/IDestination.cs index 08fc85f57..18d2b26ef 100644 --- a/GreenshotPlugin/Interfaces/IDestination.cs +++ b/GreenshotPlugin/Interfaces/IDestination.cs @@ -25,75 +25,28 @@ using System.Windows.Forms; namespace Greenshot.Plugin { public class ExportInformation { - private string uri; - private string filepath; - - private bool exportMade; - private readonly string destinationDesignation; - private string destinationDescription; - - private string errorMessage; - public ExportInformation(string destinationDesignation, string destinationDescription) { - this.destinationDesignation = destinationDesignation; - this.destinationDescription = destinationDescription; + DestinationDesignation = destinationDesignation; + DestinationDescription = destinationDescription; } public ExportInformation(string destinationDesignation, string destinationDescription, bool exportMade): this(destinationDesignation, destinationDescription) { - this.exportMade = exportMade; + ExportMade = exportMade; } - public string DestinationDesignation { - get { - return destinationDesignation; - } - } - public string DestinationDescription { - get { - return destinationDescription; - } - set { - destinationDescription = value; - } - } + public string DestinationDesignation { get; } + + public string DestinationDescription { get; set; } /// /// Set to true to specify if the export worked. /// - public bool ExportMade { - get { - return exportMade; - } - set { - exportMade = value; - } - } + public bool ExportMade { get; set; } - public string Uri { - get { - return uri; - } - set { - uri = value; - } - } + public string Uri { get; set; } - public string ErrorMessage { - get { - return errorMessage; - } - set { - errorMessage = value; - } - } + public string ErrorMessage { get; set; } - public string Filepath { - get { - return filepath; - } - set { - filepath = value; - } - } + public string Filepath { get; set; } } /// @@ -131,7 +84,7 @@ namespace Greenshot.Plugin { /// /// Returns if the destination is active /// - bool isActive { + bool IsActive { get; } @@ -159,21 +112,21 @@ namespace Greenshot.Plugin { /// /// Returns true if this destination can be dynamic /// - bool isDynamic { + bool IsDynamic { get; } /// /// Returns if the destination is active /// - bool useDynamicsOnly { + bool UseDynamicsOnly { get; } /// /// Returns true if this destination returns a link /// - bool isLinkable { + bool IsLinkable { get; } diff --git a/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs b/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs index c56cc6570..7a19d4e4a 100644 --- a/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs +++ b/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs @@ -26,6 +26,7 @@ using System.Windows.Forms; using GreenshotPlugin.Core; using Greenshot.IniFile; using Greenshot.Core; +using GreenshotPlugin.Effects; namespace Greenshot.Plugin { [Serializable] diff --git a/GreenshotPlugin/Interop/COMWrapper.cs b/GreenshotPlugin/Interop/COMWrapper.cs index 243180939..48671c940 100644 --- a/GreenshotPlugin/Interop/COMWrapper.cs +++ b/GreenshotPlugin/Interop/COMWrapper.cs @@ -34,7 +34,7 @@ namespace Greenshot.Interop { /// Wraps a late-bound COM server. /// public sealed class COMWrapper : RealProxy, IDisposable, IRemotingTypeInfo { - private static readonly ILog LOG = LogManager.GetLogger(typeof(COMWrapper)); + private static readonly ILog Log = LogManager.GetLogger(typeof(COMWrapper)); private const int MK_E_UNAVAILABLE = -2147221021; private const int CO_E_CLASSSTRING = -2147221005; public const int RPC_E_CALL_REJECTED = unchecked((int)0x80010001); @@ -105,13 +105,13 @@ namespace Greenshot.Interop { try { GetActiveObject(ref guid, IntPtr.Zero, out comObject); } catch (Exception) { - LOG.WarnFormat("Error {0} getting instance for class id {1}", result, progIdAttribute.Value); + Log.WarnFormat("Error {0} getting instance for class id {1}", result, progIdAttribute.Value); } if (comObject == null) { - LOG.WarnFormat("Error {0} getting progId {1}", result, progIdAttribute.Value); + Log.WarnFormat("Error {0} getting progId {1}", result, progIdAttribute.Value); } } else { - LOG.InfoFormat("Mapped {0} to progId {1}", progIdAttribute.Value, progId); + Log.InfoFormat("Mapped {0} to progId {1}", progIdAttribute.Value, progId); } } @@ -120,14 +120,14 @@ namespace Greenshot.Interop { comObject = Marshal.GetActiveObject(progId); } catch (COMException comE) { if (comE.ErrorCode == MK_E_UNAVAILABLE) { - LOG.DebugFormat("No current instance of {0} object available.", progId); + Log.DebugFormat("No current instance of {0} object available.", progId); } else if (comE.ErrorCode == CO_E_CLASSSTRING) { - LOG.WarnFormat("Unknown progId {0}", progId); + Log.WarnFormat("Unknown progId {0}", progId); } else { - LOG.Warn("Error getting active object for " + progIdAttribute.Value, comE); + Log.Warn("Error getting active object for " + progIdAttribute.Value, comE); } } catch (Exception e) { - LOG.Warn("Error getting active object for " + progIdAttribute.Value, e); + Log.Warn("Error getting active object for " + progIdAttribute.Value, e); } } @@ -166,13 +166,13 @@ namespace Greenshot.Interop { try { comType = Type.GetTypeFromCLSID(guid); } catch (Exception ex) { - LOG.WarnFormat("Error {1} type for {0}", progId, ex.Message); + Log.WarnFormat("Error {1} type for {0}", progId, ex.Message); } } else { try { comType = Type.GetTypeFromProgID(progId, true); } catch (Exception ex) { - LOG.WarnFormat("Error {1} type for {0}", progId, ex.Message); + Log.WarnFormat("Error {1} type for {0}", progId, ex.Message); } } object comObject = null; @@ -180,10 +180,10 @@ namespace Greenshot.Interop { try { comObject = Activator.CreateInstance(comType); if (comObject != null) { - LOG.DebugFormat("Created new instance of {0} object.", progId); + Log.DebugFormat("Created new instance of {0} object.", progId); } } catch (Exception e) { - LOG.WarnFormat("Error {1} creating object for {0}", progId, e.Message); + Log.WarnFormat("Error {1} creating object for {0}", progId, e.Message); throw; } } @@ -229,13 +229,13 @@ namespace Greenshot.Interop { try { GetActiveObject(ref guid, IntPtr.Zero, out comObject); } catch (Exception) { - LOG.WarnFormat("Error {0} getting instance for class id {1}", result, progIdAttribute.Value); + Log.WarnFormat("Error {0} getting instance for class id {1}", result, progIdAttribute.Value); } if (comObject == null) { - LOG.WarnFormat("Error {0} getting progId {1}", result, progIdAttribute.Value); + Log.WarnFormat("Error {0} getting progId {1}", result, progIdAttribute.Value); } } else { - LOG.InfoFormat("Mapped {0} to progId {1}", progIdAttribute.Value, progId); + Log.InfoFormat("Mapped {0} to progId {1}", progIdAttribute.Value, progId); } } @@ -245,15 +245,15 @@ namespace Greenshot.Interop { comObject = Marshal.GetActiveObject(progId); } catch (COMException comE) { if (comE.ErrorCode == MK_E_UNAVAILABLE) { - LOG.DebugFormat("No current instance of {0} object available.", progId); + Log.DebugFormat("No current instance of {0} object available.", progId); } else if (comE.ErrorCode == CO_E_CLASSSTRING) { - LOG.WarnFormat("Unknown progId {0} (application not installed)", progId); + Log.WarnFormat("Unknown progId {0} (application not installed)", progId); return default(T); } else { - LOG.Warn("Error getting active object for " + progId, comE); + Log.Warn("Error getting active object for " + progId, comE); } } catch (Exception e) { - LOG.Warn("Error getting active object for " + progId, e); + Log.Warn("Error getting active object for " + progId, e); } } } @@ -266,7 +266,7 @@ namespace Greenshot.Interop { if (Guid.Empty != guid) { comType = Type.GetTypeFromCLSID(guid); } else { - LOG.Warn("Error type for " + progId, ex); + Log.Warn("Error type for " + progId, ex); } } @@ -274,10 +274,10 @@ namespace Greenshot.Interop { try { comObject = Activator.CreateInstance(comType); if (comObject != null) { - LOG.DebugFormat("Created new instance of {0} object.", progId); + Log.DebugFormat("Created new instance of {0} object.", progId); } } catch (Exception e) { - LOG.Warn("Error creating object for " + progId, e); + Log.Warn("Error creating object for " + progId, e); } } } @@ -356,7 +356,7 @@ namespace Greenshot.Interop { /// sure that the COM object is still cleaned up. /// ~COMWrapper() { - LOG.DebugFormat("Finalize {0}", _interceptType); + Log.DebugFormat("Finalize {0}", _interceptType); Dispose(false); } @@ -377,20 +377,20 @@ namespace Greenshot.Interop { /// private void Dispose(bool disposing) { if (null != _comObject) { - LOG.DebugFormat("Disposing {0}", _interceptType); + Log.DebugFormat("Disposing {0}", _interceptType); if (Marshal.IsComObject(_comObject)) { try { int count; do { count = Marshal.ReleaseComObject(_comObject); - LOG.DebugFormat("RCW count for {0} now is {1}", _interceptType, count); + Log.DebugFormat("RCW count for {0} now is {1}", _interceptType, count); } while (count > 0); } catch (Exception ex) { - LOG.WarnFormat("Problem releasing COM object {0}", _comType); - LOG.Warn("Error: ", ex); + Log.WarnFormat("Problem releasing COM object {0}", _comType); + Log.Warn("Error: ", ex); } } else { - LOG.WarnFormat("{0} is not a COM object", _comType); + Log.WarnFormat("{0} is not a COM object", _comType); } } } @@ -479,13 +479,13 @@ namespace Greenshot.Interop { public override IMessage Invoke(IMessage myMessage) { IMethodCallMessage callMessage = myMessage as IMethodCallMessage; if (null == callMessage) { - LOG.DebugFormat("Message type not implemented: {0}", myMessage.GetType()); + Log.DebugFormat("Message type not implemented: {0}", myMessage.GetType()); return null; } MethodInfo method = callMessage.MethodBase as MethodInfo; if (null == method) { - LOG.DebugFormat("Unrecognized Invoke call: {0}", callMessage.MethodBase); + Log.DebugFormat("Unrecognized Invoke call: {0}", callMessage.MethodBase); return null; } @@ -598,7 +598,7 @@ namespace Greenshot.Interop { break; } catch (InvalidComObjectException icoEx) { // Should assist BUG-1616 and others - LOG.WarnFormat("COM object {0} has been separated from its underlying RCW cannot be used. The COM object was released while it was still in use on another thread.", _interceptType.FullName); + Log.WarnFormat("COM object {0} has been separated from its underlying RCW cannot be used. The COM object was released while it was still in use on another thread.", _interceptType.FullName); return new ReturnMessage(icoEx, callMessage); } catch (Exception ex) { // Test for rejected diff --git a/GreenshotPlugin/Interop/ComProgIdAttribute.cs b/GreenshotPlugin/Interop/ComProgIdAttribute.cs index 620ad8e0d..58e3d3c6a 100644 --- a/GreenshotPlugin/Interop/ComProgIdAttribute.cs +++ b/GreenshotPlugin/Interop/ComProgIdAttribute.cs @@ -24,10 +24,8 @@ namespace Greenshot.Interop { /// /// An attribute to specifiy the ProgID of the COM class to create. (As suggested by Kristen Wegner) /// - [AttributeUsage(AttributeTargets.Interface, Inherited = false, AllowMultiple = false)] + [AttributeUsage(AttributeTargets.Interface)] public sealed class ComProgIdAttribute : Attribute { - private readonly string _value; - /// /// Extracts the attribute from the specified type. /// @@ -42,24 +40,26 @@ namespace Greenshot.Interop { /// public static ComProgIdAttribute GetAttribute(Type interfaceType) { if (null == interfaceType) { - throw new ArgumentNullException("interfaceType"); + throw new ArgumentNullException(nameof(interfaceType)); } Type attributeType = typeof(ComProgIdAttribute); object[] attributes = interfaceType.GetCustomAttributes(attributeType, false); - if (null == attributes || 0 == attributes.Length) { + if (0 == attributes.Length) + { Type[] interfaces = interfaceType.GetInterfaces(); - for (int i = 0; i < interfaces.Length; i++) { - interfaceType = interfaces[i]; + foreach (Type t in interfaces) + { + interfaceType = t; attributes = interfaceType.GetCustomAttributes(attributeType, false); - if (null != attributes && 0 != attributes.Length) { + if (0 != attributes.Length) { break; } } } - if (null == attributes || 0 == attributes.Length) { + if (0 == attributes.Length) { return null; } return (ComProgIdAttribute)attributes[0]; @@ -68,14 +68,12 @@ namespace Greenshot.Interop { /// Constructor /// The COM ProgID. public ComProgIdAttribute(string value) { - _value = value; + Value = value; } /// /// Returns the COM ProgID /// - public string Value { - get { return _value; } - } + public string Value { get; } } } diff --git a/GreenshotPlugin/Interop/IUnknown.cs b/GreenshotPlugin/Interop/IUnknown.cs index a5781e647..e3f153ff8 100644 --- a/GreenshotPlugin/Interop/IUnknown.cs +++ b/GreenshotPlugin/Interop/IUnknown.cs @@ -28,9 +28,9 @@ namespace Greenshot.Interop { IntPtr QueryInterface(ref Guid riid); [PreserveSig] - UInt32 AddRef(); + uint AddRef(); [PreserveSig] - UInt32 Release(); + uint Release(); } } diff --git a/GreenshotPlugin/UnmanagedHelpers/DWM.cs b/GreenshotPlugin/UnmanagedHelpers/DWM.cs index 3a809713a..64638eec1 100644 --- a/GreenshotPlugin/UnmanagedHelpers/DWM.cs +++ b/GreenshotPlugin/UnmanagedHelpers/DWM.cs @@ -148,11 +148,9 @@ namespace GreenshotPlugin.UnmanagedHelpers { public static Color ColorizationColor { get { using (RegistryKey key = Registry.CurrentUser.OpenSubKey(COLORIZATION_COLOR_KEY, false)) { - if (key != null) { - object dwordValue = key.GetValue("ColorizationColor"); - if (dwordValue != null) { - return Color.FromArgb((Int32)dwordValue); - } + object dwordValue = key?.GetValue("ColorizationColor"); + if (dwordValue != null) { + return Color.FromArgb((int)dwordValue); } } return Color.White; diff --git a/GreenshotPlugin/UnmanagedHelpers/GDI32.cs b/GreenshotPlugin/UnmanagedHelpers/GDI32.cs index 036bc33a2..f3411e245 100644 --- a/GreenshotPlugin/UnmanagedHelpers/GDI32.cs +++ b/GreenshotPlugin/UnmanagedHelpers/GDI32.cs @@ -168,7 +168,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { public class SafeCompatibleDCHandle : SafeDCHandle { [DllImport("gdi32", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool DeleteDC(IntPtr hDC); + private static extern bool DeleteDC(IntPtr hDC); /// /// Needed for marshalling return values @@ -367,7 +367,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { // V5 bV5RedMask = (uint)255 << 16; bV5GreenMask = (uint)255 << 8; - bV5BlueMask = (uint)255; + bV5BlueMask = 255; bV5AlphaMask = (uint)255 << 24; bV5CSType = 1934772034; // sRGB bV5Endpoints = new CIEXYZTRIPLE diff --git a/GreenshotPlugin/UnmanagedHelpers/GDIplus.cs b/GreenshotPlugin/UnmanagedHelpers/GDIplus.cs index fa62f1224..f8671f335 100644 --- a/GreenshotPlugin/UnmanagedHelpers/GDIplus.cs +++ b/GreenshotPlugin/UnmanagedHelpers/GDIplus.cs @@ -92,7 +92,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// GDIplus Helpers /// public static class GDIplus { - private static readonly ILog LOG = LogManager.GetLogger(typeof(GDIplus)); + private static readonly ILog Log = LogManager.GetLogger(typeof(GDIplus)); [DllImport("gdiplus.dll", SetLastError = true, ExactSpelling = true)] private static extern int GdipBitmapApplyEffect(IntPtr bitmap, IntPtr effect, ref RECT rectOfInterest, bool useAuxData, IntPtr auxData, int auxDataSize); @@ -170,15 +170,12 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// This accounts for the "bug" I reported here: http://social.technet.microsoft.com/Forums/en/w8itprogeneral/thread/99ddbe9d-556d-475a-8bab-84e25aa13a2c /// /// - /// + /// false if blur is not possible public static bool IsBlurPossible(int radius) { if (!_isBlurEnabled) { return false; } - if (Environment.OSVersion.Version.Minor >= 2 && radius < 20) { - return false; - } - return true; + return Environment.OSVersion.Version.Minor < 2 || radius >= 20; } /// @@ -197,18 +194,24 @@ namespace GreenshotPlugin.UnmanagedHelpers { IntPtr hEffect = IntPtr.Zero; try { + // Create the GDI+ BlurEffect, using the Guid + int status = GdipCreateEffect(BlurEffectGuid, out hEffect); + if (status != 0) + { + return false; + } // Create a BlurParams struct and set the values - BlurParams blurParams = new BlurParams(); - blurParams.Radius = radius; - blurParams.ExpandEdges = expandEdges; + var blurParams = new BlurParams + { + Radius = radius, + ExpandEdges = expandEdges + }; // Allocate space in unmanaged memory hBlurParams = Marshal.AllocHGlobal(Marshal.SizeOf(blurParams)); // Copy the structure to the unmanaged memory Marshal.StructureToPtr(blurParams, hBlurParams, false); - // Create the GDI+ BlurEffect, using the Guid - int status = GdipCreateEffect(BlurEffectGuid, out hEffect); // Set the blurParams to the effect GdipSetEffectParameters(hEffect, hBlurParams, (uint)Marshal.SizeOf(blurParams)); @@ -226,7 +229,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { return true; } catch (Exception ex) { _isBlurEnabled = false; - LOG.Error("Problem using GdipBitmapApplyEffect: ", ex); + Log.Error("Problem using GdipBitmapApplyEffect: ", ex); return false; } finally { try { @@ -240,7 +243,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { } } catch (Exception ex) { _isBlurEnabled = false; - LOG.Error("Problem cleaning up ApplyBlur: ", ex); + Log.Error("Problem cleaning up ApplyBlur: ", ex); } } } @@ -258,20 +261,26 @@ namespace GreenshotPlugin.UnmanagedHelpers { IntPtr hEffect = IntPtr.Zero; try { + // Create the GDI+ BlurEffect, using the Guid + int status = GdipCreateEffect(BlurEffectGuid, out hEffect); + if (status != 0) + { + return false; + } + // Create a BlurParams struct and set the values - BlurParams blurParams = new BlurParams(); - blurParams.Radius = radius; + var blurParams = new BlurParams + { + Radius = radius, + ExpandEdges = false + }; //blurParams.Padding = radius; - blurParams.ExpandEdges = false; // Allocate space in unmanaged memory hBlurParams = Marshal.AllocHGlobal(Marshal.SizeOf(blurParams)); // Copy the structure to the unmanaged memory Marshal.StructureToPtr(blurParams, hBlurParams, true); - // Create the GDI+ BlurEffect, using the Guid - int status = GdipCreateEffect(BlurEffectGuid, out hEffect); - // Set the blurParams to the effect GdipSetEffectParameters(hEffect, hBlurParams, (uint)Marshal.SizeOf(blurParams)); @@ -283,15 +292,15 @@ namespace GreenshotPlugin.UnmanagedHelpers { IntPtr hAttributes = GetNativeImageAttributes(imageAttributes); // Create a RECT from the Rectangle - RECTF sourceRECF = new RECTF(source); + RECTF sourceRecf = new RECTF(source); // Apply the effect to the bitmap in the specified area - GdipDrawImageFX(hGraphics, hBitmap, ref sourceRECF, hMatrix, hEffect, hAttributes, GpUnit.UnitPixel); + GdipDrawImageFX(hGraphics, hBitmap, ref sourceRecf, hMatrix, hEffect, hAttributes, GpUnit.UnitPixel); // Everything worked, return true return true; } catch (Exception ex) { _isBlurEnabled = false; - LOG.Error("Problem using GdipDrawImageFX: ", ex); + Log.Error("Problem using GdipDrawImageFX: ", ex); return false; } finally { try { @@ -305,7 +314,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { } } catch (Exception ex) { _isBlurEnabled = false; - LOG.Error("Problem cleaning up DrawWithBlur: ", ex); + Log.Error("Problem cleaning up DrawWithBlur: ", ex); } } } diff --git a/GreenshotPlugin/UnmanagedHelpers/Shell32.cs b/GreenshotPlugin/UnmanagedHelpers/Shell32.cs index b78b22ed1..42e44aec7 100644 --- a/GreenshotPlugin/UnmanagedHelpers/Shell32.cs +++ b/GreenshotPlugin/UnmanagedHelpers/Shell32.cs @@ -196,12 +196,12 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// /// The path to the file that contains an image. /// The System.Drawing.Icon representation of the image contained in the specified file. - public static Icon ExtractAssociatedIcon(String filePath) { + public static Icon ExtractAssociatedIcon(string filePath) { int index = 0; Uri uri; if (filePath == null) { - throw new ArgumentException(String.Format("'{0}' is not valid for '{1}'", "null", "filePath"), "filePath"); + throw new ArgumentException("Null is not valid for filePath", nameof(filePath)); } try { uri = new Uri(filePath); diff --git a/GreenshotPlugin/UnmanagedHelpers/Structs.cs b/GreenshotPlugin/UnmanagedHelpers/Structs.cs index ea9abc1fd..42c7ecf94 100644 --- a/GreenshotPlugin/UnmanagedHelpers/Structs.cs +++ b/GreenshotPlugin/UnmanagedHelpers/Structs.cs @@ -30,10 +30,12 @@ namespace GreenshotPlugin.UnmanagedHelpers { public SIZE(Size size) : this(size.Width, size.Height) { } + public SIZE(int width, int height) { Width = width; Height = height; } + public Size ToSize() { return new Size(Width, Height); } @@ -82,11 +84,11 @@ namespace GreenshotPlugin.UnmanagedHelpers { public RECT(Rectangle rectangle) : this(rectangle.Left, rectangle.Top, rectangle.Right, rectangle.Bottom) { } - public RECT(int Left, int Top, int Right, int Bottom) { - _Left = Left; - _Top = Top; - _Right = Right; - _Bottom = Bottom; + public RECT(int left, int top, int right, int bottom) { + _Left = left; + _Top = top; + _Right = right; + _Bottom = bottom; } public int X { @@ -172,17 +174,17 @@ namespace GreenshotPlugin.UnmanagedHelpers { } } - public static implicit operator Rectangle(RECT Rectangle) { - return new Rectangle(Rectangle.Left, Rectangle.Top, Rectangle.Width, Rectangle.Height); + public static implicit operator Rectangle(RECT rectangle) { + return new Rectangle(rectangle.Left, rectangle.Top, rectangle.Width, rectangle.Height); } - public static implicit operator RECT(Rectangle Rectangle) { - return new RECT(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom); + public static implicit operator RECT(Rectangle rectangle) { + return new RECT(rectangle.Left, rectangle.Top, rectangle.Right, rectangle.Bottom); } - public static bool operator ==(RECT Rectangle1, RECT Rectangle2) { - return Rectangle1.Equals(Rectangle2); + public static bool operator ==(RECT rectangle1, RECT rectangle2) { + return rectangle1.Equals(rectangle2); } - public static bool operator !=(RECT Rectangle1, RECT Rectangle2) { - return !Rectangle1.Equals(Rectangle2); + public static bool operator !=(RECT rectangle1, RECT rectangle2) { + return !rectangle1.Equals(rectangle2); } public override string ToString() { @@ -193,8 +195,8 @@ namespace GreenshotPlugin.UnmanagedHelpers { return ToString().GetHashCode(); } - public bool Equals(RECT Rectangle) { - return Rectangle.Left == _Left && Rectangle.Top == _Top && Rectangle.Right == _Right && Rectangle.Bottom == _Bottom; + public bool Equals(RECT rectangle) { + return rectangle.Left == _Left && rectangle.Top == _Top && rectangle.Right == _Right && rectangle.Bottom == _Bottom; } public Rectangle ToRectangle() { @@ -313,7 +315,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// The structure for the WindowInfo /// See: http://msdn.microsoft.com/en-us/library/windows/desktop/ms632610%28v=vs.85%29.aspx /// - [StructLayout(LayoutKind.Sequential), Serializable()] + [StructLayout(LayoutKind.Sequential), Serializable] public struct WindowInfo { public uint cbSize; public RECT rcWindow; @@ -326,8 +328,8 @@ namespace GreenshotPlugin.UnmanagedHelpers { public ushort atomWindowType; public ushort wCreatorVersion; // Allows automatic initialization of "cbSize" with "new WINDOWINFO(null/true/false)". - public WindowInfo(Boolean? filler) : this() { - cbSize = (UInt32)(Marshal.SizeOf(typeof(WindowInfo))); + public WindowInfo(bool? filler) : this() { + cbSize = (uint)(Marshal.SizeOf(typeof(WindowInfo))); } } @@ -383,8 +385,8 @@ namespace GreenshotPlugin.UnmanagedHelpers { [StructLayout(LayoutKind.Sequential)] public struct CursorInfo { - public Int32 cbSize; - public Int32 flags; + public int cbSize; + public int flags; public IntPtr hCursor; public POINT ptScreenPos; } @@ -392,8 +394,8 @@ namespace GreenshotPlugin.UnmanagedHelpers { [StructLayout(LayoutKind.Sequential)] public struct IconInfo { public bool fIcon; - public Int32 xHotspot; - public Int32 yHotspot; + public int xHotspot; + public int yHotspot; public IntPtr hbmMask; public IntPtr hbmColor; } diff --git a/GreenshotPlugin/UnmanagedHelpers/User32.cs b/GreenshotPlugin/UnmanagedHelpers/User32.cs index 5d26374a7..97e8fe497 100644 --- a/GreenshotPlugin/UnmanagedHelpers/User32.cs +++ b/GreenshotPlugin/UnmanagedHelpers/User32.cs @@ -58,7 +58,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { public const int MONITOR_DEFAULTTONULL = 0; public const int MONITOR_DEFAULTTOPRIMARY = 1; public const int MONITOR_DEFAULTTONEAREST = 2; - public const Int32 CURSOR_SHOWING = 0x00000001; + public const int CURSOR_SHOWING = 0x00000001; #region DllImports [DllImport("user32", SetLastError = true)] @@ -382,7 +382,7 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// /// A WindowDC SafeHandle implementation /// - public class SafeWindowDCHandle : SafeHandleZeroOrMinusOneIsInvalid { + public class SafeWindowDcHandle : SafeHandleZeroOrMinusOneIsInvalid { [DllImport("user32", SetLastError = true)] private static extern IntPtr GetWindowDC(IntPtr hWnd); [DllImport("user32", SetLastError = true)] @@ -393,12 +393,12 @@ namespace GreenshotPlugin.UnmanagedHelpers { /// /// Needed for marshalling return values /// - public SafeWindowDCHandle() : base(true) + public SafeWindowDcHandle() : base(true) { } [SecurityCritical] - public SafeWindowDCHandle(IntPtr hWnd, IntPtr preexistingHandle) : base(true) { + public SafeWindowDcHandle(IntPtr hWnd, IntPtr preexistingHandle) : base(true) { _hWnd = hWnd; SetHandle(preexistingHandle); } @@ -409,10 +409,10 @@ namespace GreenshotPlugin.UnmanagedHelpers { return returnValue; } - public static SafeWindowDCHandle FromDesktop() { + public static SafeWindowDcHandle FromDesktop() { IntPtr hWndDesktop = User32.GetDesktopWindow(); IntPtr hDCDesktop = GetWindowDC(hWndDesktop); - return new SafeWindowDCHandle(hWndDesktop, hDCDesktop); + return new SafeWindowDcHandle(hWndDesktop, hDCDesktop); } } } diff --git a/GreenshotPlugin/UnmanagedHelpers/Win32Errors.cs b/GreenshotPlugin/UnmanagedHelpers/Win32Errors.cs index 01e435daa..8e8d24761 100644 --- a/GreenshotPlugin/UnmanagedHelpers/Win32Errors.cs +++ b/GreenshotPlugin/UnmanagedHelpers/Win32Errors.cs @@ -103,10 +103,10 @@ namespace GreenshotPlugin.UnmanagedHelpers { int error = (int)errorCode; if ((error & 0x80000000) == 0x80000000) { - return (long)error; + return error; } - return (long)(0x80070000 | (uint)(error & 0xffff)); + return 0x80070000 | (uint)(error & 0xffff); } public static string GetMessage(Win32Error errorCode) {