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