diff --git a/src/.editorconfig b/src/.editorconfig index ecc46e465..383823176 100644 --- a/src/.editorconfig +++ b/src/.editorconfig @@ -94,6 +94,14 @@ dotnet_diagnostic.S4136.severity = silent # IDE1006: Naming Styles dotnet_diagnostic.IDE1006.severity = none +dotnet_diagnostic.S927.severity = suggestion + +# S1481: Unused local variables should be removed +dotnet_diagnostic.S1481.severity = silent + +# IDE0076: Invalid global 'SuppressMessageAttribute' +dotnet_diagnostic.IDE0076.severity = none +dotnet_diagnostic.S101.severity = silent [*.{cs,vb}] #### Naming styles #### diff --git a/src/Greenshot.Base/Controls/AnimatingForm.cs b/src/Greenshot.Base/Controls/AnimatingForm.cs index 44f2389d8..ac197d302 100644 --- a/src/Greenshot.Base/Controls/AnimatingForm.cs +++ b/src/Greenshot.Base/Controls/AnimatingForm.cs @@ -54,17 +54,15 @@ namespace Greenshot.Base.Controls /// /// /// Number of frames, 1 if in Terminal Server Session - protected int FramesForMillis(int milliseconds) - { + protected int FramesForMillis(int milliseconds) => // If we are in a Terminal Server Session we return 1 - return IsTerminalServerSession ? 1 : milliseconds / VRefresh; - } + IsTerminalServerSession ? 1 : milliseconds / VRefresh; /// /// Calculate the interval for the timer to animate the frames /// /// Milliseconds for the interval - protected int Interval() => (int)1000 / VRefresh; + protected int Interval() => 1000 / VRefresh; /// /// Initialize the animation @@ -114,9 +112,6 @@ namespace Greenshot.Base.Controls /// /// This method will be called every frame, so implement your animation/redraw logic here. /// - protected virtual void Animate() - { - throw new NotImplementedException(); - } + protected virtual void Animate() => throw new NotImplementedException(); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Controls/BackgroundForm.cs b/src/Greenshot.Base/Controls/BackgroundForm.cs index fed465e5e..900c314d1 100644 --- a/src/Greenshot.Base/Controls/BackgroundForm.cs +++ b/src/Greenshot.Base/Controls/BackgroundForm.cs @@ -23,6 +23,7 @@ using System; using System.Drawing; using System.Windows.Forms; using Greenshot.Base.Core; +using System.Linq; namespace Greenshot.Base.Controls { @@ -52,14 +53,13 @@ namespace Greenshot.Base.Controls { base.Show(); bool positioned = false; - foreach (Screen screen in Screen.AllScreens) + foreach (var screen in from Screen screen in Screen.AllScreens + where screen.Bounds.Contains(Cursor.Position) + select screen) { - if (screen.Bounds.Contains(Cursor.Position)) - { - positioned = true; - Location = new Point(screen.Bounds.X + (screen.Bounds.Width / 2) - (Width / 2), screen.Bounds.Y + (screen.Bounds.Height / 2) - (Height / 2)); - break; - } + positioned = true; + Location = new Point(screen.Bounds.X + (screen.Bounds.Width / 2) - (Width / 2), screen.Bounds.Y + (screen.Bounds.Height / 2) - (Height / 2)); + break; } if (!positioned) @@ -91,9 +91,6 @@ namespace Greenshot.Base.Controls Application.DoEvents(); } - private void BackgroundFormFormClosing(object sender, FormClosingEventArgs e) - { - timer_checkforclose.Stop(); - } + private void BackgroundFormFormClosing(object sender, FormClosingEventArgs e) => timer_checkforclose.Stop(); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Controls/ExtendedWebBrowser.cs b/src/Greenshot.Base/Controls/ExtendedWebBrowser.cs index 05cc4c88a..87555cf70 100644 --- a/src/Greenshot.Base/Controls/ExtendedWebBrowser.cs +++ b/src/Greenshot.Base/Controls/ExtendedWebBrowser.cs @@ -40,29 +40,20 @@ namespace Greenshot.Base.Controls { } - public int QueryStatus(Guid pguidCmdGroup, int cCmds, IntPtr prgCmds, IntPtr pCmdText) - { - return OLECMDERR_E_NOTSUPPORTED; - } + public int QueryStatus(Guid pguidCmdGroup, int cCmds, IntPtr prgCmds, IntPtr pCmdText) => OLECMDERR_E_NOTSUPPORTED; public int Exec(Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { - if (pguidCmdGroup == CGID_DocHostCommandHandler) + if (pguidCmdGroup == CGID_DocHostCommandHandler && nCmdID == OLECMDID_SHOWSCRIPTERROR) { - if (nCmdID == OLECMDID_SHOWSCRIPTERROR) - { - // do not need to alter pvaOut as the docs says, enough to return S_OK here - return S_OK; - } + // do not need to alter pvaOut as the docs says, enough to return S_OK here + return S_OK; } return OLECMDERR_E_NOTSUPPORTED; } } - protected override WebBrowserSiteBase CreateWebBrowserSiteBase() - { - return new ExtendedWebBrowserSite(this); - } + protected override WebBrowserSiteBase CreateWebBrowserSiteBase() => new ExtendedWebBrowserSite(this); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Controls/FormWithoutActivation.cs b/src/Greenshot.Base/Controls/FormWithoutActivation.cs index 0a69bc043..721fb97ce 100644 --- a/src/Greenshot.Base/Controls/FormWithoutActivation.cs +++ b/src/Greenshot.Base/Controls/FormWithoutActivation.cs @@ -28,9 +28,6 @@ namespace Greenshot.Base.Controls /// public class FormWithoutActivation : Form { - protected override bool ShowWithoutActivation - { - get { return true; } - } + protected override bool ShowWithoutActivation => true; } } \ No newline at end of file diff --git a/src/Greenshot.Base/Controls/GreenshotComboBox.cs b/src/Greenshot.Base/Controls/GreenshotComboBox.cs index c82da65f4..8dba6baee 100644 --- a/src/Greenshot.Base/Controls/GreenshotComboBox.cs +++ b/src/Greenshot.Base/Controls/GreenshotComboBox.cs @@ -37,10 +37,7 @@ namespace Greenshot.Base.Controls [Category("Greenshot"), DefaultValue(null), Description("Specifies the property name to map the configuration.")] public string PropertyName { get; set; } - public GreenshotComboBox() - { - SelectedIndexChanged += delegate { StoreSelectedEnum(); }; - } + public GreenshotComboBox() => SelectedIndexChanged += delegate { StoreSelectedEnum(); }; public void SetValue(Enum currentValue) { @@ -108,9 +105,6 @@ namespace Greenshot.Base.Controls /// Get the selected enum value from the combobox, uses generics /// /// The enum value of the combobox - public Enum GetSelectedEnum() - { - return _selectedEnum; - } + public Enum GetSelectedEnum() => _selectedEnum; } } \ No newline at end of file diff --git a/src/Greenshot.Base/Controls/GreenshotDoubleClickButton.cs b/src/Greenshot.Base/Controls/GreenshotDoubleClickButton.cs index a70fff93c..e6e79f005 100644 --- a/src/Greenshot.Base/Controls/GreenshotDoubleClickButton.cs +++ b/src/Greenshot.Base/Controls/GreenshotDoubleClickButton.cs @@ -4,9 +4,6 @@ namespace Greenshot.Base.Controls { public class GreenshotDoubleClickButton : Button { - public GreenshotDoubleClickButton() - { - SetStyle(ControlStyles.StandardClick | ControlStyles.StandardDoubleClick, true); - } + public GreenshotDoubleClickButton() => SetStyle(ControlStyles.StandardClick | ControlStyles.StandardDoubleClick, true); } } diff --git a/src/Greenshot.Base/Controls/GreenshotForm.cs b/src/Greenshot.Base/Controls/GreenshotForm.cs index f8de3d6cd..a207ca8e0 100644 --- a/src/Greenshot.Base/Controls/GreenshotForm.cs +++ b/src/Greenshot.Base/Controls/GreenshotForm.cs @@ -72,15 +72,9 @@ namespace Greenshot.Base.Controls /// Used to check the designmode during a constructor /// /// - protected static bool IsInDesignMode - { - get - { - return (Application.ExecutablePath.IndexOf("devenv.exe", StringComparison.OrdinalIgnoreCase) > -1) || + protected static bool IsInDesignMode => (Application.ExecutablePath.IndexOf("devenv.exe", StringComparison.OrdinalIgnoreCase) > -1) || Application.ExecutablePath.IndexOf("sharpdevelop.exe", StringComparison.OrdinalIgnoreCase) > -1 || (Application.ExecutablePath.IndexOf("wdexpress.exe", StringComparison.OrdinalIgnoreCase) > -1); - } - } #endif protected bool ManualLanguageApply { get; set; } @@ -92,10 +86,7 @@ namespace Greenshot.Base.Controls /// protected bool ToFront { get; set; } - protected GreenshotForm() - { - DpiChanged += (sender, dpiChangedEventArgs) => DpiChangedHandler(dpiChangedEventArgs.DeviceDpiOld, dpiChangedEventArgs.DeviceDpiNew); - } + protected GreenshotForm() => DpiChanged += (sender, dpiChangedEventArgs) => DpiChangedHandler(dpiChangedEventArgs.DeviceDpiOld, dpiChangedEventArgs.DeviceDpiNew); /// /// This is the basic DpiChangedHandler responsible for all the DPI relative changes @@ -148,19 +139,16 @@ namespace Greenshot.Base.Controls /// protected override void OnPaint(PaintEventArgs e) { - if (DesignMode) + if (DesignMode && !_isDesignModeLanguageSet) { - if (!_isDesignModeLanguageSet) + _isDesignModeLanguageSet = true; + try { - _isDesignModeLanguageSet = true; - try - { - ApplyLanguage(); - } - catch (Exception) - { - // ignored - } + ApplyLanguage(); + } + catch (Exception) + { + // ignored } } @@ -215,13 +203,10 @@ namespace Greenshot.Base.Controls /// protected override void OnClosed(EventArgs e) { - if (!DesignMode && !ManualStoreFields) + if (!DesignMode && !ManualStoreFields && DialogResult == DialogResult.OK) { - if (DialogResult == DialogResult.OK) - { - LOG.Info("Form was closed with OK: storing field values."); - StoreFields(); - } + LOG.Info("Form was closed with OK: storing field values."); + StoreFields(); } base.OnClosed(e); diff --git a/src/Greenshot.Base/Controls/HotkeyControl.cs b/src/Greenshot.Base/Controls/HotkeyControl.cs index bb6fa857f..19b85d280 100644 --- a/src/Greenshot.Base/Controls/HotkeyControl.cs +++ b/src/Greenshot.Base/Controls/HotkeyControl.cs @@ -243,10 +243,7 @@ namespace Greenshot.Base.Controls /// Prevents the letter/whatever entered to show up in the TextBox /// Without this, a "A" key press would appear as "aControl, Alt + A" /// - private void HotkeyControl_KeyPress(object sender, KeyPressEventArgs e) - { - e.Handled = true; - } + private void HotkeyControl_KeyPress(object sender, KeyPressEventArgs e) => e.Handled = true; /// /// Handles some misc keys, such as Ctrl+Delete and Shift+Insert @@ -336,7 +333,7 @@ namespace Greenshot.Base.Controls } // Only validate input if it comes from the user - if (bCalledProgramatically == false) + if (!bCalledProgramatically) { // No modifier or shift only, AND a hotkey that needs another modifier if ((_modifiers == Keys.Shift || _modifiers == Keys.None) && _needNonShiftModifier.Contains((int)_hotkey)) @@ -344,7 +341,7 @@ namespace Greenshot.Base.Controls 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)) { _modifiers = Keys.Alt | Keys.Control; } @@ -384,10 +381,7 @@ namespace Greenshot.Base.Controls Text = HotkeyToLocalizedString(_modifiers, _hotkey); } - public override string ToString() - { - return HotkeyToString(HotkeyModifiers, Hotkey); - } + public override string ToString() => HotkeyToString(HotkeyModifiers, Hotkey); public static string GetLocalizedHotkeyStringFromString(string hotkeyString) { @@ -396,10 +390,7 @@ namespace Greenshot.Base.Controls return HotkeyToLocalizedString(modifiers, virtualKeyCode); } - public static string HotkeyToString(Keys modifierKeyCode, Keys virtualKeyCode) - { - return HotkeyModifiersToString(modifierKeyCode) + virtualKeyCode; - } + public static string HotkeyToString(Keys modifierKeyCode, Keys virtualKeyCode) => HotkeyModifiersToString(modifierKeyCode) + virtualKeyCode; public static string HotkeyModifiersToString(Keys modifierKeyCode) { @@ -427,10 +418,7 @@ namespace Greenshot.Base.Controls return hotkeyString.ToString(); } - public static string HotkeyToLocalizedString(Keys modifierKeyCode, Keys virtualKeyCode) - { - return HotkeyModifiersToLocalizedString(modifierKeyCode) + GetKeyName(virtualKeyCode); - } + public static string HotkeyToLocalizedString(Keys modifierKeyCode, Keys virtualKeyCode) => HotkeyModifiersToLocalizedString(modifierKeyCode) + GetKeyName(virtualKeyCode); public static string HotkeyModifiersToLocalizedString(Keys modifierKeyCode) { @@ -463,22 +451,22 @@ namespace Greenshot.Base.Controls Keys modifiers = Keys.None; if (!string.IsNullOrEmpty(modifiersString)) { - if (modifiersString.ToLower().Contains("alt")) + if (modifiersString.IndexOf("alt", StringComparison.CurrentCultureIgnoreCase) >= 0) { modifiers |= Keys.Alt; } - if (modifiersString.ToLower().Contains("ctrl")) + if (modifiersString.IndexOf("ctrl", StringComparison.CurrentCultureIgnoreCase) >= 0) { modifiers |= Keys.Control; } - if (modifiersString.ToLower().Contains("shift")) + if (modifiersString.IndexOf("shift", StringComparison.CurrentCultureIgnoreCase) >= 0) { modifiers |= Keys.Shift; } - if (modifiersString.ToLower().Contains("win")) + if (modifiersString.IndexOf("win", StringComparison.CurrentCultureIgnoreCase) >= 0) { modifiers |= Keys.LWin; } @@ -503,10 +491,7 @@ namespace Greenshot.Base.Controls return key; } - public static void RegisterHotkeyHwnd(IntPtr hWnd) - { - _hotkeyHwnd = hWnd; - } + public static void RegisterHotkeyHwnd(IntPtr hWnd) => _hotkeyHwnd = hWnd; /// /// Register a hotkey diff --git a/src/Greenshot.Base/Controls/OAuthLoginForm.cs b/src/Greenshot.Base/Controls/OAuthLoginForm.cs index 9d0916762..0469a8870 100644 --- a/src/Greenshot.Base/Controls/OAuthLoginForm.cs +++ b/src/Greenshot.Base/Controls/OAuthLoginForm.cs @@ -112,10 +112,8 @@ namespace Greenshot.Base.Controls } } - private void AddressTextBox_KeyPress(object sender, KeyPressEventArgs e) - { + private void AddressTextBox_KeyPress(object sender, KeyPressEventArgs e) => //Cancel the key press so the user can't enter a new url e.Handled = true; - } } } \ No newline at end of file diff --git a/src/Greenshot.Base/Controls/QualityDialog.cs b/src/Greenshot.Base/Controls/QualityDialog.cs index 2212ab35b..45a6c3eff 100644 --- a/src/Greenshot.Base/Controls/QualityDialog.cs +++ b/src/Greenshot.Base/Controls/QualityDialog.cs @@ -64,9 +64,6 @@ namespace Greenshot.Base.Controls } } - private void TrackBarJpegQualityScroll(object sender, EventArgs e) - { - textBoxJpegQuality.Text = trackBarJpegQuality.Value.ToString(); - } + private void TrackBarJpegQualityScroll(object sender, EventArgs e) => textBoxJpegQuality.Text = trackBarJpegQuality.Value.ToString(); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Controls/SaveImageFileDialog.cs b/src/Greenshot.Base/Controls/SaveImageFileDialog.cs index 0f3052bcf..9bf8e1758 100644 --- a/src/Greenshot.Base/Controls/SaveImageFileDialog.cs +++ b/src/Greenshot.Base/Controls/SaveImageFileDialog.cs @@ -51,13 +51,10 @@ namespace Greenshot.Base.Controls protected virtual void Dispose(bool disposing) { - if (disposing) + if (disposing && SaveFileDialog != null) { - if (SaveFileDialog != null) - { - SaveFileDialog.Dispose(); - SaveFileDialog = null; - } + SaveFileDialog.Dispose(); + SaveFileDialog = null; } } @@ -126,7 +123,7 @@ namespace Greenshot.Base.Controls for (int i = 0; i < _filterOptions.Length; i++) { string ifo = supportedImageFormats[i].ToString(); - if (ifo.ToLower().Equals("jpeg")) ifo = "Jpg"; // we dont want no jpeg files, so let the dialog check for jpg + if (ifo.Equals("jpeg", StringComparison.CurrentCultureIgnoreCase)) ifo = "Jpg"; // we dont want no jpeg files, so let the dialog check for jpg FilterOption fo = new() { Label = ifo.ToUpper(), @@ -204,11 +201,9 @@ namespace Greenshot.Base.Controls /// /// sets InitialDirectory and FileName property of a SaveFileDialog smartly, considering default pattern and last used path /// - private void ApplySuggestedValues() - { + private void ApplySuggestedValues() => // build the full path and set dialog properties FileName = FilenameHelper.GetFilenameWithoutExtensionFromPattern(conf.OutputFileFilenamePattern, _captureDetails); - } private class FilterOption { diff --git a/src/Greenshot.Base/Controls/ThumbnailForm.cs b/src/Greenshot.Base/Controls/ThumbnailForm.cs index a79e5fb8b..b8d88745d 100644 --- a/src/Greenshot.Base/Controls/ThumbnailForm.cs +++ b/src/Greenshot.Base/Controls/ThumbnailForm.cs @@ -50,14 +50,9 @@ namespace Greenshot.Base.Controls FormBorderStyle = FormBorderStyle.None; TopMost = false; Enabled = false; - if (conf.WindowCaptureMode == WindowCaptureMode.Auto || conf.WindowCaptureMode == WindowCaptureMode.Aero) - { - BackColor = Color.FromArgb(255, conf.DWMBackgroundColor.R, conf.DWMBackgroundColor.G, conf.DWMBackgroundColor.B); - } - else - { - BackColor = Color.White; - } + BackColor = conf.WindowCaptureMode == WindowCaptureMode.Auto || conf.WindowCaptureMode == WindowCaptureMode.Aero + ? Color.FromArgb(255, conf.DWMBackgroundColor.R, conf.DWMBackgroundColor.G, conf.DWMBackgroundColor.B) + : Color.White; // cleanup at close FormClosing += delegate { UnregisterThumbnail(); }; @@ -147,14 +142,9 @@ namespace Greenshot.Base.Controls public void AlignToControl(Control alignTo) { var screenBounds = DisplayInfo.ScreenBounds; - if (screenBounds.Contains(alignTo.Left, alignTo.Top - Height)) - { - Location = new Point(alignTo.Left + (alignTo.Width / 2) - (Width / 2), alignTo.Top - Height); - } - else - { - Location = new Point(alignTo.Left + (alignTo.Width / 2) - (Width / 2), alignTo.Bottom); - } + Location = screenBounds.Contains(alignTo.Left, alignTo.Top - Height) + ? new Point(alignTo.Left + (alignTo.Width / 2) - (Width / 2), alignTo.Top - Height) + : new Point(alignTo.Left + (alignTo.Width / 2) - (Width / 2), alignTo.Bottom); } } } \ No newline at end of file diff --git a/src/Greenshot.Base/Core/AbstractDestination.cs b/src/Greenshot.Base/Core/AbstractDestination.cs index 803e6a783..ff416bd13 100644 --- a/src/Greenshot.Base/Core/AbstractDestination.cs +++ b/src/Greenshot.Base/Core/AbstractDestination.cs @@ -86,13 +86,7 @@ namespace Greenshot.Base.Core public virtual bool IsLinkable => false; - public virtual bool IsActive - { - get - { - return (CoreConfig.ExcludeDestinations?.Contains(Designation)) != true; - } - } + public virtual bool IsActive => (CoreConfig.ExcludeDestinations?.Contains(Designation)) != true; public abstract ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails); @@ -129,10 +123,7 @@ namespace Greenshot.Base.Core } } - public override string ToString() - { - return Description; - } + public override string ToString() => Description; /// /// Helper method to add events which set the tag, this way we can see why there might be a close. @@ -188,7 +179,7 @@ namespace Greenshot.Base.Core menu.ResumeLayout(); }; - menu.Closing += delegate (object source, ToolStripDropDownClosingEventArgs eventArgs) + menu.Closing += (object source, ToolStripDropDownClosingEventArgs eventArgs) => { Log.DebugFormat("Close reason: {0}", eventArgs.CloseReason); switch (eventArgs.CloseReason) @@ -235,7 +226,7 @@ namespace Greenshot.Base.Core { // Fix foreach loop variable for the delegate ToolStripMenuItem item = destination.GetMenuItem(addDynamics, menu, - delegate (object sender, EventArgs e) + (object sender, EventArgs e) => { ToolStripMenuItem toolStripMenuItem = sender as ToolStripMenuItem; IDestination clickedDestination = (IDestination)toolStripMenuItem?.Tag; @@ -311,14 +302,7 @@ namespace Greenshot.Base.Core var menuRectangle = new NativeRect(location, menu.Size); menuRectangle = menuRectangle.Intersect(DisplayInfo.ScreenBounds); - if (menuRectangle.Height < menu.Height) - { - location = location.Offset(-40, -(menuRectangle.Height - menu.Height)); - } - else - { - location = location.Offset(-40, -10); - } + location = menuRectangle.Height < menu.Height ? location.Offset(-40, -(menuRectangle.Height - menu.Height)) : location.Offset(-40, -10); // This prevents the problem that the context menu shows in the task-bar User32Api.SetForegroundWindow(SimpleServiceProvider.Current.GetInstance().ContextMenuStrip.Handle); diff --git a/src/Greenshot.Base/Core/AccessibleHelper.cs b/src/Greenshot.Base/Core/AccessibleHelper.cs index 1b26fffb1..ee45d7269 100644 --- a/src/Greenshot.Base/Core/AccessibleHelper.cs +++ b/src/Greenshot.Base/Core/AccessibleHelper.cs @@ -86,15 +86,9 @@ namespace Greenshot.Base.Core } } - private string Name - { - get { return accessible.get_accName(CHILDID_SELF); } - } + private string Name => accessible.get_accName(CHILDID_SELF); - private int ChildCount - { - get { return accessible.accChildCount; } - } + private int ChildCount => accessible.accChildCount; public Accessible(IntPtr hWnd) { @@ -194,13 +188,10 @@ namespace Greenshot.Base.Core { _ = tab.accessible.get_accState(CHILDID_SELF); var description = tab.accessible.get_accDescription(CHILDID_SELF); - if (!string.IsNullOrEmpty(description)) + if (!string.IsNullOrEmpty(description) && description.Contains(Environment.NewLine)) { - if (description.Contains(Environment.NewLine)) - { - var url = description.Substring(description.IndexOf(Environment.NewLine)).Trim(); - yield return url; - } + var url = description.Substring(description.IndexOf(Environment.NewLine)).Trim(); + yield return url; } } } @@ -208,15 +199,9 @@ namespace Greenshot.Base.Core } } - private Accessible(IAccessible acc) - { - accessible = acc ?? throw new Exception(); - } + private Accessible(IAccessible acc) => accessible = acc ?? throw new Exception(); - private void Activate() - { - accessible.accDoDefaultAction(CHILDID_SELF); - } + private void Activate() => accessible.accDoDefaultAction(CHILDID_SELF); private static object[] GetAccessibleChildren(IAccessible ao, out int childs) { diff --git a/src/Greenshot.Base/Core/AnimationHelpers.cs b/src/Greenshot.Base/Core/AnimationHelpers.cs index 0fbbe9469..b61f8e30a 100644 --- a/src/Greenshot.Base/Core/AnimationHelpers.cs +++ b/src/Greenshot.Base/Core/AnimationHelpers.cs @@ -110,22 +110,13 @@ namespace Greenshot.Base.Core /// /// Final animation value, this is including the legs /// - public T Final - { - get - { - return _queue.Count == 0 ? Last : _queue.ToArray()[_queue.Count - 1].Destination; - } - } + public T Final => _queue.Count == 0 ? Last : _queue.ToArray()[_queue.Count - 1].Destination; /// /// This restarts the current animation and changes the last frame /// /// - public void ChangeDestination(T newDestination) - { - ChangeDestination(newDestination, Frames); - } + public void ChangeDestination(T newDestination) => ChangeDestination(newDestination, Frames); /// /// This restarts the current animation and changes the last frame @@ -146,20 +137,14 @@ namespace Greenshot.Base.Core /// All values will stay the same /// /// - public void QueueDestinationLeg(T queuedDestination) - { - QueueDestinationLeg(queuedDestination, Frames, EasingType, EasingMode); - } + public void QueueDestinationLeg(T queuedDestination) => QueueDestinationLeg(queuedDestination, Frames, EasingType, EasingMode); /// /// Queue the destination, it will be used to continue at the last frame /// /// /// - public void QueueDestinationLeg(T queuedDestination, int frames) - { - QueueDestinationLeg(queuedDestination, frames, EasingType, EasingMode); - } + public void QueueDestinationLeg(T queuedDestination, int frames) => QueueDestinationLeg(queuedDestination, frames, EasingType, EasingMode); /// /// Queue the destination, it will be used to continue at the last frame @@ -167,10 +152,7 @@ namespace Greenshot.Base.Core /// /// /// EasingType - public void QueueDestinationLeg(T queuedDestination, int frames, EasingType easingType) - { - QueueDestinationLeg(queuedDestination, frames, easingType, EasingMode); - } + public void QueueDestinationLeg(T queuedDestination, int frames, EasingType easingType) => QueueDestinationLeg(queuedDestination, frames, easingType, EasingMode); /// /// Queue the destination, it will be used to continue at the last frame @@ -204,17 +186,13 @@ namespace Greenshot.Base.Core /// /// Get the easing value, which is from 0-1 and depends on the frame /// - protected double EasingValue + protected double EasingValue => EasingMode switch { - get => - EasingMode switch - { - EasingMode.EaseOut => Easing.EaseOut(CurrentFrameNr / (double)Frames, EasingType), - EasingMode.EaseInOut => Easing.EaseInOut(CurrentFrameNr / (double)Frames, EasingType), - EasingMode.EaseIn => Easing.EaseIn(CurrentFrameNr / (double)Frames, EasingType), - _ => Easing.EaseIn(CurrentFrameNr / (double)Frames, EasingType) - }; - } + EasingMode.EaseOut => Easing.EaseOut(CurrentFrameNr / (double)Frames, EasingType), + EasingMode.EaseInOut => Easing.EaseInOut(CurrentFrameNr / (double)Frames, EasingType), + EasingMode.EaseIn => Easing.EaseIn(CurrentFrameNr / (double)Frames, EasingType), + _ => Easing.EaseIn(CurrentFrameNr / (double)Frames, EasingType) + }; /// /// Get the current (previous) frame object @@ -252,13 +230,7 @@ namespace Greenshot.Base.Core /// /// Are there more frames to animate? /// - public virtual bool HasNext - { - get - { - return CurrentFrameNr < Frames || _queue.Count > 0; - } - } + public virtual bool HasNext => CurrentFrameNr < Frames || _queue.Count > 0; /// /// Get the next animation frame value object @@ -515,10 +487,7 @@ namespace Greenshot.Base.Core _ => throw new NotImplementedException() }; - public static double EaseInOut(double linearStep, EasingType easeInType, EasingType easeOutType) - { - return linearStep < 0.5 ? EaseInOut(linearStep, easeInType) : EaseInOut(linearStep, easeOutType); - } + public static double EaseInOut(double linearStep, EasingType easeInType, EasingType easeOutType) => linearStep < 0.5 ? EaseInOut(linearStep, easeInType) : EaseInOut(linearStep, easeOutType); public static double EaseInOut(double linearStep, EasingType type) => type switch @@ -535,28 +504,16 @@ namespace Greenshot.Base.Core private static class Sine { - public static double EaseIn(double s) - { - return Math.Sin((s * (Math.PI / 2)) - (Math.PI / 2)) + 1; - } + public static double EaseIn(double s) => Math.Sin((s * (Math.PI / 2)) - (Math.PI / 2)) + 1; - public static double EaseOut(double s) - { - return Math.Sin(s * (Math.PI / 2)); - } + public static double EaseOut(double s) => Math.Sin(s * (Math.PI / 2)); - public static double EaseInOut(double s) - { - return Math.Sin((s * Math.PI) - (Math.PI / 2) + 1) / 2; - } + public static double EaseInOut(double s) => Math.Sin((s * Math.PI) - (Math.PI / 2) + 1) / 2; } private static class Power { - public static double EaseIn(double s, int power) - { - return Math.Pow(s, power); - } + public static double EaseIn(double s, int power) => Math.Pow(s, power); public static double EaseOut(double s, int power) { diff --git a/src/Greenshot.Base/Core/Cache.cs b/src/Greenshot.Base/Core/Cache.cs index bf92bb557..8b7e33f5f 100644 --- a/src/Greenshot.Base/Core/Cache.cs +++ b/src/Greenshot.Base/Core/Cache.cs @@ -52,29 +52,20 @@ namespace Greenshot.Base.Core /// Initialize the cache /// /// - public Cache(CacheObjectExpired expiredCallback) : this() - { - _expiredCallback = expiredCallback; - } + public Cache(CacheObjectExpired expiredCallback) : this() => _expiredCallback = expiredCallback; /// /// Initialize the cache with a expire setting /// /// - public Cache(int secondsToExpire) : this() - { - _secondsToExpire = secondsToExpire; - } + public Cache(int secondsToExpire) : this() => _secondsToExpire = secondsToExpire; /// /// Initialize the cache with a expire setting /// /// /// - public Cache(int secondsToExpire, CacheObjectExpired expiredCallback) : this(expiredCallback) - { - _secondsToExpire = secondsToExpire; - } + public Cache(int secondsToExpire, CacheObjectExpired expiredCallback) : this(expiredCallback) => _secondsToExpire = secondsToExpire; /// /// Enumerable for the values in the cache @@ -87,10 +78,7 @@ namespace Greenshot.Base.Core lock (_lockObject) { - foreach (TV element in _internalCache.Values) - { - elements.Add(element); - } + elements.AddRange(_internalCache.Values); } foreach (TV element in elements) @@ -140,10 +128,7 @@ namespace Greenshot.Base.Core /// /// /// - public void Add(TK key, TV value) - { - Add(key, value, null); - } + public void Add(TK key, TV value) => Add(key, value, null); /// /// Add a value to the cache @@ -156,7 +141,7 @@ namespace Greenshot.Base.Core lock (_lockObject) { var cachedItem = new CachedItem(key, value, secondsToExpire ?? _secondsToExpire); - cachedItem.Expired += delegate (TK cacheKey, TV cacheValue) + cachedItem.Expired += (TK cacheKey, TV cacheValue) => { if (_internalCache.ContainsKey(cacheKey)) { @@ -242,10 +227,7 @@ namespace Greenshot.Base.Core } } - private void timerEvent_Elapsed(object sender, ElapsedEventArgs e) - { - ExpireNow(); - } + private void timerEvent_Elapsed(object sender, ElapsedEventArgs e) => ExpireNow(); public TK Key { get; private set; } public TV Item { get; private set; } diff --git a/src/Greenshot.Base/Core/Capture.cs b/src/Greenshot.Base/Core/Capture.cs index 2a761dd29..c272dbdad 100644 --- a/src/Greenshot.Base/Core/Capture.cs +++ b/src/Greenshot.Base/Core/Capture.cs @@ -97,10 +97,7 @@ namespace Greenshot.Base.Core } } - public void NullImage() - { - _image = null; - } + public void NullImage() => _image = null; private Icon _cursor; @@ -162,10 +159,7 @@ namespace Greenshot.Base.Core /// Note: the supplied bitmap can be disposed immediately or when constructor is called. /// /// Image - public Capture(Image newImage) : this() - { - Image = newImage; - } + public Capture(Image newImage) : this() => Image = newImage; /// /// Destructor @@ -234,10 +228,7 @@ namespace Greenshot.Base.Core /// /// x coordinates to move the mouse /// y coordinates to move the mouse - public void MoveMouseLocation(int x, int y) - { - CursorLocation = CursorLocation.Offset(x, y); - } + public void MoveMouseLocation(int x, int y) => CursorLocation = CursorLocation.Offset(x, y); // TODO: Enable when the elements are usable again. ///// diff --git a/src/Greenshot.Base/Core/CaptureDetails.cs b/src/Greenshot.Base/Core/CaptureDetails.cs index 048fcf32c..b5c456e2b 100644 --- a/src/Greenshot.Base/Core/CaptureDetails.cs +++ b/src/Greenshot.Base/Core/CaptureDetails.cs @@ -23,6 +23,7 @@ using System; using System.Collections.Generic; using Greenshot.Base.Interfaces; using Greenshot.Base.Interfaces.Ocr; +using System.Linq; namespace Greenshot.Base.Core { @@ -54,10 +55,7 @@ namespace Greenshot.Base.Core public Dictionary MetaData { get; } = new Dictionary(); /// - public void AddMetaData(string key, string value) - { - MetaData[key] = value; - } + public void AddMetaData(string key, string value) => MetaData[key] = value; /// public CaptureMode CaptureMode { get; set; } @@ -66,10 +64,7 @@ namespace Greenshot.Base.Core public List CaptureDestinations { get; set; } = new List(); /// - public void ClearDestinations() - { - CaptureDestinations.Clear(); - } + public void ClearDestinations() => CaptureDestinations.Clear(); /// public void RemoveDestination(IDestination destination) @@ -92,20 +87,16 @@ namespace Greenshot.Base.Core /// public bool HasDestination(string designation) { - foreach (IDestination destination in CaptureDestinations) + foreach (var _ in from IDestination destination in CaptureDestinations + where designation.Equals(destination.Designation) + select new { }) { - if (designation.Equals(destination.Designation)) - { - return true; - } + return true; } return false; } - public CaptureDetails() - { - DateTime = DateTime.Now; - } + public CaptureDetails() => DateTime = DateTime.Now; } } \ No newline at end of file diff --git a/src/Greenshot.Base/Core/ClipboardHelper.cs b/src/Greenshot.Base/Core/ClipboardHelper.cs index 770e293f6..de2b8293e 100644 --- a/src/Greenshot.Base/Core/ClipboardHelper.cs +++ b/src/Greenshot.Base/Core/ClipboardHelper.cs @@ -187,14 +187,9 @@ EndSelection:<<<<<<<4 { string messageText; string clipboardOwner = GetClipboardOwner(); - if (clipboardOwner != null) - { - messageText = Language.GetFormattedString("clipboard_inuse", clipboardOwner); - } - else - { - messageText = Language.GetString("clipboard_error"); - } + messageText = clipboardOwner != null + ? Language.GetFormattedString("clipboard_inuse", clipboardOwner) + : Language.GetString("clipboard_error"); Log.Error(messageText, clipboardSetException); } @@ -221,14 +216,9 @@ EndSelection:<<<<<<<4 { string messageText; string clipboardOwner = GetClipboardOwner(); - if (clipboardOwner != null) - { - messageText = Language.GetFormattedString("clipboard_inuse", clipboardOwner); - } - else - { - messageText = Language.GetString("clipboard_error"); - } + messageText = clipboardOwner != null + ? Language.GetFormattedString("clipboard_inuse", clipboardOwner) + : Language.GetString("clipboard_error"); Log.Error(messageText, ee); } @@ -254,12 +244,9 @@ EndSelection:<<<<<<<4 /// public static bool ContainsText(IDataObject dataObject) { - if (dataObject != null) + if (dataObject != null && (dataObject.GetDataPresent(DataFormats.Text) || dataObject.GetDataPresent(DataFormats.UnicodeText))) { - if (dataObject.GetDataPresent(DataFormats.Text) || dataObject.GetDataPresent(DataFormats.UnicodeText)) - { - return true; - } + return true; } return false; @@ -487,10 +474,7 @@ EndSelection:<<<<<<<4 /// /// /// true if there is a valid stream - private static bool IsValidStream(MemoryStream memoryStream) - { - return memoryStream?.Length > 0; - } + private static bool IsValidStream(MemoryStream memoryStream) => memoryStream?.Length > 0; /// /// Wrapper for Clipboard.GetImage, Created for Bug #3432313 @@ -885,10 +869,7 @@ EndSelection:<<<<<<<4 /// Get Text from the DataObject /// /// string if there is text on the clipboard - public static string GetText(IDataObject dataObject) - { - return ContainsText(dataObject) ? (string)dataObject.GetData(DataFormats.Text) : null; - } + public static string GetText(IDataObject dataObject) => ContainsText(dataObject) ? (string)dataObject.GetData(DataFormats.Text) : null; /// /// Set text to the clipboard @@ -1177,23 +1158,17 @@ EndSelection:<<<<<<<4 /// IDataObject /// string with format /// true if one the format is found - public static bool ContainsFormat(IDataObject dataObject, string format) - { - return ContainsFormat(dataObject, new[] + public static bool ContainsFormat(IDataObject dataObject, string format) => ContainsFormat(dataObject, new[] { format }); - } /// /// Check if there is currently something on the clipboard which has one of the supplied formats /// /// string[] with formats /// true if one of the formats was found - public static bool ContainsFormat(string[] formats) - { - return ContainsFormat(GetDataObject(), formats); - } + public static bool ContainsFormat(string[] formats) => ContainsFormat(GetDataObject(), formats); /// /// Check if there is currently something on the clipboard which has one of the supplied formats @@ -1210,13 +1185,12 @@ EndSelection:<<<<<<<4 return false; } - foreach (string format in formats) + foreach (var _ in from string format in formats + where currentFormats.Contains(format) + select new { }) { - if (currentFormats.Contains(format)) - { - formatFound = true; - break; - } + formatFound = true; + break; } return formatFound; @@ -1228,10 +1202,7 @@ EndSelection:<<<<<<<4 /// IDataObject /// Type to get /// object from IDataObject - public static object GetFromDataObject(IDataObject dataObj, Type type) - { - return type != null ? GetFromDataObject(dataObj, type.FullName) : null; - } + public static object GetFromDataObject(IDataObject dataObj, Type type) => type != null ? GetFromDataObject(dataObj, type.FullName) : null; /// /// Get ImageFilenames from the IDataObject diff --git a/src/Greenshot.Base/Core/CoreConfiguration.cs b/src/Greenshot.Base/Core/CoreConfiguration.cs index 7a1c7ef06..f38834ddf 100644 --- a/src/Greenshot.Base/Core/CoreConfiguration.cs +++ b/src/Greenshot.Base/Core/CoreConfiguration.cs @@ -365,7 +365,7 @@ namespace Greenshot.Base.Core if (_iconSize != newSize) { _iconSize = value; - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IconSize")); + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IconSize))); } } } @@ -383,10 +383,7 @@ namespace Greenshot.Base.Core /// /// /// - public bool IsExperimentalFeatureEnabled(string experimentalFeature) - { - return ExperimentalFeatures?.Contains(experimentalFeature) == true; - } + public bool IsExperimentalFeatureEnabled(string experimentalFeature) => ExperimentalFeatures?.Contains(experimentalFeature) == true; private string CreateOutputFilePath() { @@ -456,20 +453,14 @@ namespace Greenshot.Base.Core public override string PreCheckValue(string propertyName, string propertyValue) { // Changed the separator, now we need to correct this - if ("Destinations".Equals(propertyName)) + if ("Destinations".Equals(propertyName) && propertyValue != null) { - if (propertyValue != null) - { - return propertyValue.Replace('|', ','); - } + return propertyValue.Replace('|', ','); } - if ("OutputFilePath".Equals(propertyName)) + if ("OutputFilePath".Equals(propertyName) && string.IsNullOrEmpty(propertyValue)) { - if (string.IsNullOrEmpty(propertyValue)) - { - return null; - } + return null; } return base.PreCheckValue(propertyName, propertyValue); @@ -528,12 +519,9 @@ namespace Greenshot.Base.Core } // Enable OneNote if upgrading from 1.1 - if (ExcludeDestinations?.Contains("OneNote") == true) + if (ExcludeDestinations?.Contains("OneNote") == true && LastSaveWithVersion?.StartsWith("1.1") == true) { - if (LastSaveWithVersion?.StartsWith("1.1") == true) - { - ExcludeDestinations.Remove("OneNote"); - } + ExcludeDestinations.Remove("OneNote"); } if (OutputDestinations == null) @@ -568,14 +556,11 @@ namespace Greenshot.Base.Core if (NoGDICaptureForProduct != null) { // Fix error in configuration - if (NoGDICaptureForProduct.Count >= 2) + if (NoGDICaptureForProduct.Count >= 2 && "intellij".Equals(NoGDICaptureForProduct[0]) && "idea".Equals(NoGDICaptureForProduct[1])) { - if ("intellij".Equals(NoGDICaptureForProduct[0]) && "idea".Equals(NoGDICaptureForProduct[1])) - { - NoGDICaptureForProduct.RemoveRange(0, 2); - NoGDICaptureForProduct.Add("Intellij Idea"); - IsDirty = true; - } + NoGDICaptureForProduct.RemoveRange(0, 2); + NoGDICaptureForProduct.Add("Intellij Idea"); + IsDirty = true; } for (int i = 0; i < NoGDICaptureForProduct.Count; i++) @@ -587,14 +572,11 @@ namespace Greenshot.Base.Core if (NoDWMCaptureForProduct != null) { // Fix error in configuration - if (NoDWMCaptureForProduct.Count >= 3) + if (NoDWMCaptureForProduct.Count >= 3 && "citrix".Equals(NoDWMCaptureForProduct[0]) && "ica".Equals(NoDWMCaptureForProduct[1]) && "client".Equals(NoDWMCaptureForProduct[2])) { - if ("citrix".Equals(NoDWMCaptureForProduct[0]) && "ica".Equals(NoDWMCaptureForProduct[1]) && "client".Equals(NoDWMCaptureForProduct[2])) - { - NoDWMCaptureForProduct.RemoveRange(0, 3); - NoDWMCaptureForProduct.Add("Citrix ICA Client"); - IsDirty = true; - } + NoDWMCaptureForProduct.RemoveRange(0, 3); + NoDWMCaptureForProduct.Add("Citrix ICA Client"); + IsDirty = true; } for (int i = 0; i < NoDWMCaptureForProduct.Count; i++) diff --git a/src/Greenshot.Base/Core/CredentialsHelper.cs b/src/Greenshot.Base/Core/CredentialsHelper.cs index a08e61d42..5ec1e6ec0 100644 --- a/src/Greenshot.Base/Core/CredentialsHelper.cs +++ b/src/Greenshot.Base/Core/CredentialsHelper.cs @@ -275,10 +275,7 @@ namespace Greenshot.Base.Core /// Shows the credentials dialog with the specified name. /// The name for the credentials. /// Returns a DialogResult indicating the user action. - public DialogResult Show(string name) - { - return Show(null, name, Password, SaveChecked); - } + public DialogResult Show(string name) => Show(null, name, Password, SaveChecked); /// Shows the credentials dialog with the specified owner, name, password and save checkbox status. /// The System.Windows.Forms.IWin32Window the dialog will display in front of. diff --git a/src/Greenshot.Base/Core/DestinationHelper.cs b/src/Greenshot.Base/Core/DestinationHelper.cs index d80bb694d..7f2fa803e 100644 --- a/src/Greenshot.Base/Core/DestinationHelper.cs +++ b/src/Greenshot.Base/Core/DestinationHelper.cs @@ -37,12 +37,8 @@ namespace Greenshot.Base.Core /// Method to get all the destinations from the plugins /// /// List of IDestination - public static IEnumerable GetAllDestinations() - { - return SimpleServiceProvider.Current.GetAllInstances() - .Where(destination => destination.IsActive) - .Where(destination => CoreConfig.ExcludeDestinations?.Contains(destination.Designation) != true).OrderBy(p => p.Priority).ThenBy(p => p.Description); - } + public static IEnumerable GetAllDestinations() => SimpleServiceProvider.Current.GetAllInstances() + .Where(destination => destination.IsActive && CoreConfig.ExcludeDestinations?.Contains(destination.Designation) != true).OrderBy(p => p.Priority).ThenBy(p => p.Description); /// /// Get a destination by a designation @@ -56,12 +52,11 @@ namespace Greenshot.Base.Core return null; } - foreach (IDestination destination in GetAllDestinations()) + foreach (var destination in from IDestination destination in GetAllDestinations() + where designation.Equals(destination.Designation) + select destination) { - if (designation.Equals(destination.Designation)) - { - return destination; - } + return destination; } return null; @@ -74,10 +69,7 @@ namespace Greenshot.Base.Core /// WellKnownDestinations /// ISurface /// ICaptureDetails - public static ExportInformation ExportCapture(bool manuallyInitiated, WellKnownDestinations designation, ISurface surface, ICaptureDetails captureDetails) - { - return ExportCapture(manuallyInitiated, designation.ToString(), surface, captureDetails); - } + public static ExportInformation ExportCapture(bool manuallyInitiated, WellKnownDestinations designation, ISurface surface, ICaptureDetails captureDetails) => ExportCapture(manuallyInitiated, designation.ToString(), surface, captureDetails); /// /// A simple helper method which will call ExportCapture for the destination with the specified designation diff --git a/src/Greenshot.Base/Core/DisplayKeyAttribute.cs b/src/Greenshot.Base/Core/DisplayKeyAttribute.cs index 9d80fa533..5b887a573 100644 --- a/src/Greenshot.Base/Core/DisplayKeyAttribute.cs +++ b/src/Greenshot.Base/Core/DisplayKeyAttribute.cs @@ -28,10 +28,7 @@ namespace Greenshot.Base.Core { public string Value { get; } - public DisplayKeyAttribute(string v) - { - Value = v; - } + public DisplayKeyAttribute(string v) => Value = v; public DisplayKeyAttribute() { diff --git a/src/Greenshot.Base/Core/EffectConverter.cs b/src/Greenshot.Base/Core/EffectConverter.cs index 6f333a683..de3124356 100644 --- a/src/Greenshot.Base/Core/EffectConverter.cs +++ b/src/Greenshot.Base/Core/EffectConverter.cs @@ -20,10 +20,7 @@ namespace Greenshot.Base.Core _numberFormatInfo.NumberGroupSeparator = ","; } - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) - { - return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); - } + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) => sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { @@ -53,7 +50,7 @@ namespace Greenshot.Base.Core return sb.ToString(); } - if (value.GetType() == typeof(TornEdgeEffect)) + if (value is TornEdgeEffect) { TornEdgeEffect effect = value as TornEdgeEffect; RetrieveDropShadowEffectValues(effect, sb); @@ -108,12 +105,9 @@ namespace Greenshot.Base.Core { case "Darkness": // Fix to prevent BUG-1753 - if (pair[1] != null && float.TryParse(pair[1], NumberStyles.Float, _numberFormatInfo, out var darkness)) + if (pair[1] != null && float.TryParse(pair[1], NumberStyles.Float, _numberFormatInfo, out var darkness) && darkness <= 1.0) { - if (darkness <= 1.0) - { - effect.Darkness = darkness; - } + effect.Darkness = darkness; } break; @@ -206,17 +200,12 @@ namespace Greenshot.Base.Core } } - private void RetrieveDropShadowEffectValues(DropShadowEffect effect, StringBuilder sb) - { + 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, + 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/src/Greenshot.Base/Core/EnvironmentInfo.cs b/src/Greenshot.Base/Core/EnvironmentInfo.cs index c99f05e77..a2e2fc76c 100644 --- a/src/Greenshot.Base/Core/EnvironmentInfo.cs +++ b/src/Greenshot.Base/Core/EnvironmentInfo.cs @@ -54,11 +54,9 @@ namespace Greenshot.Base.Core } } - public static bool IsNet45OrNewer() - { + public static bool IsNet45OrNewer() => // Class "ReflectionContext" exists from .NET 4.5 onwards. - return Type.GetType("System.Reflection.ReflectionContext", false) != null; - } + Type.GetType("System.Reflection.ReflectionContext", false) != null; public static string GetGreenshotVersion(bool shortVersion = false) { @@ -304,84 +302,82 @@ namespace Greenshot.Base.Core var productType = osVersionInfo.ProductType; var suiteMask = osVersionInfo.SuiteMask; - if (majorVersion == 4) + switch (majorVersion) { - if (productType == WindowsProductTypes.VER_NT_WORKSTATION) - { - // Windows NT 4.0 Workstation - edition = "Workstation"; - } - else if (productType == WindowsProductTypes.VER_NT_SERVER) - { - edition = (suiteMask & WindowsSuites.Enterprise) != 0 ? "Enterprise Server" : "Standard Server"; - } - } - else if (majorVersion == 5) - { - if (productType == WindowsProductTypes.VER_NT_WORKSTATION) - { - if ((suiteMask & WindowsSuites.Personal) != 0) + case 4: + if (productType == WindowsProductTypes.VER_NT_WORKSTATION) { - // Windows XP Home Edition - edition = "Home"; + // Windows NT 4.0 Workstation + edition = "Workstation"; } - else + else if (productType == WindowsProductTypes.VER_NT_SERVER) { - // Windows XP / Windows 2000 Professional - edition = "Professional"; + edition = (suiteMask & WindowsSuites.Enterprise) != 0 ? "Enterprise Server" : "Standard Server"; } - } - else if (productType == WindowsProductTypes.VER_NT_SERVER) - { - if (minorVersion == 0) + break; + case 5: + if (productType == WindowsProductTypes.VER_NT_WORKSTATION) { - if ((suiteMask & WindowsSuites.DataCenter) != 0) + if ((suiteMask & WindowsSuites.Personal) != 0) { - // Windows 2000 Datacenter Server - edition = "Datacenter Server"; - } - else if ((suiteMask & WindowsSuites.Enterprise) != 0) - { - // Windows 2000 Advanced Server - edition = "Advanced Server"; + // Windows XP Home Edition + edition = "Home"; } else { - // Windows 2000 Server - edition = "Server"; + // Windows XP / Windows 2000 Professional + edition = "Professional"; } } - else + else if (productType == WindowsProductTypes.VER_NT_SERVER) { - if ((suiteMask & WindowsSuites.DataCenter) != 0) + switch (minorVersion) { - // Windows Server 2003 Datacenter Edition - edition = "Datacenter"; - } - else if ((suiteMask & WindowsSuites.Enterprise) != 0) - { - // Windows Server 2003 Enterprise Edition - edition = "Enterprise"; - } - else if ((suiteMask & WindowsSuites.Blade) != 0) - { - // Windows Server 2003 Web Edition - edition = "Web Edition"; - } - else - { - // Windows Server 2003 Standard Edition - edition = "Standard"; + case 0: + if ((suiteMask & WindowsSuites.DataCenter) != 0) + { + // Windows 2000 Datacenter Server + edition = "Datacenter Server"; + } + else if ((suiteMask & WindowsSuites.Enterprise) != 0) + { + // Windows 2000 Advanced Server + edition = "Advanced Server"; + } + else + { + // Windows 2000 Server + edition = "Server"; + } + break; + default: + if ((suiteMask & WindowsSuites.DataCenter) != 0) + { + // Windows Server 2003 Datacenter Edition + edition = "Datacenter"; + } + else if ((suiteMask & WindowsSuites.Enterprise) != 0) + { + // Windows Server 2003 Enterprise Edition + edition = "Enterprise"; + } + else if ((suiteMask & WindowsSuites.Blade) != 0) + { + // Windows Server 2003 Web Edition + edition = "Web Edition"; + } + else + { + // Windows Server 2003 Standard Edition + edition = "Standard"; + } + break; } } - } - } - else if (majorVersion == 6) - { - if (Kernel32Api.GetProductInfo(majorVersion, minorVersion, osVersionInfo.ServicePackMajor, osVersionInfo.ServicePackMinor, out var windowsProduct)) - { + break; + case 6 when Kernel32Api.GetProductInfo(majorVersion, minorVersion, osVersionInfo.ServicePackMajor, osVersionInfo.ServicePackMinor, out var windowsProduct): edition = windowsProduct.GetEnumDescription(); - } + break; } } @@ -423,14 +419,7 @@ namespace Greenshot.Base.Core switch (minorVersion) { case 0: - if (csdVersion == "B" || csdVersion == "C") - { - name = "Windows 95 OSR2"; - } - else - { - name = "Windows 95"; - } + name = csdVersion == "B" || csdVersion == "C" ? "Windows 95 OSR2" : "Windows 95"; break; case 10: diff --git a/src/Greenshot.Base/Core/EventDelay.cs b/src/Greenshot.Base/Core/EventDelay.cs index 0e0075e22..27cf9ecd8 100644 --- a/src/Greenshot.Base/Core/EventDelay.cs +++ b/src/Greenshot.Base/Core/EventDelay.cs @@ -28,14 +28,12 @@ namespace Greenshot.Base.Core private long lastCheck; private readonly long waitTime; - public EventDelay(long ticks) - { - waitTime = ticks; - } + public EventDelay(long ticks) => waitTime = ticks; + private readonly object _lockObject = new(); // Prevent RCS1059 public bool Check() { - lock (this) + lock (_lockObject) { long now = DateTime.Now.Ticks; bool isPassed = now - lastCheck > waitTime; diff --git a/src/Greenshot.Base/Core/FastBitmap.cs b/src/Greenshot.Base/Core/FastBitmap.cs index b5e0c058e..7a184082b 100644 --- a/src/Greenshot.Base/Core/FastBitmap.cs +++ b/src/Greenshot.Base/Core/FastBitmap.cs @@ -290,15 +290,9 @@ namespace Greenshot.Base.Core protected bool BitsLocked; protected byte* Pointer; - public static IFastBitmap Create(Bitmap source) - { - return Create(source, NativeRect.Empty); - } + public static IFastBitmap Create(Bitmap source) => Create(source, NativeRect.Empty); - public void SetResolution(float horizontal, float vertical) - { - Bitmap.SetResolution(horizontal, vertical); - } + public void SetResolution(float horizontal, float vertical) => Bitmap.SetResolution(horizontal, vertical); /// /// Factory for creating a FastBitmap depending on the pixelformat of the source @@ -324,10 +318,7 @@ namespace Greenshot.Base.Core /// Bitmap to clone /// new PixelFormat /// IFastBitmap - public static IFastBitmap CreateCloneOf(Image source, PixelFormat pixelFormat) - { - return CreateCloneOf(source, pixelFormat, NativeRect.Empty); - } + public static IFastBitmap CreateCloneOf(Image source, PixelFormat pixelFormat) => CreateCloneOf(source, pixelFormat, NativeRect.Empty); /// /// Factory for creating a FastBitmap as a destination for the source @@ -335,10 +326,7 @@ namespace Greenshot.Base.Core /// Bitmap to clone /// Area of the bitmap to access, can be NativeRect.Empty for the whole /// IFastBitmap - public static IFastBitmap CreateCloneOf(Image source, NativeRect area) - { - return CreateCloneOf(source, PixelFormat.DontCare, area); - } + public static IFastBitmap CreateCloneOf(Image source, NativeRect area) => CreateCloneOf(source, PixelFormat.DontCare, area); /// /// Factory for creating a FastBitmap as a destination for the source @@ -408,35 +396,17 @@ namespace Greenshot.Base.Core /// /// Return the size of the image /// - public NativeSize Size - { - get - { - return Area == NativeRect.Empty ? (NativeSize)Bitmap.Size : Area.Size; - } - } + public NativeSize Size => Area == NativeRect.Empty ? (NativeSize)Bitmap.Size : Area.Size; /// /// Return the width of the image /// - public int Width - { - get - { - return Area == NativeRect.Empty ? Bitmap.Width : Area.Width; - } - } + public int Width => Area == NativeRect.Empty ? Bitmap.Width : Area.Width; /// /// Return the height of the image /// - public int Height - { - get - { - return Area == NativeRect.Empty ? Bitmap.Height : Area.Height; - } - } + public int Height => Area == NativeRect.Empty ? Bitmap.Height : Area.Height; private int _left; @@ -532,12 +502,9 @@ namespace Greenshot.Base.Core protected virtual void Dispose(bool disposing) { Unlock(); - if (disposing) + if (disposing && Bitmap != null && NeedsDispose) { - if (Bitmap != null && NeedsDispose) - { - Bitmap.Dispose(); - } + Bitmap.Dispose(); } Bitmap = null; @@ -580,10 +547,7 @@ namespace Greenshot.Base.Core /// /// /// - public void DrawTo(Graphics graphics, NativePoint destination) - { - DrawTo(graphics, new NativeRect(destination, Area.Size)); - } + public void DrawTo(Graphics graphics, NativePoint destination) => DrawTo(graphics, new NativeRect(destination, Area.Size)); /// /// Draw the stored Bitmap on the Destination bitmap with the specified rectangle @@ -609,10 +573,7 @@ namespace Greenshot.Base.Core /// /// /// true if x & y are inside the FastBitmap - public bool Contains(int x, int y) - { - return Area.Contains(x - Left, y - Top); - } + public bool Contains(int x, int y) => Area.Contains(x - Left, y - Top); public abstract Color GetColorAt(int x, int y); public abstract void SetColorAt(int x, int y, Color color); @@ -653,10 +614,7 @@ namespace Greenshot.Base.Core /// /// /// true if x & y are inside the FastBitmap - bool IFastBitmapWithOffset.Contains(int x, int y) - { - return Area.Contains(x - Left, y - Top); - } + bool IFastBitmapWithOffset.Contains(int x, int y) => Area.Contains(x - Left, y - Top); Color IFastBitmapWithOffset.GetColorAt(int x, int y) { @@ -696,10 +654,7 @@ namespace Greenshot.Base.Core private readonly Color[] _colorEntries; private readonly Dictionary _colorCache = new(); - public FastChunkyBitmap(Bitmap source, NativeRect area) : base(source, area) - { - _colorEntries = Bitmap.Palette.Entries; - } + public FastChunkyBitmap(Bitmap source, NativeRect area) : base(source, area) => _colorEntries = Bitmap.Palette.Entries; /// /// Get the color from the specified location @@ -720,10 +675,7 @@ namespace Greenshot.Base.Core /// /// /// byte[4] as reference - public override void GetColorAt(int x, int y, byte[] color) - { - throw new NotImplementedException("No performance gain!"); - } + public override void GetColorAt(int x, int y, byte[] color) => throw new NotImplementedException("No performance gain!"); /// /// Set the color at the specified location from the specified array @@ -731,10 +683,7 @@ namespace Greenshot.Base.Core /// /// /// byte[4] as reference - public override void SetColorAt(int x, int y, byte[] color) - { - throw new NotImplementedException("No performance gain!"); - } + public override void SetColorAt(int x, int y, byte[] color) => throw new NotImplementedException("No performance gain!"); /// /// Get the color-index from the specified location @@ -934,10 +883,7 @@ namespace Greenshot.Base.Core public Color BackgroundBlendColor { get; set; } - public Fast32ArgbBitmap(Bitmap source, NativeRect area) : base(source, area) - { - BackgroundBlendColor = Color.White; - } + public Fast32ArgbBitmap(Bitmap source, NativeRect area) : base(source, area) => BackgroundBlendColor = Color.White; /// /// Retrieve the color at location x,y diff --git a/src/Greenshot.Base/Core/FileFormatHandlers/FileFormatHandlerExtensions.cs b/src/Greenshot.Base/Core/FileFormatHandlers/FileFormatHandlerExtensions.cs index 918bf1a64..618e20c17 100644 --- a/src/Greenshot.Base/Core/FileFormatHandlers/FileFormatHandlerExtensions.cs +++ b/src/Greenshot.Base/Core/FileFormatHandlers/FileFormatHandlerExtensions.cs @@ -56,10 +56,7 @@ namespace Greenshot.Base.Core.FileFormatHandlers /// IEnumerable{IFileFormatHandler} /// /// - public static IEnumerable ExtensionsFor(this IEnumerable fileFormatHandlers, FileFormatHandlerActions fileFormatHandlerAction) - { - return fileFormatHandlers.Where(ffh => ffh.SupportedExtensions.ContainsKey(fileFormatHandlerAction)).SelectMany(ffh => ffh.SupportedExtensions[fileFormatHandlerAction]).Distinct().OrderBy(e => e); - } + public static IEnumerable ExtensionsFor(this IEnumerable fileFormatHandlers, FileFormatHandlerActions fileFormatHandlerAction) => fileFormatHandlers.Where(ffh => ffh.SupportedExtensions.ContainsKey(fileFormatHandlerAction)).SelectMany(ffh => ffh.SupportedExtensions[fileFormatHandlerAction]).Distinct().OrderBy(e => e); /// /// Extension method to check if a certain IFileFormatHandler supports a certain action with a specific extension @@ -98,12 +95,11 @@ namespace Greenshot.Base.Core.FileFormatHandlers return false; } - foreach (var fileFormatHandler in saveFileFormatHandlers) + foreach (var _ in from fileFormatHandler in saveFileFormatHandlers + where fileFormatHandler.TrySaveToStream(bitmap, destination, extension, surface) + select new { }) { - if (fileFormatHandler.TrySaveToStream(bitmap, destination, extension, surface)) - { - return true; - } + return true; } return false; diff --git a/src/Greenshot.Base/Core/FilenameHelper.cs b/src/Greenshot.Base/Core/FilenameHelper.cs index 83cb0d4ec..09ad85fc0 100644 --- a/src/Greenshot.Base/Core/FilenameHelper.cs +++ b/src/Greenshot.Base/Core/FilenameHelper.cs @@ -103,25 +103,13 @@ namespace Greenshot.Base.Core return path; } - public static string GetFilenameWithoutExtensionFromPattern(string pattern) - { - return GetFilenameWithoutExtensionFromPattern(pattern, null); - } + public static string GetFilenameWithoutExtensionFromPattern(string pattern) => GetFilenameWithoutExtensionFromPattern(pattern, null); - public static string GetFilenameWithoutExtensionFromPattern(string pattern, ICaptureDetails captureDetails) - { - return FillPattern(pattern, captureDetails, true); - } + public static string GetFilenameWithoutExtensionFromPattern(string pattern, ICaptureDetails captureDetails) => FillPattern(pattern, captureDetails, true); - public static string GetFilenameFromPattern(string pattern, OutputFormat imageFormat) - { - return GetFilenameFromPattern(pattern, imageFormat, null); - } + public static string GetFilenameFromPattern(string pattern, OutputFormat imageFormat) => GetFilenameFromPattern(pattern, imageFormat, null); - public static string GetFilenameFromPattern(string pattern, OutputFormat imageFormat, ICaptureDetails captureDetails) - { - return FillPattern(pattern, captureDetails, true) + "." + imageFormat.ToString().ToLower(); - } + public static string GetFilenameFromPattern(string pattern, OutputFormat imageFormat, ICaptureDetails captureDetails) => FillPattern(pattern, captureDetails, true) + "." + imageFormat.ToString().ToLower(); /// /// Return a filename for the current image format (png,jpg etc) with the default file pattern diff --git a/src/Greenshot.Base/Core/GreenshotResources.cs b/src/Greenshot.Base/Core/GreenshotResources.cs index 36f102f26..17dbcd23f 100644 --- a/src/Greenshot.Base/Core/GreenshotResources.cs +++ b/src/Greenshot.Base/Core/GreenshotResources.cs @@ -31,19 +31,10 @@ namespace Greenshot.Base.Core { private static readonly ComponentResourceManager GreenshotResourceManager = new(typeof(GreenshotResources)); - public static Image GetImage(string imageName) - { - return (Image)GreenshotResourceManager.GetObject(imageName); - } + public static Image GetImage(string imageName) => (Image)GreenshotResourceManager.GetObject(imageName); - public static Icon GetIcon(string imageName) - { - return (Icon)GreenshotResourceManager.GetObject(imageName); - } + public static Icon GetIcon(string imageName) => (Icon)GreenshotResourceManager.GetObject(imageName); - public static Icon GetGreenshotIcon() - { - return GetIcon("Greenshot.Icon"); - } + public static Icon GetGreenshotIcon() => GetIcon("Greenshot.Icon"); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Core/IEHelper.cs b/src/Greenshot.Base/Core/IEHelper.cs index a03d09902..8de4f07a4 100644 --- a/src/Greenshot.Base/Core/IEHelper.cs +++ b/src/Greenshot.Base/Core/IEHelper.cs @@ -106,10 +106,7 @@ namespace Greenshot.Base.Core /// /// Name of the process /// true to ignore the doctype when loading a page - public static void FixBrowserVersion(string applicationName, bool ignoreDoctype = true) - { - FixBrowserVersion(applicationName, GetEmbVersion(ignoreDoctype)); - } + public static void FixBrowserVersion(string applicationName, bool ignoreDoctype = true) => FixBrowserVersion(applicationName, GetEmbVersion(ignoreDoctype)); /// /// Fix the browser version for the specified application diff --git a/src/Greenshot.Base/Core/ImageHelper.cs b/src/Greenshot.Base/Core/ImageHelper.cs index 458d5a4b4..6c49c119b 100644 --- a/src/Greenshot.Base/Core/ImageHelper.cs +++ b/src/Greenshot.Base/Core/ImageHelper.cs @@ -244,12 +244,9 @@ namespace Greenshot.Base.Core } } - if (!(NativePoint.Empty.Equals(min) && max.Equals(new NativePoint(area.Value.Width - 1, area.Value.Height - 1)))) + if (!(NativePoint.Empty.Equals(min) && max.Equals(new NativePoint(area.Value.Width - 1, area.Value.Height - 1))) && !(min.X == int.MaxValue || min.Y == int.MaxValue || max.X == int.MinValue || min.X == int.MinValue)) { - if (!(min.X == int.MaxValue || min.Y == int.MaxValue || max.X == int.MinValue || min.X == int.MinValue)) - { - cropNativeRect = new NativeRect(min.X, min.Y, max.X - min.X + 1, max.Y - min.Y + 1); - } + cropNativeRect = new NativeRect(min.X, min.Y, max.X - min.X + 1, max.Y - min.Y + 1); } return cropNativeRect; @@ -811,16 +808,9 @@ namespace Greenshot.Base.Core { Matrix00 = 0, Matrix11 = 0, - Matrix22 = 0 + Matrix22 = 0, + Matrix33 = useGdiBlur ? darkness + 0.1f : darkness }; - if (useGdiBlur) - { - maskMatrix.Matrix33 = darkness + 0.1f; - } - else - { - maskMatrix.Matrix33 = darkness; - } NativeRect shadowNativeRect = new(new NativePoint(shadowSize, shadowSize), sourceBitmap.Size); ApplyColorMatrix((Bitmap)sourceBitmap, NativeRect.Empty, returnImage, shadowNativeRect, maskMatrix); @@ -897,10 +887,7 @@ namespace Greenshot.Base.Core /// /// Image to apply matrix to /// ColorMatrix to apply - public static void ApplyColorMatrix(Bitmap source, ColorMatrix colorMatrix) - { - ApplyColorMatrix(source, NativeRect.Empty, source, NativeRect.Empty, colorMatrix); - } + public static void ApplyColorMatrix(Bitmap source, ColorMatrix colorMatrix) => ApplyColorMatrix(source, NativeRect.Empty, source, NativeRect.Empty, colorMatrix); /// /// Apply a color matrix by copying from the source to the destination @@ -1130,23 +1117,17 @@ namespace Greenshot.Base.Core /// /// PixelFormat to check /// bool if we support it - public static bool SupportsPixelFormat(PixelFormat pixelformat) - { - return pixelformat.Equals(PixelFormat.Format32bppArgb) || + public static bool SupportsPixelFormat(PixelFormat pixelformat) => pixelformat.Equals(PixelFormat.Format32bppArgb) || pixelformat.Equals(PixelFormat.Format32bppPArgb) || pixelformat.Equals(PixelFormat.Format32bppRgb) || pixelformat.Equals(PixelFormat.Format24bppRgb); - } /// /// Wrapper for just cloning which calls the CloneArea /// /// Image to clone /// Bitmap with clone image data - public static Image Clone(Image sourceImage) - { - return sourceImage is Metafile ? (Image)sourceImage.Clone() : CloneArea(sourceImage, NativeRect.Empty, PixelFormat.DontCare); - } + public static Image Clone(Image sourceImage) => sourceImage is Metafile ? (Image)sourceImage.Clone() : CloneArea(sourceImage, NativeRect.Empty, PixelFormat.DontCare); /// /// Wrapper for just cloning & TargetFormat which calls the CloneArea @@ -1154,10 +1135,7 @@ namespace Greenshot.Base.Core /// Image to clone /// Target Format, use PixelFormat.DontCare if you want the original (or a default if the source PixelFormat is not supported) /// Bitmap with clone image data - public static Bitmap Clone(Image sourceBitmap, PixelFormat targetFormat) - { - return CloneArea(sourceBitmap, NativeRect.Empty, targetFormat); - } + public static Bitmap Clone(Image sourceBitmap, PixelFormat targetFormat) => CloneArea(sourceBitmap, NativeRect.Empty, targetFormat); /// /// Clone an image, taking some rules into account: @@ -1176,14 +1154,9 @@ namespace Greenshot.Base.Core NativeRect bitmapRect = new(0, 0, sourceImage.Width, sourceImage.Height); // Make sure the source is not NativeRect.Empty - if (NativeRect.Empty.Equals(sourceRect)) - { - sourceRect = new NativeRect(0, 0, sourceImage.Width, sourceImage.Height); - } - else - { - sourceRect = sourceRect.Intersect(bitmapRect); - } + sourceRect = NativeRect.Empty.Equals(sourceRect) + ? new NativeRect(0, 0, sourceImage.Width, sourceImage.Height) + : sourceRect.Intersect(bitmapRect); // If no pixelformat is supplied if (targetFormat is PixelFormat.DontCare or PixelFormat.Undefined) @@ -1192,13 +1165,9 @@ namespace Greenshot.Base.Core { targetFormat = sourceImage.PixelFormat; } - else if (Image.IsAlphaPixelFormat(sourceImage.PixelFormat)) - { - targetFormat = PixelFormat.Format32bppArgb; - } else { - targetFormat = PixelFormat.Format24bppRgb; + targetFormat = Image.IsAlphaPixelFormat(sourceImage.PixelFormat) ? PixelFormat.Format32bppArgb : PixelFormat.Format24bppRgb; } } @@ -1369,10 +1338,7 @@ namespace Greenshot.Base.Core /// /// /// - public static Image ResizeImage(Image sourceImage, bool maintainAspectRatio, int newWidth, int newHeight, Matrix matrix) - { - return ResizeImage(sourceImage, maintainAspectRatio, false, Color.Empty, newWidth, newHeight, matrix); - } + public static Image ResizeImage(Image sourceImage, bool maintainAspectRatio, int newWidth, int newHeight, Matrix matrix) => ResizeImage(sourceImage, maintainAspectRatio, false, Color.Empty, newWidth, newHeight, matrix); /// /// Count how many times the supplied color exists diff --git a/src/Greenshot.Base/Core/JSONHelper.cs b/src/Greenshot.Base/Core/JSONHelper.cs index df08540c0..22d018305 100644 --- a/src/Greenshot.Base/Core/JSONHelper.cs +++ b/src/Greenshot.Base/Core/JSONHelper.cs @@ -84,51 +84,50 @@ namespace Greenshot.Base.Core while (!done) { token = LookAhead(json, index); - if (token == TOKEN_NONE) + switch (token) { - success = false; - return null; - } - else if (token == TOKEN_COMMA) - { - NextToken(json, ref index); - } - else if (token == TOKEN_CURLY_CLOSE) - { - NextToken(json, ref index); - return table; - } - else - { - // name - string name = ParseString(json, ref index, ref success); - if (!success) - { + case TOKEN_NONE: success = false; return null; - } + case TOKEN_COMMA: + NextToken(json, ref index); + break; + case TOKEN_CURLY_CLOSE: + NextToken(json, ref index); + return table; + default: + { + // name + string name = ParseString(json, ref index, ref success); + if (!success) + { + success = false; + return null; + } - // : - token = NextToken(json, ref index); - if (token != TOKEN_COLON) - { - success = false; - return null; - } + // : + token = NextToken(json, ref index); + if (token != TOKEN_COLON) + { + success = false; + return null; + } - // value - object value = ParseValue(json, ref index, ref success); - if (!success) - { - success = false; - return null; - } + // value + object value = ParseValue(json, ref index, ref success); + if (!success) + { + success = false; + return null; + } - table.Add(name, value); + table.Add(name, value); + break; + } } } - return table; + // return table; } protected static IList ParseArray(char[] json, ref int index, ref bool success) @@ -391,43 +390,34 @@ namespace Greenshot.Base.Core int remainingLength = json.Length - index; // false - if (remainingLength >= 5) - { - if (json[index] == 'f' && + if (remainingLength >= 5 && json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e') - { - index += 5; - return TOKEN_FALSE; - } + { + index += 5; + return TOKEN_FALSE; } // true - if (remainingLength >= 4) - { - if (json[index] == 't' && + if (remainingLength >= 4 && json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e') - { - index += 4; - return TOKEN_TRUE; - } + { + index += 4; + return TOKEN_TRUE; } // null - if (remainingLength >= 4) - { - if (json[index] == 'n' && + if (remainingLength >= 4 && json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l') - { - index += 4; - return TOKEN_NULL; - } + { + index += 4; + return TOKEN_NULL; } return TOKEN_NONE; diff --git a/src/Greenshot.Base/Core/Language.cs b/src/Greenshot.Base/Core/Language.cs index 5a413eb24..bd9fc3f62 100644 --- a/src/Greenshot.Base/Core/Language.cs +++ b/src/Greenshot.Base/Core/Language.cs @@ -328,13 +328,7 @@ namespace Greenshot.Base.Core /// /// Return the path to the help-file /// - public static string HelpFilePath - { - get - { - return HelpFiles.ContainsKey(_currentLanguage) ? HelpFiles[_currentLanguage] : HelpFiles[DefaultLanguage]; - } - } + public static string HelpFilePath => HelpFiles.ContainsKey(_currentLanguage) ? HelpFiles[_currentLanguage] : HelpFiles[DefaultLanguage]; /// /// Load the resources from the language file @@ -573,20 +567,14 @@ namespace Greenshot.Base.Core /// /// /// true if available - public static bool HasKey(string prefix, string key) - { - return HasKey(prefix + "." + key); - } + public static bool HasKey(string prefix, string key) => HasKey(prefix + "." + key); /// /// Check if a resource with key exists /// /// /// true if available - public static bool HasKey(string key) - { - return key != null && Resources.ContainsKey(key); - } + public static bool HasKey(string key) => key != null && Resources.ContainsKey(key); /// /// TryGet method which combines HasKey & GetString @@ -594,10 +582,7 @@ namespace Greenshot.Base.Core /// /// out string /// - public static bool TryGetString(string key, out string languageString) - { - return Resources.TryGetValue(key, out languageString); - } + public static bool TryGetString(string key, out string languageString) => Resources.TryGetValue(key, out languageString); /// /// TryGet method which combines HasKey & GetString @@ -606,10 +591,7 @@ namespace Greenshot.Base.Core /// string with key /// out string /// - public static bool TryGetString(string prefix, string key, out string languageString) - { - return Resources.TryGetValue(prefix + "." + key, out languageString); - } + public static bool TryGetString(string prefix, string key, out string languageString) => Resources.TryGetValue(prefix + "." + key, out languageString); /// /// TryGet method which combines HasKey & GetString @@ -618,10 +600,7 @@ namespace Greenshot.Base.Core /// Enum with key /// out string /// - public static bool TryGetString(string prefix, Enum key, out string languageString) - { - return Resources.TryGetValue(prefix + "." + key, out languageString); - } + public static bool TryGetString(string prefix, Enum key, out string languageString) => Resources.TryGetValue(prefix + "." + key, out languageString); /// /// Translate @@ -640,10 +619,7 @@ namespace Greenshot.Base.Core /// /// Enum /// resource or a "string ###key### not found" - public static string GetString(Enum key) - { - return key == null ? null : GetString(key.ToString()); - } + public static string GetString(Enum key) => key == null ? null : GetString(key.ToString()); /// /// Get the resource for prefix.key @@ -651,10 +627,7 @@ namespace Greenshot.Base.Core /// string /// Enum /// resource or a "string ###prefix.key### not found" - public static string GetString(string prefix, Enum key) - { - return key == null ? null : GetString(prefix + "." + key); - } + public static string GetString(string prefix, Enum key) => key == null ? null : GetString(prefix + "." + key); /// /// Get the resource for prefix.key @@ -662,10 +635,7 @@ namespace Greenshot.Base.Core /// string /// string /// resource or a "string ###prefix.key### not found" - public static string GetString(string prefix, string key) - { - return GetString(prefix + "." + key); - } + public static string GetString(string prefix, string key) => GetString(prefix + "." + key); /// /// Get the resource for key @@ -688,10 +658,7 @@ namespace Greenshot.Base.Core /// Enum /// object /// formatted resource or a "string ###key### not found" - public static string GetFormattedString(Enum key, object param) - { - return GetFormattedString(key.ToString(), param); - } + public static string GetFormattedString(Enum key, object param) => GetFormattedString(key.ToString(), param); /// /// Get the resource for prefix.key, format with with string.format an supply the parameters @@ -700,10 +667,7 @@ namespace Greenshot.Base.Core /// Enum /// object /// formatted resource or a "string ###prefix.key### not found" - public static string GetFormattedString(string prefix, Enum key, object param) - { - return GetFormattedString(prefix, key.ToString(), param); - } + public static string GetFormattedString(string prefix, Enum key, object param) => GetFormattedString(prefix, key.ToString(), param); /// /// Get the resource for prefix.key, format with with string.format an supply the parameters @@ -712,10 +676,7 @@ namespace Greenshot.Base.Core /// string /// object /// formatted resource or a "string ###prefix.key### not found" - public static string GetFormattedString(string prefix, string key, object param) - { - return GetFormattedString(prefix + "." + key, param); - } + public static string GetFormattedString(string prefix, string key, object param) => GetFormattedString(prefix + "." + key, param); /// /// Get the resource for key, format with with string.format an supply the parameters @@ -723,9 +684,6 @@ namespace Greenshot.Base.Core /// string /// object /// formatted resource or a "string ###key### not found" - public static string GetFormattedString(string key, object param) - { - return !Resources.TryGetValue(key, out var returnValue) ? "string ###" + key + "### not found" : string.Format(returnValue, param); - } + public static string GetFormattedString(string key, object param) => !Resources.TryGetValue(key, out var returnValue) ? "string ###" + key + "### not found" : string.Format(returnValue, param); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Core/NetworkHelper.cs b/src/Greenshot.Base/Core/NetworkHelper.cs index 01390f094..fbdb82de1 100644 --- a/src/Greenshot.Base/Core/NetworkHelper.cs +++ b/src/Greenshot.Base/Core/NetworkHelper.cs @@ -214,10 +214,7 @@ namespace Greenshot.Base.Core /// /// string with uri to connect to /// WebRequest - public static HttpWebRequest CreateWebRequest(string uri) - { - return CreateWebRequest(new Uri(uri)); - } + public static HttpWebRequest CreateWebRequest(string uri) => CreateWebRequest(new Uri(uri)); /// /// Helper method to create a web request with a lot of default settings @@ -225,10 +222,7 @@ namespace Greenshot.Base.Core /// string with uri to connect to /// /// Method to use /// WebRequest - public static HttpWebRequest CreateWebRequest(string uri, HTTPMethod method) - { - return CreateWebRequest(new Uri(uri), method); - } + public static HttpWebRequest CreateWebRequest(string uri, HTTPMethod method) => CreateWebRequest(new Uri(uri), method); /// /// Helper method to create a web request with a lot of default settings @@ -593,10 +587,7 @@ namespace Greenshot.Base.Core /// The request object. /// The response data. /// TODO: This method should handle the StatusCode better! - public static string GetResponseAsString(HttpWebRequest webRequest) - { - return GetResponseAsString(webRequest, false); - } + public static string GetResponseAsString(HttpWebRequest webRequest) => GetResponseAsString(webRequest, false); /// /// Read the response as string @@ -766,11 +757,9 @@ namespace Greenshot.Base.Core /// A plain "write data to stream" /// /// - public void WriteToStream(Stream dataStream) - { + public void WriteToStream(Stream dataStream) => // Write the file data directly to the Stream, rather than serializing it to a string. ImageIO.SaveToStream(_surface, dataStream, _outputSettings); - } /// /// Upload the Surface as image to the webrequest diff --git a/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs b/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs index fe9ff0498..cfd240a98 100644 --- a/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs +++ b/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs @@ -71,13 +71,7 @@ Greenshot received information from CloudServiceName. You can close this browser /// /// The URL to redirect to /// - protected string RedirectUri - { - get - { - return !string.IsNullOrEmpty(_redirectUri) ? _redirectUri : (_redirectUri = string.Format(LoopbackCallbackUrl, GetRandomUnusedPort())); - } - } + protected string RedirectUri => !string.IsNullOrEmpty(_redirectUri) ? _redirectUri : (_redirectUri = string.Format(LoopbackCallbackUrl, GetRandomUnusedPort())); private string _cloudServiceName; diff --git a/src/Greenshot.Base/Core/OAuth/OAuth2Helper.cs b/src/Greenshot.Base/Core/OAuth/OAuth2Helper.cs index d18c2dcf6..137009a89 100644 --- a/src/Greenshot.Base/Core/OAuth/OAuth2Helper.cs +++ b/src/Greenshot.Base/Core/OAuth/OAuth2Helper.cs @@ -135,12 +135,9 @@ namespace Greenshot.Base.Core.OAuth { var expiresIn = callbackParameters[ExpiresIn]; settings.AccessTokenExpires = DateTimeOffset.MaxValue; - if (expiresIn != null) + if (expiresIn != null && double.TryParse(expiresIn, out var seconds)) { - if (double.TryParse(expiresIn, out var seconds)) - { - settings.AccessTokenExpires = DateTimeOffset.Now.AddSeconds(seconds); - } + settings.AccessTokenExpires = DateTimeOffset.Now.AddSeconds(seconds); } } @@ -393,12 +390,9 @@ namespace Greenshot.Base.Core.OAuth public static void CheckAndAuthenticateOrRefresh(OAuth2Settings settings) { // Get Refresh / Access token - if (string.IsNullOrEmpty(settings.RefreshToken)) + if (string.IsNullOrEmpty(settings.RefreshToken) && !Authorize(settings)) { - if (!Authorize(settings)) - { - throw new Exception("Authentication cancelled"); - } + throw new Exception("Authentication cancelled"); } if (settings.IsAccessTokenExpired) diff --git a/src/Greenshot.Base/Core/OAuth/OAuthSession.cs b/src/Greenshot.Base/Core/OAuth/OAuthSession.cs index 340c46297..c98d59527 100644 --- a/src/Greenshot.Base/Core/OAuth/OAuthSession.cs +++ b/src/Greenshot.Base/Core/OAuth/OAuthSession.cs @@ -29,6 +29,7 @@ using System.Text; using System.Threading; using Greenshot.Base.Controls; using log4net; +using System.Linq; namespace Greenshot.Base.Core.OAuth { @@ -219,11 +220,9 @@ namespace Greenshot.Base.Core.OAuth /// Generate a nonce /// /// - public static string GenerateNonce() - { + public static string GenerateNonce() => // Just a simple implementation of a random number between 123400 and 9999999 - return random.Next(123400, 9999999).ToString(); - } + random.Next(123400, 9999999).ToString(); /// /// Get the request token using the consumer key and secret. Also initializes tokensecret @@ -270,19 +269,16 @@ namespace Greenshot.Base.Core.OAuth Log.DebugFormat("Opening AuthorizationLink: {0}", AuthorizationLink); OAuthLoginForm oAuthLoginForm = new(LoginTitle, BrowserSize, AuthorizationLink, CallbackUrl); oAuthLoginForm.ShowDialog(); - if (oAuthLoginForm.IsOk) + if (oAuthLoginForm.IsOk && oAuthLoginForm.CallbackParameters != null) { - if (oAuthLoginForm.CallbackParameters != null) + if (oAuthLoginForm.CallbackParameters.TryGetValue(OAUTH_TOKEN_KEY, out var tokenValue)) { - if (oAuthLoginForm.CallbackParameters.TryGetValue(OAUTH_TOKEN_KEY, out var tokenValue)) - { - Token = tokenValue; - } + Token = tokenValue; + } - if (oAuthLoginForm.CallbackParameters.TryGetValue(OAUTH_VERIFIER_KEY, out var verifierValue)) - { - Verifier = verifierValue; - } + if (oAuthLoginForm.CallbackParameters.TryGetValue(OAUTH_VERIFIER_KEY, out var verifierValue)) + { + Verifier = verifierValue; } } @@ -383,10 +379,7 @@ namespace Greenshot.Base.Core.OAuth /// 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); - } + IBinaryContainer postData) => MakeOAuthRequest(method, requestUrl, requestUrl, null, parametersToSign, additionalParameters, postData); /// /// Submit a web request using oAuth. @@ -399,10 +392,7 @@ namespace Greenshot.Base.Core.OAuth /// 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); - } + IDictionary additionalParameters, IBinaryContainer postData) => MakeOAuthRequest(method, requestUrl, requestUrl, headers, parametersToSign, additionalParameters, postData); /// /// Submit a web request using oAuth. @@ -415,10 +405,7 @@ namespace Greenshot.Base.Core.OAuth /// 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); - } + IDictionary additionalParameters, IBinaryContainer postData) => MakeOAuthRequest(method, signUrl, requestUrl, null, parametersToSign, additionalParameters, postData); /// /// Submit a web request using oAuth. @@ -444,12 +431,9 @@ namespace Greenshot.Base.Core.OAuth while (retries-- > 0) { // If we are not trying to get a Authorization or Accestoken, and we don't have a token, create one - if (string.IsNullOrEmpty(Token)) + if (string.IsNullOrEmpty(Token) && (!AutoLogin || !Authorize())) { - if (!AutoLogin || !Authorize()) - { - throw new Exception("Not authorized"); - } + throw new Exception("Not authorized"); } try @@ -480,14 +464,9 @@ namespace Greenshot.Base.Core.OAuth TokenSecret = null; // Remove oauth keys, so they aren't added double List keysToDelete = new(); - foreach (string parameterKey in parametersToSign.Keys) - { - if (parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX)) - { - keysToDelete.Add(parameterKey); - } - } - + keysToDelete.AddRange(from string parameterKey in parametersToSign.Keys + where parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX) + select parameterKey); foreach (string keyToDelete in keysToDelete) { parametersToSign.Remove(keyToDelete); @@ -632,13 +611,10 @@ namespace Greenshot.Base.Core.OAuth requestParameters = parameters; } - if (HTTPMethod.GET == method || postData != null) + if ((HTTPMethod.GET == method || postData != null) && requestParameters.Count > 0) { - if (requestParameters.Count > 0) - { - // Add the parameters to the request - requestUrl += "?" + NetworkHelper.GenerateQueryParameters(requestParameters); - } + // Add the parameters to the request + requestUrl += "?" + NetworkHelper.GenerateQueryParameters(requestParameters); } // Create webrequest diff --git a/src/Greenshot.Base/Core/PluginUtils.cs b/src/Greenshot.Base/Core/PluginUtils.cs index 9e51c122c..8aad3acb4 100644 --- a/src/Greenshot.Base/Core/PluginUtils.cs +++ b/src/Greenshot.Base/Core/PluginUtils.cs @@ -42,10 +42,7 @@ namespace Greenshot.Base.Core private const string PathKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\"; private static readonly IDictionary ExeIconCache = new Dictionary(); - static PluginUtils() - { - CoreConfig.PropertyChanged += OnIconSizeChanged; - } + static PluginUtils() => CoreConfig.PropertyChanged += OnIconSizeChanged; /// /// Clear icon cache diff --git a/src/Greenshot.Base/Core/QuantizerHelper.cs b/src/Greenshot.Base/Core/QuantizerHelper.cs index efdb78d82..8577f7425 100644 --- a/src/Greenshot.Base/Core/QuantizerHelper.cs +++ b/src/Greenshot.Base/Core/QuantizerHelper.cs @@ -113,13 +113,10 @@ namespace Greenshot.Base.Core protected virtual void Dispose(bool disposing) { - if (disposing) + if (disposing && resultBitmap != null) { - if (resultBitmap != null) - { - resultBitmap.Dispose(); - resultBitmap = null; - } + resultBitmap.Dispose(); + resultBitmap = null; } } @@ -174,15 +171,9 @@ namespace Greenshot.Base.Core { for (int x = 0; x < sourceFastBitmap.Width; x++) { - Color color; - if (sourceFastBitmap is not IFastBitmapWithBlend sourceFastBitmapWithBlend) - { - color = sourceFastBitmap.GetColorAt(x, y); - } - else - { - color = sourceFastBitmapWithBlend.GetBlendedColorAt(x, y); - } + Color color = sourceFastBitmap is not IFastBitmapWithBlend sourceFastBitmapWithBlend + ? sourceFastBitmap.GetColorAt(x, y) + : sourceFastBitmapWithBlend.GetBlendedColorAt(x, y); // To count the colors int index = color.ToArgb() & 0x00ffffff; @@ -216,10 +207,7 @@ namespace Greenshot.Base.Core /// /// See for more details. /// - public int GetColorCount() - { - return colorCount; - } + public int GetColorCount() => colorCount; /// /// Reindex the 24/32 BPP (A)RGB image to a 8BPP @@ -240,16 +228,7 @@ namespace Greenshot.Base.Core { for (int x = 0; x < bbbSrc.Width; x++) { - Color color; - if (bbbSrc is IFastBitmapWithBlend bbbSrcBlend) - { - color = bbbSrcBlend.GetBlendedColorAt(x, y); - } - else - { - color = bbbSrc.GetColorAt(x, y); - } - + Color color = bbbSrc is IFastBitmapWithBlend bbbSrcBlend ? bbbSrcBlend.GetBlendedColorAt(x, y) : bbbSrc.GetColorAt(x, y); if (lookup.ContainsKey(color)) { index = lookup[color]; @@ -271,14 +250,7 @@ namespace Greenshot.Base.Core Color[] entries = imagePalette.Entries; for (int paletteIndex = 0; paletteIndex < 256; paletteIndex++) { - if (paletteIndex < colorCount) - { - entries[paletteIndex] = colors[paletteIndex]; - } - else - { - entries[paletteIndex] = Color.Black; - } + entries[paletteIndex] = paletteIndex < colorCount ? colors[paletteIndex] : Color.Black; } resultBitmap.Palette = imagePalette; @@ -527,9 +499,7 @@ namespace Greenshot.Base.Core /// /// Computes the volume of the cube in a specific moment. /// - private static long Volume(WuColorCube cube, long[,,] moment) - { - return moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] - + private static long Volume(WuColorCube cube, long[,,] moment) => moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] - moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] - moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] + moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] - @@ -537,14 +507,11 @@ namespace Greenshot.Base.Core moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] + moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] - moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum]; - } /// /// Computes the volume of the cube in a specific moment. For the floating-point values. /// - private static float VolumeFloat(WuColorCube cube, float[,,] moment) - { - return moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] - + private static float VolumeFloat(WuColorCube cube, float[,,] moment) => moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] - moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] - moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] + moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] - @@ -552,53 +519,46 @@ namespace Greenshot.Base.Core moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] + moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] - moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum]; - } /// /// Splits the cube in given position, and color direction. /// - private static long Top(WuColorCube cube, int direction, int position, long[,,] moment) + private static long Top(WuColorCube cube, int direction, int position, long[,,] moment) => direction switch { - return direction switch - { - RED => moment[position, cube.GreenMaximum, cube.BlueMaximum] - - moment[position, cube.GreenMaximum, cube.BlueMinimum] - - moment[position, cube.GreenMinimum, cube.BlueMaximum] + - moment[position, cube.GreenMinimum, cube.BlueMinimum], - GREEN => moment[cube.RedMaximum, position, cube.BlueMaximum] - - moment[cube.RedMaximum, position, cube.BlueMinimum] - - moment[cube.RedMinimum, position, cube.BlueMaximum] + - moment[cube.RedMinimum, position, cube.BlueMinimum], - BLUE => moment[cube.RedMaximum, cube.GreenMaximum, position] - - moment[cube.RedMaximum, cube.GreenMinimum, position] - - moment[cube.RedMinimum, cube.GreenMaximum, position] + - moment[cube.RedMinimum, cube.GreenMinimum, position], - _ => 0, - }; - } + RED => moment[position, cube.GreenMaximum, cube.BlueMaximum] - + moment[position, cube.GreenMaximum, cube.BlueMinimum] - + moment[position, cube.GreenMinimum, cube.BlueMaximum] + + moment[position, cube.GreenMinimum, cube.BlueMinimum], + GREEN => moment[cube.RedMaximum, position, cube.BlueMaximum] - + moment[cube.RedMaximum, position, cube.BlueMinimum] - + moment[cube.RedMinimum, position, cube.BlueMaximum] + + moment[cube.RedMinimum, position, cube.BlueMinimum], + BLUE => moment[cube.RedMaximum, cube.GreenMaximum, position] - + moment[cube.RedMaximum, cube.GreenMinimum, position] - + moment[cube.RedMinimum, cube.GreenMaximum, position] + + moment[cube.RedMinimum, cube.GreenMinimum, position], + _ => 0, + }; /// /// Splits the cube in a given color direction at its minimum. /// - private static long Bottom(WuColorCube cube, int direction, long[,,] moment) + private static long Bottom(WuColorCube cube, int direction, long[,,] moment) => direction switch { - return direction switch - { - RED => -moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMaximum] + - moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] + - moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] - - moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum], - GREEN => -moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] + - moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] + - moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] - - moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum], - BLUE => -moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] + - moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] + - moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] - - moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum], - _ => 0 - }; - } + RED => -moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMaximum] + + moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] + + moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] - + moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum], + GREEN => -moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] + + moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] + + moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] - + moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum], + BLUE => -moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] + + moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] + + moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] - + moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum], + _ => 0 + }; /// /// Calculates statistical variance for a given cube. @@ -703,14 +663,7 @@ namespace Greenshot.Base.Core } else { - if ((maxGreen >= maxRed) && (maxGreen >= maxBlue)) - { - direction = GREEN; - } - else - { - direction = BLUE; - } + direction = (maxGreen >= maxRed) && (maxGreen >= maxBlue) ? GREEN : BLUE; } second.RedMaximum = first.RedMaximum; diff --git a/src/Greenshot.Base/Core/SimpleServiceProvider.cs b/src/Greenshot.Base/Core/SimpleServiceProvider.cs index c72d5b9bd..fe9441e91 100644 --- a/src/Greenshot.Base/Core/SimpleServiceProvider.cs +++ b/src/Greenshot.Base/Core/SimpleServiceProvider.cs @@ -20,10 +20,7 @@ namespace Greenshot.Base.Core return !_services.TryGetValue(typeOfService, out var results) ? Array.Empty() : (IReadOnlyList)results.Cast().ToArray(); } - public TService GetInstance() - { - return GetAllInstances().SingleOrDefault(); - } + public TService GetInstance() => GetAllInstances().SingleOrDefault(); public void AddService(IEnumerable services) { @@ -45,9 +42,6 @@ namespace Greenshot.Base.Core } } - public void AddService(params TService[] services) - { - AddService(services.AsEnumerable()); - } + public void AddService(params TService[] services) => AddService(services.AsEnumerable()); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Core/StringExtensions.cs b/src/Greenshot.Base/Core/StringExtensions.cs index 4db75b166..2fc9d7903 100644 --- a/src/Greenshot.Base/Core/StringExtensions.cs +++ b/src/Greenshot.Base/Core/StringExtensions.cs @@ -41,10 +41,7 @@ namespace Greenshot.Base.Core /// String with formatting, like {name} /// Object used for the formatting /// Formatted string - public static string FormatWith(this string format, object source) - { - return FormatWith(format, null, source); - } + public static string FormatWith(this string format, object source) => FormatWith(format, null, source); /// /// Format the string "format" with the source @@ -85,7 +82,7 @@ namespace Greenshot.Base.Core RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); List values = new(); - string rewrittenFormat = r.Replace(format, delegate (Match m) + string rewrittenFormat = r.Replace(format, (Match m) => { Group startGroup = m.Groups["start"]; Group propertyGroup = m.Groups["property"]; diff --git a/src/Greenshot.Base/Core/WindowCapture.cs b/src/Greenshot.Base/Core/WindowCapture.cs index 564ce9a65..1a2f07d5a 100644 --- a/src/Greenshot.Base/Core/WindowCapture.cs +++ b/src/Greenshot.Base/Core/WindowCapture.cs @@ -41,6 +41,7 @@ using Dapplo.Windows.User32.Structs; using Greenshot.Base.IniFile; using Greenshot.Base.Interfaces; using log4net; +using System.Linq; namespace Greenshot.Base.Core { @@ -59,10 +60,7 @@ namespace Greenshot.Base.Core /// /// Point with cursor location, relative to the top left corner of the monitor setup (which itself might actually not be on any screen) /// - public static NativePoint GetCursorLocationRelativeToScreenBounds() - { - return GetLocationRelativeToScreenBounds(User32Api.GetCursorLocation()); - } + public static NativePoint GetCursorLocationRelativeToScreenBounds() => GetLocationRelativeToScreenBounds(User32Api.GetCursorLocation()); /// /// Converts locationRelativeToScreenOrigin to be relative to top left corner of all screen bounds, which might @@ -338,13 +336,9 @@ namespace Greenshot.Base.Core { // Collect all screens inside this capture List screensInsideCapture = new(); - foreach (Screen screen in Screen.AllScreens) - { - if (screen.Bounds.IntersectsWith(captureBounds)) - { - screensInsideCapture.Add(screen); - } - } + screensInsideCapture.AddRange(from Screen screen in Screen.AllScreens + where screen.Bounds.IntersectsWith(captureBounds) + select screen); // Check all all screens are of an equal size bool offscreenContent; diff --git a/src/Greenshot.Base/Core/WindowDetails.cs b/src/Greenshot.Base/Core/WindowDetails.cs index e614841d3..39566c8cc 100644 --- a/src/Greenshot.Base/Core/WindowDetails.cs +++ b/src/Greenshot.Base/Core/WindowDetails.cs @@ -78,10 +78,7 @@ namespace Greenshot.Base.Core } } - internal static bool IsIgnoreHandle(IntPtr handle) - { - return IgnoreHandles.Contains(handle); - } + internal static bool IsIgnoreHandle(IntPtr handle) => IgnoreHandles.Contains(handle); private IList _childWindows; private IntPtr _parentHandle = IntPtr.Zero; @@ -106,15 +103,9 @@ namespace Greenshot.Base.Core /// objects for the same Window will be equal. /// /// The Window Handle for this window - public override int GetHashCode() - { - return Handle.ToInt32(); - } + public override int GetHashCode() => Handle.ToInt32(); - public override bool Equals(object right) - { - return Equals(right as WindowDetails); - } + public override bool Equals(object right) => Equals(right as WindowDetails); /// /// Compare two windows details @@ -144,18 +135,12 @@ namespace Greenshot.Base.Core /// /// Freeze information updates /// - public void FreezeDetails() - { - _frozen = true; - } + public void FreezeDetails() => _frozen = true; /// /// Make the information update again. /// - public void UnfreezeDetails() - { - _frozen = false; - } + public void UnfreezeDetails() => _frozen = false; /// /// Get the file path to the exe for the process which owns this window @@ -270,19 +255,13 @@ namespace Greenshot.Base.Core /// Use this to make remove internal windows, like the mainform and the captureforms, invisible /// /// - public static void RegisterIgnoreHandle(IntPtr ignoreHandle) - { - IgnoreHandles.Add(ignoreHandle); - } + public static void RegisterIgnoreHandle(IntPtr ignoreHandle) => IgnoreHandles.Add(ignoreHandle); /// /// Use this to remove the with RegisterIgnoreHandle registered handle /// /// - public static void UnregisterIgnoreHandle(IntPtr ignoreHandle) - { - IgnoreHandles.Remove(ignoreHandle); - } + public static void UnregisterIgnoreHandle(IntPtr ignoreHandle) => IgnoreHandles.Remove(ignoreHandle); public IList Children { @@ -302,12 +281,11 @@ namespace Greenshot.Base.Core /// public WindowDetails GetChild(string childClassname) { - foreach (var child in Children) + foreach (var child in from child in Children + where childClassname.Equals(child.ClassName) + select child) { - if (childClassname.Equals(child.ClassName)) - { - return child; - } + return child; } return null; @@ -361,10 +339,7 @@ namespace Greenshot.Base.Core /// Retrieve all the children, this only stores the children internally. /// One should normally use the getter "Children" /// - public IList GetChildren() - { - return _childWindows ?? GetChildren(0); - } + public IList GetChildren() => _childWindows ?? GetChildren(0); /// /// Retrieve all the children, this only stores the children internally, use the "Children" property for the value @@ -467,22 +442,14 @@ namespace Greenshot.Base.Core /// /// Returns if this window is cloaked /// - public bool IsCloaked - { - get => DwmApi.IsWindowCloaked(Handle); - } + public bool IsCloaked => DwmApi.IsWindowCloaked(Handle); /// /// Gets whether the window is visible. /// - public bool Visible - { - get - { + public bool Visible => // Tip from Raymond Chen https://devblogs.microsoft.com/oldnewthing/20200302-00/?p=103507 - return !IsCloaked && User32Api.IsWindowVisible(Handle); - } - } + !IsCloaked && User32Api.IsWindowVisible(Handle); public bool HasParent { @@ -543,14 +510,11 @@ namespace Greenshot.Base.Core if (DwmApi.IsDwmEnabled) { bool gotFrameBounds = GetExtendedFrameBounds(out windowRect); - if (IsWin10App) + // Pre-Cache for maximized call, this is only on Windows 8 apps (full screen) + if (IsWin10App && gotFrameBounds) { - // Pre-Cache for maximized call, this is only on Windows 8 apps (full screen) - if (gotFrameBounds) - { - _previousWindowRectangle = windowRect; - _lastWindowRectangleRetrieveTime = now; - } + _previousWindowRectangle = windowRect; + _lastWindowRectangleRetrieveTime = now; } if (gotFrameBounds && WindowsVersion.IsWindows10OrLater && !Maximised) @@ -564,13 +528,10 @@ namespace Greenshot.Base.Core } } - if (windowRect.IsEmpty) + if (windowRect.IsEmpty && !GetWindowRect(out windowRect)) { - if (!GetWindowRect(out windowRect)) - { - Win32Error error = Win32.GetLastErrorCode(); - Log.WarnFormat("Couldn't retrieve the windows rectangle: {0}", Win32.GetMessage(error)); - } + Win32Error error = Win32.GetLastErrorCode(); + Log.WarnFormat("Couldn't retrieve the windows rectangle: {0}", Win32.GetMessage(error)); } _lastWindowRectangleRetrieveTime = now; @@ -588,18 +549,12 @@ namespace Greenshot.Base.Core /// /// Gets the location of the window relative to the screen. /// - public NativePoint Location - { - get => WindowRectangle.Location; - } + public NativePoint Location => WindowRectangle.Location; /// /// Gets the size of the window. /// - public NativeSize Size - { - get => WindowRectangle.Size; - } + public NativeSize Size => WindowRectangle.Size; /// /// Get the client rectangle, this is the part of the window inside the borders (drawable area) @@ -623,10 +578,7 @@ namespace Greenshot.Base.Core /// /// Point with the coordinates to check /// true if the point lies within - public bool Contains(NativePoint p) - { - return WindowRectangle.Contains(p); - } + public bool Contains(NativePoint p) => WindowRectangle.Contains(p); /// /// Restores and Brings the window to the front, @@ -796,18 +748,15 @@ namespace Greenshot.Base.Core captureRectangle = captureRectangle.Inflate(Conf.Win10BorderCrop); } - if (autoMode) + // check if the capture fits + if (autoMode && !doesCaptureFit) { - // check if the capture fits - if (!doesCaptureFit) + // if GDI is allowed.. (a screenshot won't be better than we comes if we continue) + using Process thisWindowProcess = Process; + if (WindowCapture.IsGdiAllowed(thisWindowProcess)) { - // if GDI is allowed.. (a screenshot won't be better than we comes if we continue) - using Process thisWindowProcess = Process; - if (WindowCapture.IsGdiAllowed(thisWindowProcess)) - { - // we return null which causes the capturing code to try another method. - return null; - } + // we return null which causes the capturing code to try another method. + return null; } } } @@ -894,26 +843,20 @@ namespace Greenshot.Base.Core capturedBitmap = WindowCapture.CaptureRectangle(captureRectangle); } - if (capturedBitmap != null) + // Only if the Inivalue is set, not maximized and it's not a tool window. + // Not needed for Windows 8 + if (capturedBitmap != null && !WindowsVersion.IsWindows8OrLater && Conf.WindowCaptureRemoveCorners && !Maximised && (ExtendedWindowStyle & ExtendedWindowStyleFlags.WS_EX_TOOLWINDOW) == 0) { - // Not needed for Windows 8 - if (!WindowsVersion.IsWindows8OrLater) + // Remove corners + if (!Image.IsAlphaPixelFormat(capturedBitmap.PixelFormat)) { - // Only if the Inivalue is set, not maximized and it's not a tool window. - if (Conf.WindowCaptureRemoveCorners && !Maximised && (ExtendedWindowStyle & ExtendedWindowStyleFlags.WS_EX_TOOLWINDOW) == 0) - { - // Remove corners - if (!Image.IsAlphaPixelFormat(capturedBitmap.PixelFormat)) - { - Log.Debug("Changing pixelformat to Alpha for the RemoveCorners"); - Bitmap tmpBitmap = ImageHelper.Clone(capturedBitmap, PixelFormat.Format32bppArgb); - capturedBitmap.Dispose(); - capturedBitmap = tmpBitmap; - } - - RemoveCorners(capturedBitmap); - } + Log.Debug("Changing pixelformat to Alpha for the RemoveCorners"); + Bitmap tmpBitmap = ImageHelper.Clone(capturedBitmap, PixelFormat.Format32bppArgb); + capturedBitmap.Dispose(); + capturedBitmap = tmpBitmap; } + + RemoveCorners(capturedBitmap); } } finally @@ -1076,14 +1019,7 @@ namespace Greenshot.Base.Core var windowInfo = new WindowInfo(); // Get the Window Info for this window bool result = User32Api.GetWindowInfo(Handle, ref windowInfo); - if (IsHidden(windowInfo.Bounds)) - { - rectangle = NativeRect.Empty; - } - else - { - rectangle = result ? windowInfo.Bounds : NativeRect.Empty; - } + rectangle = IsHidden(windowInfo.Bounds) ? NativeRect.Empty : result ? windowInfo.Bounds : NativeRect.Empty; return result; } @@ -1146,10 +1082,7 @@ namespace Greenshot.Base.Core /// /// Set the window as foreground window /// - public void ToForeground() - { - ToForeground(Handle); - } + public void ToForeground() => ToForeground(Handle); /// /// Get the region for a window @@ -1178,7 +1111,7 @@ namespace Greenshot.Base.Core return false; } - if (titleOrProcessname.ToLower().Contains("greenshot")) + if (titleOrProcessname.IndexOf("greenshot", StringComparison.CurrentCultureIgnoreCase) >= 0) { return false; } @@ -1339,10 +1272,7 @@ namespace Greenshot.Base.Core /// the specified Window Handle. /// /// The Window Handle - public WindowDetails(IntPtr hWnd) - { - Handle = hWnd; - } + public WindowDetails(IntPtr hWnd) => Handle = hWnd; /// /// Gets an instance of the current active foreground window @@ -1370,28 +1300,19 @@ namespace Greenshot.Base.Core /// Gets the Desktop window /// /// WindowDetails for the desktop window - public static WindowDetails GetDesktopWindow() - { - return new WindowDetails(User32Api.GetDesktopWindow()); - } + public static WindowDetails GetDesktopWindow() => new(User32Api.GetDesktopWindow()); /// /// Get all the top level windows /// /// List of WindowDetails with all the top level windows - public static IList GetAllWindows() - { - return GetAllWindows(null); - } + public static IList GetAllWindows() => GetAllWindows(null); /// /// Get all the top level windows, with matching classname /// /// List WindowDetails with all the top level windows - public static IList GetAllWindows(string classname) - { - return new WindowsEnumerator().GetWindows(IntPtr.Zero, classname).Items; - } + public static IList GetAllWindows(string classname) => new WindowsEnumerator().GetWindows(IntPtr.Zero, classname).Items; /// /// Recursive "find children which" @@ -1618,13 +1539,7 @@ namespace Greenshot.Base.Core /// Return true if the metro-app-launcher is visible /// /// - public static bool IsAppLauncherVisible - { - get - { - return AppVisibility != null && AppVisibility.IsLauncherVisible; - } - } + public static bool IsAppLauncherVisible => AppVisibility?.IsLauncherVisible == true; /// /// Make a string representation of the window details diff --git a/src/Greenshot.Base/Core/WindowsVersion.cs b/src/Greenshot.Base/Core/WindowsVersion.cs index b7e883f72..a8531b564 100644 --- a/src/Greenshot.Base/Core/WindowsVersion.cs +++ b/src/Greenshot.Base/Core/WindowsVersion.cs @@ -62,9 +62,6 @@ namespace Greenshot.Base.Core /// /// int /// bool - public static bool IsWindows10BuildOrLater(int minimalBuildNumber) - { - return IsWindows10 && WinVersion.Build >= minimalBuildNumber; - } + public static bool IsWindows10BuildOrLater(int minimalBuildNumber) => IsWindows10 && WinVersion.Build >= minimalBuildNumber; } } \ No newline at end of file diff --git a/src/Greenshot.Base/Core/WmInputLangChangeRequestFilter.cs b/src/Greenshot.Base/Core/WmInputLangChangeRequestFilter.cs index 26d36ff14..01a5c770d 100644 --- a/src/Greenshot.Base/Core/WmInputLangChangeRequestFilter.cs +++ b/src/Greenshot.Base/Core/WmInputLangChangeRequestFilter.cs @@ -38,10 +38,7 @@ namespace Greenshot.Base.Core /// /// Message /// true if the message should be filtered - public bool PreFilterMessage(ref Message m) - { - return PreFilterMessageExternal(ref m); - } + public bool PreFilterMessage(ref Message m) => PreFilterMessageExternal(ref m); /// /// Also used in the MainForm WndProc diff --git a/src/Greenshot.Base/Effects/AdjustEffect.cs b/src/Greenshot.Base/Effects/AdjustEffect.cs index d6448eec9..74bced2b7 100644 --- a/src/Greenshot.Base/Effects/AdjustEffect.cs +++ b/src/Greenshot.Base/Effects/AdjustEffect.cs @@ -30,10 +30,7 @@ namespace Greenshot.Base.Effects /// public class AdjustEffect : IEffect { - public AdjustEffect() - { - Reset(); - } + public AdjustEffect() => Reset(); public float Contrast { get; set; } public float Brightness { get; set; } @@ -46,9 +43,6 @@ namespace Greenshot.Base.Effects Gamma = 1f; } - public Image Apply(Image sourceImage, Matrix matrix) - { - return ImageHelper.Adjust(sourceImage, Brightness, Contrast, Gamma); - } + public Image Apply(Image sourceImage, Matrix matrix) => ImageHelper.Adjust(sourceImage, Brightness, Contrast, Gamma); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Effects/BorderEffect.cs b/src/Greenshot.Base/Effects/BorderEffect.cs index 9fd3b33b5..165111c45 100644 --- a/src/Greenshot.Base/Effects/BorderEffect.cs +++ b/src/Greenshot.Base/Effects/BorderEffect.cs @@ -30,10 +30,7 @@ namespace Greenshot.Base.Effects /// public class BorderEffect : IEffect { - public BorderEffect() - { - Reset(); - } + public BorderEffect() => Reset(); public Color Color { get; set; } public int Width { get; set; } @@ -44,9 +41,6 @@ namespace Greenshot.Base.Effects Color = Color.Black; } - public Image Apply(Image sourceImage, Matrix matrix) - { - return ImageHelper.CreateBorder(sourceImage, Width, Color, sourceImage.PixelFormat, matrix); - } + public Image Apply(Image sourceImage, Matrix matrix) => ImageHelper.CreateBorder(sourceImage, Width, Color, sourceImage.PixelFormat, matrix); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Effects/DropShadowEffect.cs b/src/Greenshot.Base/Effects/DropShadowEffect.cs index b597e4463..af1b4d4e8 100644 --- a/src/Greenshot.Base/Effects/DropShadowEffect.cs +++ b/src/Greenshot.Base/Effects/DropShadowEffect.cs @@ -34,10 +34,7 @@ namespace Greenshot.Base.Effects [TypeConverter(typeof(EffectConverter))] public class DropShadowEffect : IEffect { - public DropShadowEffect() - { - Reset(); - } + public DropShadowEffect() => Reset(); public float Darkness { get; set; } @@ -52,9 +49,6 @@ namespace Greenshot.Base.Effects ShadowOffset = new Point(-1, -1); } - public virtual Image Apply(Image sourceImage, Matrix matrix) - { - return ImageHelper.CreateShadow(sourceImage, Darkness, ShadowSize, ShadowOffset, matrix, PixelFormat.Format32bppArgb); - } + public virtual Image Apply(Image sourceImage, Matrix matrix) => ImageHelper.CreateShadow(sourceImage, Darkness, ShadowSize, ShadowOffset, matrix, PixelFormat.Format32bppArgb); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Effects/GrayscaleEffect.cs b/src/Greenshot.Base/Effects/GrayscaleEffect.cs index 72535a12b..64db54e6b 100644 --- a/src/Greenshot.Base/Effects/GrayscaleEffect.cs +++ b/src/Greenshot.Base/Effects/GrayscaleEffect.cs @@ -30,10 +30,7 @@ namespace Greenshot.Base.Effects /// public class GrayscaleEffect : IEffect { - public Image Apply(Image sourceImage, Matrix matrix) - { - return ImageHelper.CreateGrayscale(sourceImage); - } + public Image Apply(Image sourceImage, Matrix matrix) => ImageHelper.CreateGrayscale(sourceImage); public void Reset() { diff --git a/src/Greenshot.Base/Effects/InvertEffect.cs b/src/Greenshot.Base/Effects/InvertEffect.cs index 939ad9d49..2372a545d 100644 --- a/src/Greenshot.Base/Effects/InvertEffect.cs +++ b/src/Greenshot.Base/Effects/InvertEffect.cs @@ -30,10 +30,7 @@ namespace Greenshot.Base.Effects /// public class InvertEffect : IEffect { - public Image Apply(Image sourceImage, Matrix matrix) - { - return ImageHelper.CreateNegative(sourceImage); - } + public Image Apply(Image sourceImage, Matrix matrix) => ImageHelper.CreateNegative(sourceImage); public void Reset() { diff --git a/src/Greenshot.Base/Effects/MonochromeEffect.cs b/src/Greenshot.Base/Effects/MonochromeEffect.cs index 8928bf09c..78b74c4dc 100644 --- a/src/Greenshot.Base/Effects/MonochromeEffect.cs +++ b/src/Greenshot.Base/Effects/MonochromeEffect.cs @@ -33,19 +33,13 @@ namespace Greenshot.Base.Effects private readonly byte _threshold; /// Threshold for monochrome filter (0 - 255), lower value means less black - public MonochromeEffect(byte threshold) - { - _threshold = threshold; - } + 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); - } + public Image Apply(Image sourceImage, Matrix matrix) => ImageHelper.CreateMonochrome(sourceImage, _threshold); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Effects/ReduceColorsEffect.cs b/src/Greenshot.Base/Effects/ReduceColorsEffect.cs index bca3ae680..1d0136836 100644 --- a/src/Greenshot.Base/Effects/ReduceColorsEffect.cs +++ b/src/Greenshot.Base/Effects/ReduceColorsEffect.cs @@ -34,17 +34,11 @@ namespace Greenshot.Base.Effects { private static readonly ILog Log = LogManager.GetLogger(typeof(ReduceColorsEffect)); - public ReduceColorsEffect() - { - Reset(); - } + public ReduceColorsEffect() => Reset(); public int Colors { get; set; } - public void Reset() - { - Colors = 256; - } + public void Reset() => Colors = 256; public Image Apply(Image sourceImage, Matrix matrix) { diff --git a/src/Greenshot.Base/Effects/ResizeCanvasEffect.cs b/src/Greenshot.Base/Effects/ResizeCanvasEffect.cs index 87fca1aef..ce3590324 100644 --- a/src/Greenshot.Base/Effects/ResizeCanvasEffect.cs +++ b/src/Greenshot.Base/Effects/ResizeCanvasEffect.cs @@ -50,9 +50,6 @@ namespace Greenshot.Base.Effects // 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 Image Apply(Image sourceImage, Matrix matrix) => ImageHelper.ResizeCanvas(sourceImage, BackgroundColor, Left, Right, Top, Bottom, matrix); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Effects/ResizeEffect.cs b/src/Greenshot.Base/Effects/ResizeEffect.cs index bf6298445..7abb61b6c 100644 --- a/src/Greenshot.Base/Effects/ResizeEffect.cs +++ b/src/Greenshot.Base/Effects/ResizeEffect.cs @@ -46,9 +46,6 @@ namespace Greenshot.Base.Effects // values don't have a default value } - public Image Apply(Image sourceImage, Matrix matrix) - { - return ImageHelper.ResizeImage(sourceImage, MaintainAspectRatio, Width, Height, matrix); - } + public Image Apply(Image sourceImage, Matrix matrix) => ImageHelper.ResizeImage(sourceImage, MaintainAspectRatio, Width, Height, matrix); } } \ No newline at end of file diff --git a/src/Greenshot.Base/Effects/RotateEffect.cs b/src/Greenshot.Base/Effects/RotateEffect.cs index 86db7db21..8daf0a382 100644 --- a/src/Greenshot.Base/Effects/RotateEffect.cs +++ b/src/Greenshot.Base/Effects/RotateEffect.cs @@ -31,10 +31,7 @@ namespace Greenshot.Base.Effects /// public class RotateEffect : IEffect { - public RotateEffect(int angle) - { - Angle = angle; - } + public RotateEffect(int angle) => Angle = angle; public int Angle { get; set; } diff --git a/src/Greenshot.Base/Effects/TornEdgeEffect.cs b/src/Greenshot.Base/Effects/TornEdgeEffect.cs index 43dc75d39..edc9389cb 100644 --- a/src/Greenshot.Base/Effects/TornEdgeEffect.cs +++ b/src/Greenshot.Base/Effects/TornEdgeEffect.cs @@ -33,10 +33,7 @@ namespace Greenshot.Base.Effects [TypeConverter(typeof(EffectConverter))] public sealed class TornEdgeEffect : DropShadowEffect { - public TornEdgeEffect() - { - Reset(); - } + public TornEdgeEffect() => Reset(); public int ToothHeight { get; set; } public int HorizontalToothRange { get; set; } diff --git a/src/Greenshot.Base/IniFile/IniAttributes.cs b/src/Greenshot.Base/IniFile/IniAttributes.cs index 72c16126c..4d8e45245 100644 --- a/src/Greenshot.Base/IniFile/IniAttributes.cs +++ b/src/Greenshot.Base/IniFile/IniAttributes.cs @@ -29,10 +29,7 @@ namespace Greenshot.Base.IniFile [AttributeUsage(AttributeTargets.Class)] public class IniSectionAttribute : Attribute { - public IniSectionAttribute(string name) - { - Name = name; - } + public IniSectionAttribute(string name) => Name = name; public string Description; public string Name { get; set; } @@ -44,15 +41,9 @@ namespace Greenshot.Base.IniFile [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class IniPropertyAttribute : Attribute { - public IniPropertyAttribute() - { - Separator = ","; - } + public IniPropertyAttribute() => Separator = ","; - public IniPropertyAttribute(string name) : this() - { - Name = name; - } + public IniPropertyAttribute(string name) : this() => Name = name; public string Description { get; set; } public string Separator { get; set; } diff --git a/src/Greenshot.Base/IniFile/IniConfig.cs b/src/Greenshot.Base/IniFile/IniConfig.cs index c6e638b3e..604974b7d 100644 --- a/src/Greenshot.Base/IniFile/IniConfig.cs +++ b/src/Greenshot.Base/IniFile/IniConfig.cs @@ -26,6 +26,7 @@ using System.Reflection; using System.Text; using System.Threading; using log4net; +using System.Linq; namespace Greenshot.Base.IniFile { @@ -152,15 +153,9 @@ namespace Greenshot.Base.IniFile /// /// Get the location of the configuration /// - public static string ConfigLocation - { - get - { - return IsInitialized + public static string ConfigLocation => IsInitialized ? CreateIniLocation(_configName + IniExtension, false) : throw new InvalidOperationException("Ini configuration was not initialized!"); - } - } /// /// Create the location of the configuration file @@ -325,12 +320,11 @@ namespace Greenshot.Base.IniFile return; } - foreach (string fixedPropertyKey in fixedPropertiesForSection.Keys) + foreach (var fixedPropertyKey in from string fixedPropertyKey in fixedPropertiesForSection.Keys + where section.Values.ContainsKey(fixedPropertyKey) + select fixedPropertyKey) { - if (section.Values.ContainsKey(fixedPropertyKey)) - { - section.Values[fixedPropertyKey].IsFixed = true; - } + section.Values[fixedPropertyKey].IsFixed = true; } } @@ -409,10 +403,7 @@ namespace Greenshot.Base.IniFile /// /// IniSection Type to get the configuration for /// Filled instance of IniSection type which was supplied - public static T GetIniSection() where T : IniSection - { - return GetIniSection(true); - } + public static T GetIniSection() where T : IniSection => GetIniSection(true); /// /// diff --git a/src/Greenshot.Base/IniFile/IniSection.cs b/src/Greenshot.Base/IniFile/IniSection.cs index e88fa75a5..695020a04 100644 --- a/src/Greenshot.Base/IniFile/IniSection.cs +++ b/src/Greenshot.Base/IniFile/IniSection.cs @@ -25,6 +25,7 @@ using System.IO; using System.Reflection; using Greenshot.Base.Core; using log4net; +using System.Linq; namespace Greenshot.Base.IniFile { @@ -39,21 +40,12 @@ namespace Greenshot.Base.IniFile [NonSerialized] private readonly IDictionary values = new Dictionary(); [NonSerialized] private IniSectionAttribute iniSectionAttribute; - public IniSectionAttribute IniSectionAttribute - { - get - { - return iniSectionAttribute ??= GetIniSectionAttribute(GetType()); - } - } + public IniSectionAttribute IniSectionAttribute => iniSectionAttribute ??= GetIniSectionAttribute(GetType()); /// /// Get the dictionary with all the IniValues /// - public IDictionary Values - { - get { return values; } - } + public IDictionary Values => values; /// /// Flag to specify if values have been changed @@ -65,10 +57,7 @@ namespace Greenshot.Base.IniFile /// /// The property to return a default for /// object with the default value for the supplied property - public virtual object GetDefault(string property) - { - return null; - } + public virtual object GetDefault(string property) => null; /// /// This method will be called before converting the property, making to possible to correct a certain value @@ -77,10 +66,7 @@ namespace Greenshot.Base.IniFile /// The name of the property /// The string value of the property /// string with the propertyValue, modified or not... - public virtual string PreCheckValue(string propertyName, string propertyValue) - { - return propertyValue; - } + public virtual string PreCheckValue(string propertyName, string propertyValue) => propertyValue; /// /// This method will be called after reading the configuration, so eventually some corrections can be made @@ -129,29 +115,23 @@ namespace Greenshot.Base.IniFile public void Fill(IDictionary properties) { Type iniSectionType = GetType(); - // Iterate over the members and create IniValueContainers - foreach (FieldInfo fieldInfo in iniSectionType.GetFields()) + foreach (var (fieldInfo, iniPropertyAttribute) in + from FieldInfo fieldInfo in iniSectionType.GetFields() + where Attribute.IsDefined(fieldInfo, typeof(IniPropertyAttribute)) + let iniPropertyAttribute = (IniPropertyAttribute)fieldInfo.GetCustomAttributes(typeof(IniPropertyAttribute), false)[0] + where !Values.ContainsKey(iniPropertyAttribute.Name) + select (fieldInfo, iniPropertyAttribute)) { - if (Attribute.IsDefined(fieldInfo, typeof(IniPropertyAttribute))) - { - IniPropertyAttribute iniPropertyAttribute = (IniPropertyAttribute)fieldInfo.GetCustomAttributes(typeof(IniPropertyAttribute), false)[0]; - if (!Values.ContainsKey(iniPropertyAttribute.Name)) - { - Values[iniPropertyAttribute.Name] = new IniValue(this, fieldInfo, iniPropertyAttribute); - } - } + Values[iniPropertyAttribute.Name] = new IniValue(this, fieldInfo, iniPropertyAttribute); } foreach (PropertyInfo propertyInfo in iniSectionType.GetProperties()) { - if (Attribute.IsDefined(propertyInfo, typeof(IniPropertyAttribute))) + if (Attribute.IsDefined(propertyInfo, typeof(IniPropertyAttribute)) && !Values.ContainsKey(propertyInfo.Name)) { - if (!Values.ContainsKey(propertyInfo.Name)) - { - IniPropertyAttribute iniPropertyAttribute = (IniPropertyAttribute)propertyInfo.GetCustomAttributes(typeof(IniPropertyAttribute), false)[0]; - Values[iniPropertyAttribute.Name] = new IniValue(this, propertyInfo, iniPropertyAttribute); - } + IniPropertyAttribute iniPropertyAttribute = (IniPropertyAttribute)propertyInfo.GetCustomAttributes(typeof(IniPropertyAttribute), false)[0]; + Values[iniPropertyAttribute.Name] = new IniValue(this, propertyInfo, iniPropertyAttribute); } } @@ -161,12 +141,9 @@ namespace Greenshot.Base.IniFile try { iniValue.SetValueFromProperties(properties); - if (iniValue.Attributes.Encrypted) + if (iniValue.Attributes.Encrypted && iniValue.Value is string stringValue && stringValue.Length > 2) { - if (iniValue.Value is string stringValue && stringValue.Length > 2) - { - iniValue.Value = stringValue.Decrypt(); - } + iniValue.Value = stringValue.Decrypt(); } } catch (Exception ex) @@ -202,22 +179,16 @@ namespace Greenshot.Base.IniFile foreach (IniValue value in Values.Values) { - if (value.Attributes.Encrypted) + if (value.Attributes.Encrypted && value.Value is string stringValue && stringValue.Length > 2) { - if (value.Value is string stringValue && stringValue.Length > 2) - { - value.Value = stringValue.Encrypt(); - } + value.Value = stringValue.Encrypt(); } // Write the value value.Write(writer, onlyProperties); - if (value.Attributes.Encrypted) + if (value.Attributes.Encrypted && value.Value is string stringValue2 && stringValue2.Length > 2) { - if (value.Value is string stringValue && stringValue.Length > 2) - { - value.Value = stringValue.Decrypt(); - } + value.Value = stringValue2.Decrypt(); } } } diff --git a/src/Greenshot.Base/IniFile/IniValue.cs b/src/Greenshot.Base/IniFile/IniValue.cs index 2299e494a..34d776386 100644 --- a/src/Greenshot.Base/IniFile/IniValue.cs +++ b/src/Greenshot.Base/IniFile/IniValue.cs @@ -59,7 +59,7 @@ namespace Greenshot.Base.IniFile { get { - return Attributes != null && Attributes.FixedValue; + return Attributes?.FixedValue == true; } set { @@ -77,7 +77,7 @@ namespace Greenshot.Base.IniFile { get { - return Attributes != null && Attributes.Expert; + return Attributes?.Expert == true; } set { @@ -98,13 +98,7 @@ namespace Greenshot.Base.IniFile /// public bool IsVisible => !IsExpert; - public MemberInfo MemberInfo - { - get - { - return _propertyInfo == null ? _fieldInfo : _propertyInfo; - } - } + public MemberInfo MemberInfo => _propertyInfo == null ? _fieldInfo : _propertyInfo; /// /// Returns the IniSection this value is contained in @@ -193,12 +187,9 @@ namespace Greenshot.Base.IniFile } } - if (myValue == null) + if (myValue == null && Attributes.ExcludeIfNull) { - if (Attributes.ExcludeIfNull) - { - return; - } + return; } if (!onlyProperties) @@ -520,10 +511,7 @@ namespace Greenshot.Base.IniFile /// Override of ToString which calls the ConvertValueToString /// /// string representation of this - public override string ToString() - { - return ConvertValueToString(ValueType, Value, Attributes.Separator); - } + public override string ToString() => ConvertValueToString(ValueType, Value, Attributes.Separator); /// /// Convert the supplied value to a string diff --git a/src/Greenshot.Base/Interfaces/Drawing/IField.cs b/src/Greenshot.Base/Interfaces/Drawing/IField.cs index 8bbaaae66..b3dd16b42 100644 --- a/src/Greenshot.Base/Interfaces/Drawing/IField.cs +++ b/src/Greenshot.Base/Interfaces/Drawing/IField.cs @@ -57,9 +57,6 @@ namespace Greenshot.Base.Interfaces.Drawing { public IField Field { get; private set; } - public FieldChangedEventArgs(IField field) - { - Field = field; - } + public FieldChangedEventArgs(IField field) => Field = field; } } \ No newline at end of file diff --git a/src/Greenshot.Base/Interfaces/IDestination.cs b/src/Greenshot.Base/Interfaces/IDestination.cs index bfb520c1e..3e548e28f 100644 --- a/src/Greenshot.Base/Interfaces/IDestination.cs +++ b/src/Greenshot.Base/Interfaces/IDestination.cs @@ -34,10 +34,7 @@ namespace Greenshot.Base.Interfaces DestinationDescription = destinationDescription; } - public ExportInformation(string destinationDesignation, string destinationDescription, bool exportMade) : this(destinationDesignation, destinationDescription) - { - ExportMade = exportMade; - } + public ExportInformation(string destinationDesignation, string destinationDescription, bool exportMade) : this(destinationDesignation, destinationDescription) => ExportMade = exportMade; public string DestinationDesignation { get; } diff --git a/src/Greenshot.Base/Interfaces/Ocr/Line.cs b/src/Greenshot.Base/Interfaces/Ocr/Line.cs index ff5914a4e..43b11e14c 100644 --- a/src/Greenshot.Base/Interfaces/Ocr/Line.cs +++ b/src/Greenshot.Base/Interfaces/Ocr/Line.cs @@ -77,10 +77,7 @@ namespace Greenshot.Base.Interfaces.Ocr /// /// Return the calculated bounds for the whole line /// - public NativeRect CalculatedBounds - { - get { return _calculatedBounds ??= CalculateBounds(); } - } + public NativeRect CalculatedBounds => _calculatedBounds ??= CalculateBounds(); /// /// Offset the words with the specified x and y coordinates diff --git a/src/Greenshot.Base/Interfaces/Plugin/SurfaceOutputSettings.cs b/src/Greenshot.Base/Interfaces/Plugin/SurfaceOutputSettings.cs index 68be7ebb6..7d867b1d7 100644 --- a/src/Greenshot.Base/Interfaces/Plugin/SurfaceOutputSettings.cs +++ b/src/Greenshot.Base/Interfaces/Plugin/SurfaceOutputSettings.cs @@ -41,20 +41,11 @@ namespace Greenshot.Base.Interfaces.Plugin ReduceColors = CoreConfig.OutputFileReduceColors; } - public SurfaceOutputSettings(OutputFormat format) : this() - { - Format = format; - } + public SurfaceOutputSettings(OutputFormat format) : this() => Format = format; - public SurfaceOutputSettings(OutputFormat format, int quality) : this(format) - { - JPGQuality = quality; - } + public SurfaceOutputSettings(OutputFormat format, int quality) : this(format) => JPGQuality = quality; - public SurfaceOutputSettings(OutputFormat format, int quality, bool reduceColors) : this(format, quality) - { - ReduceColors = reduceColors; - } + public SurfaceOutputSettings(OutputFormat format, int quality, bool reduceColors) : this(format, quality) => ReduceColors = reduceColors; /// /// BUG-2056 reported a logical issue, using greenshot format as the default causes issues with the external commands. @@ -84,7 +75,7 @@ namespace Greenshot.Base.Interfaces.Plugin get { // Fix for Bug #3468436, force quantizing when output format is gif as this has only 256 colors! - return OutputFormat.gif.Equals(Format) || _reduceColors; + return !(!OutputFormat.gif.Equals(Format) && !_reduceColors); } set { _reduceColors = value; } } diff --git a/src/Greenshot.Base/Interop/COMWrapper.cs b/src/Greenshot.Base/Interop/COMWrapper.cs index 3f75165a4..0ac8b10c2 100644 --- a/src/Greenshot.Base/Interop/COMWrapper.cs +++ b/src/Greenshot.Base/Interop/COMWrapper.cs @@ -232,10 +232,7 @@ namespace Greenshot.Base.Interop /// /// The full name of the intercepted type. /// - public override string ToString() - { - return _interceptType.FullName; - } + public override string ToString() => _interceptType.FullName; /// /// Returns the hash code of the wrapped object. @@ -243,10 +240,7 @@ namespace Greenshot.Base.Interop /// /// The hash code of the wrapped object. /// - public override int GetHashCode() - { - return _comObject.GetHashCode(); - } + public override int GetHashCode() => _comObject.GetHashCode(); /// /// Compares this object to another. @@ -259,12 +253,9 @@ namespace Greenshot.Base.Interop /// public override bool Equals(object value) { - if (value != null && RemotingServices.IsTransparentProxy(value)) + if (value != null && RemotingServices.IsTransparentProxy(value) && RemotingServices.GetRealProxy(value) is COMWrapper wrapper) { - if (RemotingServices.GetRealProxy(value) is COMWrapper wrapper) - { - return _comObject == wrapper._comObject; - } + return _comObject == wrapper._comObject; } return base.Equals(value); @@ -559,24 +550,21 @@ namespace Greenshot.Base.Interop { arg = Enum.Parse(byValType, arg.ToString()); } - else if (byValType.IsInterface) + else if (byValType.IsInterface && Marshal.IsComObject(arg)) { - if (Marshal.IsComObject(arg)) + wrapper = originalArgs[i]; + if (wrapper != null && wrapper._comObject != arg) { - wrapper = originalArgs[i]; - if (wrapper != null && wrapper._comObject != arg) - { - wrapper.Dispose(); - wrapper = null; - } - - if (wrapper == null) - { - wrapper = new COMWrapper(arg, byValType, _targetName); - } - - arg = wrapper.GetTransparentProxy(); + wrapper.Dispose(); + wrapper = null; } + + if (wrapper == null) + { + wrapper = new COMWrapper(arg, byValType, _targetName); + } + + arg = wrapper.GetTransparentProxy(); } outArgs[i] = arg; diff --git a/src/Greenshot.Base/Interop/ComProgIdAttribute.cs b/src/Greenshot.Base/Interop/ComProgIdAttribute.cs index f4e6fcebc..5d54efed9 100644 --- a/src/Greenshot.Base/Interop/ComProgIdAttribute.cs +++ b/src/Greenshot.Base/Interop/ComProgIdAttribute.cs @@ -70,10 +70,7 @@ namespace Greenshot.Base.Interop /// Constructor /// The COM ProgID. - public ComProgIdAttribute(string value) - { - Value = value; - } + public ComProgIdAttribute(string value) => Value = value; /// /// Returns the COM ProgID diff --git a/src/Greenshot.Editor/Controls/BindableToolStripButton.cs b/src/Greenshot.Editor/Controls/BindableToolStripButton.cs index a79d6c801..1fb80fbdd 100644 --- a/src/Greenshot.Editor/Controls/BindableToolStripButton.cs +++ b/src/Greenshot.Editor/Controls/BindableToolStripButton.cs @@ -36,14 +36,8 @@ namespace Greenshot.Editor.Controls [Category("Greenshot"), DefaultValue(null), Description("Specifies key of the language file to use when displaying the text.")] public string LanguageKey { get; set; } - public BindableToolStripButton() - { - CheckedChanged += BindableToolStripButton_CheckedChanged; - } + public BindableToolStripButton() => CheckedChanged += BindableToolStripButton_CheckedChanged; - private void BindableToolStripButton_CheckedChanged(object sender, EventArgs e) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Checked")); - } + private void BindableToolStripButton_CheckedChanged(object sender, EventArgs e) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Checked")); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Controls/BindableToolStripComboBox.cs b/src/Greenshot.Editor/Controls/BindableToolStripComboBox.cs index ac56641f1..c8a0de905 100644 --- a/src/Greenshot.Editor/Controls/BindableToolStripComboBox.cs +++ b/src/Greenshot.Editor/Controls/BindableToolStripComboBox.cs @@ -36,14 +36,8 @@ namespace Greenshot.Editor.Controls [Category("Greenshot"), DefaultValue(null), Description("Specifies key of the language file to use when displaying the text.")] public string LanguageKey { get; set; } - public BindableToolStripComboBox() - { - SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged; - } + public BindableToolStripComboBox() => SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged; - private void BindableToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedItem")); - } + private void BindableToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedItem")); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Controls/ColorButton.cs b/src/Greenshot.Editor/Controls/ColorButton.cs index 9e968afbc..6a01aeb62 100644 --- a/src/Greenshot.Editor/Controls/ColorButton.cs +++ b/src/Greenshot.Editor/Controls/ColorButton.cs @@ -41,10 +41,7 @@ namespace Greenshot.Editor.Controls [Category("Greenshot"), DefaultValue(null), Description("Specifies key of the language file to use when displaying the text.")] public string LanguageKey { get; set; } - public ColorButton() - { - Click += ColorButtonClick; - } + public ColorButton() => Click += ColorButtonClick; public Color SelectedColor { @@ -53,16 +50,7 @@ namespace Greenshot.Editor.Controls { _selectedColor = value; - Brush brush; - if (value != Color.Transparent) - { - brush = new SolidBrush(value); - } - else - { - brush = new HatchBrush(HatchStyle.Percent50, Color.White, Color.Gray); - } - + Brush brush = value != Color.Transparent ? new SolidBrush(value) : new HatchBrush(HatchStyle.Percent50, Color.White, Color.Gray); if (Image != null) { using Graphics graphics = Graphics.FromImage(Image); diff --git a/src/Greenshot.Editor/Controls/CustomToolStripProfessionalRenderer.cs b/src/Greenshot.Editor/Controls/CustomToolStripProfessionalRenderer.cs index 578aaf655..213ab8485 100644 --- a/src/Greenshot.Editor/Controls/CustomToolStripProfessionalRenderer.cs +++ b/src/Greenshot.Editor/Controls/CustomToolStripProfessionalRenderer.cs @@ -30,35 +30,17 @@ namespace Greenshot.Editor.Controls /// internal class CustomProfessionalColorTable : ProfessionalColorTable { - public override Color ToolStripGradientBegin - { - get { return SystemColors.Control; } - } + public override Color ToolStripGradientBegin => SystemColors.Control; - public override Color ToolStripGradientMiddle - { - get { return SystemColors.Control; } - } + public override Color ToolStripGradientMiddle => SystemColors.Control; - public override Color ToolStripGradientEnd - { - get { return SystemColors.Control; } - } + public override Color ToolStripGradientEnd => SystemColors.Control; - public override Color OverflowButtonGradientBegin - { - get { return SystemColors.Control; } - } + public override Color OverflowButtonGradientBegin => SystemColors.Control; - public override Color OverflowButtonGradientMiddle - { - get { return SystemColors.Control; } - } + public override Color OverflowButtonGradientMiddle => SystemColors.Control; - public override Color OverflowButtonGradientEnd - { - get { return SystemColors.Control; } - } + public override Color OverflowButtonGradientEnd => SystemColors.Control; } /// @@ -67,10 +49,7 @@ namespace Greenshot.Editor.Controls /// public class CustomToolStripProfessionalRenderer : ToolStripProfessionalRenderer { - public CustomToolStripProfessionalRenderer() : base(new CustomProfessionalColorTable()) - { - RoundedEdges = false; - } + public CustomToolStripProfessionalRenderer() : base(new CustomProfessionalColorTable()) => RoundedEdges = false; /// /// By overriding the OnRenderToolStripBorder we can make the ToolStrip without border diff --git a/src/Greenshot.Editor/Controls/NonJumpingPanel.cs b/src/Greenshot.Editor/Controls/NonJumpingPanel.cs index 3ce0fbdaf..fcdd40b96 100644 --- a/src/Greenshot.Editor/Controls/NonJumpingPanel.cs +++ b/src/Greenshot.Editor/Controls/NonJumpingPanel.cs @@ -29,12 +29,10 @@ namespace Greenshot.Editor.Controls /// public class NonJumpingPanel : Panel { - protected override Point ScrollToControl(Control activeControl) - { + protected override Point ScrollToControl(Control activeControl) => // Returning the current location prevents the panel from // scrolling to the active control when the panel loses and regains focus - return DisplayRectangle.Location; - } + DisplayRectangle.Location; /// /// Add horizontal scrolling to the panel, when using the wheel and the shift key is pressed diff --git a/src/Greenshot.Editor/Controls/Pipette.cs b/src/Greenshot.Editor/Controls/Pipette.cs index 9a07f235a..830a7ab72 100644 --- a/src/Greenshot.Editor/Controls/Pipette.cs +++ b/src/Greenshot.Editor/Controls/Pipette.cs @@ -78,10 +78,7 @@ namespace Greenshot.Editor.Controls /// /// The bulk of the clean-up code is implemented in Dispose(bool) /// - public new void Dispose() - { - Dispose(true); - } + public new void Dispose() => Dispose(true); /// /// This Dispose is called from the Dispose and the Destructor. @@ -176,15 +173,9 @@ namespace Greenshot.Editor.Controls public bool PreFilterMessage(ref Message m) { - if (_dragging) + if (_dragging && m.Msg == (int)WindowsMessages.WM_CHAR && (int)m.WParam == VkEsc) { - if (m.Msg == (int)WindowsMessages.WM_CHAR) - { - if ((int)m.WParam == VkEsc) - { - User32Api.ReleaseCapture(); - } - } + User32Api.ReleaseCapture(); } return false; @@ -195,9 +186,6 @@ namespace Greenshot.Editor.Controls { public Color Color; - public PipetteUsedArgs(Color c) - { - Color = c; - } + public PipetteUsedArgs(Color c) => Color = c; } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Controls/ToolStripColorButton.cs b/src/Greenshot.Editor/Controls/ToolStripColorButton.cs index eb05a0fcc..c0eae1707 100644 --- a/src/Greenshot.Editor/Controls/ToolStripColorButton.cs +++ b/src/Greenshot.Editor/Controls/ToolStripColorButton.cs @@ -39,10 +39,7 @@ namespace Greenshot.Editor.Controls private Color _selectedColor = Color.Transparent; - public ToolStripColorButton() - { - Click += ColorButtonClick; - } + public ToolStripColorButton() => Click += ColorButtonClick; public Color SelectedColor { @@ -51,16 +48,7 @@ namespace Greenshot.Editor.Controls { _selectedColor = value; - Brush brush; - if (value != Color.Transparent) - { - brush = new SolidBrush(value); - } - else - { - brush = new HatchBrush(HatchStyle.Percent50, Color.White, Color.Gray); - } - + Brush brush = value != Color.Transparent ? new SolidBrush(value) : new HatchBrush(HatchStyle.Percent50, Color.White, Color.Gray); if (Image != null) { using Graphics graphics = Graphics.FromImage(Image); diff --git a/src/Greenshot.Editor/Controls/ToolStripNumericUpDown.cs b/src/Greenshot.Editor/Controls/ToolStripNumericUpDown.cs index c8b41a4a5..7de612b60 100644 --- a/src/Greenshot.Editor/Controls/ToolStripNumericUpDown.cs +++ b/src/Greenshot.Editor/Controls/ToolStripNumericUpDown.cs @@ -79,9 +79,6 @@ namespace Greenshot.Editor.Controls NumericUpDown.ValueChanged -= _valueChanged; } - private void _valueChanged(object sender, EventArgs e) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value")); - } + private void _valueChanged(object sender, EventArgs e) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value")); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Destinations/EditorDestination.cs b/src/Greenshot.Editor/Destinations/EditorDestination.cs index 95d6d42ba..b465c97c3 100644 --- a/src/Greenshot.Editor/Destinations/EditorDestination.cs +++ b/src/Greenshot.Editor/Destinations/EditorDestination.cs @@ -48,22 +48,13 @@ namespace Greenshot.Editor.Destinations // Do not remove, is needed for the framework } - public EditorDestination(IImageEditor editor) - { - this.editor = editor; - } + public EditorDestination(IImageEditor editor) => this.editor = editor; public override string Designation => DESIGNATION; - public override string Description - { - get - { - return editor == null + public override string Description => editor == null ? Language.GetString(LangKey.settings_destination_editor) : Language.GetString(LangKey.settings_destination_editor) + " - " + editor.CaptureDetails.Title?.Substring(0, Math.Min(20, editor.CaptureDetails.Title.Length)); - } - } public override int Priority => 1; diff --git a/src/Greenshot.Editor/Drawing/Adorners/AbstractAdorner.cs b/src/Greenshot.Editor/Drawing/Adorners/AbstractAdorner.cs index c53f098c8..9b8efbe19 100644 --- a/src/Greenshot.Editor/Drawing/Adorners/AbstractAdorner.cs +++ b/src/Greenshot.Editor/Drawing/Adorners/AbstractAdorner.cs @@ -51,10 +51,7 @@ namespace Greenshot.Editor.Drawing.Adorners /// /// Returns the cursor for when the mouse is over the adorner /// - public virtual Cursor Cursor - { - get { return Cursors.SizeAll; } - } + public virtual Cursor Cursor => Cursors.SizeAll; public IDrawableContainer Owner { get; set; } @@ -92,10 +89,7 @@ namespace Greenshot.Editor.Drawing.Adorners /// /// /// - public virtual void MouseUp(object sender, MouseEventArgs mouseEventArgs) - { - EditStatus = EditStatus.IDLE; - } + public virtual void MouseUp(object sender, MouseEventArgs mouseEventArgs) => EditStatus = EditStatus.IDLE; /// /// Return the location of the adorner @@ -129,19 +123,13 @@ namespace Greenshot.Editor.Drawing.Adorners /// /// The adorner is active if the edit status is not idle or undrawn /// - public virtual bool IsActive - { - get { return EditStatus != EditStatus.IDLE && EditStatus != EditStatus.UNDRAWN; } - } + public virtual bool IsActive => EditStatus != EditStatus.IDLE && EditStatus != EditStatus.UNDRAWN; /// /// Adjust UI elements to the supplied DPI settings /// /// uint - public void AdjustToDpi(int dpi) - { - Size = DpiCalculator.ScaleWithDpi(DefaultSize, dpi); - } + public void AdjustToDpi(int dpi) => Size = DpiCalculator.ScaleWithDpi(DefaultSize, dpi); public Color OutlineColor { get; set; } = Color.White; public Color FillColor { get; set; } = Color.Black; diff --git a/src/Greenshot.Editor/Drawing/Adorners/MoveAdorner.cs b/src/Greenshot.Editor/Drawing/Adorners/MoveAdorner.cs index 61fc8de11..a898d4729 100644 --- a/src/Greenshot.Editor/Drawing/Adorners/MoveAdorner.cs +++ b/src/Greenshot.Editor/Drawing/Adorners/MoveAdorner.cs @@ -37,10 +37,7 @@ namespace Greenshot.Editor.Drawing.Adorners public Positions Position { get; private set; } - public MoveAdorner(IDrawableContainer owner, Positions position) : base(owner) - { - Position = position; - } + public MoveAdorner(IDrawableContainer owner, Positions position) : base(owner) => Position = position; /// /// Returns the cursor for when the mouse is over the adorner diff --git a/src/Greenshot.Editor/Drawing/Adorners/ResizeAdorner.cs b/src/Greenshot.Editor/Drawing/Adorners/ResizeAdorner.cs index 263d5a31e..4942c2780 100644 --- a/src/Greenshot.Editor/Drawing/Adorners/ResizeAdorner.cs +++ b/src/Greenshot.Editor/Drawing/Adorners/ResizeAdorner.cs @@ -37,10 +37,7 @@ namespace Greenshot.Editor.Drawing.Adorners public Positions Position { get; private set; } - public ResizeAdorner(IDrawableContainer owner, Positions position) : base(owner) - { - Position = position; - } + public ResizeAdorner(IDrawableContainer owner, Positions position) : base(owner) => Position = position; /// /// Returns the cursor for when the mouse is over the adorner diff --git a/src/Greenshot.Editor/Drawing/Adorners/TargetAdorner.cs b/src/Greenshot.Editor/Drawing/Adorners/TargetAdorner.cs index 11028df1d..d1e883af7 100644 --- a/src/Greenshot.Editor/Drawing/Adorners/TargetAdorner.cs +++ b/src/Greenshot.Editor/Drawing/Adorners/TargetAdorner.cs @@ -45,10 +45,7 @@ namespace Greenshot.Editor.Drawing.Adorners /// /// object /// MouseEventArgs - public override void MouseDown(object sender, MouseEventArgs mouseEventArgs) - { - EditStatus = EditStatus.MOVING; - } + public override void MouseDown(object sender, MouseEventArgs mouseEventArgs) => EditStatus = EditStatus.MOVING; /// /// Handle the mouse move diff --git a/src/Greenshot.Editor/Drawing/CropContainer.cs b/src/Greenshot.Editor/Drawing/CropContainer.cs index 5960c63c3..ae3f3536d 100644 --- a/src/Greenshot.Editor/Drawing/CropContainer.cs +++ b/src/Greenshot.Editor/Drawing/CropContainer.cs @@ -59,10 +59,7 @@ namespace Greenshot.Editor.Drawing Horizontal } - public CropContainer(ISurface parent) : base(parent) - { - Init(); - } + public CropContainer(ISurface parent) : base(parent) => Init(); protected override void OnDeserialized(StreamingContext streamingContext) { @@ -133,22 +130,13 @@ namespace Greenshot.Editor.Drawing AddField(GetType(), FieldType.CROPMODE, CropModes.Default); } - public override void Invalidate() - { - _parent?.Invalidate(); - } + public override void Invalidate() => _parent?.Invalidate(); /// /// We need to override the DrawingBound, return a rectangle in the size of the image, to make sure this element is always draw /// (we create a transparent brown over the complete picture) /// - public override NativeRect DrawingBounds - { - get - { - return _parent?.Image is { } image ? new NativeRect(0, 0, image.Width, image.Height) : NativeRect.Empty; - } - } + public override NativeRect DrawingBounds => _parent?.Image is { } image ? new NativeRect(0, 0, image.Width, image.Height) : NativeRect.Empty; public override void Draw(Graphics g, RenderMode rm) { @@ -195,17 +183,14 @@ namespace Greenshot.Editor.Drawing /// public override bool HasContextMenu => false; - public override bool HandleMouseDown(int x, int y) + public override bool HandleMouseDown(int x, int y) => GetFieldValue(FieldType.CROPMODE) switch { - return GetFieldValue(FieldType.CROPMODE) switch - { - //force horizontal crop to left edge - CropModes.Horizontal => base.HandleMouseDown(0, y), - //force vertical crop to top edge - CropModes.Vertical => base.HandleMouseDown(x, 0), - _ => base.HandleMouseDown(x, y), - }; - } + //force horizontal crop to left edge + CropModes.Horizontal => base.HandleMouseDown(0, y), + //force vertical crop to top edge + CropModes.Vertical => base.HandleMouseDown(x, 0), + _ => base.HandleMouseDown(x, y), + }; public override bool HandleMouseMove(int x, int y) { diff --git a/src/Greenshot.Editor/Drawing/CursorContainer.cs b/src/Greenshot.Editor/Drawing/CursorContainer.cs index a3bc851d7..47076a3d4 100644 --- a/src/Greenshot.Editor/Drawing/CursorContainer.cs +++ b/src/Greenshot.Editor/Drawing/CursorContainer.cs @@ -42,10 +42,7 @@ namespace Greenshot.Editor.Drawing protected Cursor cursor; - public CursorContainer(ISurface parent) : base(parent) - { - Init(); - } + public CursorContainer(ISurface parent) : base(parent) => Init(); protected override void OnDeserialized(StreamingContext streamingContext) { @@ -53,15 +50,9 @@ namespace Greenshot.Editor.Drawing Init(); } - private void Init() - { - CreateDefaultAdorners(); - } + private void Init() => CreateDefaultAdorners(); - public CursorContainer(ISurface parent, string filename) : this(parent) - { - Load(filename); - } + public CursorContainer(ISurface parent, string filename) : this(parent) => Load(filename); public Cursor Cursor { diff --git a/src/Greenshot.Editor/Drawing/DrawableContainer.cs b/src/Greenshot.Editor/Drawing/DrawableContainer.cs index f3236f25c..deedd7ee8 100644 --- a/src/Greenshot.Editor/Drawing/DrawableContainer.cs +++ b/src/Greenshot.Editor/Drawing/DrawableContainer.cs @@ -74,10 +74,7 @@ namespace Greenshot.Editor.Drawing protected EditStatus _defaultEditMode = EditStatus.DRAWING; - public EditStatus DefaultEditMode - { - get { return _defaultEditMode; } - } + public EditStatus DefaultEditMode => _defaultEditMode; /// /// The public accessible Dispose @@ -137,10 +134,7 @@ namespace Greenshot.Editor.Drawing set => SwitchParent(value); } - protected Surface InternalParent - { - get => (Surface)_parent; - } + protected Surface InternalParent => (Surface)_parent; [NonSerialized] private TargetAdorner _targetAdorner; public TargetAdorner TargetAdorner => _targetAdorner; @@ -153,7 +147,7 @@ namespace Greenshot.Editor.Drawing set { _selected = value; - OnPropertyChanged("Selected"); + OnPropertyChanged(nameof(Selected)); } } @@ -290,15 +284,9 @@ namespace Greenshot.Editor.Drawing _parent = parent; } - public void Add(IFilter filter) - { - AddChild(filter); - } + public void Add(IFilter filter) => AddChild(filter); - public void Remove(IFilter filter) - { - RemoveChild(filter); - } + public void Remove(IFilter filter) => RemoveChild(filter); private static int Round(float f) { @@ -352,10 +340,7 @@ namespace Greenshot.Editor.Drawing } } - public virtual bool InitContent() - { - return true; - } + public virtual bool InitContent() => true; public virtual void OnDoubleClick() { @@ -454,10 +439,7 @@ namespace Greenshot.Editor.Drawing // Empty as we do not want to add something to the context menu for every element } - public virtual bool Contains(int x, int y) - { - return Bounds.Contains(x, y); - } + public virtual bool Contains(int x, int y) => Bounds.Contains(x, y); public virtual bool ClickableAt(int x, int y) { @@ -608,20 +590,14 @@ namespace Greenshot.Editor.Drawing /// /// /// - public static float CalculateScaleY(Matrix matrix) - { - return matrix.Elements[M22]; - } + public static float CalculateScaleY(Matrix matrix) => matrix.Elements[M22]; /// /// Retrieve the X scale from the matrix /// /// /// - public static float CalculateScaleX(Matrix matrix) - { - return matrix.Elements[M11]; - } + public static float CalculateScaleX(Matrix matrix) => matrix.Elements[M11]; /// /// Retrieve the rotation angle from the matrix @@ -630,9 +606,8 @@ namespace Greenshot.Editor.Drawing /// public static int CalculateAngle(Matrix matrix) { - const int M11 = 0; const int M21 = 2; - var radians = Math.Atan2(matrix.Elements[M21], matrix.Elements[M11]); + var radians = Math.Atan2(matrix.Elements[M21], matrix.Elements[0]); return (int)-Math.Round(radians * 180 / Math.PI); } @@ -665,10 +640,7 @@ namespace Greenshot.Editor.Drawing Height = points[1].Y - points[0].Y; } - protected virtual IDoubleProcessor GetAngleRoundProcessor() - { - return ShapeAngleRoundBehavior.INSTANCE; - } + protected virtual IDoubleProcessor GetAngleRoundProcessor() => ShapeAngleRoundBehavior.INSTANCE; public virtual bool HasContextMenu => true; diff --git a/src/Greenshot.Editor/Drawing/DrawableContainerList.cs b/src/Greenshot.Editor/Drawing/DrawableContainerList.cs index c1a06a50a..f4804fa92 100644 --- a/src/Greenshot.Editor/Drawing/DrawableContainerList.cs +++ b/src/Greenshot.Editor/Drawing/DrawableContainerList.cs @@ -53,15 +53,9 @@ namespace Greenshot.Editor.Drawing { } - public DrawableContainerList(IEnumerable elements) - { - AddRange(elements); - } + public DrawableContainerList(IEnumerable elements) => AddRange(elements); - public DrawableContainerList(Guid parentId) - { - ParentID = parentId; - } + public DrawableContainerList(Guid parentId) => ParentID = parentId; public EditStatus Status { @@ -78,10 +72,7 @@ namespace Greenshot.Editor.Drawing public List AsIDrawableContainerList() { List interfaceList = new(); - foreach (IDrawableContainer container in this) - { - interfaceList.Add(container); - } + interfaceList.AddRange(this); return interfaceList; } @@ -275,12 +266,11 @@ namespace Greenshot.Editor.Drawing /// public bool IntersectsWith(NativeRect clipRectangle) { - foreach (var dc in this) + foreach (var _ in from dc in this + where dc.DrawingBounds.IntersectsWith(clipRectangle) + select new { }) { - if (dc.DrawingBounds.IntersectsWith(clipRectangle)) - { - return true; - } + return true; } return false; @@ -758,11 +748,9 @@ namespace Greenshot.Editor.Drawing } // This code added to correctly implement the disposable pattern. - public void Dispose() - { + public void Dispose() => // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); - } /// /// Adjust UI elements to the supplied DPI settings diff --git a/src/Greenshot.Editor/Drawing/EllipseContainer.cs b/src/Greenshot.Editor/Drawing/EllipseContainer.cs index 5b4816678..66263fa3a 100644 --- a/src/Greenshot.Editor/Drawing/EllipseContainer.cs +++ b/src/Greenshot.Editor/Drawing/EllipseContainer.cs @@ -38,10 +38,7 @@ namespace Greenshot.Editor.Drawing [Serializable()] public class EllipseContainer : DrawableContainer { - public EllipseContainer(ISurface parent) : base(parent) - { - Init(); - } + public EllipseContainer(ISurface parent) : base(parent) => Init(); protected override void OnDeserialized(StreamingContext streamingContext) { @@ -49,10 +46,7 @@ namespace Greenshot.Editor.Drawing Init(); } - private void Init() - { - CreateDefaultAdorners(); - } + private void Init() => CreateDefaultAdorners(); protected override void InitializeFields() { @@ -124,10 +118,7 @@ namespace Greenshot.Editor.Drawing } } - public override bool Contains(int x, int y) - { - return EllipseContains(this, x, y); - } + public override bool Contains(int x, int y) => EllipseContains(this, x, y); /// /// Allow the code to be used externally @@ -141,7 +132,7 @@ namespace Greenshot.Editor.Drawing double xDistanceFromCenter = x - (caller.Left + (caller.Width / 2)); double yDistanceFromCenter = y - (caller.Top + (caller.Height / 2)); // ellipse: x^2/a^2 + y^2/b^2 = 1 - return (Math.Pow(xDistanceFromCenter, 2) / Math.Pow(caller.Width / 2, 2)) + (Math.Pow(yDistanceFromCenter, 2) / Math.Pow(caller.Height / 2, 2)) < 1; + return (Math.Pow(xDistanceFromCenter, 2) / Math.Pow(caller.Width / 2F, 2)) + (Math.Pow(yDistanceFromCenter, 2) / Math.Pow(caller.Height / 2, 2)) < 1; } public override bool ClickableAt(int x, int y) @@ -155,12 +146,9 @@ namespace Greenshot.Editor.Drawing public static bool EllipseClickableAt(NativeRect rect, int lineThickness, Color fillColor, int x, int y) { // If we clicked inside the rectangle and it's visible we are clickable at. - if (!Color.Transparent.Equals(fillColor)) + if (!Color.Transparent.Equals(fillColor) && rect.Contains(x, y)) { - if (rect.Contains(x, y)) - { - return true; - } + return true; } // check the rest of the lines diff --git a/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolder.cs b/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolder.cs index 1bcc6c68b..16b6ab273 100644 --- a/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolder.cs +++ b/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolder.cs @@ -69,10 +69,7 @@ namespace Greenshot.Editor.Drawing.Fields } } - public void AddField(Type requestingType, IFieldType fieldType, object fieldValue) - { - AddField(EditorConfig.CreateField(requestingType, fieldType, fieldValue)); - } + public void AddField(Type requestingType, IFieldType fieldType, object fieldValue) => AddField(EditorConfig.CreateField(requestingType, fieldType, fieldValue)); public virtual void AddField(IField field) { @@ -82,12 +79,9 @@ namespace Greenshot.Editor.Drawing.Fields return; } - if (_fieldsByType.ContainsKey(field.FieldType)) + if (_fieldsByType.ContainsKey(field.FieldType) && LOG.IsDebugEnabled) { - if (LOG.IsDebugEnabled) - { - LOG.DebugFormat("A field with of type '{0}' already exists in this {1}, will overwrite.", field.FieldType, GetType()); - } + LOG.DebugFormat("A field with of type '{0}' already exists in this {1}, will overwrite.", field.FieldType, GetType()); } _fieldsByType[field.FieldType] = field; @@ -104,10 +98,7 @@ namespace Greenshot.Editor.Drawing.Fields _handlers.Remove(field); } - public IList GetFields() - { - return fields; - } + public IList GetFields() => fields; public IField GetField(IFieldType fieldType) { @@ -121,55 +112,25 @@ namespace Greenshot.Editor.Drawing.Fields } } - public object GetFieldValue(IFieldType fieldType) - { - return GetField(fieldType)?.Value; - } + public object GetFieldValue(IFieldType fieldType) => GetField(fieldType)?.Value; - public string GetFieldValueAsString(IFieldType fieldType) - { - return Convert.ToString(GetFieldValue(fieldType)); - } + public string GetFieldValueAsString(IFieldType fieldType) => Convert.ToString(GetFieldValue(fieldType)); - public int GetFieldValueAsInt(IFieldType fieldType) - { - return Convert.ToInt32(GetFieldValue(fieldType)); - } + public int GetFieldValueAsInt(IFieldType fieldType) => Convert.ToInt32(GetFieldValue(fieldType)); - public decimal GetFieldValueAsDecimal(IFieldType fieldType) - { - return Convert.ToDecimal(GetFieldValue(fieldType)); - } + public decimal GetFieldValueAsDecimal(IFieldType fieldType) => Convert.ToDecimal(GetFieldValue(fieldType)); - public double GetFieldValueAsDouble(IFieldType fieldType) - { - return Convert.ToDouble(GetFieldValue(fieldType)); - } + public double GetFieldValueAsDouble(IFieldType fieldType) => Convert.ToDouble(GetFieldValue(fieldType)); - public float GetFieldValueAsFloat(IFieldType fieldType) - { - return Convert.ToSingle(GetFieldValue(fieldType)); - } + public float GetFieldValueAsFloat(IFieldType fieldType) => Convert.ToSingle(GetFieldValue(fieldType)); - public bool GetFieldValueAsBool(IFieldType fieldType) - { - return Convert.ToBoolean(GetFieldValue(fieldType)); - } + public bool GetFieldValueAsBool(IFieldType fieldType) => Convert.ToBoolean(GetFieldValue(fieldType)); - public Color GetFieldValueAsColor(IFieldType fieldType, Color defaultColor = default) - { - return (Color)(GetFieldValue(fieldType) ?? defaultColor); - } + public Color GetFieldValueAsColor(IFieldType fieldType, Color defaultColor = default) => (Color)(GetFieldValue(fieldType) ?? defaultColor); - public bool HasField(IFieldType fieldType) - { - return _fieldsByType.ContainsKey(fieldType); - } + public bool HasField(IFieldType fieldType) => _fieldsByType.ContainsKey(fieldType); - public bool HasFieldValue(IFieldType fieldType) - { - return HasField(fieldType) && _fieldsByType[fieldType].HasValue; - } + public bool HasFieldValue(IFieldType fieldType) => HasField(fieldType) && _fieldsByType[fieldType].HasValue; public void SetFieldValue(IFieldType fieldType, object value) { @@ -183,9 +144,6 @@ namespace Greenshot.Editor.Drawing.Fields } } - protected void OnFieldChanged(object sender, FieldChangedEventArgs e) - { - _fieldChanged?.Invoke(sender, e); - } + protected void OnFieldChanged(object sender, FieldChangedEventArgs e) => _fieldChanged?.Invoke(sender, e); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolderWithChildren.cs b/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolderWithChildren.cs index 6116ad3cb..1eba099f1 100644 --- a/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolderWithChildren.cs +++ b/src/Greenshot.Editor/Drawing/Fields/AbstractFieldHolderWithChildren.cs @@ -23,6 +23,7 @@ using System; using System.Collections.Generic; using System.Runtime.Serialization; using Greenshot.Base.Interfaces.Drawing; +using System.Linq; namespace Greenshot.Editor.Drawing.Fields { @@ -46,10 +47,7 @@ namespace Greenshot.Editor.Drawing.Fields public IList Children = new List(); - protected AbstractFieldHolderWithChildren() - { - _fieldChangedEventHandler = OnFieldChanged; - } + protected AbstractFieldHolderWithChildren() => _fieldChangedEventHandler = OnFieldChanged; [OnDeserialized()] private void OnDeserialized(StreamingContext context) @@ -98,13 +96,12 @@ namespace Greenshot.Editor.Drawing.Fields } else { - foreach (IFieldHolder fh in Children) + foreach (var fh in from IFieldHolder fh in Children + where fh.HasField(fieldType) + select fh) { - if (fh.HasField(fieldType)) - { - ret = fh.GetField(fieldType); - break; - } + ret = fh.GetField(fieldType); + break; } } @@ -116,13 +113,12 @@ namespace Greenshot.Editor.Drawing.Fields bool ret = base.HasField(fieldType); if (!ret) { - foreach (IFieldHolder fh in Children) + foreach (var _ in from IFieldHolder fh in Children + where fh.HasField(fieldType) + select new { }) { - if (fh.HasField(fieldType)) - { - ret = true; - break; - } + ret = true; + break; } } diff --git a/src/Greenshot.Editor/Drawing/Fields/Binding/AbstractBindingConverter.cs b/src/Greenshot.Editor/Drawing/Fields/Binding/AbstractBindingConverter.cs index 3cd8b0f3b..464a0c283 100644 --- a/src/Greenshot.Editor/Drawing/Fields/Binding/AbstractBindingConverter.cs +++ b/src/Greenshot.Editor/Drawing/Fields/Binding/AbstractBindingConverter.cs @@ -28,15 +28,12 @@ namespace Greenshot.Editor.Drawing.Fields.Binding /// public abstract class AbstractBindingConverter : IBindingConverter { - public object convert(object o) + public object convert(object o) => o switch { - return o switch - { - null => null, - T1 => convert((T1)o), - _ => o is T2 t ? (object)convert(t) : throw new ArgumentException("Cannot handle argument of type " + o.GetType()) - }; - } + null => null, + T1 => convert((T1)o), + _ => o is T2 t ? (object)convert(t) : throw new ArgumentException("Cannot handle argument of type " + o.GetType()) + }; protected abstract T2 convert(T1 o); protected abstract T1 convert(T2 o); diff --git a/src/Greenshot.Editor/Drawing/Fields/Binding/BidirectionalBinding.cs b/src/Greenshot.Editor/Drawing/Fields/Binding/BidirectionalBinding.cs index ac14baede..212d4fb71 100644 --- a/src/Greenshot.Editor/Drawing/Fields/Binding/BidirectionalBinding.cs +++ b/src/Greenshot.Editor/Drawing/Fields/Binding/BidirectionalBinding.cs @@ -72,10 +72,7 @@ namespace Greenshot.Editor.Drawing.Fields.Binding /// Property of 2nd object to bind /// taking care of converting the synchronized value to the correct target format and back public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, - IBindingConverter converter) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) - { - Converter = converter; - } + IBindingConverter converter) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) => Converter = converter; /// /// Bind properties of two objects bidirectionally, converting the values using a converter. @@ -87,10 +84,7 @@ namespace Greenshot.Editor.Drawing.Fields.Binding /// Property of 2nd object to bind /// validator to intercept synchronization if the value does not match certain criteria public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, - IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) - { - _validator = validator; - } + IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) => _validator = validator; /// /// Bind properties of two objects bidirectionally, converting the values using a converter. @@ -103,10 +97,7 @@ namespace Greenshot.Editor.Drawing.Fields.Binding /// taking care of converting the synchronized value to the correct target format and back /// validator to intercept synchronization if the value does not match certain criteria public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, - IBindingConverter converter, IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName, converter) - { - _validator = validator; - } + IBindingConverter converter, IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName, converter) => _validator = validator; public void ControlPropertyChanged(object sender, PropertyChangedEventArgs e) { diff --git a/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalDoublePercentageConverter.cs b/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalDoublePercentageConverter.cs index 0e8a35ddf..9c9c0af0d 100644 --- a/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalDoublePercentageConverter.cs +++ b/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalDoublePercentageConverter.cs @@ -34,19 +34,10 @@ namespace Greenshot.Editor.Drawing.Fields.Binding { } - protected override decimal convert(double o) - { - return Convert.ToDecimal(o) * 100; - } + protected override decimal convert(double o) => Convert.ToDecimal(o) * 100; - protected override double convert(decimal o) - { - return Convert.ToDouble(o) / 100; - } + protected override double convert(decimal o) => Convert.ToDouble(o) / 100; - public static DecimalDoublePercentageConverter GetInstance() - { - return _uniqueInstance ??= new DecimalDoublePercentageConverter(); - } + public static DecimalDoublePercentageConverter GetInstance() => _uniqueInstance ??= new DecimalDoublePercentageConverter(); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalFloatConverter.cs b/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalFloatConverter.cs index 1f8e7a182..25fd58b04 100644 --- a/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalFloatConverter.cs +++ b/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalFloatConverter.cs @@ -34,19 +34,10 @@ namespace Greenshot.Editor.Drawing.Fields.Binding { } - protected override decimal convert(float o) - { - return Convert.ToDecimal(o); - } + protected override decimal convert(float o) => Convert.ToDecimal(o); - protected override float convert(decimal o) - { - return Convert.ToSingle(o); - } + protected override float convert(decimal o) => Convert.ToSingle(o); - public static DecimalFloatConverter GetInstance() - { - return _uniqueInstance ??= new DecimalFloatConverter(); - } + public static DecimalFloatConverter GetInstance() => _uniqueInstance ??= new DecimalFloatConverter(); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalIntConverter.cs b/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalIntConverter.cs index 882ceaac9..63110c45e 100644 --- a/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalIntConverter.cs +++ b/src/Greenshot.Editor/Drawing/Fields/Binding/DecimalIntConverter.cs @@ -34,19 +34,10 @@ namespace Greenshot.Editor.Drawing.Fields.Binding { } - protected override decimal convert(int o) - { - return Convert.ToDecimal(o); - } + protected override decimal convert(int o) => Convert.ToDecimal(o); - protected override int convert(decimal o) - { - return Convert.ToInt32(o); - } + protected override int convert(decimal o) => Convert.ToInt32(o); - public static DecimalIntConverter GetInstance() - { - return _uniqueInstance ??= new DecimalIntConverter(); - } + public static DecimalIntConverter GetInstance() => _uniqueInstance ??= new DecimalIntConverter(); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/Fields/Binding/NotNullValidator.cs b/src/Greenshot.Editor/Drawing/Fields/Binding/NotNullValidator.cs index 426a560ee..d3e588f8e 100644 --- a/src/Greenshot.Editor/Drawing/Fields/Binding/NotNullValidator.cs +++ b/src/Greenshot.Editor/Drawing/Fields/Binding/NotNullValidator.cs @@ -32,14 +32,8 @@ namespace Greenshot.Editor.Drawing.Fields.Binding { } - public bool validate(object o) - { - return o != null; - } + public bool validate(object o) => o != null; - public static NotNullValidator GetInstance() - { - return _uniqueInstance ??= new NotNullValidator(); - } + public static NotNullValidator GetInstance() => _uniqueInstance ??= new NotNullValidator(); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/Fields/Field.cs b/src/Greenshot.Editor/Drawing/Fields/Field.cs index 2d31f47e8..951ed6c58 100644 --- a/src/Greenshot.Editor/Drawing/Fields/Field.cs +++ b/src/Greenshot.Editor/Drawing/Fields/Field.cs @@ -44,7 +44,7 @@ namespace Greenshot.Editor.Drawing.Fields if (!Equals(_myValue, value)) { _myValue = value; - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value")); + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value))); } } } @@ -75,10 +75,7 @@ namespace Greenshot.Editor.Drawing.Fields Scope = scope; } - public Field(IFieldType fieldType) - { - FieldType = fieldType; - } + public Field(IFieldType fieldType) => FieldType = fieldType; /// /// Returns true if this field holds a value other than null. @@ -89,13 +86,10 @@ namespace Greenshot.Editor.Drawing.Fields /// Creates a flat clone of this Field. The fields value itself is not cloned. /// /// - public Field Clone() + public Field Clone() => new(FieldType, Scope) { - return new Field(FieldType, Scope) - { - Value = Value - }; - } + Value = Value + }; public override int GetHashCode() { @@ -110,14 +104,8 @@ namespace Greenshot.Editor.Drawing.Fields return hashCode; } - public override bool Equals(object obj) - { - return obj is Field other && FieldType == other.FieldType && Equals(Scope, other.Scope); - } + public override bool Equals(object obj) => obj is Field other && FieldType == other.FieldType && Equals(Scope, other.Scope); - public override string ToString() - { - return string.Format("[Field FieldType={1} Value={0} Scope={2}]", _myValue, FieldType, Scope); - } + public override string ToString() => string.Format("[Field FieldType={1} Value={0} Scope={2}]", _myValue, FieldType, Scope); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/Fields/FieldAggregator.cs b/src/Greenshot.Editor/Drawing/Fields/FieldAggregator.cs index 045312a42..b109745e5 100644 --- a/src/Greenshot.Editor/Drawing/Fields/FieldAggregator.cs +++ b/src/Greenshot.Editor/Drawing/Fields/FieldAggregator.cs @@ -164,29 +164,26 @@ namespace Greenshot.Editor.Drawing.Fields private IList FindCommonFields() { IList returnFields = null; - if (_boundContainers.Count > 0) + // take all fields from the least selected container... + if (_boundContainers.Count > 0 && _boundContainers[_boundContainers.Count - 1] is DrawableContainer leastSelectedContainer) { - // take all fields from the least selected container... - if (_boundContainers[_boundContainers.Count - 1] is DrawableContainer leastSelectedContainer) + returnFields = leastSelectedContainer.GetFields(); + for (int i = 0; i < _boundContainers.Count - 1; i++) { - returnFields = leastSelectedContainer.GetFields(); - for (int i = 0; i < _boundContainers.Count - 1; i++) + if (_boundContainers[i] is not DrawableContainer dc) continue; + IList fieldsToRemove = new List(); + foreach (IField field in returnFields) { - if (_boundContainers[i] is not DrawableContainer dc) continue; - IList fieldsToRemove = new List(); - foreach (IField field in returnFields) + // ... throw out those that do not apply to one of the other containers + if (!dc.HasField(field.FieldType)) { - // ... throw out those that do not apply to one of the other containers - if (!dc.HasField(field.FieldType)) - { - fieldsToRemove.Add(field); - } + fieldsToRemove.Add(field); } + } - foreach (var field in fieldsToRemove) - { - returnFields.Remove(field); - } + foreach (var field in fieldsToRemove) + { + returnFields.Remove(field); } } } diff --git a/src/Greenshot.Editor/Drawing/Fields/FieldType.cs b/src/Greenshot.Editor/Drawing/Fields/FieldType.cs index 9983e2e4a..1a79fb6f9 100644 --- a/src/Greenshot.Editor/Drawing/Fields/FieldType.cs +++ b/src/Greenshot.Editor/Drawing/Fields/FieldType.cs @@ -61,15 +61,9 @@ namespace Greenshot.Editor.Drawing.Fields public string Name { get; set; } - private FieldType(string name) - { - Name = name; - } + private FieldType(string name) => Name = name; - public override string ToString() - { - return Name; - } + public override string ToString() => Name; public override int GetHashCode() { @@ -89,14 +83,8 @@ namespace Greenshot.Editor.Drawing.Fields return other != null && Equals(Name, other.Name); } - public static bool operator ==(FieldType a, FieldType b) - { - return Equals(a, b); - } + public static bool operator ==(FieldType a, FieldType b) => Equals(a, b); - public static bool operator !=(FieldType a, FieldType b) - { - return !Equals(a, b); - } + public static bool operator !=(FieldType a, FieldType b) => !Equals(a, b); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/FilterContainer.cs b/src/Greenshot.Editor/Drawing/FilterContainer.cs index 3a4a7395a..8d29275b3 100644 --- a/src/Greenshot.Editor/Drawing/FilterContainer.cs +++ b/src/Greenshot.Editor/Drawing/FilterContainer.cs @@ -54,10 +54,7 @@ namespace Greenshot.Editor.Drawing MAGNIFICATION }; - protected FilterContainer(ISurface parent) : base(parent) - { - Init(); - } + protected FilterContainer(ISurface parent) : base(parent) => Init(); protected override void OnDeserialized(StreamingContext streamingContext) { @@ -65,10 +62,7 @@ namespace Greenshot.Editor.Drawing Init(); } - private void Init() - { - CreateDefaultAdorners(); - } + private void Init() => CreateDefaultAdorners(); protected override void InitializeFields() { diff --git a/src/Greenshot.Editor/Drawing/Filters/AbstractFilter.cs b/src/Greenshot.Editor/Drawing/Filters/AbstractFilter.cs index 334a7c1af..e1b9ea13b 100644 --- a/src/Greenshot.Editor/Drawing/Filters/AbstractFilter.cs +++ b/src/Greenshot.Editor/Drawing/Filters/AbstractFilter.cs @@ -52,7 +52,7 @@ namespace Greenshot.Editor.Drawing.Filters set { invert = value; - OnPropertyChanged("Invert"); + OnPropertyChanged(nameof(Invert)); } } @@ -64,21 +64,12 @@ namespace Greenshot.Editor.Drawing.Filters set { parent = value; } } - protected AbstractFilter(DrawableContainer parent) - { - this.parent = parent; - } + protected AbstractFilter(DrawableContainer parent) => this.parent = parent; - public DrawableContainer GetParent() - { - return parent; - } + public DrawableContainer GetParent() => parent; public abstract void Apply(Graphics graphics, Bitmap applyBitmap, NativeRect rect, RenderMode renderMode); - protected void OnPropertyChanged(string propertyName) - { - propertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } + protected void OnPropertyChanged(string propertyName) => propertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/Filters/BlurFilter.cs b/src/Greenshot.Editor/Drawing/Filters/BlurFilter.cs index 010cfd2cb..9a90a0235 100644 --- a/src/Greenshot.Editor/Drawing/Filters/BlurFilter.cs +++ b/src/Greenshot.Editor/Drawing/Filters/BlurFilter.cs @@ -41,7 +41,7 @@ namespace Greenshot.Editor.Drawing.Filters set { previewQuality = value; - OnPropertyChanged("PreviewQuality"); + OnPropertyChanged(nameof(PreviewQuality)); } } diff --git a/src/Greenshot.Editor/Drawing/Filters/BrightnessFilter.cs b/src/Greenshot.Editor/Drawing/Filters/BrightnessFilter.cs index 639b0e5ac..5168a7916 100644 --- a/src/Greenshot.Editor/Drawing/Filters/BrightnessFilter.cs +++ b/src/Greenshot.Editor/Drawing/Filters/BrightnessFilter.cs @@ -33,10 +33,7 @@ namespace Greenshot.Editor.Drawing.Filters [Serializable()] public class BrightnessFilter : AbstractFilter { - public BrightnessFilter(DrawableContainer parent) : base(parent) - { - AddField(GetType(), FieldType.BRIGHTNESS, 0.9d); - } + public BrightnessFilter(DrawableContainer parent) : base(parent) => AddField(GetType(), FieldType.BRIGHTNESS, 0.9d); /// /// Implements the Apply code for the Brightness Filet diff --git a/src/Greenshot.Editor/Drawing/Filters/HighlightFilter.cs b/src/Greenshot.Editor/Drawing/Filters/HighlightFilter.cs index 24624d193..8b807dc33 100644 --- a/src/Greenshot.Editor/Drawing/Filters/HighlightFilter.cs +++ b/src/Greenshot.Editor/Drawing/Filters/HighlightFilter.cs @@ -35,10 +35,7 @@ namespace Greenshot.Editor.Drawing.Filters [Serializable()] public class HighlightFilter : AbstractFilter { - public HighlightFilter(DrawableContainer parent) : base(parent) - { - AddField(GetType(), FieldType.FILL_COLOR, Color.Yellow); - } + public HighlightFilter(DrawableContainer parent) : base(parent) => AddField(GetType(), FieldType.FILL_COLOR, Color.Yellow); /// /// Implements the Apply code for the Brightness Filet diff --git a/src/Greenshot.Editor/Drawing/Filters/MagnifierFilter.cs b/src/Greenshot.Editor/Drawing/Filters/MagnifierFilter.cs index 47a8e3a58..a1e366047 100644 --- a/src/Greenshot.Editor/Drawing/Filters/MagnifierFilter.cs +++ b/src/Greenshot.Editor/Drawing/Filters/MagnifierFilter.cs @@ -35,10 +35,7 @@ namespace Greenshot.Editor.Drawing.Filters [Serializable] public class MagnifierFilter : AbstractFilter { - public MagnifierFilter(DrawableContainer parent) : base(parent) - { - AddField(GetType(), FieldType.MAGNIFICATION_FACTOR, 2); - } + public MagnifierFilter(DrawableContainer parent) : base(parent) => AddField(GetType(), FieldType.MAGNIFICATION_FACTOR, 2); public override void Apply(Graphics graphics, Bitmap applyBitmap, NativeRect rect, RenderMode renderMode) { diff --git a/src/Greenshot.Editor/Drawing/Filters/PixelizationFilter.cs b/src/Greenshot.Editor/Drawing/Filters/PixelizationFilter.cs index 97604e995..06cfb7942 100644 --- a/src/Greenshot.Editor/Drawing/Filters/PixelizationFilter.cs +++ b/src/Greenshot.Editor/Drawing/Filters/PixelizationFilter.cs @@ -36,10 +36,7 @@ namespace Greenshot.Editor.Drawing.Filters [Serializable()] public class PixelizationFilter : AbstractFilter { - public PixelizationFilter(DrawableContainer parent) : base(parent) - { - AddField(GetType(), FieldType.PIXEL_SIZE, 5); - } + public PixelizationFilter(DrawableContainer parent) : base(parent) => AddField(GetType(), FieldType.PIXEL_SIZE, 5); public override void Apply(Graphics graphics, Bitmap applyBitmap, NativeRect rect, RenderMode renderMode) { diff --git a/src/Greenshot.Editor/Drawing/FreehandContainer.cs b/src/Greenshot.Editor/Drawing/FreehandContainer.cs index bae2025d5..0c604b49c 100644 --- a/src/Greenshot.Editor/Drawing/FreehandContainer.cs +++ b/src/Greenshot.Editor/Drawing/FreehandContainer.cs @@ -76,10 +76,7 @@ namespace Greenshot.Editor.Drawing RecalculatePath(); } - protected override void OnDeserialized(StreamingContext context) - { - RecalculatePath(); - } + protected override void OnDeserialized(StreamingContext context) => RecalculatePath(); /// /// This Dispose is called from the Dispose and the Destructor. @@ -204,7 +201,7 @@ namespace Greenshot.Editor.Drawing { Width = lineThickness }; - if (!(pen.Width > 0)) + if (pen.Width <= 0) { return; } @@ -294,10 +291,7 @@ namespace Greenshot.Editor.Drawing return ret; } - public override int GetHashCode() - { - return freehandPath?.GetHashCode() ?? 0; - } + public override int GetHashCode() => freehandPath?.GetHashCode() ?? 0; public override bool ClickableAt(int x, int y) { diff --git a/src/Greenshot.Editor/Drawing/HighlightContainer.cs b/src/Greenshot.Editor/Drawing/HighlightContainer.cs index 62994bd87..c84698921 100644 --- a/src/Greenshot.Editor/Drawing/HighlightContainer.cs +++ b/src/Greenshot.Editor/Drawing/HighlightContainer.cs @@ -34,10 +34,7 @@ namespace Greenshot.Editor.Drawing [Serializable] public class HighlightContainer : FilterContainer { - public HighlightContainer(ISurface parent) : base(parent) - { - Init(); - } + public HighlightContainer(ISurface parent) : base(parent) => Init(); /// /// Use settings from base, extend with our own field @@ -48,10 +45,7 @@ namespace Greenshot.Editor.Drawing AddField(GetType(), FieldType.PREPARED_FILTER_HIGHLIGHT, PreparedFilter.TEXT_HIGHTLIGHT); } - protected override void OnDeserialized(StreamingContext context) - { - Init(); - } + protected override void OnDeserialized(StreamingContext context) => Init(); private void Init() { diff --git a/src/Greenshot.Editor/Drawing/IconContainer.cs b/src/Greenshot.Editor/Drawing/IconContainer.cs index 6ef6d49df..44441e533 100644 --- a/src/Greenshot.Editor/Drawing/IconContainer.cs +++ b/src/Greenshot.Editor/Drawing/IconContainer.cs @@ -41,10 +41,7 @@ namespace Greenshot.Editor.Drawing protected Icon icon; - public IconContainer(ISurface parent) : base(parent) - { - Init(); - } + public IconContainer(ISurface parent) : base(parent) => Init(); protected override void OnDeserialized(StreamingContext streamingContext) { @@ -52,20 +49,11 @@ namespace Greenshot.Editor.Drawing Init(); } - private void Init() - { - CreateDefaultAdorners(); - } + private void Init() => CreateDefaultAdorners(); - public IconContainer(ISurface parent, string filename) : base(parent) - { - Load(filename); - } + public IconContainer(ISurface parent, string filename) : base(parent) => Load(filename); - public IconContainer(ISurface parent, Stream stream) : base(parent) - { - Load(stream); - } + public IconContainer(ISurface parent, Stream stream) : base(parent) => Load(stream); public Icon Icon { diff --git a/src/Greenshot.Editor/Drawing/ImageContainer.cs b/src/Greenshot.Editor/Drawing/ImageContainer.cs index 089c9a54e..e8f83c787 100644 --- a/src/Greenshot.Editor/Drawing/ImageContainer.cs +++ b/src/Greenshot.Editor/Drawing/ImageContainer.cs @@ -56,10 +56,7 @@ namespace Greenshot.Editor.Drawing /// [NonSerialized] private readonly NativePoint _shadowOffset = new(-1, -1); - public ImageContainer(ISurface parent, string filename) : this(parent) - { - Load(filename); - } + public ImageContainer(ISurface parent, string filename) : this(parent) => Load(filename); public ImageContainer(ISurface parent) : base(parent) { @@ -73,15 +70,9 @@ namespace Greenshot.Editor.Drawing Init(); } - private void Init() - { - CreateDefaultAdorners(); - } + private void Init() => CreateDefaultAdorners(); - protected override void InitializeFields() - { - AddField(GetType(), FieldType.SHADOW, false); - } + protected override void InitializeFields() => AddField(GetType(), FieldType.SHADOW, false); protected void BitmapContainer_OnFieldChanged(object sender, FieldChangedEventArgs e) { diff --git a/src/Greenshot.Editor/Drawing/LineContainer.cs b/src/Greenshot.Editor/Drawing/LineContainer.cs index d9f03abbf..cb0c83eba 100644 --- a/src/Greenshot.Editor/Drawing/LineContainer.cs +++ b/src/Greenshot.Editor/Drawing/LineContainer.cs @@ -37,10 +37,7 @@ namespace Greenshot.Editor.Drawing [Serializable()] public class LineContainer : DrawableContainer { - public LineContainer(ISurface parent) : base(parent) - { - Init(); - } + public LineContainer(ISurface parent) : base(parent) => Init(); protected override void InitializeFields() { @@ -49,10 +46,7 @@ namespace Greenshot.Editor.Drawing AddField(GetType(), FieldType.SHADOW, true); } - protected override void OnDeserialized(StreamingContext context) - { - Init(); - } + protected override void OnDeserialized(StreamingContext context) => Init(); protected void Init() { @@ -114,9 +108,6 @@ namespace Greenshot.Editor.Drawing return false; } - protected override IDoubleProcessor GetAngleRoundProcessor() - { - return LineAngleRoundBehavior.INSTANCE; - } + protected override IDoubleProcessor GetAngleRoundProcessor() => LineAngleRoundBehavior.INSTANCE; } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Drawing/ObfuscateContainer.cs b/src/Greenshot.Editor/Drawing/ObfuscateContainer.cs index 453735457..62183518d 100644 --- a/src/Greenshot.Editor/Drawing/ObfuscateContainer.cs +++ b/src/Greenshot.Editor/Drawing/ObfuscateContainer.cs @@ -34,10 +34,7 @@ namespace Greenshot.Editor.Drawing [Serializable] public class ObfuscateContainer : FilterContainer { - public ObfuscateContainer(ISurface parent) : base(parent) - { - Init(); - } + public ObfuscateContainer(ISurface parent) : base(parent) => Init(); protected override void InitializeFields() { @@ -45,10 +42,7 @@ namespace Greenshot.Editor.Drawing AddField(GetType(), FieldType.PREPARED_FILTER_OBFUSCATE, PreparedFilter.PIXELIZE); } - protected override void OnDeserialized(StreamingContext context) - { - Init(); - } + protected override void OnDeserialized(StreamingContext context) => Init(); private void Init() { @@ -59,12 +53,9 @@ namespace Greenshot.Editor.Drawing protected void ObfuscateContainer_OnFieldChanged(object sender, FieldChangedEventArgs e) { - if (sender.Equals(this)) + if (sender.Equals(this) && Equals(e.Field.FieldType, FieldType.PREPARED_FILTER_OBFUSCATE)) { - if (Equals(e.Field.FieldType, FieldType.PREPARED_FILTER_OBFUSCATE)) - { - ConfigurePreparedFilters(); - } + ConfigurePreparedFilters(); } } diff --git a/src/Greenshot.Editor/Drawing/Positions.cs b/src/Greenshot.Editor/Drawing/Positions.cs index 815876255..fd19d1c2f 100644 --- a/src/Greenshot.Editor/Drawing/Positions.cs +++ b/src/Greenshot.Editor/Drawing/Positions.cs @@ -24,7 +24,7 @@ namespace Greenshot.Editor.Drawing /// /// Position /// - public enum Positions : int + public enum Positions { TopLeft = 0, TopCenter = 1, diff --git a/src/Greenshot.Editor/Drawing/RectangleContainer.cs b/src/Greenshot.Editor/Drawing/RectangleContainer.cs index 14faa69c2..316738104 100644 --- a/src/Greenshot.Editor/Drawing/RectangleContainer.cs +++ b/src/Greenshot.Editor/Drawing/RectangleContainer.cs @@ -38,10 +38,7 @@ namespace Greenshot.Editor.Drawing [Serializable] public class RectangleContainer : DrawableContainer { - public RectangleContainer(ISurface parent) : base(parent) - { - Init(); - } + public RectangleContainer(ISurface parent) : base(parent) => Init(); /// /// Do some logic to make sure all field are initiated correctly @@ -53,10 +50,7 @@ namespace Greenshot.Editor.Drawing Init(); } - private void Init() - { - CreateDefaultAdorners(); - } + private void Init() => CreateDefaultAdorners(); protected override void InitializeFields() { @@ -145,12 +139,9 @@ namespace Greenshot.Editor.Drawing public static bool RectangleClickableAt(NativeRect rect, int lineThickness, Color fillColor, int x, int y) { // If we clicked inside the rectangle and it's visible we are clickable at. - if (!Color.Transparent.Equals(fillColor)) + if (!Color.Transparent.Equals(fillColor) && rect.Contains(x, y)) { - if (rect.Contains(x, y)) - { - return true; - } + return true; } // check the rest of the lines diff --git a/src/Greenshot.Editor/Drawing/SpeechbubbleContainer.cs b/src/Greenshot.Editor/Drawing/SpeechbubbleContainer.cs index 477985a0a..274a52bb3 100644 --- a/src/Greenshot.Editor/Drawing/SpeechbubbleContainer.cs +++ b/src/Greenshot.Editor/Drawing/SpeechbubbleContainer.cs @@ -380,10 +380,7 @@ namespace Greenshot.Editor.Drawing return false; } - public override bool ClickableAt(int x, int y) - { - return Contains(x, y); - } + public override bool ClickableAt(int x, int y) => Contains(x, y); /// /// Additional to the Transform of the TextContainer the bubble tail coordinates also need to be moved diff --git a/src/Greenshot.Editor/Drawing/StepLabelContainer.cs b/src/Greenshot.Editor/Drawing/StepLabelContainer.cs index 198a209db..1a07ea317 100644 --- a/src/Greenshot.Editor/Drawing/StepLabelContainer.cs +++ b/src/Greenshot.Editor/Drawing/StepLabelContainer.cs @@ -50,10 +50,7 @@ namespace Greenshot.Editor.Drawing Init(); } - private void Init() - { - CreateDefaultAdorners(); - } + private void Init() => CreateDefaultAdorners(); // Used to store the counter start of the Surface, as the surface is NOT stored. private int _counterStart = 1; @@ -128,10 +125,7 @@ namespace Greenshot.Editor.Drawing /// /// This makes it possible for the label to be placed exactly in the middle of the pointer. /// - public override bool HandleMouseDown(int mouseX, int mouseY) - { - return base.HandleMouseDown(mouseX - (Width / 2), mouseY - (Height / 2)); - } + public override bool HandleMouseDown(int mouseX, int mouseY) => base.HandleMouseDown(mouseX - (Width / 2), mouseY - (Height / 2)); /// /// We set our own field values diff --git a/src/Greenshot.Editor/Drawing/Surface.cs b/src/Greenshot.Editor/Drawing/Surface.cs index 715f81742..409c3b655 100644 --- a/src/Greenshot.Editor/Drawing/Surface.cs +++ b/src/Greenshot.Editor/Drawing/Surface.cs @@ -242,10 +242,7 @@ namespace Greenshot.Editor.Drawing } } - public void RemoveStepLabel(StepLabelContainer stepLabel) - { - _stepLabels.Remove(stepLabel); - } + public void RemoveStepLabel(StepLabelContainer stepLabel) => _stepLabels.Remove(stepLabel); /// /// The start value of the counter objects @@ -878,14 +875,9 @@ namespace Greenshot.Editor.Drawing } else { - if (ClipboardHelper.ContainsImage(e.Data) || ClipboardHelper.ContainsFormat(e.Data, "DragImageBits")) - { - e.Effect = DragDropEffects.Copy; - } - else - { - e.Effect = DragDropEffects.None; - } + e.Effect = ClipboardHelper.ContainsImage(e.Data) || ClipboardHelper.ContainsFormat(e.Data, "DragImageBits") + ? DragDropEffects.Copy + : DragDropEffects.None; } } @@ -1426,7 +1418,7 @@ namespace Greenshot.Editor.Drawing _mouseDown = true; _isSurfaceMoveMadeUndoable = false; - if (_cropContainer != null && ((_undrawnElement == null) || (_undrawnElement != null && DrawingMode != DrawingModes.Crop))) + if (_cropContainer != null && ((_undrawnElement == null) || (DrawingMode != DrawingModes.Crop))) { RemoveElement(_cropContainer, false); _cropContainer = null; @@ -1675,10 +1667,7 @@ namespace Greenshot.Editor.Drawing /// This returns the image "result" of this surface, with all the elements rendered on it. /// /// - public Image GetImageForExport() - { - return GetImage(RenderMode.EXPORT); - } + public Image GetImageForExport() => GetImage(RenderMode.EXPORT); private static NativeRect ZoomClipRectangle(NativeRect rc, double scale, int inflateAmount = 0) { @@ -1735,13 +1724,10 @@ namespace Greenshot.Editor.Drawing if (Elements.HasIntersectingFilters(imageClipRectangle) || _zoomFactor > Fraction.Identity) { - if (_buffer != null) + if (_buffer != null && (_buffer.Width != Image.Width || _buffer.Height != Image.Height || _buffer.PixelFormat != Image.PixelFormat)) { - if (_buffer.Width != Image.Width || _buffer.Height != Image.Height || _buffer.PixelFormat != Image.PixelFormat) - { - _buffer.Dispose(); - _buffer = null; - } + _buffer.Dispose(); + _buffer = null; } if (_buffer == null) @@ -2373,10 +2359,7 @@ namespace Greenshot.Editor.Drawing /// /// Deselect all the selected elements /// - public void DeselectAllElements() - { - DeselectElements(selectedElements); - } + public void DeselectAllElements() => DeselectElements(selectedElements); /// /// Select the supplied element @@ -2409,10 +2392,7 @@ namespace Greenshot.Editor.Drawing /// /// Select all elements, this is called when Ctrl+A is pressed /// - public void SelectAllElements() - { - SelectElements(Elements); - } + public void SelectAllElements() => SelectElements(Elements); /// /// Select the supplied elements @@ -2630,29 +2610,17 @@ namespace Greenshot.Editor.Drawing /// indicates whether the selected elements could be pulled up in hierarchy /// /// true if selected elements could be pulled up, false otherwise - public bool CanPullSelectionUp() - { - return Elements.CanPullUp(selectedElements); - } + public bool CanPullSelectionUp() => Elements.CanPullUp(selectedElements); /// /// indicates whether the selected elements could be pushed down in hierarchy /// /// true if selected elements could be pushed down, false otherwise - public bool CanPushSelectionDown() - { - return Elements.CanPushDown(selectedElements); - } + public bool CanPushSelectionDown() => Elements.CanPushDown(selectedElements); - private void Element_FieldChanged(object sender, FieldChangedEventArgs e) - { - selectedElements.HandleFieldChangedEvent(sender, e); - } + private void Element_FieldChanged(object sender, FieldChangedEventArgs e) => selectedElements.HandleFieldChangedEvent(sender, e); - public bool IsOnSurface(IDrawableContainer container) - { - return Elements.Contains(container); - } + public bool IsOnSurface(IDrawableContainer container) => Elements.Contains(container); public NativePoint ToSurfaceCoordinates(NativePoint point) { diff --git a/src/Greenshot.Editor/Drawing/TextContainer.cs b/src/Greenshot.Editor/Drawing/TextContainer.cs index 170d91607..6db53e4e6 100644 --- a/src/Greenshot.Editor/Drawing/TextContainer.cs +++ b/src/Greenshot.Editor/Drawing/TextContainer.cs @@ -85,10 +85,7 @@ namespace Greenshot.Editor.Drawing OnPropertyChanged("Text"); } - public TextContainer(ISurface parent) : base(parent) - { - Init(); - } + public TextContainer(ISurface parent) : base(parent) => Init(); protected override void InitializeFields() { @@ -272,10 +269,7 @@ namespace Greenshot.Editor.Drawing } } - public override void OnDoubleClick() - { - ShowTextBox(); - } + public override void OnDoubleClick() => ShowTextBox(); private void CreateTextBox() { @@ -322,14 +316,7 @@ namespace Greenshot.Editor.Drawing } Color lc = GetFieldValueAsColor(FieldType.LINE_COLOR); - if (lc.R > 203 && lc.G > 203 && lc.B > 203) - { - _textBox.BackColor = Color.FromArgb(51, 51, 51); - } - else - { - _textBox.BackColor = Color.White; - } + _textBox.BackColor = lc.R > 203 && lc.G > 203 && lc.B > 203 ? Color.FromArgb(51, 51, 51) : Color.White; } private void HideTextBox() diff --git a/src/Greenshot.Editor/Drawing/VectorGraphicsContainer.cs b/src/Greenshot.Editor/Drawing/VectorGraphicsContainer.cs index 8d710dd65..ce43a679e 100644 --- a/src/Greenshot.Editor/Drawing/VectorGraphicsContainer.cs +++ b/src/Greenshot.Editor/Drawing/VectorGraphicsContainer.cs @@ -48,10 +48,7 @@ namespace Greenshot.Editor.Drawing /// Constructor takes care of calling Init /// /// ISurface - protected VectorGraphicsContainer(ISurface parent) : base(parent) - { - Init(); - } + protected VectorGraphicsContainer(ISurface parent) : base(parent) => Init(); /// /// Make sure Init is called after deserializing diff --git a/src/Greenshot.Editor/EditorInitialize.cs b/src/Greenshot.Editor/EditorInitialize.cs index c1ee27db8..337442023 100644 --- a/src/Greenshot.Editor/EditorInitialize.cs +++ b/src/Greenshot.Editor/EditorInitialize.cs @@ -27,9 +27,7 @@ namespace Greenshot.Editor { public static class EditorInitialize { - public static void Initialize() - { - SimpleServiceProvider.Current.AddService( + public static void Initialize() => SimpleServiceProvider.Current.AddService( // All generic things, like gif, png, jpg etc. new DefaultFileFormatHandler(), // Greenshot format @@ -45,6 +43,5 @@ namespace Greenshot.Editor // JPG XR new WpfFileFormatHandler() ); - } } } diff --git a/src/Greenshot.Editor/FileFormatHandlers/AbstractFileFormatHandler.cs b/src/Greenshot.Editor/FileFormatHandlers/AbstractFileFormatHandler.cs index 7c2621a0d..c3e3de27b 100644 --- a/src/Greenshot.Editor/FileFormatHandlers/AbstractFileFormatHandler.cs +++ b/src/Greenshot.Editor/FileFormatHandlers/AbstractFileFormatHandler.cs @@ -35,10 +35,7 @@ namespace Greenshot.Editor.FileFormatHandlers public IDictionary> SupportedExtensions { get; } = new Dictionary>(); /// - public virtual int PriorityFor(FileFormatHandlerActions fileFormatHandlerAction, string extension) - { - return 0; - } + public virtual int PriorityFor(FileFormatHandlerActions fileFormatHandlerAction, string extension) => 0; public abstract bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null); diff --git a/src/Greenshot.Editor/FileFormatHandlers/MetaFileFormatHandler.cs b/src/Greenshot.Editor/FileFormatHandlers/MetaFileFormatHandler.cs index 09b52b6b3..b82857e61 100644 --- a/src/Greenshot.Editor/FileFormatHandlers/MetaFileFormatHandler.cs +++ b/src/Greenshot.Editor/FileFormatHandlers/MetaFileFormatHandler.cs @@ -45,10 +45,7 @@ namespace Greenshot.Editor.FileFormatHandlers } /// - public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null) - { - return false; - } + public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null) => false; /// public override bool TryLoadFromStream(Stream stream, string extension, out Bitmap bitmap) diff --git a/src/Greenshot.Editor/FileFormatHandlers/SvgFileFormatHandler.cs b/src/Greenshot.Editor/FileFormatHandlers/SvgFileFormatHandler.cs index 14a33246e..43fa3f463 100644 --- a/src/Greenshot.Editor/FileFormatHandlers/SvgFileFormatHandler.cs +++ b/src/Greenshot.Editor/FileFormatHandlers/SvgFileFormatHandler.cs @@ -63,11 +63,9 @@ namespace Greenshot.Editor.FileFormatHandlers return false; } - public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null) - { + public override bool TrySaveToStream(Bitmap bitmap, Stream destination, string extension, ISurface surface = null, SurfaceOutputSettings surfaceOutputSettings = null) => // TODO: Implement this - return false; - } + false; public override IEnumerable LoadDrawablesFromStream(Stream stream, string extension, ISurface parent = null) { diff --git a/src/Greenshot.Editor/FileFormatHandlers/WpfFileFormatHandler.cs b/src/Greenshot.Editor/FileFormatHandlers/WpfFileFormatHandler.cs index 9d81d394b..aa1e5cf93 100644 --- a/src/Greenshot.Editor/FileFormatHandlers/WpfFileFormatHandler.cs +++ b/src/Greenshot.Editor/FileFormatHandlers/WpfFileFormatHandler.cs @@ -47,7 +47,7 @@ namespace Greenshot.Editor.FileFormatHandlers public WpfFileFormatHandler() { - LoadFromStreamExtensions = LoadFromStreamExtensions.ToList().Concat(RetrieveSupportedExtensions()).OrderBy(e => e).Distinct().ToArray(); + LoadFromStreamExtensions = LoadFromStreamExtensions.AsEnumerable().Concat(RetrieveSupportedExtensions()).OrderBy(e => e).Distinct().ToArray(); SupportedExtensions[FileFormatHandlerActions.LoadDrawableFromStream] = LoadFromStreamExtensions; SupportedExtensions[FileFormatHandlerActions.LoadFromStream] = LoadFromStreamExtensions; @@ -60,16 +60,7 @@ namespace Greenshot.Editor.FileFormatHandlers /// IEnumerable{string} private IEnumerable RetrieveSupportedExtensions() { - string baseKeyPath; - if (Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess) - { - baseKeyPath = "Wow6432Node\\CLSID"; - } - else - { - baseKeyPath = "CLSID"; - } - + string baseKeyPath = Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess ? "Wow6432Node\\CLSID" : "CLSID"; using RegistryKey baseKey = Registry.ClassesRoot.OpenSubKey(baseKeyPath, false); if (baseKey == null) yield break; diff --git a/src/Greenshot.Editor/Forms/ColorDialog.cs b/src/Greenshot.Editor/Forms/ColorDialog.cs index 5b30e64e2..7853788ca 100644 --- a/src/Greenshot.Editor/Forms/ColorDialog.cs +++ b/src/Greenshot.Editor/Forms/ColorDialog.cs @@ -108,10 +108,7 @@ namespace Greenshot.Editor.Forms } } - private Button CreateColorButton(int red, int green, int blue, int x, int y, int w, int h) - { - return CreateColorButton(Color.FromArgb(255, red, green, blue), x, y, w, h); - } + private Button CreateColorButton(int red, int green, int blue, int x, int y, int w, int h) => CreateColorButton(Color.FromArgb(255, red, green, blue), x, y, w, h); private Button CreateColorButton(Color color, int x, int y, int w, int h) { @@ -235,10 +232,7 @@ namespace Greenshot.Editor.Forms GetColorPartIntFromString(textBoxBlue.Text)), textBox); } - private void TextBoxGotFocus(object sender, EventArgs e) - { - textBoxHtmlColor.SelectAll(); - } + private void TextBoxGotFocus(object sender, EventArgs e) => textBoxHtmlColor.SelectAll(); private void TextBoxKeyDown(object sender, KeyEventArgs e) { @@ -254,15 +248,9 @@ namespace Greenshot.Editor.Forms PreviewColor(b.BackColor, b); } - private void SetButtonTooltip(Button colorButton, Color color) - { - _toolTip.SetToolTip(colorButton, ColorTranslator.ToHtml(color) + " | R:" + color.R + ", G:" + color.G + ", B:" + color.B); - } + private void SetButtonTooltip(Button colorButton, Color color) => _toolTip.SetToolTip(colorButton, ColorTranslator.ToHtml(color) + " | R:" + color.R + ", G:" + color.G + ", B:" + color.B); - private void BtnTransparentClick(object sender, EventArgs e) - { - ColorButtonClick(sender, e); - } + private void BtnTransparentClick(object sender, EventArgs e) => ColorButtonClick(sender, e); private void BtnApplyClick(object sender, EventArgs e) { @@ -286,9 +274,6 @@ namespace Greenshot.Editor.Forms return ret; } - private void PipetteUsed(object sender, PipetteUsedArgs e) - { - Color = e.Color; - } + private void PipetteUsed(object sender, PipetteUsedArgs e) => Color = e.Color; } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Forms/ColorPickerToolStripButton.cs b/src/Greenshot.Editor/Forms/ColorPickerToolStripButton.cs index 6e1fbb942..c1c7421ca 100644 --- a/src/Greenshot.Editor/Forms/ColorPickerToolStripButton.cs +++ b/src/Greenshot.Editor/Forms/ColorPickerToolStripButton.cs @@ -88,9 +88,6 @@ namespace Greenshot.Editor.Forms { public Color Color; - public ColorPickerEventArgs(Color color) - { - Color = color; - } + public ColorPickerEventArgs(Color color) => Color = color; } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Forms/ImageEditorForm.cs b/src/Greenshot.Editor/Forms/ImageEditorForm.cs index 816f9234d..9afcca2cb 100644 --- a/src/Greenshot.Editor/Forms/ImageEditorForm.cs +++ b/src/Greenshot.Editor/Forms/ImageEditorForm.cs @@ -135,10 +135,7 @@ namespace Greenshot.Editor.Forms Initialize(surface, false); } - public ImageEditorForm(ISurface surface, bool outputMade) - { - Initialize(surface, outputMade); - } + public ImageEditorForm(ISurface surface, bool outputMade) => Initialize(surface, outputMade); private void Initialize(ISurface surface, bool outputMade) { @@ -331,40 +328,37 @@ namespace Greenshot.Editor.Forms /// /// Get all the destinations and display them in the file menu and the buttons /// - private void AddDestinations() - { - Invoke((MethodInvoker)delegate - { - // Create export buttons - foreach (IDestination destination in DestinationHelper.GetAllDestinations()) - { - if (destination.Priority <= 2) - { - continue; - } + private void AddDestinations() => Invoke((MethodInvoker)delegate + { + // Create export buttons + foreach (IDestination destination in DestinationHelper.GetAllDestinations()) + { + if (destination.Priority <= 2) + { + continue; + } - if (!destination.IsActive) - { - continue; - } + if (!destination.IsActive) + { + continue; + } - if (destination.DisplayIcon == null) - { - continue; - } + if (destination.DisplayIcon == null) + { + continue; + } - try - { - AddDestinationButton(destination); - } - catch (Exception addingException) - { - Log.WarnFormat("Problem adding destination {0}", destination.Designation); - Log.Warn("Exception: ", addingException); - } - } - }); - } + try + { + AddDestinationButton(destination); + } + catch (Exception addingException) + { + Log.WarnFormat("Problem adding destination {0}", destination.Designation); + Log.Warn("Exception: ", addingException); + } + } + }); private void AddDestinationButton(IDestination toolstripDestination) { @@ -515,40 +509,28 @@ namespace Greenshot.Editor.Forms /// /// object /// SurfaceForegroundColorEventArgs - private void ForegroundColorChanged(object sender, SurfaceForegroundColorEventArgs eventArgs) - { - _surface.FieldAggregator.GetField(FieldType.LINE_COLOR).Value = eventArgs.Color; - } + private void ForegroundColorChanged(object sender, SurfaceForegroundColorEventArgs eventArgs) => _surface.FieldAggregator.GetField(FieldType.LINE_COLOR).Value = eventArgs.Color; /// /// This is called when the background color of the select element chances, used for shortcuts /// /// object /// SurfaceBackgroundColorEventArgs - private void BackgroundColorChanged(object sender, SurfaceBackgroundColorEventArgs eventArgs) - { - _surface.FieldAggregator.GetField(FieldType.FILL_COLOR).Value = eventArgs.Color; - } + private void BackgroundColorChanged(object sender, SurfaceBackgroundColorEventArgs eventArgs) => _surface.FieldAggregator.GetField(FieldType.FILL_COLOR).Value = eventArgs.Color; /// /// This is called when the line thickness of the select element chances, used for shortcuts /// /// object /// SurfaceLineThicknessEventArgs - private void LineThicknessChanged(object sender, SurfaceLineThicknessEventArgs eventArgs) - { - _surface.FieldAggregator.GetField(FieldType.LINE_THICKNESS).Value = eventArgs.Thickness; - } + private void LineThicknessChanged(object sender, SurfaceLineThicknessEventArgs eventArgs) => _surface.FieldAggregator.GetField(FieldType.LINE_THICKNESS).Value = eventArgs.Thickness; /// /// This is called when the shadow of the select element chances, used for shortcuts /// /// object /// SurfaceShadowEventArgs - private void ShadowChanged(object sender, SurfaceShadowEventArgs eventArgs) - { - _surface.FieldAggregator.GetField(FieldType.SHADOW).Value = eventArgs.HasShadow; - } + private void ShadowChanged(object sender, SurfaceShadowEventArgs eventArgs) => _surface.FieldAggregator.GetField(FieldType.SHADOW).Value = eventArgs.HasShadow; /// /// This is called when the size of the surface chances, used for resizing and displaying the size information @@ -637,10 +619,7 @@ namespace Greenshot.Editor.Forms /** * Interfaces for plugins, see GreenshotInterface for more details! */ - public Image GetImageForExport() - { - return _surface.GetImageForExport(); - } + public Image GetImageForExport() => _surface.GetImageForExport(); public ICaptureDetails CaptureDetails => _surface.CaptureDetails; @@ -655,21 +634,13 @@ namespace Greenshot.Editor.Forms DestinationHelper.ExportCapture(true, destinationDesignation, _surface, _surface.CaptureDetails); } - private void BtnClipboardClick(object sender, EventArgs e) - { - DestinationHelper.ExportCapture(true, WellKnownDestinations.Clipboard, _surface, _surface.CaptureDetails); - } + private void BtnClipboardClick(object sender, EventArgs e) => DestinationHelper.ExportCapture(true, WellKnownDestinations.Clipboard, _surface, _surface.CaptureDetails); - private void BtnPrintClick(object sender, EventArgs e) - { + private void BtnPrintClick(object sender, EventArgs e) => // The BeginInvoke is a solution for the printdialog not having focus BeginInvoke((MethodInvoker)delegate { DestinationHelper.ExportCapture(true, WellKnownDestinations.Printer, _surface, _surface.CaptureDetails); }); - } - private void CloseToolStripMenuItemClick(object sender, EventArgs e) - { - Close(); - } + private void CloseToolStripMenuItemClick(object sender, EventArgs e) => Close(); private void BtnEllipseClick(object sender, EventArgs e) { @@ -763,55 +734,25 @@ namespace Greenshot.Editor.Forms } } - private void AddRectangleToolStripMenuItemClick(object sender, EventArgs e) - { - BtnRectClick(sender, e); - } + private void AddRectangleToolStripMenuItemClick(object sender, EventArgs e) => BtnRectClick(sender, e); - private void DrawFreehandToolStripMenuItemClick(object sender, EventArgs e) - { - BtnFreehandClick(sender, e); - } + private void DrawFreehandToolStripMenuItemClick(object sender, EventArgs e) => BtnFreehandClick(sender, e); - private void AddEllipseToolStripMenuItemClick(object sender, EventArgs e) - { - BtnEllipseClick(sender, e); - } + private void AddEllipseToolStripMenuItemClick(object sender, EventArgs e) => BtnEllipseClick(sender, e); - private void AddTextBoxToolStripMenuItemClick(object sender, EventArgs e) - { - BtnTextClick(sender, e); - } + private void AddTextBoxToolStripMenuItemClick(object sender, EventArgs e) => BtnTextClick(sender, e); - private void AddSpeechBubbleToolStripMenuItemClick(object sender, EventArgs e) - { - BtnSpeechBubbleClick(sender, e); - } + private void AddSpeechBubbleToolStripMenuItemClick(object sender, EventArgs e) => BtnSpeechBubbleClick(sender, e); - private void AddCounterToolStripMenuItemClick(object sender, EventArgs e) - { - BtnStepLabelClick(sender, e); - } + private void AddCounterToolStripMenuItemClick(object sender, EventArgs e) => BtnStepLabelClick(sender, e); - private void DrawLineToolStripMenuItemClick(object sender, EventArgs e) - { - BtnLineClick(sender, e); - } + private void DrawLineToolStripMenuItemClick(object sender, EventArgs e) => BtnLineClick(sender, e); - private void DrawArrowToolStripMenuItemClick(object sender, EventArgs e) - { - BtnArrowClick(sender, e); - } + private void DrawArrowToolStripMenuItemClick(object sender, EventArgs e) => BtnArrowClick(sender, e); - private void RemoveObjectToolStripMenuItemClick(object sender, EventArgs e) - { - _surface.RemoveSelectedElements(); - } + private void RemoveObjectToolStripMenuItemClick(object sender, EventArgs e) => _surface.RemoveSelectedElements(); - private void BtnDeleteClick(object sender, EventArgs e) - { - RemoveObjectToolStripMenuItemClick(sender, e); - } + private void BtnDeleteClick(object sender, EventArgs e) => RemoveObjectToolStripMenuItemClick(sender, e); private void CutToolStripMenuItemClick(object sender, EventArgs e) { @@ -819,10 +760,7 @@ namespace Greenshot.Editor.Forms UpdateClipboardSurfaceDependencies(); } - private void BtnCutClick(object sender, EventArgs e) - { - CutToolStripMenuItemClick(sender, e); - } + private void BtnCutClick(object sender, EventArgs e) => CutToolStripMenuItemClick(sender, e); private void CopyToolStripMenuItemClick(object sender, EventArgs e) { @@ -830,10 +768,7 @@ namespace Greenshot.Editor.Forms UpdateClipboardSurfaceDependencies(); } - private void BtnCopyClick(object sender, EventArgs e) - { - CopyToolStripMenuItemClick(sender, e); - } + private void BtnCopyClick(object sender, EventArgs e) => CopyToolStripMenuItemClick(sender, e); private void PasteToolStripMenuItemClick(object sender, EventArgs e) { @@ -841,10 +776,7 @@ namespace Greenshot.Editor.Forms UpdateClipboardSurfaceDependencies(); } - private void BtnPasteClick(object sender, EventArgs e) - { - PasteToolStripMenuItemClick(sender, e); - } + private void BtnPasteClick(object sender, EventArgs e) => PasteToolStripMenuItemClick(sender, e); private void UndoToolStripMenuItemClick(object sender, EventArgs e) { @@ -852,10 +784,7 @@ namespace Greenshot.Editor.Forms UpdateUndoRedoSurfaceDependencies(); } - private void BtnUndoClick(object sender, EventArgs e) - { - UndoToolStripMenuItemClick(sender, e); - } + private void BtnUndoClick(object sender, EventArgs e) => UndoToolStripMenuItemClick(sender, e); private void RedoToolStripMenuItemClick(object sender, EventArgs e) { @@ -863,10 +792,7 @@ namespace Greenshot.Editor.Forms UpdateUndoRedoSurfaceDependencies(); } - private void BtnRedoClick(object sender, EventArgs e) - { - RedoToolStripMenuItemClick(sender, e); - } + private void BtnRedoClick(object sender, EventArgs e) => RedoToolStripMenuItemClick(sender, e); private void DuplicateToolStripMenuItemClick(object sender, EventArgs e) { @@ -874,30 +800,15 @@ namespace Greenshot.Editor.Forms UpdateClipboardSurfaceDependencies(); } - private void UpOneLevelToolStripMenuItemClick(object sender, EventArgs e) - { - _surface.PullElementsUp(); - } + private void UpOneLevelToolStripMenuItemClick(object sender, EventArgs e) => _surface.PullElementsUp(); - private void DownOneLevelToolStripMenuItemClick(object sender, EventArgs e) - { - _surface.PushElementsDown(); - } + private void DownOneLevelToolStripMenuItemClick(object sender, EventArgs e) => _surface.PushElementsDown(); - private void UpToTopToolStripMenuItemClick(object sender, EventArgs e) - { - _surface.PullElementsToTop(); - } + private void UpToTopToolStripMenuItemClick(object sender, EventArgs e) => _surface.PullElementsToTop(); - private void DownToBottomToolStripMenuItemClick(object sender, EventArgs e) - { - _surface.PushElementsToBottom(); - } + private void DownToBottomToolStripMenuItemClick(object sender, EventArgs e) => _surface.PushElementsToBottom(); - private void HelpToolStripMenuItem1Click(object sender, EventArgs e) - { - HelpFileLoader.LoadHelp(); - } + private void HelpToolStripMenuItem1Click(object sender, EventArgs e) => HelpFileLoader.LoadHelp(); private void AboutToolStripMenuItemClick(object sender, EventArgs e) { @@ -911,15 +822,9 @@ namespace Greenshot.Editor.Forms mainForm.ShowSetting(); } - private void BtnSettingsClick(object sender, EventArgs e) - { - PreferencesToolStripMenuItemClick(sender, e); - } + private void BtnSettingsClick(object sender, EventArgs e) => PreferencesToolStripMenuItemClick(sender, e); - private void BtnHelpClick(object sender, EventArgs e) - { - HelpToolStripMenuItem1Click(sender, e); - } + private void BtnHelpClick(object sender, EventArgs e) => HelpToolStripMenuItem1Click(sender, e); private void ImageEditorFormActivated(object sender, EventArgs e) { @@ -1099,30 +1004,27 @@ namespace Greenshot.Editor.Forms /// MouseEventArgs private void PanelMouseWheel(object sender, MouseEventArgs e) { - if (System.Windows.Forms.Control.ModifierKeys.Equals(Keys.Control)) + //waiting for next zoom step 100 ms + if (System.Windows.Forms.Control.ModifierKeys.Equals(Keys.Control) && _zoomStartTime.AddMilliseconds(100) < DateTime.Now) { - if (_zoomStartTime.AddMilliseconds(100) < DateTime.Now) //waiting for next zoom step 100 ms + _zoomStartTime = DateTime.Now; + switch (e.Delta) { - _zoomStartTime = DateTime.Now; - if (e.Delta > 0) - { + case > 0: ZoomInMenuItemClick(sender, e); - } - else if (e.Delta < 0) - { + break; + case < 0: ZoomOutMenuItemClick(sender, e); - } + break; } } panel1.Focus(); } - protected override bool ProcessKeyPreview(ref Message msg) - { + protected override bool ProcessKeyPreview(ref Message msg) => // disable default key handling if surface has requested a lock - return !_surface.KeysLocked && base.ProcessKeyPreview(ref msg); - } + !_surface.KeysLocked && base.ProcessKeyPreview(ref msg); protected override bool ProcessCmdKey(ref Message msg, Keys keys) { @@ -1171,12 +1073,9 @@ namespace Greenshot.Editor.Forms btnUndo.Enabled = canUndo; undoToolStripMenuItem.Enabled = canUndo; string undoAction = string.Empty; - if (canUndo) + if (canUndo && _surface.UndoActionLanguageKey != LangKey.none) { - if (_surface.UndoActionLanguageKey != LangKey.none) - { - undoAction = Language.GetString(_surface.UndoActionLanguageKey); - } + undoAction = Language.GetString(_surface.UndoActionLanguageKey); } string undoText = Language.GetFormattedString(LangKey.editor_undo, undoAction); @@ -1187,12 +1086,9 @@ namespace Greenshot.Editor.Forms btnRedo.Enabled = canRedo; redoToolStripMenuItem.Enabled = canRedo; string redoAction = string.Empty; - if (canRedo) + if (canRedo && _surface.RedoActionLanguageKey != LangKey.none) { - if (_surface.RedoActionLanguageKey != LangKey.none) - { - redoAction = Language.GetString(_surface.RedoActionLanguageKey); - } + redoAction = Language.GetString(_surface.RedoActionLanguageKey); } string redoText = Language.GetFormattedString(LangKey.editor_redo, redoAction); @@ -1240,15 +1136,9 @@ namespace Greenshot.Editor.Forms ss.ContextMenuStrip?.Show(ss, e.X, e.Y); } - private void CopyPathMenuItemClick(object sender, EventArgs e) - { - ClipboardHelper.SetClipboardData(_surface.LastSaveFullPath); - } + private void CopyPathMenuItemClick(object sender, EventArgs e) => ClipboardHelper.SetClipboardData(_surface.LastSaveFullPath); - private void OpenDirectoryMenuItemClick(object sender, EventArgs e) - { - ExplorerHelper.OpenInExplorer(_surface.LastSaveFullPath); - } + private void OpenDirectoryMenuItemClick(object sender, EventArgs e) => ExplorerHelper.OpenInExplorer(_surface.LastSaveFullPath); private void BindFieldControls() { @@ -1339,16 +1229,9 @@ namespace Greenshot.Editor.Forms private void RefreshEditorControls() { int stepLabels = _surface.CountStepLabels(null); - Image icon; - if (stepLabels <= 20) - { - icon = (Image)resources.GetObject($"btnStepLabel{stepLabels:00}.Image"); - } - else - { - icon = (Image)resources.GetObject("btnStepLabel20+.Image"); - } - + Image icon = stepLabels <= 20 + ? (Image)resources.GetObject($"btnStepLabel{stepLabels:00}.Image") + : (Image)resources.GetObject("btnStepLabel20+.Image"); btnStepLabel.Image = icon; addCounterToolStripMenuItem.Image = icon; @@ -1400,10 +1283,7 @@ namespace Greenshot.Editor.Forms RefreshFieldControls(); } - private void ArrowHeadsToolStripMenuItemClick(object sender, EventArgs e) - { - _surface.FieldAggregator.GetField(FieldType.ARROWHEADS).Value = (ArrowContainer.ArrowHeadCombination)((ToolStripMenuItem)sender).Tag; - } + private void ArrowHeadsToolStripMenuItemClick(object sender, EventArgs e) => _surface.FieldAggregator.GetField(FieldType.ARROWHEADS).Value = (ArrowContainer.ArrowHeadCombination)((ToolStripMenuItem)sender).Tag; private void EditToolStripMenuItemClick(object sender, EventArgs e) { @@ -1449,8 +1329,7 @@ namespace Greenshot.Editor.Forms fontItalicButton.Enabled = italicAvailable; } - bool regularAvailable = fontFamily.IsStyleAvailable(FontStyle.Regular); - if (regularAvailable) + if (fontFamily.IsStyleAvailable(FontStyle.Regular)) { return; } @@ -1462,12 +1341,9 @@ namespace Greenshot.Editor.Forms fontBoldButton.Checked = true; } } - else if (italicAvailable) + else if (italicAvailable && fontItalicButton != null) { - if (fontItalicButton != null) - { - fontItalicButton.Checked = true; - } + fontItalicButton.Checked = true; } } @@ -1481,25 +1357,13 @@ namespace Greenshot.Editor.Forms } } - private void FontBoldButtonClick(object sender, EventArgs e) - { - _originalBoldCheckState = fontBoldButton.Checked; - } + private void FontBoldButtonClick(object sender, EventArgs e) => _originalBoldCheckState = fontBoldButton.Checked; - private void FontItalicButtonClick(object sender, EventArgs e) - { - _originalItalicCheckState = fontItalicButton.Checked; - } + private void FontItalicButtonClick(object sender, EventArgs e) => _originalItalicCheckState = fontItalicButton.Checked; - private void ToolBarFocusableElementGotFocus(object sender, EventArgs e) - { - _surface.KeysLocked = true; - } + private void ToolBarFocusableElementGotFocus(object sender, EventArgs e) => _surface.KeysLocked = true; - private void ToolBarFocusableElementLostFocus(object sender, EventArgs e) - { - _surface.KeysLocked = false; - } + private void ToolBarFocusableElementLostFocus(object sender, EventArgs e) => _surface.KeysLocked = false; private void SaveElementsToolStripMenuItemClick(object sender, EventArgs e) { @@ -1602,10 +1466,7 @@ namespace Greenshot.Editor.Forms RefreshEditorControls(); } - private void SelectAllToolStripMenuItemClick(object sender, EventArgs e) - { - _surface.SelectAllElements(); - } + private void SelectAllToolStripMenuItemClick(object sender, EventArgs e) => _surface.SelectAllElements(); private void BtnConfirmClick(object sender, EventArgs e) { @@ -1803,10 +1664,7 @@ namespace Greenshot.Editor.Forms UpdateUndoRedoSurfaceDependencies(); } - private void ImageEditorFormResize(object sender, EventArgs e) - { - AlignCanvasPositionAfterResize(); - } + private void ImageEditorFormResize(object sender, EventArgs e) => AlignCanvasPositionAfterResize(); private void AlignCanvasPositionAfterResize() { @@ -1826,23 +1684,9 @@ namespace Greenshot.Editor.Forms int offsetX = -panel.HorizontalScroll.Value; int offsetY = -panel.VerticalScroll.Value; - if (currentClientSize.Width > canvasSize.Width) - { - canvas.Left = offsetX + ((currentClientSize.Width - canvasSize.Width) / 2); - } - else - { - canvas.Left = offsetX + 0; - } + canvas.Left = currentClientSize.Width > canvasSize.Width ? offsetX + ((currentClientSize.Width - canvasSize.Width) / 2) : offsetX + 0; - if (currentClientSize.Height > canvasSize.Height) - { - canvas.Top = offsetY + ((currentClientSize.Height - canvasSize.Height) / 2); - } - else - { - canvas.Top = offsetY + 0; - } + canvas.Top = currentClientSize.Height > canvasSize.Height ? offsetY + ((currentClientSize.Height - canvasSize.Height) / 2) : offsetY + 0; } /// diff --git a/src/Greenshot.Editor/Forms/MovableShowColorForm.cs b/src/Greenshot.Editor/Forms/MovableShowColorForm.cs index a07d283e6..7061bd1f7 100644 --- a/src/Greenshot.Editor/Forms/MovableShowColorForm.cs +++ b/src/Greenshot.Editor/Forms/MovableShowColorForm.cs @@ -27,6 +27,7 @@ using Dapplo.Windows.Common.Structs; using Dapplo.Windows.Gdi32; using Dapplo.Windows.Gdi32.SafeHandles; using Dapplo.Windows.User32; +using System.Linq; namespace Greenshot.Editor.Forms { @@ -36,15 +37,9 @@ namespace Greenshot.Editor.Forms /// public partial class MovableShowColorForm : Form { - public Color Color - { - get { return preview.BackColor; } - } + public Color Color => preview.BackColor; - public MovableShowColorForm() - { - InitializeComponent(); - } + public MovableShowColorForm() => InitializeComponent(); /// /// Move the MovableShowColorForm to the specified location and display the color under the (current mouse) coordinates @@ -65,12 +60,11 @@ namespace Greenshot.Editor.Forms var zoomerLocation = new NativePoint(screenCoordinates.X, screenCoordinates.Y) .Offset(cursorSize.Width + 5 - hotspot.X, cursorSize.Height + 5 - hotspot.Y); - - foreach (var displayInfo in DisplayInfo.AllDisplayInfos) + foreach (var (displayInfo, screenRectangle) in from displayInfo in DisplayInfo.AllDisplayInfos + let screenRectangle = displayInfo.Bounds + select (displayInfo, screenRectangle)) { - NativeRect screenRectangle = displayInfo.Bounds; if (!displayInfo.Bounds.Contains(screenCoordinates)) continue; - if (zoomerLocation.X < screenRectangle.X) { zoomerLocation = zoomerLocation.ChangeX(screenRectangle.X); diff --git a/src/Greenshot.Editor/Forms/ResizeSettingsForm.cs b/src/Greenshot.Editor/Forms/ResizeSettingsForm.cs index 5af9f6679..cc7eab831 100644 --- a/src/Greenshot.Editor/Forms/ResizeSettingsForm.cs +++ b/src/Greenshot.Editor/Forms/ResizeSettingsForm.cs @@ -90,31 +90,13 @@ namespace Greenshot.Editor.Forms private void DisplayWidth() { - double displayValue; - if (_valuePercent.Equals(combobox_width.SelectedItem)) - { - displayValue = _newWidth / _effect.Width * 100d; - } - else - { - displayValue = _newWidth; - } - + double displayValue = _valuePercent.Equals(combobox_width.SelectedItem) ? _newWidth / _effect.Width * 100d : _newWidth; textbox_width.Text = ((int)displayValue).ToString(); } private void DisplayHeight() { - double displayValue; - if (_valuePercent.Equals(combobox_height.SelectedItem)) - { - displayValue = _newHeight / _effect.Height * 100d; - } - else - { - displayValue = _newHeight; - } - + double displayValue = _valuePercent.Equals(combobox_height.SelectedItem) ? _newHeight / _effect.Height * 100d : _newHeight; textbox_height.Text = ((int)displayValue).ToString(); } @@ -188,10 +170,7 @@ namespace Greenshot.Editor.Forms } } - private void Textbox_Validating(object sender, System.ComponentModel.CancelEventArgs e) - { - Validate(sender); - } + private void Textbox_Validating(object sender, System.ComponentModel.CancelEventArgs e) => Validate(sender); /// /// diff --git a/src/Greenshot.Editor/Helpers/Colors.cs b/src/Greenshot.Editor/Helpers/Colors.cs index 74ffe9aad..5252abf1e 100644 --- a/src/Greenshot.Editor/Helpers/Colors.cs +++ b/src/Greenshot.Editor/Helpers/Colors.cs @@ -26,10 +26,7 @@ namespace Greenshot.Editor.Helpers { public static class Colors { - public static bool IsVisible(Color c) - { - return c != null && !c.Equals(Color.Empty) && !c.Equals(Color.Transparent) && c.A > 0; - } + public static bool IsVisible(Color c) => c != null && !c.Equals(Color.Empty) && !c.Equals(Color.Transparent) && c.A > 0; public static Color Mix(List colors) { diff --git a/src/Greenshot.Editor/Helpers/GeometryHelper.cs b/src/Greenshot.Editor/Helpers/GeometryHelper.cs index 2c104bfa2..b1e17e695 100644 --- a/src/Greenshot.Editor/Helpers/GeometryHelper.cs +++ b/src/Greenshot.Editor/Helpers/GeometryHelper.cs @@ -56,9 +56,6 @@ namespace Greenshot.Editor.Helpers /// The point on the y-axis of the first point /// The point on the y-axis of the second point /// - public static double Angle2D(int x1, int y1, int x2, int y2) - { - return Math.Atan2(y2 - y1, x2 - x1) * 180 / Math.PI; - } + public static double Angle2D(int x1, int y1, int x2, int y2) => Math.Atan2(y2 - y1, x2 - x1) * 180 / Math.PI; } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Helpers/LineAngleRoundBehavior.cs b/src/Greenshot.Editor/Helpers/LineAngleRoundBehavior.cs index 6811f66cf..27b00d698 100644 --- a/src/Greenshot.Editor/Helpers/LineAngleRoundBehavior.cs +++ b/src/Greenshot.Editor/Helpers/LineAngleRoundBehavior.cs @@ -31,9 +31,6 @@ namespace Greenshot.Editor.Helpers { } - public double Process(double angle) - { - return Math.Round(angle / 15) * 15; - } + public double Process(double angle) => Math.Round(angle / 15) * 15; } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Helpers/ScaleHelper.cs b/src/Greenshot.Editor/Helpers/ScaleHelper.cs index 567a8c4f1..11be13231 100644 --- a/src/Greenshot.Editor/Helpers/ScaleHelper.cs +++ b/src/Greenshot.Editor/Helpers/ScaleHelper.cs @@ -117,21 +117,18 @@ namespace Greenshot.Editor.Helpers /// Positions with the position of the handle/gripper being used for resized, see constants in Gripper.cs, e.g. Gripper.POSITION_TOP_LEFT /// NativePointFloat with coordinates of the used handle/gripper /// NativeRectFloat with the scaled originalRectangle - private static NativeRectFloat Scale(NativeRectFloat originalRectangle, Positions resizeHandlePosition, NativePointFloat resizeHandleCoords) + private static NativeRectFloat Scale(NativeRectFloat originalRectangle, Positions resizeHandlePosition, NativePointFloat resizeHandleCoords) => resizeHandlePosition switch { - return resizeHandlePosition switch - { - Positions.TopLeft => new NativeRectFloat(resizeHandleCoords.X, resizeHandleCoords.Y, originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X, originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y), - Positions.TopCenter => new NativeRectFloat(originalRectangle.X, resizeHandleCoords.Y, originalRectangle.Width, originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y), - Positions.TopRight => new NativeRectFloat(originalRectangle.X, resizeHandleCoords.Y, resizeHandleCoords.X - originalRectangle.Left, originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y), - Positions.MiddleLeft => new NativeRectFloat(resizeHandleCoords.X, originalRectangle.Y, originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X, originalRectangle.Height), - Positions.MiddleRight => new NativeRectFloat(originalRectangle.X, originalRectangle.Y, resizeHandleCoords.X - originalRectangle.Left, originalRectangle.Height), - Positions.BottomLeft => new NativeRectFloat(resizeHandleCoords.X, originalRectangle.Y, originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X, resizeHandleCoords.Y - originalRectangle.Top), - Positions.BottomCenter => new NativeRectFloat(originalRectangle.X, originalRectangle.Y, originalRectangle.Width, resizeHandleCoords.Y - originalRectangle.Top), - Positions.BottomRight => new NativeRectFloat(originalRectangle.X, originalRectangle.Y, resizeHandleCoords.X - originalRectangle.Left, resizeHandleCoords.Y - originalRectangle.Top), - _ => throw new ArgumentException("Position cannot be handled: " + resizeHandlePosition) - }; - } + Positions.TopLeft => new NativeRectFloat(resizeHandleCoords.X, resizeHandleCoords.Y, originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X, originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y), + Positions.TopCenter => new NativeRectFloat(originalRectangle.X, resizeHandleCoords.Y, originalRectangle.Width, originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y), + Positions.TopRight => new NativeRectFloat(originalRectangle.X, resizeHandleCoords.Y, resizeHandleCoords.X - originalRectangle.Left, originalRectangle.Top + originalRectangle.Height - resizeHandleCoords.Y), + Positions.MiddleLeft => new NativeRectFloat(resizeHandleCoords.X, originalRectangle.Y, originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X, originalRectangle.Height), + Positions.MiddleRight => new NativeRectFloat(originalRectangle.X, originalRectangle.Y, resizeHandleCoords.X - originalRectangle.Left, originalRectangle.Height), + Positions.BottomLeft => new NativeRectFloat(resizeHandleCoords.X, originalRectangle.Y, originalRectangle.Left + originalRectangle.Width - resizeHandleCoords.X, resizeHandleCoords.Y - originalRectangle.Top), + Positions.BottomCenter => new NativeRectFloat(originalRectangle.X, originalRectangle.Y, originalRectangle.Width, resizeHandleCoords.Y - originalRectangle.Top), + Positions.BottomRight => new NativeRectFloat(originalRectangle.X, originalRectangle.Y, resizeHandleCoords.X - originalRectangle.Left, resizeHandleCoords.Y - originalRectangle.Top), + _ => throw new ArgumentException("Position cannot be handled: " + resizeHandlePosition) + }; /// /// Adjusts resizeHandleCoords so that aspect ratio is kept after resizing a given rectangle with provided arguments. diff --git a/src/Greenshot.Editor/Helpers/ShapeAngleRoundBehavior.cs b/src/Greenshot.Editor/Helpers/ShapeAngleRoundBehavior.cs index 7fcd1284d..951805592 100644 --- a/src/Greenshot.Editor/Helpers/ShapeAngleRoundBehavior.cs +++ b/src/Greenshot.Editor/Helpers/ShapeAngleRoundBehavior.cs @@ -31,9 +31,6 @@ namespace Greenshot.Editor.Helpers { } - public double Process(double angle) - { - return (Math.Round((angle + 45) / 90) * 90) - 45; - } + public double Process(double angle) => (Math.Round((angle + 45) / 90) * 90) - 45; } } \ No newline at end of file diff --git a/src/Greenshot.Editor/Helpers/ToolStripItemEndisabler.cs b/src/Greenshot.Editor/Helpers/ToolStripItemEndisabler.cs index 257e362c2..674b1cb99 100644 --- a/src/Greenshot.Editor/Helpers/ToolStripItemEndisabler.cs +++ b/src/Greenshot.Editor/Helpers/ToolStripItemEndisabler.cs @@ -43,28 +43,19 @@ namespace Greenshot.Editor.Helpers /// Enables all of a ToolStrip's children (recursively), /// but not the ToolStrip itself /// - public static void Enable(ToolStrip ts) - { - Endisable(ts, true, PropagationMode.CHILDREN); - } + public static void Enable(ToolStrip ts) => Endisable(ts, true, PropagationMode.CHILDREN); /// /// Disables all of a ToolStrip's children (recursively), /// but not the ToolStrip itself /// - public static void Disable(ToolStrip ts) - { - Endisable(ts, false, PropagationMode.CHILDREN); - } + public static void Disable(ToolStrip ts) => Endisable(ts, false, PropagationMode.CHILDREN); /// /// Enables the ToolStripItem, including children (ToolStripDropDownItem) /// and ancestor (OwnerItem) /// - public static void Enable(ToolStripItem tsi) - { - Endisable(tsi, true, PropagationMode.CHILDREN | PropagationMode.ANCESTORS); - } + public static void Enable(ToolStripItem tsi) => Endisable(tsi, true, PropagationMode.CHILDREN | PropagationMode.ANCESTORS); private static void Endisable(ToolStrip ts, bool enable, PropagationMode mode) { diff --git a/src/Greenshot.Editor/Memento/AddElementMemento.cs b/src/Greenshot.Editor/Memento/AddElementMemento.cs index f9d60b7fb..c7900daea 100644 --- a/src/Greenshot.Editor/Memento/AddElementMemento.cs +++ b/src/Greenshot.Editor/Memento/AddElementMemento.cs @@ -51,10 +51,7 @@ namespace Greenshot.Editor.Memento _surface = null; } - public bool Merge(IMemento otherMemento) - { - return false; - } + public bool Merge(IMemento otherMemento) => false; public IMemento Restore() { diff --git a/src/Greenshot.Editor/Memento/AddElementsMemento.cs b/src/Greenshot.Editor/Memento/AddElementsMemento.cs index 0b11fac15..4fd810f3c 100644 --- a/src/Greenshot.Editor/Memento/AddElementsMemento.cs +++ b/src/Greenshot.Editor/Memento/AddElementsMemento.cs @@ -38,10 +38,7 @@ namespace Greenshot.Editor.Memento _containerList = containerList; } - public void Dispose() - { - Dispose(true); - } + public void Dispose() => Dispose(true); private void Dispose(bool disposing) { @@ -54,10 +51,7 @@ namespace Greenshot.Editor.Memento _surface = null; } - public bool Merge(IMemento otherMemento) - { - return false; - } + public bool Merge(IMemento otherMemento) => false; public IMemento Restore() { diff --git a/src/Greenshot.Editor/Memento/ChangeFieldHolderMemento.cs b/src/Greenshot.Editor/Memento/ChangeFieldHolderMemento.cs index bf5db52f3..4354a0a0d 100644 --- a/src/Greenshot.Editor/Memento/ChangeFieldHolderMemento.cs +++ b/src/Greenshot.Editor/Memento/ChangeFieldHolderMemento.cs @@ -39,10 +39,7 @@ namespace Greenshot.Editor.Memento _oldValue = fieldToBeChanged.Value; } - public void Dispose() - { - Dispose(true); - } + public void Dispose() => Dispose(true); private void Dispose(bool disposing) { diff --git a/src/Greenshot.Editor/Memento/DeleteElementMemento.cs b/src/Greenshot.Editor/Memento/DeleteElementMemento.cs index 1d744239d..73de769c8 100644 --- a/src/Greenshot.Editor/Memento/DeleteElementMemento.cs +++ b/src/Greenshot.Editor/Memento/DeleteElementMemento.cs @@ -56,10 +56,7 @@ namespace Greenshot.Editor.Memento } } - public bool Merge(IMemento otherMemento) - { - return false; - } + public bool Merge(IMemento otherMemento) => false; public IMemento Restore() { diff --git a/src/Greenshot.Editor/Memento/DeleteElementsMemento.cs b/src/Greenshot.Editor/Memento/DeleteElementsMemento.cs index 509bbb016..dd242ce0a 100644 --- a/src/Greenshot.Editor/Memento/DeleteElementsMemento.cs +++ b/src/Greenshot.Editor/Memento/DeleteElementsMemento.cs @@ -38,10 +38,7 @@ namespace Greenshot.Editor.Memento _containerList = containerList; } - public void Dispose() - { - Dispose(true); - } + public void Dispose() => Dispose(true); private void Dispose(bool disposing) { @@ -54,10 +51,7 @@ namespace Greenshot.Editor.Memento _surface = null; } - public bool Merge(IMemento otherMemento) - { - return false; - } + public bool Merge(IMemento otherMemento) => false; public IMemento Restore() { diff --git a/src/Greenshot.Editor/Memento/DrawableContainerBoundsChangeMemento.cs b/src/Greenshot.Editor/Memento/DrawableContainerBoundsChangeMemento.cs index b5b97e4cf..5d7cd2d0b 100644 --- a/src/Greenshot.Editor/Memento/DrawableContainerBoundsChangeMemento.cs +++ b/src/Greenshot.Editor/Memento/DrawableContainerBoundsChangeMemento.cs @@ -61,10 +61,7 @@ namespace Greenshot.Editor.Memento StoreBounds(); } - public void Dispose() - { - Dispose(true); - } + public void Dispose() => Dispose(true); private void Dispose(bool disposing) { diff --git a/src/Greenshot.Editor/Memento/SurfaceBackgroundChangeMemento.cs b/src/Greenshot.Editor/Memento/SurfaceBackgroundChangeMemento.cs index a55c140f4..250ab4dde 100644 --- a/src/Greenshot.Editor/Memento/SurfaceBackgroundChangeMemento.cs +++ b/src/Greenshot.Editor/Memento/SurfaceBackgroundChangeMemento.cs @@ -47,10 +47,7 @@ namespace Greenshot.Editor.Memento } } - public void Dispose() - { - Dispose(true); - } + public void Dispose() => Dispose(true); private void Dispose(bool disposing) { @@ -71,10 +68,7 @@ namespace Greenshot.Editor.Memento _surface = null; } - public bool Merge(IMemento otherMemento) - { - return false; - } + public bool Merge(IMemento otherMemento) => false; public IMemento Restore() { diff --git a/src/Greenshot.Editor/Memento/TextChangeMemento.cs b/src/Greenshot.Editor/Memento/TextChangeMemento.cs index 71cc9ba99..9441b0a7c 100644 --- a/src/Greenshot.Editor/Memento/TextChangeMemento.cs +++ b/src/Greenshot.Editor/Memento/TextChangeMemento.cs @@ -38,10 +38,7 @@ namespace Greenshot.Editor.Memento _oldText = textContainer.Text; } - public void Dispose() - { - Dispose(true); - } + public void Dispose() => Dispose(true); private void Dispose(bool disposing) { @@ -51,10 +48,7 @@ namespace Greenshot.Editor.Memento } } - public bool Merge(IMemento otherMemento) - { - return otherMemento is TextChangeMemento other && other._textContainer.Equals(_textContainer); - } + public bool Merge(IMemento otherMemento) => otherMemento is TextChangeMemento other && other._textContainer.Equals(_textContainer); public IMemento Restore() { diff --git a/src/Greenshot.Plugin.Box/BoxDestination.cs b/src/Greenshot.Plugin.Box/BoxDestination.cs index 0126fa1e2..e77c52954 100644 --- a/src/Greenshot.Plugin.Box/BoxDestination.cs +++ b/src/Greenshot.Plugin.Box/BoxDestination.cs @@ -30,10 +30,7 @@ namespace Greenshot.Plugin.Box { private readonly BoxPlugin _plugin; - public BoxDestination(BoxPlugin plugin) - { - _plugin = plugin; - } + public BoxDestination(BoxPlugin plugin) => _plugin = plugin; public override string Designation => "Box"; diff --git a/src/Greenshot.Plugin.Box/BoxPlugin.cs b/src/Greenshot.Plugin.Box/BoxPlugin.cs index db8c66bd6..73a2a81b0 100644 --- a/src/Greenshot.Plugin.Box/BoxPlugin.cs +++ b/src/Greenshot.Plugin.Box/BoxPlugin.cs @@ -97,23 +97,14 @@ namespace Greenshot.Plugin.Box } } - public void Shutdown() - { - LOG.Debug("Box Plugin shutdown."); - } + public void Shutdown() => LOG.Debug("Box Plugin shutdown."); /// /// Implementation of the IPlugin.Configure /// - public void Configure() - { - _config.ShowConfigDialog(); - } + public void Configure() => _config.ShowConfigDialog(); - public void ConfigMenuClick(object sender, EventArgs eventArgs) - { - _config.ShowConfigDialog(); - } + public void ConfigMenuClick(object sender, EventArgs eventArgs) => _config.ShowConfigDialog(); /// /// This will be called when the menu item in the Editor is clicked diff --git a/src/Greenshot.Plugin.Confluence/Confluence.cs b/src/Greenshot.Plugin.Confluence/Confluence.cs index 963c3e746..877291724 100644 --- a/src/Greenshot.Plugin.Confluence/Confluence.cs +++ b/src/Greenshot.Plugin.Confluence/Confluence.cs @@ -60,13 +60,10 @@ namespace Greenshot.Plugin.Confluence Logout(); } - if (disposing) + if (disposing && _confluence != null) { - if (_confluence != null) - { - _confluence.Dispose(); - _confluence = null; - } + _confluence.Dispose(); + _confluence = null; } } diff --git a/src/Greenshot.Plugin.Confluence/ConfluenceDestination.cs b/src/Greenshot.Plugin.Confluence/ConfluenceDestination.cs index b043b5264..874affa7e 100644 --- a/src/Greenshot.Plugin.Confluence/ConfluenceDestination.cs +++ b/src/Greenshot.Plugin.Confluence/ConfluenceDestination.cs @@ -72,40 +72,19 @@ namespace Greenshot.Plugin.Confluence { } - public ConfluenceDestination(Page page) - { - _page = page; - } + public ConfluenceDestination(Page page) => _page = page; - public override string Designation - { - get { return "Confluence"; } - } + public override string Designation => "Confluence"; - public override string Description - { - get - { - return _page == null + public override string Description => _page == null ? Language.GetString("confluence", LangKey.upload_menu_item) : Language.GetString("confluence", LangKey.upload_menu_item) + ": \"" + _page.Title + "\""; - } - } - public override bool IsDynamic - { - get { return true; } - } + public override bool IsDynamic => true; - public override bool IsActive - { - get { return base.IsActive && !string.IsNullOrEmpty(ConfluenceConfig.Url); } - } + public override bool IsActive => base.IsActive && !string.IsNullOrEmpty(ConfluenceConfig.Url); - public override Image DisplayIcon - { - get { return ConfluenceIcon; } - } + public override Image DisplayIcon => ConfluenceIcon; public override IEnumerable DynamicDestinations() { diff --git a/src/Greenshot.Plugin.Confluence/ConfluencePlugin.cs b/src/Greenshot.Plugin.Confluence/ConfluencePlugin.cs index e3c24ac0a..f62926ca1 100644 --- a/src/Greenshot.Plugin.Confluence/ConfluencePlugin.cs +++ b/src/Greenshot.Plugin.Confluence/ConfluencePlugin.cs @@ -64,21 +64,13 @@ namespace Greenshot.Plugin.Confluence { if (_confluenceConnector == null) { - if (_config.Url.Contains("soap-axis")) - { - _confluenceConnector = new ConfluenceConnector(_config.Url, _config.Timeout); - } - else - { - _confluenceConnector = new ConfluenceConnector(_config.Url + ConfluenceConfiguration.DEFAULT_POSTFIX2, _config.Timeout); - } + _confluenceConnector = _config.Url.Contains("soap-axis") + ? new ConfluenceConnector(_config.Url, _config.Timeout) + : new ConfluenceConnector(_config.Url + ConfluenceConfiguration.DEFAULT_POSTFIX2, _config.Timeout); } } - public static ConfluenceConnector ConfluenceConnectorNoLogin - { - get { return _confluenceConnector; } - } + public static ConfluenceConnector ConfluenceConnectorNoLogin => _confluenceConnector; public static ConfluenceConnector ConfluenceConnector { @@ -160,17 +152,14 @@ namespace Greenshot.Plugin.Confluence // copy the new object to the old... clonedConfig.CloneTo(_config); IniConfig.Save(); - if (_confluenceConnector != null) + if (_confluenceConnector != null && !url.Equals(_config.Url)) { - if (!url.Equals(_config.Url)) + if (_confluenceConnector.IsLoggedIn) { - if (_confluenceConnector.IsLoggedIn) - { - _confluenceConnector.Logout(); - } - - _confluenceConnector = null; + _confluenceConnector.Logout(); } + + _confluenceConnector = null; } } } diff --git a/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs b/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs index a2cdd2806..e56140750 100644 --- a/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs +++ b/src/Greenshot.Plugin.Confluence/ConfluenceUtils.cs @@ -89,49 +89,45 @@ namespace Greenshot.Plugin.Confluence } MatchCollection spacePageMatch = spacePageRegex.Matches(url); - if (spacePageMatch?.Count > 0) + if (spacePageMatch?.Count > 0 && spacePageMatch[0].Groups.Count >= 2) { - if (spacePageMatch[0].Groups.Count >= 2) + string space = spacePageMatch[0].Groups[1].Value; + string title = spacePageMatch[0].Groups[2].Value; + if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(space)) { - string space = spacePageMatch[0].Groups[1].Value; - string title = spacePageMatch[0].Groups[2].Value; - if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(space)) + continue; + } + + if (title.EndsWith("#")) + { + title = title.Substring(0, title.Length - 1); + } + + try + { + bool pageDouble = false; + foreach (var _ in from Page page in pages + where page.Title.Equals(title) + select new { }) { - continue; + LOG.DebugFormat("Skipping double page with title {0}", title); + pageDouble = true; + break; } - if (title.EndsWith("#")) + if (!pageDouble) { - title = title.Substring(0, title.Length - 1); - } - - try - { - bool pageDouble = false; - foreach (Page page in pages) - { - if (page.Title.Equals(title)) - { - LOG.DebugFormat("Skipping double page with title {0}", title); - pageDouble = true; - break; - } - } - - if (!pageDouble) - { - Page page = ConfluencePlugin.ConfluenceConnector.GetPage(space, title); - LOG.DebugFormat("Adding page {0}", page.Title); - pages.Add(page); - } - } - catch (Exception ex) - { - // Preventing security problems - LOG.DebugFormat("Couldn't get page details for space {0} / title {1}", space, title); - LOG.Warn(ex); + Page page = ConfluencePlugin.ConfluenceConnector.GetPage(space, title); + LOG.DebugFormat("Adding page {0}", page.Title); + pages.Add(page); } } + catch (Exception ex) + { + // Preventing security problems + LOG.DebugFormat("Couldn't get page details for space {0} / title {1}", space, title); + LOG.Warn(ex); + } } } diff --git a/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs b/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs index 2381c0d23..f29402c1d 100644 --- a/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs +++ b/src/Greenshot.Plugin.Confluence/EnumDisplayer.cs @@ -101,14 +101,8 @@ namespace Greenshot.Plugin.Confluence return dka.Value; } - object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - return _displayValues[value]; - } + object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) => _displayValues[value]; - object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - return _reverseValues[value]; - } + object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => _reverseValues[value]; } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceConfigurationForm.xaml.cs b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceConfigurationForm.xaml.cs index f8cfa6475..257816e64 100644 --- a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceConfigurationForm.xaml.cs +++ b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceConfigurationForm.xaml.cs @@ -37,9 +37,6 @@ namespace Greenshot.Plugin.Confluence.Forms InitializeComponent(); } - private void Button_OK_Click(object sender, RoutedEventArgs e) - { - DialogResult = true; - } + private void Button_OK_Click(object sender, RoutedEventArgs e) => DialogResult = true; } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Confluence/Forms/ConfluencePagePicker.xaml.cs b/src/Greenshot.Plugin.Confluence/Forms/ConfluencePagePicker.xaml.cs index 0f48dbe5a..bdac51569 100644 --- a/src/Greenshot.Plugin.Confluence/Forms/ConfluencePagePicker.xaml.cs +++ b/src/Greenshot.Plugin.Confluence/Forms/ConfluencePagePicker.xaml.cs @@ -38,10 +38,7 @@ namespace Greenshot.Plugin.Confluence.Forms InitializeComponent(); } - private void PageListView_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) - { - SelectionChanged(); - } + private void PageListView_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) => SelectionChanged(); private void SelectionChanged() { @@ -57,9 +54,6 @@ namespace Greenshot.Plugin.Confluence.Forms } } - private void Page_Loaded(object sender, System.Windows.RoutedEventArgs e) - { - SelectionChanged(); - } + private void Page_Loaded(object sender, System.Windows.RoutedEventArgs e) => SelectionChanged(); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceSearch.xaml.cs b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceSearch.xaml.cs index e473fd8ef..64d2ff1be 100644 --- a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceSearch.xaml.cs +++ b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceSearch.xaml.cs @@ -42,43 +42,30 @@ namespace Greenshot.Plugin.Confluence.Forms _confluenceUpload = confluenceUpload; DataContext = this; InitializeComponent(); - if (ConfluenceConfig.SearchSpaceKey == null) + switch (ConfluenceConfig.SearchSpaceKey) { - SpaceComboBox.SelectedItem = Spaces.FirstOrDefault(); - } - else - { - foreach (var space in Spaces) - { - if (space.Key.Equals(ConfluenceConfig.SearchSpaceKey)) + case null: + SpaceComboBox.SelectedItem = Spaces.FirstOrDefault(); + break; + default: { - SpaceComboBox.SelectedItem = space; + foreach (var space in from space in Spaces + where space.Key.Equals(ConfluenceConfig.SearchSpaceKey) + select space) + { + SpaceComboBox.SelectedItem = space; + } + + break; } - } } } - private void PageListView_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) - { - SelectionChanged(); - } + private void PageListView_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) => SelectionChanged(); - private void SelectionChanged() - { - if (PageListView.HasItems && PageListView.SelectedItems.Count > 0) - { - _confluenceUpload.SelectedPage = (Page)PageListView.SelectedItem; - } - else - { - _confluenceUpload.SelectedPage = null; - } - } + private void SelectionChanged() => _confluenceUpload.SelectedPage = PageListView.HasItems && PageListView.SelectedItems.Count > 0 ? (Page)PageListView.SelectedItem : null; - private void Search_Click(object sender, RoutedEventArgs e) - { - DoSearch(); - } + private void Search_Click(object sender, RoutedEventArgs e) => DoSearch(); private void DoSearch() { @@ -100,14 +87,8 @@ namespace Greenshot.Plugin.Confluence.Forms } } - private void Page_Loaded(object sender, RoutedEventArgs e) - { - SelectionChanged(); - } + private void Page_Loaded(object sender, RoutedEventArgs e) => SelectionChanged(); - private void SearchText_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e) - { - Search.IsEnabled = !string.IsNullOrEmpty(searchText.Text); - } + private void SearchText_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e) => Search.IsEnabled = !string.IsNullOrEmpty(searchText.Text); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceUpload.xaml.cs b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceUpload.xaml.cs index be002b301..2f2a9d21b 100644 --- a/src/Greenshot.Plugin.Confluence/Forms/ConfluenceUpload.xaml.cs +++ b/src/Greenshot.Plugin.Confluence/Forms/ConfluenceUpload.xaml.cs @@ -54,17 +54,11 @@ namespace Greenshot.Plugin.Confluence.Forms private System.Windows.Controls.Page _searchPage; - public System.Windows.Controls.Page SearchPage - { - get { return _searchPage ??= new ConfluenceSearch(this); } - } + public System.Windows.Controls.Page SearchPage => _searchPage ??= new ConfluenceSearch(this); private System.Windows.Controls.Page _browsePage; - public System.Windows.Controls.Page BrowsePage - { - get { return _browsePage ??= new ConfluenceTreePicker(this); } - } + public System.Windows.Controls.Page BrowsePage => _browsePage ??= new ConfluenceTreePicker(this); private Page _selectedPage; @@ -135,9 +129,6 @@ namespace Greenshot.Plugin.Confluence.Forms } } - private void Upload_Click(object sender, RoutedEventArgs e) - { - DialogResult = true; - } + private void Upload_Click(object sender, RoutedEventArgs e) => DialogResult = true; } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Confluence/Support/LanguageChangedEventManager.cs b/src/Greenshot.Plugin.Confluence/Support/LanguageChangedEventManager.cs index 29568023f..e86216624 100644 --- a/src/Greenshot.Plugin.Confluence/Support/LanguageChangedEventManager.cs +++ b/src/Greenshot.Plugin.Confluence/Support/LanguageChangedEventManager.cs @@ -5,20 +5,11 @@ namespace Greenshot.Plugin.Confluence.Support { public class LanguageChangedEventManager : WeakEventManager { - public static void AddListener(TranslationManager source, IWeakEventListener listener) - { - CurrentManager.ProtectedAddListener(source, listener); - } + public static void AddListener(TranslationManager source, IWeakEventListener listener) => CurrentManager.ProtectedAddListener(source, listener); - public static void RemoveListener(TranslationManager source, IWeakEventListener listener) - { - CurrentManager.ProtectedRemoveListener(source, listener); - } + public static void RemoveListener(TranslationManager source, IWeakEventListener listener) => CurrentManager.ProtectedRemoveListener(source, listener); - private void OnLanguageChanged(object sender, EventArgs e) - { - DeliverEvent(sender, e); - } + private void OnLanguageChanged(object sender, EventArgs e) => DeliverEvent(sender, e); protected override void StartListening(object source) { diff --git a/src/Greenshot.Plugin.Confluence/Support/LanguageXMLTranslationProvider.cs b/src/Greenshot.Plugin.Confluence/Support/LanguageXMLTranslationProvider.cs index 330ae6b83..883624b6f 100644 --- a/src/Greenshot.Plugin.Confluence/Support/LanguageXMLTranslationProvider.cs +++ b/src/Greenshot.Plugin.Confluence/Support/LanguageXMLTranslationProvider.cs @@ -10,9 +10,6 @@ namespace Greenshot.Plugin.Confluence.Support /// /// See /// - public object Translate(string key) - { - return Language.HasKey("confluence", key) ? Language.GetString("confluence", key) : (object)key; - } + public object Translate(string key) => Language.HasKey("confluence", key) ? Language.GetString("confluence", key) : (object)key; } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Confluence/Support/TranslateExtension.cs b/src/Greenshot.Plugin.Confluence/Support/TranslateExtension.cs index 6472e23a9..e0a4c4ec5 100644 --- a/src/Greenshot.Plugin.Confluence/Support/TranslateExtension.cs +++ b/src/Greenshot.Plugin.Confluence/Support/TranslateExtension.cs @@ -14,10 +14,7 @@ namespace Greenshot.Plugin.Confluence.Support /// Initializes a new instance of the class. /// /// The key. - public TranslateExtension(string key) - { - Key = key; - } + public TranslateExtension(string key) => Key = key; [ConstructorArgument("key")] public string Key { get; set; } diff --git a/src/Greenshot.Plugin.Confluence/Support/TranslationData.cs b/src/Greenshot.Plugin.Confluence/Support/TranslationData.cs index 0ebce8300..31e95cda8 100644 --- a/src/Greenshot.Plugin.Confluence/Support/TranslationData.cs +++ b/src/Greenshot.Plugin.Confluence/Support/TranslationData.cs @@ -40,10 +40,7 @@ namespace Greenshot.Plugin.Confluence.Support return false; } - private void OnLanguageChanged(object sender, EventArgs e) - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value")); - } + private void OnLanguageChanged(object sender, EventArgs e) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value")); public event PropertyChangedEventHandler PropertyChanged; } diff --git a/src/Greenshot.Plugin.Confluence/Web References/confluence/Reference.cs b/src/Greenshot.Plugin.Confluence/Web References/confluence/Reference.cs index aba156d27..5127f796c 100644 --- a/src/Greenshot.Plugin.Confluence/Web References/confluence/Reference.cs +++ b/src/Greenshot.Plugin.Confluence/Web References/confluence/Reference.cs @@ -68,30 +68,31 @@ namespace GreenshotConfluencePlugin.confluence { } } - public new string Url { - get { - return base.Url; - } - set { - if ((((this.IsLocalFileSystemWebService(base.Url) == true) - && (this.useDefaultCredentialsSetExplicitly == false)) - && (this.IsLocalFileSystemWebService(value) == false))) { + public new string Url + { + get => base.Url; + set + { + if ((((this.IsLocalFileSystemWebService(base.Url) == true) + && (this.useDefaultCredentialsSetExplicitly == false)) + && (this.IsLocalFileSystemWebService(value) == false))) + { base.UseDefaultCredentials = false; } base.Url = value; } } - - public new bool UseDefaultCredentials { - get { - return base.UseDefaultCredentials; - } - set { + + public new bool UseDefaultCredentials + { + get => base.UseDefaultCredentials; + set + { base.UseDefaultCredentials = value; this.useDefaultCredentialsSetExplicitly = true; } } - + /// public event searchCompletedEventHandler searchCompleted; @@ -135,12 +136,10 @@ namespace GreenshotConfluencePlugin.confluence { in2}); return ((RemoteSearchResult[])(results[0])); } - + /// - public void searchAsync(string in0, string in1, int in2) { - this.searchAsync(in0, in1, in2, null); - } - + public void searchAsync(string in0, string in1, int in2) => this.searchAsync(in0, in1, in2, null); + /// public void searchAsync(string in0, string in1, int in2, object userState) { if ((this.searchOperationCompleted == null)) { @@ -168,12 +167,10 @@ namespace GreenshotConfluencePlugin.confluence { in1}); return ((RemoteSpace)(results[0])); } - + /// - public void getSpaceAsync(string in0, string in1) { - this.getSpaceAsync(in0, in1, null); - } - + public void getSpaceAsync(string in0, string in1) => this.getSpaceAsync(in0, in1, null); + /// public void getSpaceAsync(string in0, string in1, object userState) { if ((this.getSpaceOperationCompleted == null)) { @@ -200,12 +197,10 @@ namespace GreenshotConfluencePlugin.confluence { in1}); return ((RemotePageSummary[])(results[0])); } - + /// - public void getChildrenAsync(string in0, long in1) { - this.getChildrenAsync(in0, in1, null); - } - + public void getChildrenAsync(string in0, long in1) => this.getChildrenAsync(in0, in1, null); + /// public void getChildrenAsync(string in0, long in1, object userState) { if ((this.getChildrenOperationCompleted == null)) { @@ -232,12 +227,10 @@ namespace GreenshotConfluencePlugin.confluence { in1}); return ((string)(results[0])); } - + /// - public void loginAsync(string in0, string in1) { - this.loginAsync(in0, in1, null); - } - + public void loginAsync(string in0, string in1) => this.loginAsync(in0, in1, null); + /// public void loginAsync(string in0, string in1, object userState) { if ((this.loginOperationCompleted == null)) { @@ -265,12 +258,10 @@ namespace GreenshotConfluencePlugin.confluence { in2}); return ((RemotePage)(results[0])); } - + /// - public void getPageAsync(string in0, string in1, string in2) { - this.getPageAsync(in0, in1, in2, null); - } - + public void getPageAsync(string in0, string in1, string in2) => this.getPageAsync(in0, in1, in2, null); + /// public void getPageAsync(string in0, string in1, string in2, object userState) { if ((this.getPageOperationCompleted == null)) { @@ -299,12 +290,10 @@ namespace GreenshotConfluencePlugin.confluence { in1}); return ((RemotePage)(results[0])); } - + /// - public void getPage1Async(string in0, long in1) { - this.getPage1Async(in0, in1, null); - } - + public void getPage1Async(string in0, long in1) => this.getPage1Async(in0, in1, null); + /// public void getPage1Async(string in0, long in1, object userState) { if ((this.getPage1OperationCompleted == null)) { @@ -330,12 +319,10 @@ namespace GreenshotConfluencePlugin.confluence { in0}); return ((bool)(results[0])); } - + /// - public void logoutAsync(string in0) { - this.logoutAsync(in0, null); - } - + public void logoutAsync(string in0) => this.logoutAsync(in0, null); + /// public void logoutAsync(string in0, object userState) { if ((this.logoutOperationCompleted == null)) { @@ -363,12 +350,10 @@ namespace GreenshotConfluencePlugin.confluence { in3}); return ((RemoteAttachment)(results[0])); } - + /// - public void addAttachmentAsync(string in0, long in1, RemoteAttachment in2, byte[] in3) { - this.addAttachmentAsync(in0, in1, in2, in3, null); - } - + public void addAttachmentAsync(string in0, long in1, RemoteAttachment in2, byte[] in3) => this.addAttachmentAsync(in0, in1, in2, in3, null); + /// public void addAttachmentAsync(string in0, long in1, RemoteAttachment in2, byte[] in3, object userState) { if ((this.addAttachmentOperationCompleted == null)) { @@ -399,12 +384,10 @@ namespace GreenshotConfluencePlugin.confluence { in2}); return ((RemoteAttachment)(results[0])); } - + /// - public void addAttachment1Async(string in0, RemoteAttachment in1, byte[] in2) { - this.addAttachment1Async(in0, in1, in2, null); - } - + public void addAttachment1Async(string in0, RemoteAttachment in1, byte[] in2) => this.addAttachment1Async(in0, in1, in2, null); + /// public void addAttachment1Async(string in0, RemoteAttachment in1, byte[] in2, object userState) { if ((this.addAttachment1OperationCompleted == null)) { @@ -431,12 +414,10 @@ namespace GreenshotConfluencePlugin.confluence { in0}); return ((RemoteSpaceSummary[])(results[0])); } - + /// - public void getSpacesAsync(string in0) { - this.getSpacesAsync(in0, null); - } - + public void getSpacesAsync(string in0) => this.getSpacesAsync(in0, null); + /// public void getSpacesAsync(string in0, object userState) { if ((this.getSpacesOperationCompleted == null)) { @@ -462,12 +443,10 @@ namespace GreenshotConfluencePlugin.confluence { in1}); return ((RemotePageSummary[])(results[0])); } - + /// - public void getPagesAsync(string in0, string in1) { - this.getPagesAsync(in0, in1, null); - } - + public void getPagesAsync(string in0, string in1) => this.getPagesAsync(in0, in1, null); + /// public void getPagesAsync(string in0, string in1, object userState) { if ((this.getPagesOperationCompleted == null)) { @@ -484,12 +463,10 @@ namespace GreenshotConfluencePlugin.confluence { this.getPagesCompleted(this, new getPagesCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } - + /// - public new void CancelAsync(object userState) { - base.CancelAsync(userState); - } - + public new void CancelAsync(object userState) => base.CancelAsync(userState); + private bool IsLocalFileSystemWebService(string url) { if (((url == null) || (url == string.Empty))) { @@ -525,55 +502,35 @@ namespace GreenshotConfluencePlugin.confluence { /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string excerpt { - get { - return this.excerptField; - } - set { - this.excerptField = value; - } + get => this.excerptField; + set => this.excerptField = value; } - + /// public long id { - get { - return this.idField; - } - set { - this.idField = value; - } + get => this.idField; + set => this.idField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string title { - get { - return this.titleField; - } - set { - this.titleField = value; - } + get => this.titleField; + set => this.titleField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string type { - get { - return this.typeField; - } - set { - this.typeField = value; - } + get => this.typeField; + set => this.typeField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string url { - get { - return this.urlField; - } - set { - this.urlField = value; - } + get => this.urlField; + set => this.urlField = value; } } @@ -608,108 +565,68 @@ namespace GreenshotConfluencePlugin.confluence { /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string comment { - get { - return this.commentField; - } - set { - this.commentField = value; - } + get => this.commentField; + set => this.commentField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string contentType { - get { - return this.contentTypeField; - } - set { - this.contentTypeField = value; - } + get => this.contentTypeField; + set => this.contentTypeField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public System.Nullable created { - get { - return this.createdField; - } - set { - this.createdField = value; - } + get => this.createdField; + set => this.createdField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string creator { - get { - return this.creatorField; - } - set { - this.creatorField = value; - } + get => this.creatorField; + set => this.creatorField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string fileName { - get { - return this.fileNameField; - } - set { - this.fileNameField = value; - } + get => this.fileNameField; + set => this.fileNameField = value; } - + /// public long fileSize { - get { - return this.fileSizeField; - } - set { - this.fileSizeField = value; - } + get => this.fileSizeField; + set => this.fileSizeField = value; } - + /// public long id { - get { - return this.idField; - } - set { - this.idField = value; - } + get => this.idField; + set => this.idField = value; } - + /// public long pageId { - get { - return this.pageIdField; - } - set { - this.pageIdField = value; - } + get => this.pageIdField; + set => this.pageIdField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string title { - get { - return this.titleField; - } - set { - this.titleField = value; - } + get => this.titleField; + set => this.titleField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string url { - get { - return this.urlField; - } - set { - this.urlField = value; - } + get => this.urlField; + set => this.urlField = value; } } @@ -735,55 +652,35 @@ namespace GreenshotConfluencePlugin.confluence { /// public long id { - get { - return this.idField; - } - set { - this.idField = value; - } + get => this.idField; + set => this.idField = value; } - + /// public int permissions { - get { - return this.permissionsField; - } - set { - this.permissionsField = value; - } + get => this.permissionsField; + set => this.permissionsField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string space { - get { - return this.spaceField; - } - set { - this.spaceField = value; - } + get => this.spaceField; + set => this.spaceField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string title { - get { - return this.titleField; - } - set { - this.titleField = value; - } + get => this.titleField; + set => this.titleField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string url { - get { - return this.urlField; - } - set { - this.urlField = value; - } + get => this.urlField; + set => this.urlField = value; } } @@ -800,12 +697,8 @@ namespace GreenshotConfluencePlugin.confluence { /// public long parentId { - get { - return this.parentIdField; - } - set { - this.parentIdField = value; - } + get => this.parentIdField; + set => this.parentIdField = value; } } @@ -838,97 +731,61 @@ namespace GreenshotConfluencePlugin.confluence { /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string content { - get { - return this.contentField; - } - set { - this.contentField = value; - } + get => this.contentField; + set => this.contentField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string contentStatus { - get { - return this.contentStatusField; - } - set { - this.contentStatusField = value; - } + get => this.contentStatusField; + set => this.contentStatusField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public System.Nullable created { - get { - return this.createdField; - } - set { - this.createdField = value; - } + get => this.createdField; + set => this.createdField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string creator { - get { - return this.creatorField; - } - set { - this.creatorField = value; - } + get => this.creatorField; + set => this.creatorField = value; } - + /// public bool current { - get { - return this.currentField; - } - set { - this.currentField = value; - } + get => this.currentField; + set => this.currentField = value; } - + /// public bool homePage { - get { - return this.homePageField; - } - set { - this.homePageField = value; - } + get => this.homePageField; + set => this.homePageField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public System.Nullable modified { - get { - return this.modifiedField; - } - set { - this.modifiedField = value; - } + get => this.modifiedField; + set => this.modifiedField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string modifier { - get { - return this.modifierField; - } - set { - this.modifierField = value; - } + get => this.modifierField; + set => this.modifierField = value; } - + /// public int version { - get { - return this.versionField; - } - set { - this.versionField = value; - } + get => this.versionField; + set => this.versionField = value; } } @@ -952,45 +809,29 @@ namespace GreenshotConfluencePlugin.confluence { /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string key { - get { - return this.keyField; - } - set { - this.keyField = value; - } + get => this.keyField; + set => this.keyField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string name { - get { - return this.nameField; - } - set { - this.nameField = value; - } + get => this.nameField; + set => this.nameField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string type { - get { - return this.typeField; - } - set { - this.typeField = value; - } + get => this.typeField; + set => this.typeField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string url { - get { - return this.urlField; - } - set { - this.urlField = value; - } + get => this.urlField; + set => this.urlField = value; } } @@ -1011,33 +852,21 @@ namespace GreenshotConfluencePlugin.confluence { /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string description { - get { - return this.descriptionField; - } - set { - this.descriptionField = value; - } + get => this.descriptionField; + set => this.descriptionField = value; } - + /// public long homePage { - get { - return this.homePageField; - } - set { - this.homePageField = value; - } + get => this.homePageField; + set => this.homePageField = value; } - + /// [System.Xml.Serialization.SoapElementAttribute(IsNullable=true)] public string spaceGroup { - get { - return this.spaceGroupField; - } - set { - this.spaceGroupField = value; - } + get => this.spaceGroupField; + set => this.spaceGroupField = value; } } @@ -1052,12 +881,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class searchCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal searchCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal searchCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public RemoteSearchResult[] Result { get { @@ -1078,12 +905,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class getSpaceCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal getSpaceCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal getSpaceCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public RemoteSpace Result { get { @@ -1104,12 +929,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class getChildrenCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal getChildrenCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal getChildrenCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public RemotePageSummary[] Result { get { @@ -1130,12 +953,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class loginCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal loginCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal loginCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public string Result { get { @@ -1156,12 +977,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class getPageCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal getPageCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal getPageCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public RemotePage Result { get { @@ -1182,12 +1001,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class getPage1CompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal getPage1CompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal getPage1CompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public RemotePage Result { get { @@ -1208,12 +1025,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class logoutCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal logoutCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal logoutCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public bool Result { get { @@ -1234,12 +1049,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class addAttachmentCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal addAttachmentCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal addAttachmentCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public RemoteAttachment Result { get { @@ -1260,12 +1073,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class addAttachment1CompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal addAttachment1CompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal addAttachment1CompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public RemoteAttachment Result { get { @@ -1286,12 +1097,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class getSpacesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal getSpacesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal getSpacesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public RemoteSpaceSummary[] Result { get { @@ -1312,12 +1121,10 @@ namespace GreenshotConfluencePlugin.confluence { public partial class getPagesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; - - internal getPagesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : - base(exception, cancelled, userState) { - this.results = results; - } - + + internal getPagesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) => this.results = results; + /// public RemotePageSummary[] Result { get { diff --git a/src/Greenshot.Plugin.Dropbox/DropboxDestination.cs b/src/Greenshot.Plugin.Dropbox/DropboxDestination.cs index 00f103cfe..3733c726e 100644 --- a/src/Greenshot.Plugin.Dropbox/DropboxDestination.cs +++ b/src/Greenshot.Plugin.Dropbox/DropboxDestination.cs @@ -33,10 +33,7 @@ namespace Greenshot.Plugin.Dropbox private readonly DropboxPlugin _plugin; - public DropboxDestination(DropboxPlugin plugin) - { - _plugin = plugin; - } + public DropboxDestination(DropboxPlugin plugin) => _plugin = plugin; public override string Designation => "Dropbox"; diff --git a/src/Greenshot.Plugin.Dropbox/DropboxPlugin.cs b/src/Greenshot.Plugin.Dropbox/DropboxPlugin.cs index ab32b5162..2e89183e0 100644 --- a/src/Greenshot.Plugin.Dropbox/DropboxPlugin.cs +++ b/src/Greenshot.Plugin.Dropbox/DropboxPlugin.cs @@ -94,23 +94,14 @@ namespace Greenshot.Plugin.Dropbox } } - public void Shutdown() - { - Log.Debug("Dropbox Plugin shutdown."); - } + public void Shutdown() => Log.Debug("Dropbox Plugin shutdown."); /// /// Implementation of the IPlugin.Configure /// - public void Configure() - { - _config.ShowConfigDialog(); - } + public void Configure() => _config.ShowConfigDialog(); - public void ConfigMenuClick(object sender, EventArgs eventArgs) - { - _config.ShowConfigDialog(); - } + public void ConfigMenuClick(object sender, EventArgs eventArgs) => _config.ShowConfigDialog(); /// /// This will be called when the menu item in the Editor is clicked diff --git a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandConfiguration.cs b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandConfiguration.cs index b3d471a8f..17dca597c 100644 --- a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandConfiguration.cs +++ b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandConfiguration.cs @@ -121,12 +121,9 @@ namespace Greenshot.Plugin.ExternalCommand Commandline.Remove(command); Argument.Remove(command); RunInbackground.Remove(command); - if (MsPaint.Equals(command) || PaintDotNet.Equals(command)) + if ((MsPaint.Equals(command) || PaintDotNet.Equals(command)) && !DeletedBuildInCommands.Contains(command)) { - if (!DeletedBuildInCommands.Contains(command)) - { - DeletedBuildInCommands.Add(command); - } + DeletedBuildInCommands.Add(command); } } @@ -161,7 +158,7 @@ namespace Greenshot.Plugin.ExternalCommand public override object GetDefault(string property) => property switch { - nameof(DeletedBuildInCommands) => (object)new List(), + nameof(DeletedBuildInCommands) => new List(), nameof(Commands) => new List(), nameof(Commandline) => new Dictionary(), nameof(Argument) => new Dictionary(), diff --git a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandDestination.cs b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandDestination.cs index 9f57bca33..18170203d 100644 --- a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandDestination.cs +++ b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandDestination.cs @@ -47,10 +47,7 @@ namespace Greenshot.Plugin.ExternalCommand private static readonly ExternalCommandConfiguration config = IniConfig.GetIniSection(); private readonly string _presetCommand; - public ExternalCommandDestination(string commando) - { - _presetCommand = commando; - } + public ExternalCommandDestination(string commando) => _presetCommand = commando; public override string Designation => "External " + _presetCommand.Replace(',', '_'); @@ -83,7 +80,7 @@ namespace Greenshot.Plugin.ExternalCommand string error; if (runInBackground) { - Thread commandThread = new(delegate () + Thread commandThread = new(() => { CallExternalCommand(exportInformation, fullPath, out output, out error); ProcessExport(exportInformation, surface); @@ -264,9 +261,6 @@ namespace Greenshot.Plugin.ExternalCommand return -1; } - public static string FormatArguments(string arguments, string fullpath) - { - return string.Format(arguments, fullpath); - } + public static string FormatArguments(string arguments, string fullpath) => string.Format(arguments, fullpath); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandPlugin.cs b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandPlugin.cs index 7f576ccdd..236067a63 100644 --- a/src/Greenshot.Plugin.ExternalCommand/ExternalCommandPlugin.cs +++ b/src/Greenshot.Plugin.ExternalCommand/ExternalCommandPlugin.cs @@ -181,15 +181,9 @@ namespace Greenshot.Plugin.ExternalCommand } } - public virtual void Shutdown() - { - Log.Debug("Shutdown"); - } + public virtual void Shutdown() => Log.Debug("Shutdown"); - private void ConfigMenuClick(object sender, EventArgs eventArgs) - { - Configure(); - } + private void ConfigMenuClick(object sender, EventArgs eventArgs) => Configure(); /// /// Implementation of the IPlugin.Configure diff --git a/src/Greenshot.Plugin.ExternalCommand/IconCache.cs b/src/Greenshot.Plugin.ExternalCommand/IconCache.cs index 0de573a43..39c38cd90 100644 --- a/src/Greenshot.Plugin.ExternalCommand/IconCache.cs +++ b/src/Greenshot.Plugin.ExternalCommand/IconCache.cs @@ -35,18 +35,15 @@ namespace Greenshot.Plugin.ExternalCommand public static Image IconForCommand(string commandName) { Image icon = null; - if (commandName != null) + if (commandName != null && config.Commandline.ContainsKey(commandName) && File.Exists(config.Commandline[commandName])) { - if (config.Commandline.ContainsKey(commandName) && File.Exists(config.Commandline[commandName])) + try { - try - { - icon = PluginUtils.GetCachedExeIcon(config.Commandline[commandName], 0); - } - catch (Exception ex) - { - LOG.Warn("Problem loading icon for " + config.Commandline[commandName], ex); - } + icon = PluginUtils.GetCachedExeIcon(config.Commandline[commandName], 0); + } + catch (Exception ex) + { + LOG.Warn("Problem loading icon for " + config.Commandline[commandName], ex); } } diff --git a/src/Greenshot.Plugin.ExternalCommand/SettingsForm.cs b/src/Greenshot.Plugin.ExternalCommand/SettingsForm.cs index 992fff3f5..0d680b572 100644 --- a/src/Greenshot.Plugin.ExternalCommand/SettingsForm.cs +++ b/src/Greenshot.Plugin.ExternalCommand/SettingsForm.cs @@ -44,10 +44,7 @@ namespace Greenshot.Plugin.ExternalCommand UpdateView(); } - private void ButtonOkClick(object sender, EventArgs e) - { - IniConfig.Save(); - } + private void ButtonOkClick(object sender, EventArgs e) => IniConfig.Save(); private void ButtonAddClick(object sender, EventArgs e) { @@ -101,15 +98,9 @@ namespace Greenshot.Plugin.ExternalCommand button_edit.Enabled = listView1.SelectedItems.Count > 0; } - private void ListView1ItemSelectionChanged(object sender, EventArgs e) - { - button_edit.Enabled = listView1.SelectedItems.Count > 0; - } + private void ListView1ItemSelectionChanged(object sender, EventArgs e) => button_edit.Enabled = listView1.SelectedItems.Count > 0; - private void ButtonEditClick(object sender, EventArgs e) - { - ListView1DoubleClick(sender, e); - } + private void ButtonEditClick(object sender, EventArgs e) => ListView1DoubleClick(sender, e); private void ListView1DoubleClick(object sender, EventArgs e) { diff --git a/src/Greenshot.Plugin.ExternalCommand/SettingsFormDetail.cs b/src/Greenshot.Plugin.ExternalCommand/SettingsFormDetail.cs index 95ebffb0d..769a55322 100644 --- a/src/Greenshot.Plugin.ExternalCommand/SettingsFormDetail.cs +++ b/src/Greenshot.Plugin.ExternalCommand/SettingsFormDetail.cs @@ -174,19 +174,10 @@ namespace Greenshot.Plugin.ExternalCommand } } - private void textBox_name_TextChanged(object sender, EventArgs e) - { - OkButtonState(); - } + private void textBox_name_TextChanged(object sender, EventArgs e) => OkButtonState(); - private void textBox_commandline_TextChanged(object sender, EventArgs e) - { - OkButtonState(); - } + private void textBox_commandline_TextChanged(object sender, EventArgs e) => OkButtonState(); - private void textBox_arguments_TextChanged(object sender, EventArgs e) - { - OkButtonState(); - } + private void textBox_arguments_TextChanged(object sender, EventArgs e) => OkButtonState(); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Flickr/FlickrDestination.cs b/src/Greenshot.Plugin.Flickr/FlickrDestination.cs index e1b2ed5e6..c40a8b203 100644 --- a/src/Greenshot.Plugin.Flickr/FlickrDestination.cs +++ b/src/Greenshot.Plugin.Flickr/FlickrDestination.cs @@ -30,10 +30,7 @@ namespace Greenshot.Plugin.Flickr { private readonly FlickrPlugin _plugin; - public FlickrDestination(FlickrPlugin plugin) - { - _plugin = plugin; - } + public FlickrDestination(FlickrPlugin plugin) => _plugin = plugin; public override string Designation => "Flickr"; diff --git a/src/Greenshot.Plugin.Flickr/FlickrPlugin.cs b/src/Greenshot.Plugin.Flickr/FlickrPlugin.cs index 597f00042..9ef671707 100644 --- a/src/Greenshot.Plugin.Flickr/FlickrPlugin.cs +++ b/src/Greenshot.Plugin.Flickr/FlickrPlugin.cs @@ -104,23 +104,14 @@ namespace Greenshot.Plugin.Flickr } } - public void Shutdown() - { - Log.Debug("Flickr Plugin shutdown."); - } + public void Shutdown() => Log.Debug("Flickr Plugin shutdown."); /// /// Implementation of the IPlugin.Configure /// - public void Configure() - { - _config.ShowConfigDialog(); - } + public void Configure() => _config.ShowConfigDialog(); - public void ConfigMenuClick(object sender, EventArgs eventArgs) - { - _config.ShowConfigDialog(); - } + public void ConfigMenuClick(object sender, EventArgs eventArgs) => _config.ShowConfigDialog(); public bool Upload(ICaptureDetails captureDetails, ISurface surface, out string uploadUrl) { diff --git a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosDestination.cs b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosDestination.cs index 217e365d0..58de9ebd0 100644 --- a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosDestination.cs +++ b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosDestination.cs @@ -29,10 +29,7 @@ namespace Greenshot.Plugin.GooglePhotos { private readonly GooglePhotosPlugin _plugin; - public GooglePhotosDestination(GooglePhotosPlugin plugin) - { - _plugin = plugin; - } + public GooglePhotosDestination(GooglePhotosPlugin plugin) => _plugin = plugin; public override string Designation => "GooglePhotos"; diff --git a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosPlugin.cs b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosPlugin.cs index d0acc8c73..7121f51a8 100644 --- a/src/Greenshot.Plugin.GooglePhotos/GooglePhotosPlugin.cs +++ b/src/Greenshot.Plugin.GooglePhotos/GooglePhotosPlugin.cs @@ -105,15 +105,9 @@ namespace Greenshot.Plugin.GooglePhotos /// /// Implementation of the IPlugin.Configure /// - public void Configure() - { - _config.ShowConfigDialog(); - } + public void Configure() => _config.ShowConfigDialog(); - public void ConfigMenuClick(object sender, EventArgs eventArgs) - { - Configure(); - } + public void ConfigMenuClick(object sender, EventArgs eventArgs) => Configure(); public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadUrl) { diff --git a/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs b/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs index f0119183c..3a90b2a60 100644 --- a/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs +++ b/src/Greenshot.Plugin.Imgur/Forms/ImgurHistory.cs @@ -218,10 +218,7 @@ namespace Greenshot.Plugin.Imgur.Forms } } - private void FinishedButtonClick(object sender, EventArgs e) - { - Hide(); - } + private void FinishedButtonClick(object sender, EventArgs e) => Hide(); private void OpenButtonClick(object sender, EventArgs e) { @@ -254,9 +251,6 @@ namespace Greenshot.Plugin.Imgur.Forms listview_imgur_uploads.Sort(); } - private void ImgurHistoryFormClosing(object sender, FormClosingEventArgs e) - { - _instance = null; - } + private void ImgurHistoryFormClosing(object sender, FormClosingEventArgs e) => _instance = null; } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Imgur/Forms/SettingsForm.cs b/src/Greenshot.Plugin.Imgur/Forms/SettingsForm.cs index 8bbf3bac5..aa48e49b9 100644 --- a/src/Greenshot.Plugin.Imgur/Forms/SettingsForm.cs +++ b/src/Greenshot.Plugin.Imgur/Forms/SettingsForm.cs @@ -40,9 +40,6 @@ namespace Greenshot.Plugin.Imgur.Forms historyButton.Enabled = ImgurUtils.IsHistoryLoadingNeeded(); } - private void ButtonHistoryClick(object sender, EventArgs e) - { - ImgurHistory.ShowHistory(); - } + private void ButtonHistoryClick(object sender, EventArgs e) => ImgurHistory.ShowHistory(); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Imgur/ImgurDestination.cs b/src/Greenshot.Plugin.Imgur/ImgurDestination.cs index c6be4d20e..21d3d97d7 100644 --- a/src/Greenshot.Plugin.Imgur/ImgurDestination.cs +++ b/src/Greenshot.Plugin.Imgur/ImgurDestination.cs @@ -33,10 +33,7 @@ namespace Greenshot.Plugin.Imgur { private readonly ImgurPlugin _plugin; - public ImgurDestination(ImgurPlugin plugin) - { - _plugin = plugin; - } + public ImgurDestination(ImgurPlugin plugin) => _plugin = plugin; public override string Designation => "Imgur"; diff --git a/src/Greenshot.Plugin.Imgur/ImgurInfo.cs b/src/Greenshot.Plugin.Imgur/ImgurInfo.cs index 438ae8638..49eefced1 100644 --- a/src/Greenshot.Plugin.Imgur/ImgurInfo.cs +++ b/src/Greenshot.Plugin.Imgur/ImgurInfo.cs @@ -148,14 +148,11 @@ namespace Greenshot.Plugin.Imgur } nodes = doc.GetElementsByTagName("datetime"); - if (nodes.Count > 0) + // Version 3 has seconds since Epoch + if (nodes.Count > 0 && double.TryParse(nodes.Item(0)?.InnerText, out var secondsSince)) { - // Version 3 has seconds since Epoch - if (double.TryParse(nodes.Item(0)?.InnerText, out var secondsSince)) - { - var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); - imgurInfo.Timestamp = epoch.AddSeconds(secondsSince).DateTime; - } + var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); + imgurInfo.Timestamp = epoch.AddSeconds(secondsSince).DateTime; } nodes = doc.GetElementsByTagName("original"); diff --git a/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs b/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs index 11befa5ef..1d9aa9995 100644 --- a/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs +++ b/src/Greenshot.Plugin.Imgur/ImgurPlugin.cs @@ -146,14 +146,7 @@ namespace Greenshot.Plugin.Imgur return; } - if (_config?.ImgurUploadHistory != null && _config.ImgurUploadHistory.Count > 0) - { - historyMenuItem.Enabled = true; - } - else - { - historyMenuItem.Enabled = false; - } + historyMenuItem.Enabled = _config?.ImgurUploadHistory != null && _config.ImgurUploadHistory.Count > 0; }); } catch (Exception ex) @@ -171,10 +164,7 @@ namespace Greenshot.Plugin.Imgur /// /// Implementation of the IPlugin.Configure /// - public virtual void Configure() - { - _config.ShowConfigDialog(); - } + public virtual void Configure() => _config.ShowConfigDialog(); /// /// Upload the capture to imgur @@ -216,14 +206,7 @@ namespace Greenshot.Plugin.Imgur IniConfig.Save(); - if (_config.UsePageLink) - { - uploadUrl = imgurInfo.Page; - } - else - { - uploadUrl = imgurInfo.Original; - } + uploadUrl = _config.UsePageLink ? imgurInfo.Page : imgurInfo.Original; if (!string.IsNullOrEmpty(uploadUrl) && _config.CopyLinkToClipboard) { diff --git a/src/Greenshot.Plugin.Imgur/ImgurUtils.cs b/src/Greenshot.Plugin.Imgur/ImgurUtils.cs index 56da1c39e..2ba81ea53 100644 --- a/src/Greenshot.Plugin.Imgur/ImgurUtils.cs +++ b/src/Greenshot.Plugin.Imgur/ImgurUtils.cs @@ -135,10 +135,7 @@ namespace Greenshot.Plugin.Imgur /// Use this to make sure Imgur knows from where the upload comes. /// /// - private static void SetClientId(HttpWebRequest webRequest) - { - webRequest.Headers.Add("Authorization", "Client-ID " + ImgurCredentials.CONSUMER_KEY); - } + private static void SetClientId(HttpWebRequest webRequest) => webRequest.Headers.Add("Authorization", "Client-ID " + ImgurCredentials.CONSUMER_KEY); /// /// Do the actual upload to Imgur @@ -292,12 +289,9 @@ namespace Greenshot.Plugin.Imgur } catch (WebException wE) { - if (wE.Status == WebExceptionStatus.ProtocolError) + if (wE.Status == WebExceptionStatus.ProtocolError && ((HttpWebResponse)wE.Response).StatusCode == HttpStatusCode.NotFound) { - if (((HttpWebResponse)wE.Response).StatusCode == HttpStatusCode.NotFound) - { - return null; - } + return null; } throw; @@ -345,12 +339,9 @@ namespace Greenshot.Plugin.Imgur catch (WebException wE) { // Allow "Bad request" this means we already deleted it - if (wE.Status == WebExceptionStatus.ProtocolError) + if (wE.Status == WebExceptionStatus.ProtocolError && ((HttpWebResponse)wE.Response).StatusCode != HttpStatusCode.BadRequest) { - if (((HttpWebResponse)wE.Response).StatusCode != HttpStatusCode.BadRequest) - { - throw; - } + throw; } } diff --git a/src/Greenshot.Plugin.Jira/AsyncMemoryCache.cs b/src/Greenshot.Plugin.Jira/AsyncMemoryCache.cs index 3cb3f78d8..a7386f41d 100644 --- a/src/Greenshot.Plugin.Jira/AsyncMemoryCache.cs +++ b/src/Greenshot.Plugin.Jira/AsyncMemoryCache.cs @@ -74,10 +74,7 @@ namespace Greenshot.Plugin.Jira /// /// TKey /// string - protected virtual string CreateKey(TKey keyObject) - { - return keyObject.ToString(); - } + protected virtual string CreateKey(TKey keyObject) => keyObject.ToString(); /// /// Get a task element from the cache, if this is not available call the create function. @@ -183,9 +180,6 @@ namespace Greenshot.Plugin.Jira /// ActivateUpdateCallback / ActivateRemovedCallback /// /// CacheEntryUpdateArguments - protected void UpdateCallback(CacheEntryUpdateArguments cacheEntryUpdateArguments) - { - _log.Verbose().WriteLine("Update request for {0} due to {1}.", cacheEntryUpdateArguments.Key, cacheEntryUpdateArguments.RemovedReason); - } + protected void UpdateCallback(CacheEntryUpdateArguments cacheEntryUpdateArguments) => _log.Verbose().WriteLine("Update request for {0} due to {1}.", cacheEntryUpdateArguments.Key, cacheEntryUpdateArguments.RemovedReason); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Jira/Forms/JiraForm.cs b/src/Greenshot.Plugin.Jira/Forms/JiraForm.cs index a7c9b87c1..49e0216b8 100644 --- a/src/Greenshot.Plugin.Jira/Forms/JiraForm.cs +++ b/src/Greenshot.Plugin.Jira/Forms/JiraForm.cs @@ -113,15 +113,9 @@ namespace Greenshot.Plugin.Jira.Forms jiraCommentBox.Enabled = enabled; } - public void SetFilename(string filename) - { - jiraFilenameBox.Text = filename; - } + public void SetFilename(string filename) => jiraFilenameBox.Text = filename; - public Issue GetJiraIssue() - { - return _selectedIssue; - } + public Issue GetJiraIssue() => _selectedIssue; public async Task UploadAsync(IBinaryContainer attachment) { diff --git a/src/Greenshot.Plugin.Jira/IssueTypeBitmapCache.cs b/src/Greenshot.Plugin.Jira/IssueTypeBitmapCache.cs index 8b626d3a6..83d9f7d5a 100644 --- a/src/Greenshot.Plugin.Jira/IssueTypeBitmapCache.cs +++ b/src/Greenshot.Plugin.Jira/IssueTypeBitmapCache.cs @@ -42,14 +42,8 @@ namespace Greenshot.Plugin.Jira ExpireTimeSpan = TimeSpan.FromHours(4); } - protected override string CreateKey(IssueType keyObject) - { - return keyObject.Name; - } + protected override string CreateKey(IssueType keyObject) => keyObject.Name; - protected override async Task CreateAsync(IssueType issueType, CancellationToken cancellationToken = new CancellationToken()) - { - return await _jiraClient.Server.GetUriContentAsync(issueType.IconUri, cancellationToken).ConfigureAwait(false); - } + protected override async Task CreateAsync(IssueType issueType, CancellationToken cancellationToken = new CancellationToken()) => await _jiraClient.Server.GetUriContentAsync(issueType.IconUri, cancellationToken).ConfigureAwait(false); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Jira/JiraConnector.cs b/src/Greenshot.Plugin.Jira/JiraConnector.cs index fbfd42543..fe8cf8df9 100644 --- a/src/Greenshot.Plugin.Jira/JiraConnector.cs +++ b/src/Greenshot.Plugin.Jira/JiraConnector.cs @@ -54,21 +54,18 @@ namespace Greenshot.Plugin.Jira /// /// Initialize some basic stuff, in the case the SVG to bitmap converter /// - static JiraConnector() - { - CoreConfig.PropertyChanged += (sender, args) => - { - if (args.PropertyName == nameof(CoreConfig.IconSize)) - { - var jiraConnector = SimpleServiceProvider.Current.GetInstance(); - jiraConnector._jiraClient?.Behaviour.SetConfig(new SvgConfiguration - { - Width = CoreConfig.IconSize.Width, - Height = CoreConfig.IconSize.Height - }); - } - }; - } + static JiraConnector() => CoreConfig.PropertyChanged += (sender, args) => + { + if (args.PropertyName == nameof(CoreConfig.IconSize)) + { + var jiraConnector = SimpleServiceProvider.Current.GetInstance(); + jiraConnector._jiraClient?.Behaviour.SetConfig(new SvgConfiguration + { + Width = CoreConfig.IconSize.Width, + Height = CoreConfig.IconSize.Height + }); + } + }; /// /// Dispose, logout the users @@ -86,10 +83,7 @@ namespace Greenshot.Plugin.Jira /// /// Constructor /// - public JiraConnector() - { - JiraConfig.Url = JiraConfig.Url.Replace(DefaultPostfix, string.Empty); - } + public JiraConnector() => JiraConfig.Url = JiraConfig.Url.Replace(DefaultPostfix, string.Empty); /// /// Access the jira monitor @@ -299,10 +293,7 @@ namespace Greenshot.Plugin.Jira /// Issue /// CancellationToken /// Bitmap - public async Task GetIssueTypeBitmapAsync(Issue issue, CancellationToken cancellationToken = default) - { - return await _issueTypeBitmapCache.GetOrCreateAsync(issue.Fields.IssueType, cancellationToken).ConfigureAwait(false); - } + public async Task GetIssueTypeBitmapAsync(Issue issue, CancellationToken cancellationToken = default) => await _issueTypeBitmapCache.GetOrCreateAsync(issue.Fields.IssueType, cancellationToken).ConfigureAwait(false); /// /// Get the base uri diff --git a/src/Greenshot.Plugin.Jira/JiraDestination.cs b/src/Greenshot.Plugin.Jira/JiraDestination.cs index abfd4da7f..29be926c3 100644 --- a/src/Greenshot.Plugin.Jira/JiraDestination.cs +++ b/src/Greenshot.Plugin.Jira/JiraDestination.cs @@ -45,10 +45,7 @@ namespace Greenshot.Plugin.Jira private static readonly JiraConfiguration Config = IniConfig.GetIniSection(); private readonly Issue _jiraIssue; - public JiraDestination(Issue jiraIssue = null) - { - _jiraIssue = jiraIssue; - } + public JiraDestination(Issue jiraIssue = null) => _jiraIssue = jiraIssue; public override string Designation => "Jira"; diff --git a/src/Greenshot.Plugin.Jira/JiraDetails.cs b/src/Greenshot.Plugin.Jira/JiraDetails.cs index ff7ddd699..abce813bd 100644 --- a/src/Greenshot.Plugin.Jira/JiraDetails.cs +++ b/src/Greenshot.Plugin.Jira/JiraDetails.cs @@ -26,10 +26,7 @@ namespace Greenshot.Plugin.Jira { public class JiraDetails : IComparable { - public JiraDetails() - { - FirstSeenAt = SeenAt = DateTimeOffset.Now; - } + public JiraDetails() => FirstSeenAt = SeenAt = DateTimeOffset.Now; public string ProjectKey { get; set; } @@ -43,9 +40,6 @@ namespace Greenshot.Plugin.Jira public DateTimeOffset SeenAt { get; set; } - public int CompareTo(JiraDetails other) - { - return SeenAt.CompareTo(other.SeenAt); - } + public int CompareTo(JiraDetails other) => SeenAt.CompareTo(other.SeenAt); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Jira/JiraMonitor.cs b/src/Greenshot.Plugin.Jira/JiraMonitor.cs index 4bd06ac87..eac3be48f 100644 --- a/src/Greenshot.Plugin.Jira/JiraMonitor.cs +++ b/src/Greenshot.Plugin.Jira/JiraMonitor.cs @@ -92,18 +92,15 @@ namespace Greenshot.Plugin.Jira /// /// /// IJiraClient - public IJiraClient GetJiraClientForKey(JiraDetails jiraDetails) - { - return _projectJiraClientMap[jiraDetails.ProjectKey]; - } + public IJiraClient GetJiraClientForKey(JiraDetails jiraDetails) => _projectJiraClientMap[jiraDetails.ProjectKey]; /// /// Get the "list" of recently seen Jiras /// public IEnumerable RecentJiras => from jiraDetails in _recentJiras.Values - orderby jiraDetails.SeenAt descending - select jiraDetails; + orderby jiraDetails.SeenAt descending + select jiraDetails; /// /// Check if this monitor has active instances @@ -121,12 +118,11 @@ namespace Greenshot.Plugin.Jira var projects = await jiraInstance.Project.GetAllAsync(cancellationToken: token).ConfigureAwait(false); if (projects != null) { - foreach (var project in projects) + foreach (var project in from project in projects + where !_projectJiraClientMap.ContainsKey(project.Key) + select project) { - if (!_projectJiraClientMap.ContainsKey(project.Key)) - { - _projectJiraClientMap.Add(project.Key, jiraInstance); - } + _projectJiraClientMap.Add(project.Key, jiraInstance); } } } diff --git a/src/Greenshot.Plugin.Jira/JiraPlugin.cs b/src/Greenshot.Plugin.Jira/JiraPlugin.cs index 7b2483f21..25280717e 100644 --- a/src/Greenshot.Plugin.Jira/JiraPlugin.cs +++ b/src/Greenshot.Plugin.Jira/JiraPlugin.cs @@ -94,10 +94,6 @@ namespace Greenshot.Plugin.Jira { LogSettings.RegisterDefaultLogger(LogLevels.Error); } - else if (Log.IsErrorEnabled) - { - LogSettings.RegisterDefaultLogger(LogLevels.Error); - } else { LogSettings.RegisterDefaultLogger(LogLevels.Fatal); @@ -123,13 +119,10 @@ namespace Greenshot.Plugin.Jira { // check for re-login var jiraConnector = SimpleServiceProvider.Current.GetInstance(); - if (jiraConnector?.IsLoggedIn == true && !string.IsNullOrEmpty(url)) + if (jiraConnector?.IsLoggedIn == true && !string.IsNullOrEmpty(url) && !url.Equals(_config.Url)) { - if (!url.Equals(_config.Url)) - { - jiraConnector.Logout(); - Task.Run(async () => { await jiraConnector.LoginAsync(); }); - } + jiraConnector.Logout(); + Task.Run(async () => { await jiraConnector.LoginAsync(); }); } } } diff --git a/src/Greenshot.Plugin.Jira/Log4NetLogger.cs b/src/Greenshot.Plugin.Jira/Log4NetLogger.cs index 07b9ffb43..d63ef7af8 100644 --- a/src/Greenshot.Plugin.Jira/Log4NetLogger.cs +++ b/src/Greenshot.Plugin.Jira/Log4NetLogger.cs @@ -29,10 +29,7 @@ namespace Greenshot.Plugin.Jira /// public class Log4NetLogger : AbstractLogger { - private ILog GetLogger(LogSource logSource) - { - return logSource.SourceType != null ? LogManager.GetLogger(logSource.SourceType) : LogManager.GetLogger(logSource.Source); - } + private ILog GetLogger(LogSource logSource) => logSource.SourceType != null ? LogManager.GetLogger(logSource.SourceType) : LogManager.GetLogger(logSource.Source); /// /// Write the supplied information to a log4net.ILog @@ -86,10 +83,7 @@ namespace Greenshot.Plugin.Jira /// /// /// - public override void WriteLine(LogInfo logInfo, string messageTemplate, params object[] logParameters) - { - Write(logInfo, messageTemplate, logParameters); - } + public override void WriteLine(LogInfo logInfo, string messageTemplate, params object[] logParameters) => Write(logInfo, messageTemplate, logParameters); /// /// Test if a certain LogLevels enum is enabled diff --git a/src/Greenshot.Plugin.Office/Com/DisposableCom.cs b/src/Greenshot.Plugin.Office/Com/DisposableCom.cs index 5b24384e8..be25ae6bf 100644 --- a/src/Greenshot.Plugin.Office/Com/DisposableCom.cs +++ b/src/Greenshot.Plugin.Office/Com/DisposableCom.cs @@ -14,9 +14,6 @@ namespace Greenshot.Plugin.Office.Com /// Type for the com object /// the com object itself /// IDisposableCom of type T - public static IDisposableCom Create(T comObject) - { - return Equals(comObject, default(T)) ? null : (IDisposableCom)new DisposableComImplementation(comObject); - } + public static IDisposableCom Create(T comObject) => Equals(comObject, default(T)) ? null : (IDisposableCom)new DisposableComImplementation(comObject); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Office/Com/DisposableComImplementation.cs b/src/Greenshot.Plugin.Office/Com/DisposableComImplementation.cs index 572de52d8..501dcd7c5 100644 --- a/src/Greenshot.Plugin.Office/Com/DisposableComImplementation.cs +++ b/src/Greenshot.Plugin.Office/Com/DisposableComImplementation.cs @@ -12,10 +12,7 @@ namespace Greenshot.Plugin.Office.Com /// Type of the com object internal class DisposableComImplementation : IDisposableCom { - public DisposableComImplementation(T obj) - { - ComObject = obj; - } + public DisposableComImplementation(T obj) => ComObject = obj; public T ComObject { get; private set; } diff --git a/src/Greenshot.Plugin.Office/Com/Ole32Api.cs b/src/Greenshot.Plugin.Office/Com/Ole32Api.cs index 3f99df5bb..bc6efd9ac 100644 --- a/src/Greenshot.Plugin.Office/Com/Ole32Api.cs +++ b/src/Greenshot.Plugin.Office/Com/Ole32Api.cs @@ -18,10 +18,7 @@ namespace Greenshot.Plugin.Office.Com /// /// string with the program ID /// Guid with the clsId - public static Guid ClassIdFromProgId(string programId) - { - return CLSIDFromProgID(programId, out Guid clsId).Succeeded() ? clsId : clsId; - } + public static Guid ClassIdFromProgId(string programId) => CLSIDFromProgID(programId, out Guid clsId).Succeeded() ? clsId : clsId; /// /// See more here diff --git a/src/Greenshot.Plugin.Office/Com/OleAut32Api.cs b/src/Greenshot.Plugin.Office/Com/OleAut32Api.cs index 7993b7365..1c4767456 100644 --- a/src/Greenshot.Plugin.Office/Com/OleAut32Api.cs +++ b/src/Greenshot.Plugin.Office/Com/OleAut32Api.cs @@ -19,10 +19,7 @@ namespace Greenshot.Plugin.Office.Com /// Type for the instance /// Guid /// IDisposableCom of T - public static IDisposableCom GetActiveObject(ref Guid clsId) - { - return GetActiveObject(ref clsId, IntPtr.Zero, out object comObject).Succeeded() ? DisposableCom.Create((T)comObject) : null; - } + public static IDisposableCom GetActiveObject(ref Guid clsId) => GetActiveObject(ref clsId, IntPtr.Zero, out object comObject).Succeeded() ? DisposableCom.Create((T)comObject) : null; /// /// Get the active instance of the com object with the specified progId diff --git a/src/Greenshot.Plugin.Office/Destinations/ExcelDestination.cs b/src/Greenshot.Plugin.Office/Destinations/ExcelDestination.cs index b4109da28..38c670b7d 100644 --- a/src/Greenshot.Plugin.Office/Destinations/ExcelDestination.cs +++ b/src/Greenshot.Plugin.Office/Destinations/ExcelDestination.cs @@ -57,10 +57,7 @@ namespace Greenshot.Plugin.Office.Destinations { } - public ExcelDestination(string workbookName) - { - _workbookName = workbookName; - } + public ExcelDestination(string workbookName) => _workbookName = workbookName; public override string Designation => "Excel"; diff --git a/src/Greenshot.Plugin.Office/Destinations/OneNoteDestination.cs b/src/Greenshot.Plugin.Office/Destinations/OneNoteDestination.cs index 8f51ff5df..15aea3005 100644 --- a/src/Greenshot.Plugin.Office/Destinations/OneNoteDestination.cs +++ b/src/Greenshot.Plugin.Office/Destinations/OneNoteDestination.cs @@ -56,43 +56,19 @@ namespace Greenshot.Plugin.Office.Destinations { } - public OneNoteDestination(OneNotePage page) - { - this.page = page; - } + public OneNoteDestination(OneNotePage page) => this.page = page; - public override string Designation - { - get { return DESIGNATION; } - } + public override string Designation => DESIGNATION; - public override string Description - { - get - { - return page == null ? "Microsoft OneNote" : page.DisplayName; - } - } + public override string Description => page == null ? "Microsoft OneNote" : page.DisplayName; - public override int Priority - { - get { return 4; } - } + public override int Priority => 4; - public override bool IsDynamic - { - get { return true; } - } + public override bool IsDynamic => true; - public override bool IsActive - { - get { return base.IsActive && exePath != null; } - } + public override bool IsActive => base.IsActive && exePath != null; - public override Image DisplayIcon - { - get { return PluginUtils.GetCachedExeIcon(exePath, ICON_APPLICATION); } - } + public override Image DisplayIcon => PluginUtils.GetCachedExeIcon(exePath, ICON_APPLICATION); public override IEnumerable DynamicDestinations() { diff --git a/src/Greenshot.Plugin.Office/Destinations/PowerpointDestination.cs b/src/Greenshot.Plugin.Office/Destinations/PowerpointDestination.cs index 8dcaadc0d..1d9a4220e 100644 --- a/src/Greenshot.Plugin.Office/Destinations/PowerpointDestination.cs +++ b/src/Greenshot.Plugin.Office/Destinations/PowerpointDestination.cs @@ -60,20 +60,11 @@ namespace Greenshot.Plugin.Office.Destinations { } - public PowerpointDestination(string presentationName) - { - _presentationName = presentationName; - } + public PowerpointDestination(string presentationName) => _presentationName = presentationName; public override string Designation => "Powerpoint"; - public override string Description - { - get - { - return _presentationName ?? "Microsoft Powerpoint"; - } - } + public override string Description => _presentationName ?? "Microsoft Powerpoint"; public override int Priority => 4; @@ -81,15 +72,9 @@ namespace Greenshot.Plugin.Office.Destinations public override bool IsActive => base.IsActive && ExePath != null; - public override Image DisplayIcon - { - get - { - return !string.IsNullOrEmpty(_presentationName) + public override Image DisplayIcon => !string.IsNullOrEmpty(_presentationName) ? PluginUtils.GetCachedExeIcon(ExePath, IconPresentation) : PluginUtils.GetCachedExeIcon(ExePath, IconApplication); - } - } public override IEnumerable DynamicDestinations() { diff --git a/src/Greenshot.Plugin.Office/Destinations/WordDestination.cs b/src/Greenshot.Plugin.Office/Destinations/WordDestination.cs index 6bc4d0d6e..dd4ec0534 100644 --- a/src/Greenshot.Plugin.Office/Destinations/WordDestination.cs +++ b/src/Greenshot.Plugin.Office/Destinations/WordDestination.cs @@ -57,10 +57,7 @@ namespace Greenshot.Plugin.Office.Destinations { } - public WordDestination(string wordCaption) - { - _documentCaption = wordCaption; - } + public WordDestination(string wordCaption) => _documentCaption = wordCaption; public override string Designation => "Word"; diff --git a/src/Greenshot.Plugin.Office/OfficeExport/OutlookEmailExporter.cs b/src/Greenshot.Plugin.Office/OfficeExport/OutlookEmailExporter.cs index 7bba19734..336d87b9d 100644 --- a/src/Greenshot.Plugin.Office/OfficeExport/OutlookEmailExporter.cs +++ b/src/Greenshot.Plugin.Office/OfficeExport/OutlookEmailExporter.cs @@ -95,12 +95,9 @@ namespace Greenshot.Plugin.Office.OfficeExport break; case AppointmentItem appointmentItem: - if ((_outlookVersion.Major >= (int)OfficeVersions.Office2010) && _officeConfiguration.OutlookAllowExportInMeetings) + if ((_outlookVersion.Major >= (int)OfficeVersions.Office2010) && _officeConfiguration.OutlookAllowExportInMeetings && !string.IsNullOrEmpty(appointmentItem.Organizer) && appointmentItem.Organizer.Equals(_currentUser)) { - if (!string.IsNullOrEmpty(appointmentItem.Organizer) && appointmentItem.Organizer.Equals(_currentUser)) - { - return ExportToInspector(null, activeExplorer, appointmentItem.Class, null, tmpFile, attachmentName); - } + return ExportToInspector(null, activeExplorer, appointmentItem.Class, null, tmpFile, attachmentName); } break; @@ -224,13 +221,10 @@ namespace Greenshot.Plugin.Office.OfficeExport // TODO: Needs to have the Microsoft Outlook 15.0 Object Library installed wordDocument = DisposableCom.Create((_Document)explorer.ComObject.ActiveInlineResponseWordEditor); } - else if (inspector != null) + else if (inspector != null && inspector.ComObject.IsWordMail() && (inspector.ComObject.EditorType == OlEditorType.olEditorWord)) { - if (inspector.ComObject.IsWordMail() && (inspector.ComObject.EditorType == OlEditorType.olEditorWord)) - { - var tmpWordDocument = (_Document)inspector.ComObject.WordEditor; - wordDocument = DisposableCom.Create(tmpWordDocument); - } + var tmpWordDocument = (_Document)inspector.ComObject.WordEditor; + wordDocument = DisposableCom.Create(tmpWordDocument); } if (wordDocument != null) @@ -495,14 +489,7 @@ namespace Greenshot.Plugin.Office.OfficeExport if (bodyIndex >= 0) { bodyIndex = bodyString.IndexOf(">", bodyIndex, StringComparison.Ordinal) + 1; - if (bodyIndex >= 0) - { - bodyString = bodyString.Insert(bodyIndex, htmlImgEmbedded); - } - else - { - bodyString = fallbackBody; - } + bodyString = bodyIndex >= 0 ? bodyString.Insert(bodyIndex, htmlImgEmbedded) : fallbackBody; } else { @@ -744,12 +731,9 @@ namespace Greenshot.Plugin.Office.OfficeExport break; case AppointmentItem appointmentItem: - if ((_outlookVersion.Major >= (int)OfficeVersions.Office2010) && _officeConfiguration.OutlookAllowExportInMeetings) + if ((_outlookVersion.Major >= (int)OfficeVersions.Office2010) && _officeConfiguration.OutlookAllowExportInMeetings && !string.IsNullOrEmpty(appointmentItem.Organizer) && appointmentItem.Organizer.Equals(_currentUser)) { - if (!string.IsNullOrEmpty(appointmentItem.Organizer) && appointmentItem.Organizer.Equals(_currentUser)) - { - inspectorCaptions.Add(caption, appointmentItem.Class); - } + inspectorCaptions.Add(caption, appointmentItem.Class); } break; diff --git a/src/Greenshot.Plugin.Office/OfficeExport/PowerpointExporter.cs b/src/Greenshot.Plugin.Office/OfficeExport/PowerpointExporter.cs index 01bdd99b6..2e63ccde9 100644 --- a/src/Greenshot.Plugin.Office/OfficeExport/PowerpointExporter.cs +++ b/src/Greenshot.Plugin.Office/OfficeExport/PowerpointExporter.cs @@ -113,14 +113,7 @@ namespace Greenshot.Plugin.Office.OfficeExport using (var shapes = DisposableCom.Create(slide.ComObject.Shapes)) { using var shape = DisposableCom.Create(shapes.ComObject.AddPicture(tmpFile, MsoTriState.msoFalse, MsoTriState.msoTrue, 0, 0, width, height)); - if (_officeConfiguration.PowerpointLockAspectRatio) - { - shape.ComObject.LockAspectRatio = MsoTriState.msoTrue; - } - else - { - shape.ComObject.LockAspectRatio = MsoTriState.msoFalse; - } + shape.ComObject.LockAspectRatio = _officeConfiguration.PowerpointLockAspectRatio ? MsoTriState.msoTrue : MsoTriState.msoFalse; shape.ComObject.ScaleHeight(1, MsoTriState.msoTrue, MsoScaleFrom.msoScaleFromMiddle); shape.ComObject.ScaleWidth(1, MsoTriState.msoTrue, MsoScaleFrom.msoScaleFromMiddle); @@ -292,12 +285,9 @@ namespace Greenshot.Plugin.Office.OfficeExport continue; } - if (IsAfter2003()) + if (IsAfter2003() && presentation.ComObject.Final) { - if (presentation.ComObject.Final) - { - continue; - } + continue; } yield return presentation.ComObject.Name; @@ -355,9 +345,6 @@ namespace Greenshot.Plugin.Office.OfficeExport return isPictureAdded; } - private bool IsAfter2003() - { - return _powerpointVersion.Major > (int)OfficeVersions.Office2003; - } + private bool IsAfter2003() => _powerpointVersion.Major > (int)OfficeVersions.Office2003; } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Office/OfficeExport/WordExporter.cs b/src/Greenshot.Plugin.Office/OfficeExport/WordExporter.cs index 21e954ab8..095e37fe7 100644 --- a/src/Greenshot.Plugin.Office/OfficeExport/WordExporter.cs +++ b/src/Greenshot.Plugin.Office/OfficeExport/WordExporter.cs @@ -121,12 +121,9 @@ namespace Greenshot.Plugin.Office.OfficeExport continue; } - if (IsAfter2003()) + if (IsAfter2003() && document.ComObject.Final) { - if (document.ComObject.Final) - { - continue; - } + continue; } using var activeWindow = DisposableCom.Create(document.ComObject.ActiveWindow); @@ -356,9 +353,6 @@ namespace Greenshot.Plugin.Office.OfficeExport /// Check if the used version is higher than Office 2003 /// /// - private bool IsAfter2003() - { - return _wordVersion.Major > (int)OfficeVersions.Office2003; - } + private bool IsAfter2003() => _wordVersion.Major > (int)OfficeVersions.Office2003; } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Office/OfficePlugin.cs b/src/Greenshot.Plugin.Office/OfficePlugin.cs index a9f85e45d..b29860890 100644 --- a/src/Greenshot.Plugin.Office/OfficePlugin.cs +++ b/src/Greenshot.Plugin.Office/OfficePlugin.cs @@ -140,17 +140,11 @@ namespace Greenshot.Plugin.Office return true; } - public void Shutdown() - { - LOG.Debug("Office Plugin shutdown."); - } + public void Shutdown() => LOG.Debug("Office Plugin shutdown."); /// /// Implementation of the IPlugin.Configure /// - public void Configure() - { - throw new NotImplementedException(); - } + public void Configure() => throw new NotImplementedException(); } } \ No newline at end of file diff --git a/src/Greenshot.Plugin.Photobucket/PhotobucketDestination.cs b/src/Greenshot.Plugin.Photobucket/PhotobucketDestination.cs index 6809724dd..904f9ba3c 100644 --- a/src/Greenshot.Plugin.Photobucket/PhotobucketDestination.cs +++ b/src/Greenshot.Plugin.Photobucket/PhotobucketDestination.cs @@ -48,13 +48,7 @@ namespace Greenshot.Plugin.Photobucket public override string Designation => "Photobucket"; - public override string Description - { - get - { - return _albumPath ?? Language.GetString("photobucket", LangKey.upload_menu_item); - } - } + public override string Description => _albumPath ?? Language.GetString("photobucket", LangKey.upload_menu_item); public override Image DisplayIcon { diff --git a/src/Greenshot.Plugin.Photobucket/PhotobucketPlugin.cs b/src/Greenshot.Plugin.Photobucket/PhotobucketPlugin.cs index 0dc64760e..c65121f8c 100644 --- a/src/Greenshot.Plugin.Photobucket/PhotobucketPlugin.cs +++ b/src/Greenshot.Plugin.Photobucket/PhotobucketPlugin.cs @@ -106,10 +106,7 @@ namespace Greenshot.Plugin.Photobucket /// /// Implementation of the IPlugin.Configure /// - public void Configure() - { - _config.ShowConfigDialog(); - } + public void Configure() => _config.ShowConfigDialog(); /// /// Upload the capture to Photobucket diff --git a/src/Greenshot.Plugin.Win10/Internal/MemoryRandomAccessStream.cs b/src/Greenshot.Plugin.Win10/Internal/MemoryRandomAccessStream.cs index 9ef117638..52b407287 100644 --- a/src/Greenshot.Plugin.Win10/Internal/MemoryRandomAccessStream.cs +++ b/src/Greenshot.Plugin.Win10/Internal/MemoryRandomAccessStream.cs @@ -64,10 +64,7 @@ namespace Greenshot.Plugin.Win10.Internal } /// - public void Seek(ulong position) - { - Seek((long)position, SeekOrigin.Begin); - } + public void Seek(ulong position) => Seek((long)position, SeekOrigin.Begin); /// public Windows.Foundation.IAsyncOperationWithProgress ReadAsync(IBuffer buffer, uint count, InputStreamOptions options) diff --git a/src/Greenshot.Plugin.Win10/ToastNotificationService.cs b/src/Greenshot.Plugin.Win10/ToastNotificationService.cs index 9af83c14d..e0bf69ff2 100644 --- a/src/Greenshot.Plugin.Win10/ToastNotificationService.cs +++ b/src/Greenshot.Plugin.Win10/ToastNotificationService.cs @@ -123,7 +123,7 @@ namespace Greenshot.Plugin.Win10 .Show(toast => { // Windows 10 first with 1903: ExpiresOnReboot = true - toast.ExpirationTime = timeout.HasValue ? DateTimeOffset.Now.Add(timeout.Value) : (DateTimeOffset?)null; + toast.ExpirationTime = timeout.HasValue ? DateTimeOffset.Now.Add(timeout.Value) : null; void ToastActivatedHandler(ToastNotification toastNotification, object sender) { @@ -183,20 +183,11 @@ namespace Greenshot.Plugin.Win10 Log.Debug(sender.Content.GetXml()); } - public void ShowWarningMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) - { - ShowMessage(message, timeout, onClickAction, onClosedAction); - } + public void ShowWarningMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) => ShowMessage(message, timeout, onClickAction, onClosedAction); - public void ShowErrorMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) - { - ShowMessage(message, timeout, onClickAction, onClosedAction); - } + public void ShowErrorMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) => ShowMessage(message, timeout, onClickAction, onClosedAction); - public void ShowInfoMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) - { - ShowMessage(message, timeout, onClickAction, onClosedAction); - } + public void ShowInfoMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) => ShowMessage(message, timeout, onClickAction, onClosedAction); /// /// Factory method, helping with checking if the notification service is even available diff --git a/src/Greenshot.Plugin.Win10/Win10Plugin.cs b/src/Greenshot.Plugin.Win10/Win10Plugin.cs index 6b15ff3c5..15c1c87da 100644 --- a/src/Greenshot.Plugin.Win10/Win10Plugin.cs +++ b/src/Greenshot.Plugin.Win10/Win10Plugin.cs @@ -41,10 +41,7 @@ namespace Greenshot.Plugin.Win10 // Nothing to dispose } - public void Configure() - { - throw new NotImplementedException(); - } + public void Configure() => throw new NotImplementedException(); /// /// Name of the plugin diff --git a/src/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs b/src/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs index 2addc0a8e..fee4abef0 100644 --- a/src/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs +++ b/src/Greenshot/Controls/ContextMenuToolStripProfessionalRenderer.cs @@ -38,10 +38,7 @@ namespace Greenshot.Controls private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection(); private static Image _scaledCheckbox; - public ContextMenuToolStripProfessionalRenderer(IProvideDeviceDpi provideDeviceDpi) - { - _provideDeviceDpi = provideDeviceDpi; - } + public ContextMenuToolStripProfessionalRenderer(IProvideDeviceDpi provideDeviceDpi) => _provideDeviceDpi = provideDeviceDpi; protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) { var newSize = DpiCalculator.ScaleWithDpi(CoreConfig.IconSize, _provideDeviceDpi.DeviceDpi); diff --git a/src/Greenshot/Destinations/ClipboardDestination.cs b/src/Greenshot/Destinations/ClipboardDestination.cs index 7db8514ec..28661ee50 100644 --- a/src/Greenshot/Destinations/ClipboardDestination.cs +++ b/src/Greenshot/Destinations/ClipboardDestination.cs @@ -36,25 +36,13 @@ namespace Greenshot.Destinations { public override string Designation => nameof(WellKnownDestinations.Clipboard); - public override string Description - { - get { return Language.GetString(LangKey.settings_destination_clipboard); } - } + public override string Description => Language.GetString(LangKey.settings_destination_clipboard); - public override int Priority - { - get { return 2; } - } + public override int Priority => 2; - public override Keys EditorShortcutKeys - { - get { return Keys.Control | Keys.Shift | Keys.C; } - } + public override Keys EditorShortcutKeys => Keys.Control | Keys.Shift | Keys.C; - public override Image DisplayIcon - { - get { return GreenshotResources.GetImage("Clipboard.Image"); } - } + public override Image DisplayIcon => GreenshotResources.GetImage("Clipboard.Image"); public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { diff --git a/src/Greenshot/Destinations/EmailDestination.cs b/src/Greenshot/Destinations/EmailDestination.cs index 83369e10d..dbc323508 100644 --- a/src/Greenshot/Destinations/EmailDestination.cs +++ b/src/Greenshot/Destinations/EmailDestination.cs @@ -53,14 +53,9 @@ namespace Greenshot.Destinations public override string Designation => nameof(WellKnownDestinations.EMail); - public override string Description - { - get - { + public override string Description => // Make sure there is some kind of "mail" name - return _mapiClient ??= Language.GetString(LangKey.editor_email); - } - } + _mapiClient ??= Language.GetString(LangKey.editor_email); public override int Priority => 3; @@ -73,7 +68,7 @@ namespace Greenshot.Destinations // 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 :( var outlookDestination = Type.GetType("GreenshotOfficePlugin.OutlookDestination,GreenshotOfficePlugin", false); - if (outlookDestination != null && _mapiClient.ToLower().Contains("microsoft outlook")) + if (outlookDestination != null && _mapiClient.IndexOf("microsoft outlook", StringComparison.CurrentCultureIgnoreCase) >= 0) { _isActiveFlag = false; } diff --git a/src/Greenshot/Destinations/FileWithDialogDestination.cs b/src/Greenshot/Destinations/FileWithDialogDestination.cs index 5c863e0c5..34305b06b 100644 --- a/src/Greenshot/Destinations/FileWithDialogDestination.cs +++ b/src/Greenshot/Destinations/FileWithDialogDestination.cs @@ -42,15 +42,9 @@ namespace Greenshot.Destinations public override int Priority => 0; - public override Keys EditorShortcutKeys - { - get { return Keys.Control | Keys.Shift | Keys.S; } - } + public override Keys EditorShortcutKeys => Keys.Control | Keys.Shift | Keys.S; - public override Image DisplayIcon - { - get { return GreenshotResources.GetImage("Save.Image"); } - } + public override Image DisplayIcon => GreenshotResources.GetImage("Save.Image"); public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) { diff --git a/src/Greenshot/Destinations/PrinterDestination.cs b/src/Greenshot/Destinations/PrinterDestination.cs index 4086264ed..ba0fc2d32 100644 --- a/src/Greenshot/Destinations/PrinterDestination.cs +++ b/src/Greenshot/Destinations/PrinterDestination.cs @@ -43,22 +43,13 @@ namespace Greenshot.Destinations { } - public PrinterDestination(string printerName) - { - _printerName = printerName; - } + public PrinterDestination(string printerName) => _printerName = printerName; public override string Designation => nameof(WellKnownDestinations.Printer); - public override string Description - { - get - { - return _printerName != null + public override string Description => _printerName != null ? Language.GetString(LangKey.settings_destination_printer) + " - " + _printerName : Language.GetString(LangKey.settings_destination_printer); - } - } public override int Priority => 2; @@ -83,7 +74,7 @@ namespace Greenshot.Destinations printers.Add(printer); } - printers.Sort(delegate (string p1, string p2) + printers.Sort((string p1, string p2) => { if (defaultPrinter.Equals(p1)) { diff --git a/src/Greenshot/Forms/BugReportForm.cs b/src/Greenshot/Forms/BugReportForm.cs index ec3d70065..b857dc7f0 100644 --- a/src/Greenshot/Forms/BugReportForm.cs +++ b/src/Greenshot/Forms/BugReportForm.cs @@ -38,15 +38,9 @@ namespace Greenshot.Forms ToFront = true; } - public BugReportForm(string bugText) : this() - { - textBoxDescription.Text = bugText; - } + public BugReportForm(string bugText) : this() => textBoxDescription.Text = bugText; - private void LinkLblBugsLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) - { - openLink((LinkLabel)sender); - } + private void LinkLblBugsLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) => openLink((LinkLabel)sender); private void openLink(LinkLabel link) { diff --git a/src/Greenshot/Forms/CaptureForm.cs b/src/Greenshot/Forms/CaptureForm.cs index e5d206769..737c43fa8 100644 --- a/src/Greenshot/Forms/CaptureForm.cs +++ b/src/Greenshot/Forms/CaptureForm.cs @@ -39,6 +39,7 @@ using Greenshot.Base.Core; using Greenshot.Base.IniFile; using Greenshot.Base.Interfaces; using Greenshot.Base.Interfaces.Ocr; +using System.Linq; namespace Greenshot.Forms { @@ -463,12 +464,11 @@ namespace Greenshot.Forms if (lineBounds.IsEmpty) continue; // Highlight the text which is selected if (!lineBounds.Contains(location)) continue; - foreach (var word in line.Words) + foreach (var _ in from word in line.Words + where word.Bounds.Contains(location) + select new { }) { - if (word.Bounds.Contains(location)) - { - return true; - } + return true; } } @@ -536,10 +536,7 @@ namespace Greenshot.Forms /// /// /// - private bool IsAnimating(IAnimator animator) - { - return animator != null && animator.HasNext; - } + private bool IsAnimating(IAnimator animator) => animator?.HasNext == true; /// /// update the frame, this only invalidates @@ -732,14 +729,7 @@ namespace Greenshot.Forms { continue; } - if (invalidateRectangle.IsEmpty) - { - invalidateRectangle = word.Bounds; - } - else - { - invalidateRectangle = invalidateRectangle.Union(word.Bounds); - } + invalidateRectangle = invalidateRectangle.IsEmpty ? word.Bounds : invalidateRectangle.Union(word.Bounds); } } else if (lineBounds.Contains(_mouseMovePos)) @@ -747,14 +737,7 @@ namespace Greenshot.Forms foreach (var word in line.Words) { if (!word.Bounds.Contains(_mouseMovePos)) continue; - if (invalidateRectangle.IsEmpty) - { - invalidateRectangle = word.Bounds; - } - else - { - invalidateRectangle = invalidateRectangle.Union(word.Bounds); - } + invalidateRectangle = invalidateRectangle.IsEmpty ? word.Bounds : invalidateRectangle.Union(word.Bounds); break; } diff --git a/src/Greenshot/Forms/LanguageDialog.cs b/src/Greenshot/Forms/LanguageDialog.cs index 7e69bc24b..6bdaf4a0c 100644 --- a/src/Greenshot/Forms/LanguageDialog.cs +++ b/src/Greenshot/Forms/LanguageDialog.cs @@ -96,9 +96,6 @@ namespace Greenshot.Forms Close(); } - public static LanguageDialog GetInstance() - { - return _uniqueInstance ??= new LanguageDialog(); - } + public static LanguageDialog GetInstance() => _uniqueInstance ??= new LanguageDialog(); } } \ No newline at end of file diff --git a/src/Greenshot/Forms/MainForm.cs b/src/Greenshot/Forms/MainForm.cs index 04b6789cb..30e8a5ad5 100644 --- a/src/Greenshot/Forms/MainForm.cs +++ b/src/Greenshot/Forms/MainForm.cs @@ -117,7 +117,7 @@ namespace Greenshot.Forms { string argument = arguments[argumentNr]; // Help - if (argument.ToLower().Equals("/help") || argument.ToLower().Equals("/h") || argument.ToLower().Equals("/?")) + if (argument.Equals("/help", StringComparison.CurrentCultureIgnoreCase) || argument.Equals("/h", StringComparison.CurrentCultureIgnoreCase) || argument.Equals("/?", StringComparison.CurrentCultureIgnoreCase)) { // Try to attach to the console bool attachedToConsole = Kernel32Api.AttachConsole(); @@ -166,7 +166,7 @@ namespace Greenshot.Forms return; } - if (argument.ToLower().Equals("/exit")) + if (argument.Equals("/exit", StringComparison.CurrentCultureIgnoreCase)) { // un-register application on uninstall (allow uninstall) try @@ -185,7 +185,7 @@ namespace Greenshot.Forms } // Reload the configuration - if (argument.ToLower().Equals("/reload")) + if (argument.Equals("/reload", StringComparison.CurrentCultureIgnoreCase)) { // Modify configuration LOG.Info("Reloading configuration!"); @@ -196,7 +196,7 @@ namespace Greenshot.Forms } // Stop running - if (argument.ToLower().Equals("/norun")) + if (argument.Equals("/norun", StringComparison.CurrentCultureIgnoreCase)) { // Make an exit possible FreeMutex(); @@ -204,7 +204,7 @@ namespace Greenshot.Forms } // Language - if (argument.ToLower().Equals("/language")) + if (argument.Equals("/language", StringComparison.CurrentCultureIgnoreCase)) { _conf.Language = arguments[++argumentNr]; IniConfig.Save(); @@ -212,7 +212,7 @@ namespace Greenshot.Forms } // Setting the INI-directory - if (argument.ToLower().Equals("/inidirectory")) + if (argument.Equals("/inidirectory", StringComparison.CurrentCultureIgnoreCase)) { IniConfig.IniDirectory = arguments[++argumentNr]; continue; @@ -769,10 +769,7 @@ namespace Greenshot.Forms /// Registers all hotkeys as configured, displaying a dialog in case of hotkey conflicts with other tools. /// /// Whether the hotkeys could be registered to the users content. This also applies if conflicts arise and the user decides to ignore these (i.e. not to register the conflicting hotkey). - public static bool RegisterHotkeys() - { - return RegisterHotkeys(false); - } + public static bool RegisterHotkeys() => RegisterHotkeys(false); /// /// Registers all hotkeys as configured, displaying a dialog in case of hotkey conflicts with other tools. @@ -814,12 +811,9 @@ namespace Greenshot.Forms success = false; } - if (_conf.IECapture) + if (_conf.IECapture && !RegisterWrapper(failedKeys, "CaptureIE", "IEHotkey", _instance.CaptureIE, ignoreFailedRegistration)) { - if (!RegisterWrapper(failedKeys, "CaptureIE", "IEHotkey", _instance.CaptureIE, ignoreFailedRegistration)) - { - success = false; - } + success = false; } if (!success) @@ -936,10 +930,7 @@ namespace Greenshot.Forms //loProcess.MinWorkingSet = (IntPtr)300000; } - private void CaptureRegion() - { - CaptureHelper.CaptureRegion(true); - } + private void CaptureRegion() => CaptureHelper.CaptureRegion(true); private void CaptureFile(IDestination destination = null) { @@ -961,23 +952,14 @@ namespace Greenshot.Forms } } - private void CaptureFullScreen() - { - CaptureHelper.CaptureFullscreen(true, _conf.ScreenCaptureMode); - } + private void CaptureFullScreen() => CaptureHelper.CaptureFullscreen(true, _conf.ScreenCaptureMode); - private void CaptureLastRegion() - { - CaptureHelper.CaptureLastRegion(true); - } + private void CaptureLastRegion() => CaptureHelper.CaptureLastRegion(true); /// /// This is used by the hotkey trigger /// - private void CaptureClipboard() - { - CaptureHelper.CaptureClipboard(DestinationHelper.GetDestination(EditorDestination.DESIGNATION)); - } + private void CaptureClipboard() => CaptureHelper.CaptureClipboard(DestinationHelper.GetDestination(EditorDestination.DESIGNATION)); private void CaptureIE() { @@ -1191,10 +1173,7 @@ namespace Greenshot.Forms AddCaptureWindowMenuItems(captureWindowFromListMenuItem, Contextmenu_CaptureWindowFromList_Click); } - private void CaptureWindowFromListMenuDropDownClosed(object sender, EventArgs e) - { - CleanupThumbnail(); - } + private void CaptureWindowFromListMenuDropDownClosed(object sender, EventArgs e) => CleanupThumbnail(); private void ShowThumbnailOnEnter(object sender, EventArgs e) { @@ -1203,10 +1182,7 @@ namespace Greenshot.Forms (_thumbnailForm ??= new ThumbnailForm()).ShowThumbnail(window, captureWindowItem.GetCurrentParent().TopLevelControl); } - private void HideThumbnailOnLeave(object sender, EventArgs e) - { - _thumbnailForm?.Hide(); - } + private void HideThumbnailOnLeave(object sender, EventArgs e) => _thumbnailForm?.Hide(); private void CleanupThumbnail() { @@ -1261,35 +1237,17 @@ namespace Greenshot.Forms } } - private void CaptureAreaToolStripMenuItemClick(object sender, EventArgs e) - { - BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureRegion(false); }); - } + private void CaptureAreaToolStripMenuItemClick(object sender, EventArgs e) => BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureRegion(false); }); - private void CaptureClipboardToolStripMenuItemClick(object sender, EventArgs e) - { - BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureClipboard(); }); - } + private void CaptureClipboardToolStripMenuItemClick(object sender, EventArgs e) => BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureClipboard(); }); - private void OpenFileToolStripMenuItemClick(object sender, EventArgs e) - { - BeginInvoke((MethodInvoker)delegate { CaptureFile(); }); - } + private void OpenFileToolStripMenuItemClick(object sender, EventArgs e) => BeginInvoke((MethodInvoker)delegate { CaptureFile(); }); - private void CaptureFullScreenToolStripMenuItemClick(object sender, EventArgs e) - { - BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureFullscreen(false, _conf.ScreenCaptureMode); }); - } + private void CaptureFullScreenToolStripMenuItemClick(object sender, EventArgs e) => BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureFullscreen(false, _conf.ScreenCaptureMode); }); - private void Contextmenu_CaptureLastRegionClick(object sender, EventArgs e) - { - BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureLastRegion(false); }); - } + private void Contextmenu_CaptureLastRegionClick(object sender, EventArgs e) => BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureLastRegion(false); }); - private void Contextmenu_CaptureWindow_Click(object sender, EventArgs e) - { - BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureWindowInteractive(false); }); - } + private void Contextmenu_CaptureWindow_Click(object sender, EventArgs e) => BeginInvoke((MethodInvoker)delegate { CaptureHelper.CaptureWindowInteractive(false); }); private void Contextmenu_CaptureWindowFromList_Click(object sender, EventArgs e) { @@ -1308,10 +1266,7 @@ namespace Greenshot.Forms }); } - private void Contextmenu_CaptureIe_Click(object sender, EventArgs e) - { - CaptureIE(); - } + private void Contextmenu_CaptureIe_Click(object sender, EventArgs e) => CaptureIE(); private void Contextmenu_CaptureIeFromList_Click(object sender, EventArgs e) { @@ -1356,20 +1311,14 @@ namespace Greenshot.Forms /// /// object /// EventArgs - private void Contextmenu_DonateClick(object sender, EventArgs e) - { - BeginInvoke((MethodInvoker)delegate { Process.Start("https://getgreenshot.org/support/?version=" + EnvironmentInfo.GetGreenshotVersion(true)); }); - } + private void Contextmenu_DonateClick(object sender, EventArgs e) => BeginInvoke((MethodInvoker)delegate { Process.Start("https://getgreenshot.org/support/?version=" + EnvironmentInfo.GetGreenshotVersion(true)); }); /// /// Context menu entry "Preferences" /// /// /// - private void Contextmenu_SettingsClick(object sender, EventArgs e) - { - BeginInvoke((MethodInvoker)ShowSetting); - } + private void Contextmenu_SettingsClick(object sender, EventArgs e) => BeginInvoke((MethodInvoker)ShowSetting); /// /// This is called indirectly from the context menu "Preferences" @@ -1404,10 +1353,7 @@ namespace Greenshot.Forms /// /// /// - private void Contextmenu_AboutClick(object sender, EventArgs e) - { - ShowAbout(); - } + private void Contextmenu_AboutClick(object sender, EventArgs e) => ShowAbout(); public void ShowAbout() { @@ -1436,20 +1382,14 @@ namespace Greenshot.Forms /// /// /// - private void Contextmenu_HelpClick(object sender, EventArgs e) - { - HelpFileLoader.LoadHelp(); - } + private void Contextmenu_HelpClick(object sender, EventArgs e) => HelpFileLoader.LoadHelp(); /// /// The "Exit" entry is clicked /// /// /// - private void Contextmenu_ExitClick(object sender, EventArgs e) - { - Exit(); - } + private void Contextmenu_ExitClick(object sender, EventArgs e) => Exit(); private void CheckStateChangedHandler(object sender, EventArgs e) { @@ -1528,15 +1468,14 @@ namespace Greenshot.Forms }; IniValue iniValue; - foreach (string propertyName in _conf.Values.Keys) + foreach (var propertyName in from string propertyName in _conf.Values.Keys + where propertyName.StartsWith("OutputPrint") + select propertyName) { - if (propertyName.StartsWith("OutputPrint")) + iniValue = _conf.Values[propertyName]; + if (iniValue.Attributes.LanguageKey != null && !iniValue.IsFixed) { - iniValue = _conf.Values[propertyName]; - if (iniValue.Attributes.LanguageKey != null && !iniValue.IsFixed) - { - selectList.AddItem(Language.GetString(iniValue.Attributes.LanguageKey), iniValue, (bool)iniValue.Value); - } + selectList.AddItem(Language.GetString(iniValue.Attributes.LanguageKey), iniValue, (bool)iniValue.Value); } } @@ -1931,10 +1870,7 @@ namespace Greenshot.Forms /// /// WindowDetails /// WindowDetails - public WindowDetails SelectCaptureWindow(WindowDetails windowToCapture) - { - return CaptureHelper.SelectCaptureWindow(windowToCapture); - } + public WindowDetails SelectCaptureWindow(WindowDetails windowToCapture) => CaptureHelper.SelectCaptureWindow(windowToCapture); /// /// TODO: Delete when the ICaptureHelper can be solve someway else @@ -1943,9 +1879,6 @@ namespace Greenshot.Forms /// ICapture /// WindowCaptureMode /// ICapture - public ICapture CaptureWindow(WindowDetails windowToCapture, ICapture capture, WindowCaptureMode coreConfigurationWindowCaptureMode) - { - return CaptureHelper.CaptureWindow(windowToCapture, capture, coreConfigurationWindowCaptureMode); - } + public ICapture CaptureWindow(WindowDetails windowToCapture, ICapture capture, WindowCaptureMode coreConfigurationWindowCaptureMode) => CaptureHelper.CaptureWindow(windowToCapture, capture, coreConfigurationWindowCaptureMode); } } \ No newline at end of file diff --git a/src/Greenshot/Forms/SettingsForm.cs b/src/Greenshot/Forms/SettingsForm.cs index a182cd13a..544b58dd6 100644 --- a/src/Greenshot/Forms/SettingsForm.cs +++ b/src/Greenshot/Forms/SettingsForm.cs @@ -68,10 +68,7 @@ namespace Greenshot.Forms /// /// /// DpiChangedEventArgs - private void AdjustToDpi(object sender, DpiChangedEventArgs dpiChangedEventArgs) - { - DisplaySettings(); - } + private void AdjustToDpi(object sender, DpiChangedEventArgs dpiChangedEventArgs) => DisplaySettings(); protected override void OnLoad(EventArgs e) { @@ -122,14 +119,7 @@ namespace Greenshot.Forms // Check if we can into the forbidden range if (currentValue > 0 && currentValue < 7) { - if (_daysBetweenCheckPreviousValue <= currentValue) - { - numericUpDown_daysbetweencheck.Value = 7; - } - else - { - numericUpDown_daysbetweencheck.Value = 0; - } + numericUpDown_daysbetweencheck.Value = _daysBetweenCheckPreviousValue <= currentValue ? 7 : 0; } if ((int)numericUpDown_daysbetweencheck.Value < 0) @@ -326,10 +316,7 @@ namespace Greenshot.Forms } // Check the settings and somehow visibly mark when something is incorrect - private bool CheckSettings() - { - return CheckFilenamePattern() && CheckStorageLocationPath(); - } + private bool CheckSettings() => CheckFilenamePattern() && CheckStorageLocationPath(); private bool CheckFilenamePattern() { @@ -370,15 +357,9 @@ namespace Greenshot.Forms } } - private void FilenamePatternChanged(object sender, EventArgs e) - { - CheckFilenamePattern(); - } + private void FilenamePatternChanged(object sender, EventArgs e) => CheckFilenamePattern(); - private void StorageLocationChanged(object sender, EventArgs e) - { - CheckStorageLocationPath(); - } + private void StorageLocationChanged(object sender, EventArgs e) => CheckStorageLocationPath(); /// /// Show all destination descriptions in the current language @@ -444,16 +425,9 @@ namespace Greenshot.Forms } else { - ListViewItem item; - if (destinationImage != null) - { - item = listview_destinations.Items.Add(currentDestination.Description, imageNr); - } - else - { - item = listview_destinations.Items.Add(currentDestination.Description); - } - + ListViewItem item = destinationImage != null + ? listview_destinations.Items.Add(currentDestination.Description, imageNr) + : listview_destinations.Items.Add(currentDestination.Description); item.Tag = currentDestination; item.Checked = coreConfiguration.OutputDestinations.Contains(currentDestination.Designation); } @@ -622,10 +596,7 @@ namespace Greenshot.Forms } } - private void Settings_cancelClick(object sender, EventArgs e) - { - DialogResult = DialogResult.Cancel; - } + private void Settings_cancelClick(object sender, EventArgs e) => DialogResult = DialogResult.Cancel; private void Settings_okayClick(object sender, EventArgs e) { @@ -651,20 +622,14 @@ namespace Greenshot.Forms { // Get the storage location and replace the environment variables folderBrowserDialog1.SelectedPath = FilenameHelper.FillVariables(textbox_storagelocation.Text, false); - if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) + // Only change if there is a change, otherwise we might overwrite the environment variables + if (folderBrowserDialog1.ShowDialog() == DialogResult.OK && folderBrowserDialog1.SelectedPath?.Equals(FilenameHelper.FillVariables(textbox_storagelocation.Text, false)) == false) { - // Only change if there is a change, otherwise we might overwrite the environment variables - if (folderBrowserDialog1.SelectedPath?.Equals(FilenameHelper.FillVariables(textbox_storagelocation.Text, false)) == false) - { - textbox_storagelocation.Text = folderBrowserDialog1.SelectedPath; - } + textbox_storagelocation.Text = folderBrowserDialog1.SelectedPath; } } - private void TrackBarJpegQualityScroll(object sender, EventArgs e) - { - textBoxJpegQuality.Text = trackBarJpegQuality.Value.ToString(CultureInfo.InvariantCulture); - } + private void TrackBarJpegQualityScroll(object sender, EventArgs e) => textBoxJpegQuality.Text = trackBarJpegQuality.Value.ToString(CultureInfo.InvariantCulture); private void BtnPatternHelpClick(object sender, EventArgs e) { @@ -674,15 +639,9 @@ namespace Greenshot.Forms MessageBox.Show(filenamepatternText, Language.GetString(LangKey.settings_filenamepattern)); } - private void Listview_pluginsSelectedIndexChanged(object sender, EventArgs e) - { - button_pluginconfigure.Enabled = PluginHelper.Instance.IsSelectedItemConfigurable(listview_plugins); - } + private void Listview_pluginsSelectedIndexChanged(object sender, EventArgs e) => button_pluginconfigure.Enabled = PluginHelper.Instance.IsSelectedItemConfigurable(listview_plugins); - private void Button_pluginconfigureClick(object sender, EventArgs e) - { - PluginHelper.Instance.ConfigureSelectedItem(listview_plugins); - } + private void Button_pluginconfigureClick(object sender, EventArgs e) => PluginHelper.Instance.ConfigureSelectedItem(listview_plugins); private void Combobox_languageSelectedIndexChanged(object sender, EventArgs e) { @@ -772,10 +731,7 @@ namespace Greenshot.Forms } } - private void DestinationsCheckStateChanged(object sender, EventArgs e) - { - CheckDestinationSettings(); - } + private void DestinationsCheckStateChanged(object sender, EventArgs e) => CheckDestinationSettings(); protected override void OnFieldsFilled() { @@ -817,10 +773,7 @@ namespace Greenshot.Forms } } - private void Radiobutton_CheckedChanged(object sender, EventArgs e) - { - combobox_window_capture_mode.Enabled = radiobuttonWindowCapture.Checked; - } + private void Radiobutton_CheckedChanged(object sender, EventArgs e) => combobox_window_capture_mode.Enabled = radiobuttonWindowCapture.Checked; } public class ListviewWithDestinationComparer : IComparer diff --git a/src/Greenshot/Forms/ToolStripMenuSelectList.cs b/src/Greenshot/Forms/ToolStripMenuSelectList.cs index 6e73874b1..daa1717c7 100644 --- a/src/Greenshot/Forms/ToolStripMenuSelectList.cs +++ b/src/Greenshot/Forms/ToolStripMenuSelectList.cs @@ -133,10 +133,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) - { - AddItem(label, null, data, isChecked); - } + public void AddItem(string label, object data, bool isChecked) => AddItem(label, null, data, isChecked); /// /// unchecks all items of the list @@ -162,10 +159,7 @@ namespace Greenshot.Forms { public ToolStripMenuSelectListItem Item { get; set; } - public ItemCheckedChangedEventArgs(ToolStripMenuSelectListItem item) - { - Item = item; - } + public ItemCheckedChangedEventArgs(ToolStripMenuSelectListItem item) => Item = item; } /// diff --git a/src/Greenshot/GreenshotMain.cs b/src/Greenshot/GreenshotMain.cs index 2d42d4b11..259811613 100644 --- a/src/Greenshot/GreenshotMain.cs +++ b/src/Greenshot/GreenshotMain.cs @@ -30,12 +30,9 @@ namespace Greenshot /// /// Description of Main. /// - public class GreenshotMain + public static class GreenshotMain { - static GreenshotMain() - { - AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; - } + static GreenshotMain() => AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { @@ -60,7 +57,7 @@ namespace Greenshot public static void Main(string[] args) { // Enable TLS 1.2 support - ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture; diff --git a/src/Greenshot/Helpers/CaptureHelper.cs b/src/Greenshot/Helpers/CaptureHelper.cs index 719e63cea..343995339 100644 --- a/src/Greenshot/Helpers/CaptureHelper.cs +++ b/src/Greenshot/Helpers/CaptureHelper.cs @@ -42,6 +42,7 @@ using Greenshot.Configuration; using Greenshot.Editor.Destinations; using Greenshot.Editor.Drawing; using Greenshot.Forms; +using System.Linq; namespace Greenshot.Helpers { @@ -203,10 +204,7 @@ namespace Greenshot.Helpers _capture = new Capture(); } - public CaptureHelper(CaptureMode captureMode, bool captureMouseCursor) : this(captureMode) - { - _captureMouseCursor = captureMouseCursor; - } + public CaptureHelper(CaptureMode captureMode, bool captureMouseCursor) : this(captureMode) => _captureMouseCursor = captureMouseCursor; public CaptureHelper(CaptureMode captureMode, bool captureMouseCursor, ScreenCaptureMode screenCaptureMode) : this(captureMode) { @@ -214,10 +212,7 @@ namespace Greenshot.Helpers _screenCaptureMode = screenCaptureMode; } - public CaptureHelper(CaptureMode captureMode, bool captureMouseCursor, IDestination destination) : this(captureMode, captureMouseCursor) - { - _capture.CaptureDetails.AddDestination(destination); - } + public CaptureHelper(CaptureMode captureMode, bool captureMouseCursor, IDestination destination) : this(captureMode, captureMouseCursor) => _capture.CaptureDetails.AddDestination(destination); public WindowDetails SelectedCaptureWindow { get; set; } @@ -350,17 +345,16 @@ namespace Greenshot.Helpers { case ScreenCaptureMode.Auto: NativePoint mouseLocation = User32Api.GetCursorLocation(); - foreach (Screen screen in Screen.AllScreens) + foreach (var screen in from Screen screen in Screen.AllScreens + where screen.Bounds.Contains(mouseLocation) + select screen) { - if (screen.Bounds.Contains(mouseLocation)) - { - _capture = WindowCapture.CaptureRectangle(_capture, screen.Bounds); - captureTaken = true; - // As the screen shot might be on a different monitor we need to correct the mouse location - var correctedCursorLocation = _capture.CursorLocation.Offset(-screen.Bounds.Location.X, -screen.Bounds.Location.Y); - _capture.CursorLocation = correctedCursorLocation; - break; - } + _capture = WindowCapture.CaptureRectangle(_capture, screen.Bounds); + captureTaken = true; + // As the screen shot might be on a different monitor we need to correct the mouse location + var correctedCursorLocation = _capture.CursorLocation.Offset(-screen.Bounds.Location.X, -screen.Bounds.Location.Y); + _capture.CursorLocation = correctedCursorLocation; + break; } break; @@ -818,12 +812,9 @@ namespace Greenshot.Helpers else { SelectedCaptureWindow = WindowDetails.GetActiveWindow(); - if (SelectedCaptureWindow != null) + if (SelectedCaptureWindow != null && 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); } } @@ -984,12 +975,9 @@ namespace Greenshot.Helpers } // Change to DWM, if enabled and allowed - if (dwmEnabled) + if (dwmEnabled && WindowCapture.IsDwmAllowed(process)) { - if (WindowCapture.IsDwmAllowed(process)) - { - windowCaptureMode = WindowCaptureMode.Aero; - } + windowCaptureMode = WindowCaptureMode.Aero; } } } diff --git a/src/Greenshot/Helpers/CopyData.cs b/src/Greenshot/Helpers/CopyData.cs index 88ca89cab..173b4ca50 100644 --- a/src/Greenshot/Helpers/CopyData.cs +++ b/src/Greenshot/Helpers/CopyData.cs @@ -47,30 +47,15 @@ namespace Greenshot.Helpers { public List> Commands { get; } - public CopyDataTransport() - { - Commands = new List>(); - } + public CopyDataTransport() => Commands = new List>(); - public CopyDataTransport(CommandEnum command) : this() - { - AddCommand(command, null); - } + public CopyDataTransport(CommandEnum command) : this() => AddCommand(command, null); - public CopyDataTransport(CommandEnum command, string commandData) : this() - { - AddCommand(command, commandData); - } + public CopyDataTransport(CommandEnum command, string commandData) : this() => AddCommand(command, commandData); - public void AddCommand(CommandEnum command) - { - Commands.Add(new KeyValuePair(command, null)); - } + public void AddCommand(CommandEnum command) => Commands.Add(new KeyValuePair(command, null)); - public void AddCommand(CommandEnum command, string commandData) - { - Commands.Add(new KeyValuePair(command, commandData)); - } + public void AddCommand(CommandEnum command, string commandData) => Commands.Add(new KeyValuePair(command, commandData)); } public delegate void CopyDataReceivedEventHandler(object sender, CopyDataReceivedEventArgs e); @@ -147,10 +132,7 @@ namespace Greenshot.Helpers /// Raises the DataReceived event from this class. /// /// The data which has been received. - protected void OnCopyDataReceived(CopyDataReceivedEventArgs e) - { - CopyDataReceived?.Invoke(this, e); - } + protected void OnCopyDataReceived(CopyDataReceivedEventArgs e) => CopyDataReceived?.Invoke(this, e); /// /// If the form's handle changes, the properties associated @@ -191,10 +173,7 @@ namespace Greenshot.Helpers /// /// Constructs a new instance of the CopyData class /// - public CopyData() - { - _channels = new CopyDataChannels(this); - } + public CopyData() => _channels = new CopyDataChannels(this); /// /// Finalises a CopyData class which has not been disposed. @@ -264,10 +243,7 @@ namespace Greenshot.Helpers /// /// An enumerator for each of the CopyDataChannel objects /// within this collection. - public new IEnumerator GetEnumerator() - { - return Dictionary.Values.GetEnumerator(); - } + public new IEnumerator GetEnumerator() => Dictionary.Values.GetEnumerator(); /// /// Returns the CopyDataChannel at the specified 0-based index. @@ -310,19 +286,13 @@ namespace Greenshot.Helpers /// Removes an existing channel. /// /// The channel to remove - public void Remove(string channelName) - { - Dictionary.Remove(channelName); - } + public void Remove(string channelName) => Dictionary.Remove(channelName); /// /// Gets/sets whether this channel contains a CopyDataChannel /// for the specified channelName. /// - public bool Contains(string channelName) - { - return Dictionary.Contains(channelName); - } + public bool Contains(string channelName) => Dictionary.Contains(channelName); /// /// Ensures the resources associated with a CopyDataChannel @@ -372,10 +342,7 @@ namespace Greenshot.Helpers /// /// The NativeWindow this collection /// will be associated with - internal CopyDataChannels(NativeWindow owner) - { - _owner = owner; - } + internal CopyDataChannels(NativeWindow owner) => _owner = owner; } /// @@ -461,19 +428,16 @@ namespace Greenshot.Helpers // the channel: foreach (WindowDetails window in WindowDetails.GetAllWindows()) { - if (!window.Handle.Equals(_owner.Handle)) + if (!window.Handle.Equals(_owner.Handle) && GetProp(window.Handle, ChannelName) != IntPtr.Zero) { - if (GetProp(window.Handle, ChannelName) != IntPtr.Zero) + COPYDATASTRUCT cds = new() { - COPYDATASTRUCT cds = new() - { - cbData = dataSize, - dwData = IntPtr.Zero, - lpData = ptrData - }; - SendMessage(window.Handle, WM_COPYDATA, _owner.Handle, ref cds); - recipients += Marshal.GetLastWin32Error() == 0 ? 1 : 0; - } + cbData = dataSize, + dwData = IntPtr.Zero, + lpData = ptrData + }; + SendMessage(window.Handle, WM_COPYDATA, _owner.Handle, ref cds); + recipients += Marshal.GetLastWin32Error() == 0 ? 1 : 0; } } @@ -486,17 +450,13 @@ namespace Greenshot.Helpers return recipients; } - private void AddChannel() - { + private void AddChannel() => // Tag this window with property "channelName" SetProp(_owner.Handle, ChannelName, _owner.Handle); - } - private void RemoveChannel() - { + private void RemoveChannel() => // Remove the "channelName" property from this window RemoveProp(_owner.Handle, ChannelName); - } /// /// If the form's handle changes, the properties associated diff --git a/src/Greenshot/Helpers/IECaptureHelper.cs b/src/Greenshot/Helpers/IECaptureHelper.cs index facfc841b..51e15a6df 100644 --- a/src/Greenshot/Helpers/IECaptureHelper.cs +++ b/src/Greenshot/Helpers/IECaptureHelper.cs @@ -112,10 +112,7 @@ namespace Greenshot.Helpers /// Simple check if IE is running /// /// bool - public static bool IsIeRunning() - { - return GetIeWindows().Any(); - } + public static bool IsIeRunning() => GetIeWindows().Any(); /// /// Gets a list of all IE Windows & tabs with the captions of the instances diff --git a/src/Greenshot/Helpers/IEInterop/IEContainer.cs b/src/Greenshot/Helpers/IEInterop/IEContainer.cs index 01cbaa703..56bb535b4 100644 --- a/src/Greenshot/Helpers/IEInterop/IEContainer.cs +++ b/src/Greenshot/Helpers/IEInterop/IEContainer.cs @@ -427,33 +427,18 @@ namespace Greenshot.Helpers.IEInterop public DocumentContainer Parent { get; set; } - private int ScaleX(int physicalValue) - { - return (int)Math.Round(physicalValue * _zoomLevelX, MidpointRounding.AwayFromZero); - } + private int ScaleX(int physicalValue) => (int)Math.Round(physicalValue * _zoomLevelX, MidpointRounding.AwayFromZero); - private int ScaleY(int physicalValue) - { - return (int)Math.Round(physicalValue * _zoomLevelY, MidpointRounding.AwayFromZero); - } + private int ScaleY(int physicalValue) => (int)Math.Round(physicalValue * _zoomLevelY, MidpointRounding.AwayFromZero); - private int UnscaleX(int physicalValue) - { - return (int)Math.Round(physicalValue / _zoomLevelX, MidpointRounding.AwayFromZero); - } + private int UnscaleX(int physicalValue) => (int)Math.Round(physicalValue / _zoomLevelX, MidpointRounding.AwayFromZero); - private int UnscaleY(int physicalValue) - { - return (int)Math.Round(physicalValue / _zoomLevelY, MidpointRounding.AwayFromZero); - } + private int UnscaleY(int physicalValue) => (int)Math.Round(physicalValue / _zoomLevelY, MidpointRounding.AwayFromZero); /// /// Set/change an int attribute on a document /// - public void SetAttribute(string attribute, int value) - { - SetAttribute(attribute, value.ToString()); - } + public void SetAttribute(string attribute, int value) => SetAttribute(attribute, value.ToString()); /// /// Set/change an attribute on a document diff --git a/src/Greenshot/Helpers/MailHelper.cs b/src/Greenshot/Helpers/MailHelper.cs index 5e5ea8912..a0285885b 100644 --- a/src/Greenshot/Helpers/MailHelper.cs +++ b/src/Greenshot/Helpers/MailHelper.cs @@ -497,15 +497,9 @@ namespace Greenshot.Helpers /// /// Adds the specified recipient to this collection. /// - public void Add(Recipient value) - { - List.Add(value); - } + public void Add(Recipient value) => List.Add(value); - internal InteropRecipientCollection GetInteropRepresentation() - { - return new InteropRecipientCollection(this); - } + internal InteropRecipientCollection GetInteropRepresentation() => new(this); /// /// Struct which contains an interop representation of a colleciton of recipients. diff --git a/src/Greenshot/Helpers/NotifyIconNotificationService.cs b/src/Greenshot/Helpers/NotifyIconNotificationService.cs index 48709a1df..e1a52b534 100644 --- a/src/Greenshot/Helpers/NotifyIconNotificationService.cs +++ b/src/Greenshot/Helpers/NotifyIconNotificationService.cs @@ -37,10 +37,7 @@ namespace Greenshot.Helpers private static readonly CoreConfiguration CoreConfiguration = IniConfig.GetIniSection(); private readonly NotifyIcon _notifyIcon; - public NotifyIconNotificationService() - { - _notifyIcon = SimpleServiceProvider.Current.GetInstance(); - } + public NotifyIconNotificationService() => _notifyIcon = SimpleServiceProvider.Current.GetInstance(); /// /// This will show a warning message to the user @@ -49,10 +46,7 @@ namespace Greenshot.Helpers /// TimeSpan /// Action called if the user clicks the notification /// Action - public void ShowWarningMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) - { - ShowMessage(message, timeout, ToolTipIcon.Warning, onClickAction, onClosedAction); - } + public void ShowWarningMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) => ShowMessage(message, timeout, ToolTipIcon.Warning, onClickAction, onClosedAction); /// /// This will show an error message to the user @@ -61,10 +55,7 @@ namespace Greenshot.Helpers /// TimeSpan /// Action called if the user clicks the notification /// Action - public void ShowErrorMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) - { - ShowMessage(message, timeout, ToolTipIcon.Error, onClickAction, onClosedAction); - } + public void ShowErrorMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) => ShowMessage(message, timeout, ToolTipIcon.Error, onClickAction, onClosedAction); /// /// This will show an info message to the user @@ -73,10 +64,7 @@ namespace Greenshot.Helpers /// TimeSpan /// Action called if the user clicks the notification /// Action - public void ShowInfoMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) - { - ShowMessage(message, timeout, ToolTipIcon.Info, onClickAction, onClosedAction); - } + public void ShowInfoMessage(string message, TimeSpan? timeout = null, Action onClickAction = null, Action onClosedAction = null) => ShowMessage(message, timeout, ToolTipIcon.Info, onClickAction, onClosedAction); /// /// This will show a message to the user diff --git a/src/Greenshot/Helpers/PluginHelper.cs b/src/Greenshot/Helpers/PluginHelper.cs index 008c22f2e..dda42661d 100644 --- a/src/Greenshot/Helpers/PluginHelper.cs +++ b/src/Greenshot/Helpers/PluginHelper.cs @@ -117,34 +117,22 @@ namespace Greenshot.Helpers /// Thumbnail width /// Thumbnail height /// Image with Thumbnail - public Image GetThumbnail(Image image, int width, int height) - { - return image.GetThumbnailImage(width, height, ThumbnailCallback, IntPtr.Zero); - } + public Image GetThumbnail(Image image, int width, int height) => image.GetThumbnailImage(width, height, ThumbnailCallback, IntPtr.Zero); /// /// Required for GetThumbnail, but not used /// /// true - private bool ThumbnailCallback() - { - return true; - } + private bool ThumbnailCallback() => true; - public ExportInformation ExportCapture(bool manuallyInitiated, string designation, ISurface surface, ICaptureDetails captureDetails) - { - return DestinationHelper.ExportCapture(manuallyInitiated, designation, surface, captureDetails); - } + public ExportInformation ExportCapture(bool manuallyInitiated, string designation, ISurface surface, ICaptureDetails captureDetails) => DestinationHelper.ExportCapture(manuallyInitiated, designation, surface, captureDetails); /// /// Make Capture with specified Handler /// /// bool false if the mouse should not be captured, true if the configuration should be checked /// IDestination - public void CaptureRegion(bool captureMouseCursor, IDestination destination) - { - CaptureHelper.CaptureRegion(captureMouseCursor, destination); - } + public void CaptureRegion(bool captureMouseCursor, IDestination destination) => CaptureHelper.CaptureRegion(captureMouseCursor, destination); /// /// Use the supplied image, and handle it as if it's captured. diff --git a/src/Greenshot/Helpers/PrintHelper.cs b/src/Greenshot/Helpers/PrintHelper.cs index d6a200412..03c41d66d 100644 --- a/src/Greenshot/Helpers/PrintHelper.cs +++ b/src/Greenshot/Helpers/PrintHelper.cs @@ -159,10 +159,7 @@ namespace Greenshot.Helpers return returnPrinterSettings; } - private bool IsColorPrint() - { - return !CoreConfig.OutputPrintGrayscale && !CoreConfig.OutputPrintMonochrome; - } + private bool IsColorPrint() => !CoreConfig.OutputPrintGrayscale && !CoreConfig.OutputPrintMonochrome; /// /// display print options dialog (if the user has not configured Greenshot not to) @@ -217,16 +214,13 @@ namespace Greenshot.Helpers GraphicsUnit gu = GraphicsUnit.Pixel; RectangleF imageRect = image.GetBounds(ref gu); // rotate the image if it fits the page better - if (CoreConfig.OutputPrintAllowRotate) + if (CoreConfig.OutputPrintAllowRotate && ((pageRect.Width > pageRect.Height && imageRect.Width < imageRect.Height) || (pageRect.Width < pageRect.Height && imageRect.Width > imageRect.Height))) { - 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); + if (alignment.Equals(ContentAlignment.TopLeft)) { - image.RotateFlip(RotateFlipType.Rotate270FlipNone); - imageRect = image.GetBounds(ref gu); - if (alignment.Equals(ContentAlignment.TopLeft)) - { - alignment = ContentAlignment.TopRight; - } + alignment = ContentAlignment.TopRight; } } diff --git a/src/Greenshot/Helpers/StartupHelper.cs b/src/Greenshot/Helpers/StartupHelper.cs index 1047ad5de..fd5d8b8ad 100644 --- a/src/Greenshot/Helpers/StartupHelper.cs +++ b/src/Greenshot/Helpers/StartupHelper.cs @@ -39,10 +39,7 @@ namespace Greenshot.Helpers private const string ApplicationName = "Greenshot"; - private static string GetExecutablePath() - { - return "\"" + Application.ExecutablePath + "\""; - } + private static string GetExecutablePath() => "\"" + Application.ExecutablePath + "\""; /// /// Return true if the current user can write the RUN key of the local machine. diff --git a/src/Greenshot/Helpers/UpdateService.cs b/src/Greenshot/Helpers/UpdateService.cs index 8cfd3c630..11d803062 100644 --- a/src/Greenshot/Helpers/UpdateService.cs +++ b/src/Greenshot/Helpers/UpdateService.cs @@ -88,10 +88,7 @@ namespace Greenshot.Helpers /// /// Start the background task which checks for updates /// - public void Startup() - { - _ = BackgroundTask(() => TimeSpan.FromDays(CoreConfig.UpdateCheckInterval), UpdateCheck, _cancellationTokenSource.Token); - } + public void Startup() => _ = BackgroundTask(() => TimeSpan.FromDays(CoreConfig.UpdateCheckInterval), UpdateCheck, _cancellationTokenSource.Token); /// /// This runs a periodic task in the background