diff --git a/src/.editorconfig b/src/.editorconfig
index 0141618f9..383823176 100644
--- a/src/.editorconfig
+++ b/src/.editorconfig
@@ -14,7 +14,7 @@ indent_size = 4
# Xml project files
[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}]
-indent_size = 2
+indent_size = 4
# Xml config files
[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}]
@@ -44,6 +44,12 @@ dotnet_style_collection_initializer = true:suggestion
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_explicit_tuple_names = true:suggestion
+dotnet_style_operator_placement_when_wrapping = beginning_of_line
+tab_width = 4
+end_of_line = crlf
+dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
+dotnet_style_prefer_auto_properties = true:silent
+dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
# CSharp code style settings:
[*.cs]
@@ -70,4 +76,77 @@ csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_object_initializers = true
-csharp_new_line_before_members_in_anonymous_types = true
\ No newline at end of file
+csharp_new_line_before_members_in_anonymous_types = true
+csharp_indent_labels = one_less_than_current
+csharp_using_directive_placement = outside_namespace:silent
+csharp_prefer_simple_using_statement = true:suggestion
+csharp_prefer_braces = true:silent
+csharp_style_namespace_declarations = block_scoped:silent
+csharp_style_prefer_method_group_conversion = true:silent
+csharp_style_prefer_top_level_statements = true:silent
+csharp_style_expression_bodied_lambdas = true:silent
+csharp_style_expression_bodied_local_functions = false:silent
+dotnet_diagnostic.S125.severity = silent
+dotnet_diagnostic.RCS1075.severity = suggestion
+dotnet_diagnostic.S1075.severity = suggestion
+dotnet_diagnostic.S112.severity = silent
+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 ####
+
+# Naming rules
+
+dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
+dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
+dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
+
+dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
+dotnet_naming_rule.types_should_be_pascal_case.symbols = types
+dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
+
+dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
+dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
+dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
+
+# Symbol specifications
+
+dotnet_naming_symbols.interface.applicable_kinds = interface
+dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
+dotnet_naming_symbols.interface.required_modifiers =
+
+dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
+dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
+dotnet_naming_symbols.types.required_modifiers =
+
+dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
+dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
+dotnet_naming_symbols.non_field_members.required_modifiers =
+
+# Naming styles
+
+dotnet_naming_style.begins_with_i.required_prefix = I
+dotnet_naming_style.begins_with_i.required_suffix =
+dotnet_naming_style.begins_with_i.word_separator =
+dotnet_naming_style.begins_with_i.capitalization = pascal_case
+
+dotnet_naming_style.pascal_case.required_prefix =
+dotnet_naming_style.pascal_case.required_suffix =
+dotnet_naming_style.pascal_case.word_separator =
+dotnet_naming_style.pascal_case.capitalization = pascal_case
+
+dotnet_naming_style.pascal_case.required_prefix =
+dotnet_naming_style.pascal_case.required_suffix =
+dotnet_naming_style.pascal_case.word_separator =
+dotnet_naming_style.pascal_case.capitalization = pascal_case
diff --git a/src/Greenshot.Base/Controls/AnimatingForm.cs b/src/Greenshot.Base/Controls/AnimatingForm.cs
index cde3997ae..ac197d302 100644
--- a/src/Greenshot.Base/Controls/AnimatingForm.cs
+++ b/src/Greenshot.Base/Controls/AnimatingForm.cs
@@ -54,22 +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
- if (IsTerminalServerSession)
- {
- return 1;
- }
-
- return 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
@@ -119,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 b0ccee3a9..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,19 +53,18 @@ 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)
{
- Location = new Point(Cursor.Position.X - Width / 2, Cursor.Position.Y - Height / 2);
+ Location = new Point(Cursor.Position.X - (Width / 2), Cursor.Position.Y - (Height / 2));
}
}
@@ -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 f53e0b489..87555cf70 100644
--- a/src/Greenshot.Base/Controls/ExtendedWebBrowser.cs
+++ b/src/Greenshot.Base/Controls/ExtendedWebBrowser.cs
@@ -31,38 +31,29 @@ namespace Greenshot.Base.Controls
{
private const int OLECMDID_SHOWSCRIPTERROR = 40;
- private static readonly Guid CGID_DocHostCommandHandler = new Guid("F38BC242-B950-11D1-8918-00C04FC2C836");
+ private static readonly Guid CGID_DocHostCommandHandler = new("F38BC242-B950-11D1-8918-00C04FC2C836");
private const int S_OK = 0;
- private const int OLECMDERR_E_NOTSUPPORTED = (-2147221248);
+ private const int OLECMDERR_E_NOTSUPPORTED = -2147221248;
public ExtendedWebBrowserSite(WebBrowser wb) : base(wb)
{
}
- 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/GreenshotColumnSorter.cs b/src/Greenshot.Base/Controls/GreenshotColumnSorter.cs
index 77b262105..cd7b00ed5 100644
--- a/src/Greenshot.Base/Controls/GreenshotColumnSorter.cs
+++ b/src/Greenshot.Base/Controls/GreenshotColumnSorter.cs
@@ -29,16 +29,6 @@ namespace Greenshot.Base.Controls
///
public class GreenshotColumnSorter : IComparer
{
- ///
- /// Specifies the column to be sorted
- ///
- private int _columnToSort;
-
- ///
- /// Specifies the order in which to sort (i.e. 'Ascending').
- ///
- private SortOrder _orderOfSort;
-
///
/// Case insensitive comparer object
///
@@ -50,10 +40,10 @@ namespace Greenshot.Base.Controls
public GreenshotColumnSorter()
{
// Initialize the column to '0'
- _columnToSort = 0;
+ SortColumn = 0;
// Initialize the sort order to 'none'
- _orderOfSort = SortOrder.None;
+ Order = SortOrder.None;
// Initialize the CaseInsensitiveComparer object
_objectCompare = new CaseInsensitiveComparer();
@@ -83,20 +73,20 @@ namespace Greenshot.Base.Controls
}
// Cast the objects to be compared to ListViewItem objects
- var listviewX = (ListViewItem) x;
- var listviewY = (ListViewItem) y;
+ var listviewX = (ListViewItem)x;
+ var listviewY = (ListViewItem)y;
// Compare the two items
- var compareResult = _objectCompare.Compare(listviewX.SubItems[_columnToSort].Text, listviewY.SubItems[_columnToSort].Text);
+ var compareResult = _objectCompare.Compare(listviewX.SubItems[SortColumn].Text, listviewY.SubItems[SortColumn].Text);
// Calculate correct return value based on object comparison
- if (_orderOfSort == SortOrder.Ascending)
+ if (Order == SortOrder.Ascending)
{
// Ascending sort is selected, return normal result of compare operation
return compareResult;
}
- if (_orderOfSort == SortOrder.Descending)
+ if (Order == SortOrder.Descending)
{
// Descending sort is selected, return negative result of compare operation
return -compareResult;
@@ -109,19 +99,11 @@ namespace Greenshot.Base.Controls
///
/// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0').
///
- public int SortColumn
- {
- set { _columnToSort = value; }
- get { return _columnToSort; }
- }
+ public int SortColumn { set; get; }
///
/// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending').
///
- public SortOrder Order
- {
- set { _orderOfSort = value; }
- get { return _orderOfSort; }
- }
+ public SortOrder Order { set; get; }
}
}
\ No newline at end of file
diff --git a/src/Greenshot.Base/Controls/GreenshotComboBox.cs b/src/Greenshot.Base/Controls/GreenshotComboBox.cs
index 88c2e29f5..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)
{
@@ -65,7 +62,7 @@ namespace Greenshot.Base.Controls
Items.Clear();
foreach (var enumValue in availableValues)
{
- Items.Add(Language.Translate((Enum) enumValue));
+ Items.Add(Language.Translate((Enum)enumValue));
}
}
@@ -101,16 +98,13 @@ namespace Greenshot.Base.Controls
}
}
- _selectedEnum = (Enum) returnValue;
+ _selectedEnum = (Enum)returnValue;
}
///
/// 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 85bc6bd4d..f246e5d95 100644
--- a/src/Greenshot.Base/Controls/GreenshotForm.cs
+++ b/src/Greenshot.Base/Controls/GreenshotForm.cs
@@ -19,7 +19,6 @@
* along with this program. If not, see .
*/
-
#if DEBUG
using System.ComponentModel;
using System.ComponentModel.Design;
@@ -48,9 +47,8 @@ namespace Greenshot.Base.Controls
private bool _isDesignModeLanguageSet;
private IDictionary _designTimeControls;
private IDictionary _designTimeToolStripItems;
+
#endif
- private bool _applyLanguageManually;
- private bool _storeFieldsManually;
static GreenshotForm()
{
@@ -74,38 +72,21 @@ 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) ||
- (Application.ExecutablePath.IndexOf("sharpdevelop.exe", StringComparison.OrdinalIgnoreCase) > -1 ||
- (Application.ExecutablePath.IndexOf("wdexpress.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 { return _applyLanguageManually; }
- set { _applyLanguageManually = value; }
- }
+ protected bool ManualLanguageApply { get; set; }
- protected bool ManualStoreFields
- {
- get { return _storeFieldsManually; }
- set { _storeFieldsManually = value; }
- }
+ protected bool ManualStoreFields { get; set; }
///
/// When this is set, the form will be brought to the foreground as soon as it is shown.
///
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
@@ -127,14 +108,12 @@ namespace Greenshot.Base.Controls
_designTimeToolStripItems = new Dictionary();
try
{
- ITypeResolutionService typeResService = GetService(typeof(ITypeResolutionService)) as ITypeResolutionService;
-
// Add a hard-path if you are using SharpDevelop
// Language.AddLanguageFilePath(@"C:\Greenshot\Greenshot\Languages");
// this "type"
Assembly currentAssembly = GetType().Assembly;
- if (typeResService == null) return;
+ if (GetService(typeof(ITypeResolutionService)) is not ITypeResolutionService typeResService) return;
string assemblyPath = typeResService.GetPathOfAssembly(currentAssembly.GetName());
string assemblyDirectory = Path.GetDirectoryName(assemblyPath);
@@ -160,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
}
}
@@ -189,7 +165,7 @@ namespace Greenshot.Base.Controls
if (!DesignMode)
{
#endif
- if (!_applyLanguageManually)
+ if (!ManualLanguageApply)
{
ApplyLanguage();
}
@@ -227,13 +203,10 @@ namespace Greenshot.Base.Controls
///
protected override void OnClosed(EventArgs e)
{
- if (!DesignMode && !_storeFieldsManually)
+ 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);
@@ -246,7 +219,7 @@ namespace Greenshot.Base.Controls
///
public override ISite Site
{
- get { return base.Site; }
+ get => base.Site;
set
{
// Clear any component change event handlers.
@@ -255,7 +228,7 @@ namespace Greenshot.Base.Controls
// Set the new Site value.
base.Site = value;
- m_changeService = (IComponentChangeService) GetService(typeof(IComponentChangeService));
+ m_changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService));
// Register event handlers for component change events.
RegisterChangeNotifications();
@@ -266,7 +239,7 @@ namespace Greenshot.Base.Controls
{
// The m_changeService value is null when not in design mode,
// as the IComponentChangeService is only available at design time.
- m_changeService = (IComponentChangeService) GetService(typeof(IComponentChangeService));
+ m_changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService));
// Clear our the component change events to prepare for re-siting.
if (m_changeService != null)
@@ -293,19 +266,19 @@ namespace Greenshot.Base.Controls
///
private void OnComponentChanged(object sender, ComponentChangedEventArgs ce)
{
- if (((IComponent) ce.Component)?.Site == null || ce.Member == null) return;
+ if (((IComponent)ce.Component)?.Site == null || ce.Member == null) return;
if (!"LanguageKey".Equals(ce.Member.Name)) return;
if (ce.Component is Control control)
{
LOG.InfoFormat("Changing LanguageKey for {0} to {1}", control.Name, ce.NewValue);
- ApplyLanguage(control, (string) ce.NewValue);
+ ApplyLanguage(control, (string)ce.NewValue);
}
else
{
if (ce.Component is ToolStripItem item)
{
LOG.InfoFormat("Changing LanguageKey for {0} to {1}", item.Name, ce.NewValue);
- ApplyLanguage(item, (string) ce.NewValue);
+ ApplyLanguage(item, (string)ce.NewValue);
}
else
{
@@ -556,14 +529,14 @@ namespace Greenshot.Base.Controls
if (controlObject is CheckBox checkBox)
{
- checkBox.Checked = (bool) iniValue.Value;
+ checkBox.Checked = (bool)iniValue.Value;
checkBox.Enabled = !iniValue.IsFixed;
continue;
}
if (controlObject is RadioButton radíoButton)
{
- radíoButton.Checked = (bool) iniValue.Value;
+ radíoButton.Checked = (bool)iniValue.Value;
radíoButton.Enabled = !iniValue.IsFixed;
continue;
}
@@ -572,7 +545,7 @@ namespace Greenshot.Base.Controls
{
if (controlObject is HotkeyControl hotkeyControl)
{
- string hotkeyValue = (string) iniValue.Value;
+ string hotkeyValue = (string)iniValue.Value;
if (!string.IsNullOrEmpty(hotkeyValue))
{
hotkeyControl.SetHotkey(hotkeyValue);
@@ -590,7 +563,7 @@ namespace Greenshot.Base.Controls
if (controlObject is GreenshotComboBox comboxBox)
{
comboxBox.Populate(iniValue.ValueType);
- comboxBox.SetValue((Enum) iniValue.Value);
+ comboxBox.SetValue((Enum)iniValue.Value);
comboxBox.Enabled = !iniValue.IsFixed;
}
}
diff --git a/src/Greenshot.Base/Controls/HotkeyControl.cs b/src/Greenshot.Base/Controls/HotkeyControl.cs
index 678b6522e..21fc25de8 100644
--- a/src/Greenshot.Base/Controls/HotkeyControl.cs
+++ b/src/Greenshot.Base/Controls/HotkeyControl.cs
@@ -40,7 +40,7 @@ namespace Greenshot.Base.Controls
{
private static readonly ILog Log = LogManager.GetLogger(typeof(HotkeyControl));
- private static readonly EventDelay EventDelay = new EventDelay(TimeSpan.FromMilliseconds(600).Ticks);
+ private static readonly EventDelay EventDelay = new(TimeSpan.FromMilliseconds(600).Ticks);
private static readonly bool IsWindows7OrOlder = Environment.OSVersion.Version.Major >= 6 && Environment.OSVersion.Version.Minor >= 1;
// Holds the list of hotkeys
@@ -102,15 +102,15 @@ namespace Greenshot.Base.Controls
private readonly IList _needNonShiftModifier = new List();
private readonly IList _needNonAltGrModifier = new List();
- private readonly ContextMenuStrip _dummy = new ContextMenuStrip();
+ private readonly ContextMenuStrip _dummy = new();
///
/// Used to make sure that there is no right-click menu available
///
public override ContextMenuStrip ContextMenuStrip
{
- get { return _dummy; }
- set { base.ContextMenuStrip = _dummy; }
+ get => _dummy;
+ set => base.ContextMenuStrip = _dummy;
}
///
@@ -118,12 +118,10 @@ namespace Greenshot.Base.Controls
///
public override bool Multiline
{
- get { return base.Multiline; }
- set
- {
+ get => base.Multiline;
+ set =>
// Ignore what the user wants; force Multiline to false
base.Multiline = false;
- }
}
///
@@ -151,43 +149,43 @@ namespace Greenshot.Base.Controls
// Shift + 0 - 9, A - Z
for (Keys k = Keys.D0; k <= Keys.Z; k++)
{
- _needNonShiftModifier.Add((int) k);
+ _needNonShiftModifier.Add((int)k);
}
// Shift + Numpad keys
for (Keys k = Keys.NumPad0; k <= Keys.NumPad9; k++)
{
- _needNonShiftModifier.Add((int) k);
+ _needNonShiftModifier.Add((int)k);
}
// Shift + Misc (,;<./ etc)
for (Keys k = Keys.Oem1; k <= Keys.OemBackslash; k++)
{
- _needNonShiftModifier.Add((int) k);
+ _needNonShiftModifier.Add((int)k);
}
// Shift + Space, PgUp, PgDn, End, Home
for (Keys k = Keys.Space; k <= Keys.Home; k++)
{
- _needNonShiftModifier.Add((int) k);
+ _needNonShiftModifier.Add((int)k);
}
// Misc keys that we can't loop through
- _needNonShiftModifier.Add((int) Keys.Insert);
- _needNonShiftModifier.Add((int) Keys.Help);
- _needNonShiftModifier.Add((int) Keys.Multiply);
- _needNonShiftModifier.Add((int) Keys.Add);
- _needNonShiftModifier.Add((int) Keys.Subtract);
- _needNonShiftModifier.Add((int) Keys.Divide);
- _needNonShiftModifier.Add((int) Keys.Decimal);
- _needNonShiftModifier.Add((int) Keys.Return);
- _needNonShiftModifier.Add((int) Keys.Escape);
- _needNonShiftModifier.Add((int) Keys.NumLock);
+ _needNonShiftModifier.Add((int)Keys.Insert);
+ _needNonShiftModifier.Add((int)Keys.Help);
+ _needNonShiftModifier.Add((int)Keys.Multiply);
+ _needNonShiftModifier.Add((int)Keys.Add);
+ _needNonShiftModifier.Add((int)Keys.Subtract);
+ _needNonShiftModifier.Add((int)Keys.Divide);
+ _needNonShiftModifier.Add((int)Keys.Decimal);
+ _needNonShiftModifier.Add((int)Keys.Return);
+ _needNonShiftModifier.Add((int)Keys.Escape);
+ _needNonShiftModifier.Add((int)Keys.NumLock);
// Ctrl+Alt + 0 - 9
for (Keys k = Keys.D0; k <= Keys.D9; k++)
{
- _needNonAltGrModifier.Add((int) k);
+ _needNonAltGrModifier.Add((int)k);
}
}
@@ -243,10 +241,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
@@ -284,7 +279,7 @@ namespace Greenshot.Base.Controls
///
public Keys Hotkey
{
- get { return _hotkey; }
+ get => _hotkey;
set
{
_hotkey = value;
@@ -307,7 +302,7 @@ namespace Greenshot.Base.Controls
///
public Keys HotkeyModifiers
{
- get { return _modifiers; }
+ get => _modifiers;
set
{
_modifiers = value;
@@ -336,15 +331,15 @@ 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))
+ if ((_modifiers == Keys.Shift || _modifiers == Keys.None) && _needNonShiftModifier.Contains((int)_hotkey))
{
if (_modifiers == Keys.None)
{
// Set Ctrl+Alt as the modifier unless Ctrl+Alt+ won't work...
- if (_needNonAltGrModifier.Contains((int) _hotkey) == false)
+ if (!_needNonAltGrModifier.Contains((int)_hotkey))
{
_modifiers = Keys.Alt | Keys.Control;
}
@@ -365,7 +360,7 @@ namespace Greenshot.Base.Controls
}
// Check all Ctrl+Alt keys
- if ((_modifiers == (Keys.Alt | Keys.Control)) && _needNonAltGrModifier.Contains((int) _hotkey))
+ if ((_modifiers == (Keys.Alt | Keys.Control)) && _needNonAltGrModifier.Contains((int)_hotkey))
{
// Ctrl+Alt+4 etc won't work; reset hotkey and tell the user
_hotkey = Keys.None;
@@ -384,10 +379,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,14 +388,11 @@ 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)
{
- StringBuilder hotkeyString = new StringBuilder();
+ StringBuilder hotkeyString = new();
if ((modifierKeyCode & Keys.Alt) > 0)
{
hotkeyString.Append("Alt").Append(" + ");
@@ -427,15 +416,11 @@ 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)
{
- StringBuilder hotkeyString = new StringBuilder();
+ StringBuilder hotkeyString = new();
if ((modifierKeyCode & Keys.Alt) > 0)
{
hotkeyString.Append(GetKeyName(Keys.Alt)).Append(" + ");
@@ -459,28 +444,27 @@ namespace Greenshot.Base.Controls
return hotkeyString.ToString();
}
-
public static Keys HotkeyModifiersFromString(string modifiersString)
{
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;
}
@@ -499,16 +483,13 @@ namespace Greenshot.Base.Controls
hotkey = hotkey.Remove(0, hotkey.LastIndexOf('+') + 1).Trim();
}
- key = (Keys) Enum.Parse(typeof(Keys), hotkey);
+ key = (Keys)Enum.Parse(typeof(Keys), hotkey);
}
return key;
}
- public static void RegisterHotkeyHwnd(IntPtr hWnd)
- {
- _hotkeyHwnd = hWnd;
- }
+ public static void RegisterHotkeyHwnd(IntPtr hWnd) => _hotkeyHwnd = hWnd;
///
/// Register a hotkey
@@ -529,31 +510,31 @@ namespace Greenshot.Base.Controls
uint modifiers = 0;
if ((modifierKeyCode & Keys.Alt) > 0)
{
- modifiers |= (uint) Modifiers.ALT;
+ modifiers |= (uint)Modifiers.ALT;
}
if ((modifierKeyCode & Keys.Control) > 0)
{
- modifiers |= (uint) Modifiers.CTRL;
+ modifiers |= (uint)Modifiers.CTRL;
}
if ((modifierKeyCode & Keys.Shift) > 0)
{
- modifiers |= (uint) Modifiers.SHIFT;
+ modifiers |= (uint)Modifiers.SHIFT;
}
if (modifierKeyCode == Keys.LWin || modifierKeyCode == Keys.RWin)
{
- modifiers |= (uint) Modifiers.WIN;
+ modifiers |= (uint)Modifiers.WIN;
}
// Disable repeating hotkey for Windows 7 and beyond, as described in #1559
if (IsWindows7OrOlder)
{
- modifiers |= (uint) Modifiers.NO_REPEAT;
+ modifiers |= (uint)Modifiers.NO_REPEAT;
}
- if (RegisterHotKey(_hotkeyHwnd, _hotKeyCounter, modifiers, (uint) virtualKeyCode))
+ if (RegisterHotKey(_hotkeyHwnd, _hotKeyCounter, modifiers, (uint)virtualKeyCode))
{
KeyHandlers.Add(_hotKeyCounter, handler);
return _hotKeyCounter++;
@@ -592,7 +573,7 @@ namespace Greenshot.Base.Controls
return true;
}
- if (KeyHandlers.TryGetValue((int) m.WParam, out var handler))
+ if (KeyHandlers.TryGetValue((int)m.WParam, out var handler))
{
handler();
}
@@ -602,7 +583,7 @@ namespace Greenshot.Base.Controls
public static string GetKeyName(Keys givenKey)
{
- StringBuilder keyName = new StringBuilder();
+ StringBuilder keyName = new();
const uint numpad = 55;
Keys virtualKey = givenKey;
@@ -641,7 +622,7 @@ namespace Greenshot.Base.Controls
return keyString + " /";
}
- uint scanCode = MapVirtualKey((uint) virtualKey, (uint) MapType.MAPVK_VK_TO_VSC);
+ uint scanCode = MapVirtualKey((uint)virtualKey, (uint)MapType.MAPVK_VK_TO_VSC);
// because MapVirtualKey strips the extended bit for some keys
switch (virtualKey)
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 091152d64..f115428df 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;
}
}
@@ -121,13 +118,13 @@ namespace Greenshot.Base.Controls
private void PrepareFilterOptions()
{
// TODO: Change to the FileFormatHandlerRegistry to look for all the supported extensions
- OutputFormat[] supportedImageFormats = (OutputFormat[]) Enum.GetValues(typeof(OutputFormat));
+ OutputFormat[] supportedImageFormats = (OutputFormat[])Enum.GetValues(typeof(OutputFormat));
_filterOptions = new FilterOption[supportedImageFormats.Length];
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
- FilterOption fo = new FilterOption
+ 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(),
Extension = ifo.ToLower()
@@ -141,8 +138,8 @@ namespace Greenshot.Base.Controls
///
public string FileName
{
- get { return SaveFileDialog.FileName; }
- set { SaveFileDialog.FileName = value; }
+ get => SaveFileDialog.FileName;
+ set => SaveFileDialog.FileName = value;
}
///
@@ -150,8 +147,8 @@ namespace Greenshot.Base.Controls
///
public string InitialDirectory
{
- get { return SaveFileDialog.InitialDirectory; }
- set { SaveFileDialog.InitialDirectory = value; }
+ get => SaveFileDialog.InitialDirectory;
+ set => SaveFileDialog.InitialDirectory = value;
}
///
@@ -181,7 +178,7 @@ namespace Greenshot.Base.Controls
///
public string Extension
{
- get { return _filterOptions[SaveFileDialog.FilterIndex - 1].Extension; }
+ get => _filterOptions[SaveFileDialog.FilterIndex - 1].Extension;
set
{
for (int i = 0; i < _filterOptions.Length; i++)
@@ -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
{
@@ -221,7 +216,7 @@ namespace Greenshot.Base.Controls
// fix for bug #3379053
try
{
- if (_eagerlyCreatedDirectory != null && _eagerlyCreatedDirectory.GetFiles().Length == 0 && _eagerlyCreatedDirectory.GetDirectories().Length == 0)
+ if (_eagerlyCreatedDirectory?.GetFiles().Length == 0 && _eagerlyCreatedDirectory.GetDirectories().Length == 0)
{
_eagerlyCreatedDirectory.Delete();
_eagerlyCreatedDirectory = null;
diff --git a/src/Greenshot.Base/Controls/ThumbnailForm.cs b/src/Greenshot.Base/Controls/ThumbnailForm.cs
index d5b8c50e8..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(); };
@@ -103,11 +98,11 @@ namespace Greenshot.Base.Controls
}
int thumbnailHeight = 200;
- int thumbnailWidth = (int) (thumbnailHeight * (sourceSize.Width / (float) sourceSize.Height));
+ int thumbnailWidth = (int)(thumbnailHeight * (sourceSize.Width / (float)sourceSize.Height));
if (parentControl != null && thumbnailWidth > parentControl.Width)
{
thumbnailWidth = parentControl.Width;
- thumbnailHeight = (int) (thumbnailWidth * (sourceSize.Height / (float) sourceSize.Width));
+ thumbnailHeight = (int)(thumbnailWidth * (sourceSize.Height / (float)sourceSize.Width));
}
Width = thumbnailWidth;
@@ -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 c76574bab..ff416bd13 100644
--- a/src/Greenshot.Base/Core/AbstractDestination.cs
+++ b/src/Greenshot.Base/Core/AbstractDestination.cs
@@ -49,12 +49,9 @@ namespace Greenshot.Base.Core
return 1;
}
- if (Priority == other.Priority)
- {
- return string.Compare(Description, other.Description, StringComparison.Ordinal);
- }
-
- return Priority - other.Priority;
+ return Priority == other.Priority
+ ? string.CompareOrdinal(Description, other.Description)
+ : Priority - other.Priority;
}
public abstract string Designation { get; }
@@ -89,18 +86,7 @@ namespace Greenshot.Base.Core
public virtual bool IsLinkable => false;
- public virtual bool IsActive
- {
- get
- {
- if (CoreConfig.ExcludeDestinations != null && CoreConfig.ExcludeDestinations.Contains(Designation))
- {
- return false;
- }
-
- return true;
- }
- }
+ public virtual bool IsActive => (CoreConfig.ExcludeDestinations?.Contains(Designation)) != true;
public abstract ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails);
@@ -111,7 +97,7 @@ namespace Greenshot.Base.Core
///
public void ProcessExport(ExportInformation exportInformation, ISurface surface)
{
- if (exportInformation != null && exportInformation.ExportMade)
+ if (exportInformation?.ExportMade == true)
{
if (!string.IsNullOrEmpty(exportInformation.Uri))
{
@@ -137,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.
@@ -176,7 +159,7 @@ namespace Greenshot.Base.Core
public ExportInformation ShowPickerMenu(bool addDynamics, ISurface surface, ICaptureDetails captureDetails, IEnumerable destinations)
{
// Generate an empty ExportInformation object, for when nothing was selected.
- ExportInformation exportInformation = new ExportInformation(Designation, Language.GetString("settings_destination_picker"));
+ ExportInformation exportInformation = new(Designation, Language.GetString("settings_destination_picker"));
var menu = new ContextMenuStrip
{
ImageScalingSize = CoreConfig.IconSize,
@@ -196,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)
@@ -243,10 +226,10 @@ 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;
+ IDestination clickedDestination = (IDestination)toolStripMenuItem?.Tag;
if (clickedDestination == null)
{
return;
@@ -255,7 +238,7 @@ namespace Greenshot.Base.Core
menu.Tag = clickedDestination.Designation;
// Export
exportInformation = clickedDestination.ExportCapture(true, surface, captureDetails);
- if (exportInformation != null && exportInformation.ExportMade)
+ if (exportInformation?.ExportMade == true)
{
Log.InfoFormat("Export to {0} success, closing menu", exportInformation.DestinationDescription);
// close menu if the destination wasn't the editor
@@ -288,7 +271,7 @@ namespace Greenshot.Base.Core
// Close
menu.Items.Add(new ToolStripSeparator());
- ToolStripMenuItem closeItem = new ToolStripMenuItem(Language.GetString("editor_close"))
+ ToolStripMenuItem closeItem = new(Language.GetString("editor_close"))
{
Image = GreenshotResources.GetImage("Close.Image")
};
@@ -307,7 +290,7 @@ namespace Greenshot.Base.Core
ShowMenuAtCursor(menu);
return exportInformation;
}
-
+
///
/// This method will show the supplied context menu at the mouse cursor, also makes sure it has focus and it's not visible in the taskbar.
///
@@ -319,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);
@@ -374,7 +350,7 @@ namespace Greenshot.Base.Core
{
if (basisMenuItem.DropDownItems.Count == 0)
{
- List subDestinations = new List();
+ List subDestinations = new();
// Fixing Bug #3536968 by catching the COMException (every exception) and not displaying the "subDestinations"
try
{
diff --git a/src/Greenshot.Base/Core/AbstractProcessor.cs b/src/Greenshot.Base/Core/AbstractProcessor.cs
index bbffae8f3..20c4d0670 100644
--- a/src/Greenshot.Base/Core/AbstractProcessor.cs
+++ b/src/Greenshot.Base/Core/AbstractProcessor.cs
@@ -31,17 +31,14 @@ namespace Greenshot.Base.Core
{
public virtual int CompareTo(object obj)
{
- if (!(obj is IProcessor other))
+ if (obj is not IProcessor other)
{
return 1;
}
- if (Priority == other.Priority)
- {
- return string.Compare(Description, other.Description, StringComparison.Ordinal);
- }
-
- return Priority - other.Priority;
+ return Priority == other.Priority
+ ? string.CompareOrdinal(Description, other.Description)
+ : Priority - other.Priority;
}
public abstract string Designation { get; }
diff --git a/src/Greenshot.Base/Core/AccessibleHelper.cs b/src/Greenshot.Base/Core/AccessibleHelper.cs
index 08c40956e..9eb0dcedf 100644
--- a/src/Greenshot.Base/Core/AccessibleHelper.cs
+++ b/src/Greenshot.Base/Core/AccessibleHelper.cs
@@ -23,6 +23,7 @@ using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Accessibility;
+using System.Linq;
namespace Greenshot.Base.Core
{
@@ -37,8 +38,8 @@ namespace Greenshot.Base.Core
{
var guid = new Guid("{618736e0-3c3d-11cf-810c-00aa00389b71}"); // IAccessible
object obj = null;
- int num = AccessibleObjectFromWindow(hWnd, (uint) idObject, ref guid, ref obj);
- acc = (IAccessible) obj;
+ int num = AccessibleObjectFromWindow(hWnd, (uint)idObject, ref guid, ref obj);
+ acc = (IAccessible)obj;
return num;
}
@@ -67,13 +68,13 @@ namespace Greenshot.Base.Core
{
get
{
- object[] res = GetAccessibleChildren(accessible, out var num);
+ object[] res = GetAccessibleChildren(accessible, out _);
if (res == null)
{
return new Accessible[0];
}
- List list = new List(res.Length);
+ List list = new(res.Length);
foreach (object obj in res)
{
if (obj is IAccessible acc)
@@ -86,15 +87,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)
{
@@ -143,7 +138,7 @@ namespace Greenshot.Base.Core
{
object tabIndex = tab.accessible.get_accState(0);
- if ((int) tabIndex == IE_ACTIVE_TAB)
+ if ((int)tabIndex == IE_ACTIVE_TAB)
{
return tab.Name;
}
@@ -182,42 +177,31 @@ namespace Greenshot.Base.Core
}
}
-
public IEnumerable IETabUrls
{
get
{
- foreach (Accessible accessor in Children)
+ foreach (var tab in from Accessible accessor in Children
+ from tab in
+ from child in accessor.Children
+ from tab in child.Children
+ select tab
+ select tab)
{
- foreach (var child in accessor.Children)
+ _ = tab.accessible.get_accState(CHILDID_SELF);
+ var description = tab.accessible.get_accDescription(CHILDID_SELF);
+ if (!string.IsNullOrEmpty(description) && description.Contains(Environment.NewLine))
{
- foreach (var tab in child.Children)
- {
- object tabIndex = tab.accessible.get_accState(CHILDID_SELF);
- var description = tab.accessible.get_accDescription(CHILDID_SELF);
- if (!string.IsNullOrEmpty(description))
- {
- 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;
}
}
}
}
- 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 fd693683f..b61f8e30a 100644
--- a/src/Greenshot.Base/Core/AnimationHelpers.cs
+++ b/src/Greenshot.Base/Core/AnimationHelpers.cs
@@ -67,7 +67,7 @@ namespace Greenshot.Base.Core
/// Type for the animation, like Point/Rectangle/Size
public abstract class AnimatorBase : IAnimator
{
- private readonly Queue> _queue = new Queue>();
+ private readonly Queue> _queue = new();
///
/// Constructor
@@ -77,7 +77,7 @@ namespace Greenshot.Base.Core
///
///
///
- public AnimatorBase(T first, T last, int frames, EasingType easingType, EasingMode easingMode)
+ protected AnimatorBase(T first, T last, int frames, EasingType easingType, EasingMode easingMode)
{
First = first;
Last = last;
@@ -110,27 +110,13 @@ namespace Greenshot.Base.Core
///
/// Final animation value, this is including the legs
///
- public T Final
- {
- get
- {
- if (_queue.Count == 0)
- {
- return Last;
- }
-
- return _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
@@ -151,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
@@ -172,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
@@ -186,7 +163,7 @@ namespace Greenshot.Base.Core
///
public void QueueDestinationLeg(T queuedDestination, int frames, EasingType easingType, EasingMode easingMode)
{
- AnimationLeg leg = new AnimationLeg
+ AnimationLeg leg = new()
{
Destination = queuedDestination,
Frames = frames,
@@ -209,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
@@ -239,7 +212,7 @@ namespace Greenshot.Base.Core
return true;
}
- if (_queue.Count <= 0)
+ if (_queue.Count == 0)
{
return false;
}
@@ -251,25 +224,13 @@ namespace Greenshot.Base.Core
EasingType = nextLeg.EasingType;
EasingMode = nextLeg.EasingMode;
return true;
-
}
}
///
/// Are there more frames to animate?
///
- public virtual bool HasNext
- {
- get
- {
- if (CurrentFrameNr < Frames)
- {
- return true;
- }
-
- return _queue.Count > 0;
- }
- }
+ public virtual bool HasNext => CurrentFrameNr < Frames || _queue.Count > 0;
///
/// Get the next animation frame value object
@@ -312,12 +273,12 @@ namespace Greenshot.Base.Core
double dx = Last.X - First.X;
double dy = Last.Y - First.Y;
- int x = First.X + (int) (easingValue * dx);
- int y = First.Y + (int) (easingValue * dy);
+ int x = First.X + (int)(easingValue * dx);
+ int y = First.Y + (int)(easingValue * dy);
double dw = Last.Width - First.Width;
double dh = Last.Height - First.Height;
- int width = First.Width + (int) (easingValue * dw);
- int height = First.Height + (int) (easingValue * dh);
+ int width = First.Width + (int)(easingValue * dw);
+ int height = First.Height + (int)(easingValue * dh);
Current = new NativeRect(x, y, width, height);
return Current;
@@ -356,8 +317,8 @@ namespace Greenshot.Base.Core
double dx = Last.X - First.X;
double dy = Last.Y - First.Y;
- int x = First.X + (int) (easingValue * dx);
- int y = First.Y + (int) (easingValue * dy);
+ int x = First.X + (int)(easingValue * dx);
+ int y = First.Y + (int)(easingValue * dy);
Current = new NativePoint(x, y);
}
@@ -396,8 +357,8 @@ namespace Greenshot.Base.Core
double easingValue = EasingValue;
double dw = Last.Width - First.Width;
double dh = Last.Height - First.Height;
- int width = First.Width + (int) (easingValue * dw);
- int height = First.Height + (int) (easingValue * dh);
+ int width = First.Width + (int)(easingValue * dw);
+ int height = First.Height + (int)(easingValue * dh);
Current = new NativeSize(width, height);
}
@@ -438,10 +399,10 @@ namespace Greenshot.Base.Core
double dr = Last.R - First.R;
double dg = Last.G - First.G;
double db = Last.B - First.B;
- int a = First.A + (int) (easingValue * da);
- int r = First.R + (int) (easingValue * dr);
- int g = First.G + (int) (easingValue * dg);
- int b = First.B + (int) (easingValue * db);
+ int a = First.A + (int)(easingValue * da);
+ int r = First.R + (int)(easingValue * dr);
+ int g = First.G + (int)(easingValue * dg);
+ int b = First.B + (int)(easingValue * db);
Current = Color.FromArgb(a, r, g, b);
}
@@ -479,7 +440,7 @@ namespace Greenshot.Base.Core
{
double easingValue = EasingValue;
double delta = Last - First;
- Current = First + (int) (easingValue * delta);
+ Current = First + (int)(easingValue * delta);
}
return Current;
@@ -497,13 +458,13 @@ namespace Greenshot.Base.Core
{
double easedStep = acceleration > 0 ? EaseIn(linearStep, type) : acceleration < 0 ? EaseOut(linearStep, type) : linearStep;
// Lerp:
- return ((easedStep - linearStep) * Math.Abs(acceleration) + linearStep);
+ return ((easedStep - linearStep) * Math.Abs(acceleration)) + linearStep;
}
public static double EaseIn(double linearStep, EasingType type) =>
type switch
{
- EasingType.Step => (linearStep < 0.5 ? 0 : 1),
+ EasingType.Step => linearStep < 0.5 ? 0 : 1,
EasingType.Linear => linearStep,
EasingType.Sine => Sine.EaseIn(linearStep),
EasingType.Quadratic => Power.EaseIn(linearStep, 2),
@@ -516,7 +477,7 @@ namespace Greenshot.Base.Core
public static double EaseOut(double linearStep, EasingType type) =>
type switch
{
- EasingType.Step => (linearStep < 0.5 ? 0 : 1),
+ EasingType.Step => linearStep < 0.5 ? 0 : 1,
EasingType.Linear => linearStep,
EasingType.Sine => Sine.EaseOut(linearStep),
EasingType.Quadratic => Power.EaseOut(linearStep, 2),
@@ -526,15 +487,12 @@ 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
{
- EasingType.Step => (linearStep < 0.5 ? 0 : 1),
+ EasingType.Step => linearStep < 0.5 ? 0 : 1,
EasingType.Linear => linearStep,
EasingType.Sine => Sine.EaseInOut(linearStep),
EasingType.Quadratic => Power.EaseInOut(linearStep, 2),
@@ -546,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)
{
@@ -584,7 +530,7 @@ namespace Greenshot.Base.Core
}
var sign = power % 2 == 0 ? -1 : 1;
- return (sign / 2.0 * (Math.Pow(s - 2, power) + sign * 2));
+ return sign / 2.0 * (Math.Pow(s - 2, power) + (sign * 2));
}
}
}
diff --git a/src/Greenshot.Base/Core/BinaryStructHelper.cs b/src/Greenshot.Base/Core/BinaryStructHelper.cs
index 68ef884dd..2f9825a40 100644
--- a/src/Greenshot.Base/Core/BinaryStructHelper.cs
+++ b/src/Greenshot.Base/Core/BinaryStructHelper.cs
@@ -63,7 +63,7 @@ namespace Greenshot.Base.Core
public static T FromIntPtr(IntPtr intPtr) where T : struct
{
object obj = Marshal.PtrToStructure(intPtr, typeof(T));
- return (T) obj;
+ return (T)obj;
}
///
diff --git a/src/Greenshot.Base/Core/Cache.cs b/src/Greenshot.Base/Core/Cache.cs
index 384f5f15c..8b7e33f5f 100644
--- a/src/Greenshot.Base/Core/Cache.cs
+++ b/src/Greenshot.Base/Core/Cache.cs
@@ -27,7 +27,7 @@ using log4net;
namespace Greenshot.Base.Core
{
///
- /// Cache class
+ /// Cache class
///
/// Type of key
/// Type of value
@@ -35,7 +35,7 @@ namespace Greenshot.Base.Core
{
private static readonly ILog Log = LogManager.GetLogger(typeof(Cache));
private readonly IDictionary _internalCache = new Dictionary();
- private readonly object _lockObject = new object();
+ private readonly object _lockObject = new();
private readonly int _secondsToExpire = 10;
private readonly CacheObjectExpired _expiredCallback;
@@ -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
@@ -83,14 +74,11 @@ namespace Greenshot.Base.Core
{
get
{
- List elements = new List();
+ List elements = new();
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 0be688727..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;
@@ -113,7 +110,7 @@ namespace Greenshot.Base.Core
set
{
_cursor?.Dispose();
- _cursor = (Icon) value.Clone();
+ _cursor = (Icon)value.Clone();
}
}
@@ -127,27 +124,15 @@ namespace Greenshot.Base.Core
///
public bool CursorVisible { get; set; }
- private NativePoint _cursorLocation = NativePoint.Empty;
-
///
/// Get/Set the CursorLocation
///
- public NativePoint CursorLocation
- {
- get => _cursorLocation;
- set => _cursorLocation = value;
- }
-
- private NativePoint _location = NativePoint.Empty;
+ public NativePoint CursorLocation { get; set; } = NativePoint.Empty;
///
/// Get/set the Location
///
- public NativePoint Location
- {
- get => _location;
- set => _location = value;
- }
+ public NativePoint Location { get; set; } = NativePoint.Empty;
private CaptureDetails _captureDetails;
@@ -157,7 +142,7 @@ namespace Greenshot.Base.Core
public ICaptureDetails CaptureDetails
{
get => _captureDetails;
- set => _captureDetails = (CaptureDetails) value;
+ set => _captureDetails = (CaptureDetails)value;
}
///
@@ -174,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
@@ -226,7 +208,7 @@ namespace Greenshot.Base.Core
return false;
}
- _location = cropRectangle.Location;
+ Location = cropRectangle.Location;
// Change mouse location according to the cropRectangle (including screenbounds) offset
MoveMouseLocation(-cropRectangle.Location.X, -cropRectangle.Location.Y);
// Move all the elements
@@ -246,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 ac6f8d364..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,17 +55,7 @@ namespace Greenshot.Base.Core
public Dictionary MetaData { get; } = new Dictionary();
///
- public void AddMetaData(string key, string value)
- {
- if (MetaData.ContainsKey(key))
- {
- MetaData[key] = value;
- }
- else
- {
- MetaData.Add(key, value);
- }
- }
+ public void AddMetaData(string key, string value) => MetaData[key] = value;
///
public CaptureMode CaptureMode { get; set; }
@@ -73,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)
@@ -99,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 ed9f2c3e9..de2b8293e 100644
--- a/src/Greenshot.Base/Core/ClipboardHelper.cs
+++ b/src/Greenshot.Base/Core/ClipboardHelper.cs
@@ -52,7 +52,7 @@ namespace Greenshot.Base.Core
public static class ClipboardHelper
{
private static readonly ILog Log = LogManager.GetLogger(typeof(ClipboardHelper));
- private static readonly object ClipboardLockObject = new object();
+ private static readonly object ClipboardLockObject = new();
private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection();
private static readonly string FORMAT_FILECONTENTS = "FileContents";
private static readonly string FORMAT_HTML = "text/html";
@@ -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;
@@ -384,7 +371,7 @@ EndSelection:<<<<<<<4
///
/// IDataObject
/// IEnumerable{(MemoryStream,string)}
- private static IEnumerable<(MemoryStream stream,string filename)> IterateClipboardContent(IDataObject dataObject)
+ private static IEnumerable<(MemoryStream stream, string filename)> IterateClipboardContent(IDataObject dataObject)
{
var fileDescriptors = AvailableFileDescriptors(dataObject);
if (fileDescriptors == null) yield break;
@@ -402,7 +389,7 @@ EndSelection:<<<<<<<4
/// IEnumerable{FileDescriptor}
private static IEnumerable AvailableFileDescriptors(IDataObject dataObject)
{
- var fileDescriptor = (MemoryStream) dataObject.GetData("FileGroupDescriptorW");
+ var fileDescriptor = (MemoryStream)dataObject.GetData("FileGroupDescriptorW");
if (fileDescriptor != null)
{
try
@@ -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
@@ -544,7 +528,6 @@ EndSelection:<<<<<<<4
{
continue;
}
-
}
catch (Exception ex)
{
@@ -569,7 +552,7 @@ EndSelection:<<<<<<<4
}
Bitmap bitmap = null;
- using FileStream fileStream = new FileStream(imageFile, FileMode.Open, FileAccess.Read, FileShare.Read);
+ using FileStream fileStream = new(imageFile, FileMode.Open, FileAccess.Read, FileShare.Read);
try
{
if (!fileFormatHandlers.TryLoadFromStream(fileStream, extension, out bitmap))
@@ -643,7 +626,7 @@ EndSelection:<<<<<<<4
{
continue;
}
- using FileStream fileStream = new FileStream(imageFile, FileMode.Open, FileAccess.Read, FileShare.Read);
+ using FileStream fileStream = new(imageFile, FileMode.Open, FileAccess.Read, FileShare.Read);
IEnumerable drawableContainers;
try
{
@@ -677,7 +660,7 @@ EndSelection:<<<<<<<4
// Found a weird bug, where PNG's from Outlook 2010 are clipped
// So I build some special logic to get the best format:
- if (formats != null && formats.Contains(FORMAT_PNG_OFFICEART) && formats.Contains(DataFormats.Dib))
+ if (formats?.Contains(FORMAT_PNG_OFFICEART) == true && formats.Contains(DataFormats.Dib))
{
// Outlook ??
Log.Info("Most likely the current clipboard contents come from Outlook, as this has a problem with PNG and others we place the DIB format to the front...");
@@ -698,7 +681,7 @@ EndSelection:<<<<<<<4
foreach (string currentFormat in retrieveFormats)
{
- if (formats != null && formats.Contains(currentFormat))
+ if (formats?.Contains(currentFormat) == true)
{
Log.InfoFormat("Found {0}, trying to retrieve.", currentFormat);
returnImage = GetImageForFormat(currentFormat, dataObject);
@@ -732,7 +715,7 @@ EndSelection:<<<<<<<4
// Found a weird bug, where PNG's from Outlook 2010 are clipped
// So I build some special logic to get the best format:
- if (formats != null && formats.Contains(FORMAT_PNG_OFFICEART) && formats.Contains(DataFormats.Dib))
+ if (formats?.Contains(FORMAT_PNG_OFFICEART) == true && formats.Contains(DataFormats.Dib))
{
// Outlook ??
Log.Info("Most likely the current clipboard contents come from Outlook, as this has a problem with PNG and others we place the DIB format to the front...");
@@ -753,7 +736,7 @@ EndSelection:<<<<<<<4
foreach (string currentFormat in retrieveFormats)
{
- if (formats != null && formats.Contains(currentFormat))
+ if (formats?.Contains(currentFormat) == true)
{
Log.InfoFormat("Found {0}, trying to retrieve.", currentFormat);
returnImage = GetDrawableForFormat(currentFormat, dataObject);
@@ -782,8 +765,7 @@ EndSelection:<<<<<<<4
/// Bitmap or null
private static Bitmap GetImageForFormat(string format, IDataObject dataObject)
{
- Bitmap bitmap = null;
-
+ Bitmap bitmap;
if (format == FORMAT_HTML)
{
var textObject = ContentAsString(dataObject, FORMAT_HTML, Encoding.UTF8);
@@ -818,11 +800,7 @@ EndSelection:<<<<<<<4
var fileFormatHandlers = SimpleServiceProvider.Current.GetAllInstances();
// From here, imageStream is a valid stream
- if (fileFormatHandlers.TryLoadFromStream(imageStream, format, out bitmap))
- {
- return bitmap;
- }
- return null;
+ return fileFormatHandlers.TryLoadFromStream(imageStream, format, out bitmap) ? bitmap : null;
}
///
@@ -835,8 +813,6 @@ EndSelection:<<<<<<<4
/// IDrawableContainer or null
private static IDrawableContainer GetDrawableForFormat(string format, IDataObject dataObject)
{
- IDrawableContainer drawableContainer = null;
-
if (format == FORMAT_HTML)
{
var textObject = ContentAsString(dataObject, FORMAT_HTML, Encoding.UTF8);
@@ -852,7 +828,7 @@ EndSelection:<<<<<<<4
var srcAttribute = imgNode.Attributes["src"];
var imageUrl = srcAttribute.Value;
Log.Debug(imageUrl);
- drawableContainer = NetworkHelper.DownloadImageAsDrawableContainer(imageUrl);
+ IDrawableContainer drawableContainer = NetworkHelper.DownloadImageAsDrawableContainer(imageUrl);
if (drawableContainer != null)
{
return drawableContainer;
@@ -893,15 +869,7 @@ EndSelection:<<<<<<<4
/// Get Text from the DataObject
///
/// string if there is text on the clipboard
- public static string GetText(IDataObject dataObject)
- {
- if (ContainsText(dataObject))
- {
- return (string) dataObject.GetData(DataFormats.Text);
- }
-
- return null;
- }
+ public static string GetText(IDataObject dataObject) => ContainsText(dataObject) ? (string)dataObject.GetData(DataFormats.Text) : null;
///
/// Set text to the clipboard
@@ -920,12 +888,12 @@ EndSelection:<<<<<<<4
utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${width}", surface.Image.Width.ToString());
utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${height}", surface.Image.Height.ToString());
utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${file}", filename.Replace("\\", "/"));
- StringBuilder sb = new StringBuilder();
+ StringBuilder sb = new();
sb.Append(utf8EncodedHtmlString);
sb.Replace("<<<<<<<1", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal) + "".Length).ToString("D8"));
- sb.Replace("<<<<<<<2", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal)).ToString("D8"));
+ sb.Replace("<<<<<<<2", utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal).ToString("D8"));
sb.Replace("<<<<<<<3", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal) + "".Length).ToString("D8"));
- sb.Replace("<<<<<<<4", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal)).ToString("D8"));
+ sb.Replace("<<<<<<<4", utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal).ToString("D8"));
return sb.ToString();
}
@@ -935,13 +903,13 @@ EndSelection:<<<<<<<4
utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${width}", surface.Image.Width.ToString());
utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${height}", surface.Image.Height.ToString());
utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${format}", "png");
- utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${data}", Convert.ToBase64String(pngStream.GetBuffer(), 0, (int) pngStream.Length));
- StringBuilder sb = new StringBuilder();
+ utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${data}", Convert.ToBase64String(pngStream.GetBuffer(), 0, (int)pngStream.Length));
+ StringBuilder sb = new();
sb.Append(utf8EncodedHtmlString);
sb.Replace("<<<<<<<1", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal) + "".Length).ToString("D8"));
- sb.Replace("<<<<<<<2", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal)).ToString("D8"));
+ sb.Replace("<<<<<<<2", utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal).ToString("D8"));
sb.Replace("<<<<<<<3", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal) + "".Length).ToString("D8"));
- sb.Replace("<<<<<<<4", (utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal)).ToString("D8"));
+ sb.Replace("<<<<<<<4", utf8EncodedHtmlString.IndexOf("", StringComparison.Ordinal).ToString("D8"));
return sb.ToString();
}
@@ -956,7 +924,7 @@ EndSelection:<<<<<<<4
///
public static void SetClipboardData(ISurface surface)
{
- DataObject dataObject = new DataObject();
+ DataObject dataObject = new();
// This will work for Office and most other applications
//ido.SetData(DataFormats.Bitmap, true, image);
@@ -968,7 +936,7 @@ EndSelection:<<<<<<<4
bool disposeImage = false;
try
{
- SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(OutputFormat.png, 100, false);
+ SurfaceOutputSettings outputSettings = new(OutputFormat.png, 100, false);
// Create the image which is going to be saved so we don't create it multiple times
disposeImage = ImageIO.CreateImageFromSurface(surface, outputSettings, out imageToSave);
try
@@ -978,7 +946,7 @@ EndSelection:<<<<<<<4
{
pngStream = new MemoryStream();
// PNG works for e.g. Powerpoint
- SurfaceOutputSettings pngOutputSettings = new SurfaceOutputSettings(OutputFormat.png, 100, false);
+ SurfaceOutputSettings pngOutputSettings = new(OutputFormat.png, 100, false);
ImageIO.SaveToStream(imageToSave, null, pngStream, pngOutputSettings);
pngStream.Seek(0, SeekOrigin.Begin);
// Set the PNG stream
@@ -1034,7 +1002,7 @@ EndSelection:<<<<<<<4
// As we have specified BI_COMPRESSION.BI_BITFIELDS, the BitfieldColorMask needs to be added
// This also makes sure the default values are set
- BitfieldColorMask colorMask = new BitfieldColorMask();
+ BitfieldColorMask colorMask = new();
// Create the byte[] from the struct
byte[] colorMaskBytes = BinaryStructHelper.ToByteArray(colorMask);
Array.Reverse(colorMaskBytes);
@@ -1042,7 +1010,7 @@ EndSelection:<<<<<<<4
dibV5Stream.Write(colorMaskBytes, 0, colorMaskBytes.Length);
// Create the raw bytes for the pixels only
- byte[] bitmapBytes = BitmapToByteArray((Bitmap) imageToSave);
+ byte[] bitmapBytes = BitmapToByteArray((Bitmap)imageToSave);
// Write to the stream
dibV5Stream.Write(bitmapBytes, 0, bitmapBytes.Length);
@@ -1065,9 +1033,9 @@ EndSelection:<<<<<<<4
else if (CoreConfig.ClipboardFormats.Contains(ClipboardFormat.HTMLDATAURL))
{
string html;
- using (MemoryStream tmpPngStream = new MemoryStream())
+ using (MemoryStream tmpPngStream = new())
{
- SurfaceOutputSettings pngOutputSettings = new SurfaceOutputSettings(OutputFormat.png, 100, false)
+ SurfaceOutputSettings pngOutputSettings = new(OutputFormat.png, 100, false)
{
// Do not allow to reduce the colors, some applications dislike 256 color images
// reported with bug #3594681
@@ -1136,7 +1104,7 @@ EndSelection:<<<<<<<4
for (int i = 0; i < bitmap.Height; i++)
{
- IntPtr pointer = new IntPtr(ptr + (bmpData.Stride * i));
+ IntPtr pointer = new(ptr + (bmpData.Stride * i));
Marshal.Copy(pointer, rgbValues, absStride * (bitmap.Height - i - 1), absStride);
}
@@ -1190,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
@@ -1223,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;
@@ -1241,15 +1202,7 @@ EndSelection:<<<<<<<4
/// IDataObject
/// Type to get
/// object from IDataObject
- public static object GetFromDataObject(IDataObject dataObj, Type type)
- {
- if (type != null)
- {
- return GetFromDataObject(dataObj, type.FullName);
- }
-
- return null;
- }
+ public static object GetFromDataObject(IDataObject dataObj, Type type) => type != null ? GetFromDataObject(dataObj, type.FullName) : null;
///
/// Get ImageFilenames from the IDataObject
@@ -1267,7 +1220,6 @@ EndSelection:<<<<<<<4
.Where(filename => !string.IsNullOrEmpty(filename))
.Where(Path.HasExtension)
.Where(filename => supportedExtensions.Contains(Path.GetExtension(filename)));
-
}
///
diff --git a/src/Greenshot.Base/Core/CoreConfiguration.cs b/src/Greenshot.Base/Core/CoreConfiguration.cs
index 3e085bc9b..be9dc5c45 100644
--- a/src/Greenshot.Base/Core/CoreConfiguration.cs
+++ b/src/Greenshot.Base/Core/CoreConfiguration.cs
@@ -334,7 +334,7 @@ namespace Greenshot.Base.Core
DefaultValue = "16,16")]
public NativeSize IconSize
{
- get { return _iconSize; }
+ get => _iconSize;
set
{
Size newSize = value;
@@ -349,7 +349,7 @@ namespace Greenshot.Base.Core
newSize.Width = 256;
}
- newSize.Width = (newSize.Width / 16) * 16;
+ newSize.Width = newSize.Width / 16 * 16;
if (newSize.Height < 16)
{
newSize.Height = 16;
@@ -359,17 +359,17 @@ namespace Greenshot.Base.Core
newSize.Height = 256;
}
- newSize.Height = (newSize.Height / 16) * 16;
+ newSize.Height = newSize.Height / 16 * 16;
}
if (_iconSize != newSize)
{
_iconSize = value;
- PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IconSize"));
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IconSize)));
}
}
}
-
+
[IniProperty("WebRequestTimeout", Description = "The connect timeout value for web requests, these are seconds", DefaultValue = "100")]
public int WebRequestTimeout { get; set; }
@@ -383,10 +383,7 @@ namespace Greenshot.Base.Core
///
///
///
- public bool IsExperimentalFeatureEnabled(string experimentalFeature)
- {
- return ExperimentalFeatures != null && ExperimentalFeatures.Contains(experimentalFeature);
- }
+ public bool IsExperimentalFeatureEnabled(string experimentalFeature) => ExperimentalFeatures?.Contains(experimentalFeature) == true;
private string CreateOutputFilePath()
{
@@ -414,7 +411,7 @@ namespace Greenshot.Base.Core
return Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
}
-
+
///
/// Supply values we can't put as defaults
///
@@ -445,7 +442,7 @@ namespace Greenshot.Base.Core
},
_ => null
};
-
+
///
/// This method will be called before converting the property, making to possible to correct a certain value
/// Can be used when migration is needed
@@ -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 != null && ExcludeDestinations.Contains("OneNote"))
+ if (ExcludeDestinations?.Contains("OneNote") == true && LastSaveWithVersion?.StartsWith("1.1") == true)
{
- if (LastSaveWithVersion != null && LastSaveWithVersion.StartsWith("1.1"))
- {
- 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 24063b7a8..20c9e3cd2 100644
--- a/src/Greenshot.Base/Core/CredentialsHelper.cs
+++ b/src/Greenshot.Base/Core/CredentialsHelper.cs
@@ -132,7 +132,7 @@ namespace Greenshot.Base.Core
/// Gets or sets the name for the credentials.
public string Name
{
- get { return _name; }
+ get => _name;
set
{
if (value?.Length > CredUi.MAX_USERNAME_LENGTH)
@@ -153,7 +153,7 @@ namespace Greenshot.Base.Core
/// Gets or sets the password for the credentials.
public string Password
{
- get { return _password; }
+ get => _password;
set
{
if (value?.Length > CredUi.MAX_PASSWORD_LENGTH)
@@ -181,7 +181,7 @@ namespace Greenshot.Base.Core
/// Gets or sets the name of the target for the credentials, typically a server name.
public string Target
{
- get { return _target; }
+ get => _target;
set
{
if (value == null)
@@ -208,7 +208,7 @@ namespace Greenshot.Base.Core
/// A null value will cause a system default caption to be used.
public string Caption
{
- get { return _caption; }
+ get => _caption;
set
{
if (value?.Length > CredUi.MAX_CAPTION_LENGTH)
@@ -230,7 +230,7 @@ namespace Greenshot.Base.Core
/// A null value will cause a system default message to be used.
public string Message
{
- get { return _message; }
+ get => _message;
set
{
if (value?.Length > CredUi.MAX_MESSAGE_LENGTH)
@@ -252,7 +252,7 @@ namespace Greenshot.Base.Core
/// A null value will cause a system default image to be used.
public Image Banner
{
- get { return _banner; }
+ get => _banner;
set
{
if (value != null)
@@ -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.
@@ -325,10 +322,10 @@ namespace Greenshot.Base.Core
private DialogResult ShowDialog(IWin32Window owner)
{
// set the api call parameters
- StringBuilder name = new StringBuilder(CredUi.MAX_USERNAME_LENGTH);
+ StringBuilder name = new(CredUi.MAX_USERNAME_LENGTH);
name.Append(Name);
- StringBuilder password = new StringBuilder(CredUi.MAX_PASSWORD_LENGTH);
+ StringBuilder password = new(CredUi.MAX_PASSWORD_LENGTH);
password.Append(Password);
int saveChecked = Convert.ToInt32(SaveChecked);
@@ -365,7 +362,7 @@ namespace Greenshot.Base.Core
/// The System.Windows.Forms.IWin32Window the dialog will display in front of.
private CredUi.INFO GetInfo(IWin32Window owner)
{
- CredUi.INFO info = new CredUi.INFO();
+ CredUi.INFO info = new();
if (owner != null) info.hWndParent = owner.Handle;
info.pszCaptionText = Caption;
info.pszMessageText = Message;
diff --git a/src/Greenshot.Base/Core/DestinationHelper.cs b/src/Greenshot.Base/Core/DestinationHelper.cs
index 641b29bbc..7f2fa803e 100644
--- a/src/Greenshot.Base/Core/DestinationHelper.cs
+++ b/src/Greenshot.Base/Core/DestinationHelper.cs
@@ -37,13 +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 == null ||
- !CoreConfig.ExcludeDestinations.Contains(destination.Designation)).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
@@ -57,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;
@@ -75,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
@@ -90,12 +81,7 @@ namespace Greenshot.Base.Core
public static ExportInformation ExportCapture(bool manuallyInitiated, string designation, ISurface surface, ICaptureDetails captureDetails)
{
IDestination destination = GetDestination(designation);
- if (destination != null && destination.IsActive)
- {
- return destination.ExportCapture(manuallyInitiated, surface, captureDetails);
- }
-
- return null;
+ return destination?.IsActive == true ? destination.ExportCapture(manuallyInitiated, surface, captureDetails) : null;
}
}
}
\ No newline at end of file
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 e5742b803..de3124356 100644
--- a/src/Greenshot.Base/Core/EffectConverter.cs
+++ b/src/Greenshot.Base/Core/EffectConverter.cs
@@ -12,7 +12,7 @@ namespace Greenshot.Base.Core
public class EffectConverter : TypeConverter
{
// Fix to prevent BUG-1753
- private readonly NumberFormatInfo _numberFormatInfo = new NumberFormatInfo();
+ private readonly NumberFormatInfo _numberFormatInfo = new();
public EffectConverter()
{
@@ -20,15 +20,7 @@ namespace Greenshot.Base.Core
_numberFormatInfo.NumberGroupSeparator = ",";
}
- public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
- {
- if (sourceType == typeof(string))
- {
- return true;
- }
-
- return 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)
{
@@ -42,12 +34,7 @@ namespace Greenshot.Base.Core
return true;
}
- if (destinationType == typeof(TornEdgeEffect))
- {
- return true;
- }
-
- return base.CanConvertTo(context, destinationType);
+ return destinationType == typeof(TornEdgeEffect) || base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
@@ -55,7 +42,7 @@ namespace Greenshot.Base.Core
// to string
if (destinationType == typeof(string))
{
- StringBuilder sb = new StringBuilder();
+ StringBuilder sb = new();
if (value.GetType() == typeof(DropShadowEffect))
{
DropShadowEffect effect = value as DropShadowEffect;
@@ -63,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);
@@ -79,14 +66,14 @@ namespace Greenshot.Base.Core
string settings = value as string;
if (destinationType == typeof(DropShadowEffect))
{
- DropShadowEffect effect = new DropShadowEffect();
+ DropShadowEffect effect = new();
ApplyDropShadowEffectValues(settings, effect);
return effect;
}
if (destinationType == typeof(TornEdgeEffect))
{
- TornEdgeEffect effect = new TornEdgeEffect();
+ TornEdgeEffect effect = new();
ApplyDropShadowEffectValues(settings, effect);
ApplyTornEdgeEffectValues(settings, effect);
return effect;
@@ -100,12 +87,9 @@ namespace Greenshot.Base.Core
{
if (value is string settings)
{
- if (settings.Contains("ToothHeight"))
- {
- return ConvertTo(context, culture, settings, typeof(TornEdgeEffect));
- }
-
- return ConvertTo(context, culture, settings, typeof(DropShadowEffect));
+ return settings.Contains("ToothHeight")
+ ? ConvertTo(context, culture, settings, typeof(TornEdgeEffect))
+ : ConvertTo(context, culture, settings, typeof(DropShadowEffect));
}
return base.ConvertFrom(context, culture, value);
@@ -121,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;
@@ -138,7 +119,7 @@ namespace Greenshot.Base.Core
break;
case "ShadowOffset":
- NativePoint shadowOffset = new NativePoint();
+ NativePoint shadowOffset = new();
string[] coordinates = pair[1].Split(',');
if (int.TryParse(coordinates[0], out var shadowOffsetX))
{
@@ -219,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 30811fb69..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)
{
@@ -99,13 +97,13 @@ namespace Greenshot.Base.Core
public static string EnvironmentToString(bool newline)
{
StringBuilder environment = new();
- environment.Append("Software version: " + GetGreenshotVersion());
+ environment.Append("Software version: ").Append(GetGreenshotVersion());
if (IniConfig.IsPortable)
{
environment.Append(" Portable");
}
- environment.Append(" (" + OsInfo.Bits + " bit)");
+ environment.Append(" (").Append(OsInfo.Bits).Append(" bit)");
if (newline)
{
@@ -116,7 +114,7 @@ namespace Greenshot.Base.Core
environment.Append(", ");
}
- environment.Append(".NET runtime version: " + Environment.Version);
+ environment.Append(".NET runtime version: ").Append(Environment.Version);
if (IsNet45OrNewer())
{
environment.Append("+");
@@ -131,7 +129,7 @@ namespace Greenshot.Base.Core
environment.Append(", ");
}
- environment.Append("Time: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss zzz"));
+ environment.Append("Time: ").Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss zzz"));
if (IsWindows)
{
@@ -144,19 +142,19 @@ namespace Greenshot.Base.Core
environment.Append(", ");
}
- environment.Append($"OS: {OsInfo.Name}");
+ environment.Append("OS: ").Append(OsInfo.Name);
if (!string.IsNullOrEmpty(OsInfo.Edition))
{
- environment.Append($" {OsInfo.Edition}");
+ environment.Append(' ').Append(OsInfo.Edition);
}
if (!string.IsNullOrEmpty(OsInfo.ServicePack))
{
- environment.Append($" {OsInfo.ServicePack}");
+ environment.Append(' ').Append(OsInfo.ServicePack);
}
- environment.Append($" x{OsInfo.Bits}");
- environment.Append($" {OsInfo.VersionString}");
+ environment.Append(" x").Append(OsInfo.Bits);
+ environment.Append(' ').Append(OsInfo.VersionString);
if (newline)
{
environment.AppendLine();
@@ -214,8 +212,8 @@ namespace Greenshot.Base.Core
StringBuilder report = new();
- report.AppendLine("Exception: " + ex.GetType());
- report.AppendLine("Message: " + ex.Message);
+ report.Append("Exception: ").Append(ex.GetType()).AppendLine();
+ report.Append("Message: ").AppendLine(ex.Message);
if (ex.Data.Count > 0)
{
report.AppendLine();
@@ -225,7 +223,7 @@ namespace Greenshot.Base.Core
object data = ex.Data[key];
if (data != null)
{
- report.AppendLine(key + " : " + data);
+ report.Append(key).Append(" : ").Append(data).AppendLine();
}
}
}
@@ -233,7 +231,7 @@ namespace Greenshot.Base.Core
if (ex is ExternalException externalException)
{
// e.g. COMException
- report.AppendLine().AppendLine("ErrorCode: 0x" + externalException.ErrorCode.ToString("X"));
+ report.AppendLine().Append("ErrorCode: 0x").AppendLine(externalException.ErrorCode.ToString("X"));
}
report.AppendLine().AppendLine("Stack:").AppendLine(ex.StackTrace);
@@ -304,86 +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;
}
}
@@ -425,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:
@@ -562,13 +549,9 @@ namespace Greenshot.Base.Core
return $"build {Environment.OSVersion.Version.Build}";
}
- if (Environment.OSVersion.Version.Revision != 0)
- {
- return
- $"{Environment.OSVersion.Version.Major}.{Environment.OSVersion.Version.Minor} build {Environment.OSVersion.Version.Build} revision {Environment.OSVersion.Version.Revision:X}";
- }
-
- return $"{Environment.OSVersion.Version.Major}.{Environment.OSVersion.Version.Minor} build {Environment.OSVersion.Version.Build}";
+ return Environment.OSVersion.Version.Revision != 0
+ ? $"{Environment.OSVersion.Version.Major}.{Environment.OSVersion.Version.Minor} build {Environment.OSVersion.Version.Build} revision {Environment.OSVersion.Version.Revision:X}"
+ : $"{Environment.OSVersion.Version.Major}.{Environment.OSVersion.Version.Minor} build {Environment.OSVersion.Version.Build}";
}
}
}
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 c0309763f..f44408369 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,50 +396,17 @@ namespace Greenshot.Base.Core
///
/// Return the size of the image
///
- public NativeSize Size
- {
- get
- {
- if (Area == NativeRect.Empty)
- {
- return Bitmap.Size;
- }
-
- return Area.Size;
- }
- }
+ public NativeSize Size => Area == NativeRect.Empty ? (NativeSize)Bitmap.Size : Area.Size;
///
/// Return the width of the image
///
- public int Width
- {
- get
- {
- if (Area == NativeRect.Empty)
- {
- return Bitmap.Width;
- }
-
- return Area.Width;
- }
- }
+ public int Width => Area == NativeRect.Empty ? Bitmap.Width : Area.Width;
///
/// Return the height of the image
///
- public int Height
- {
- get
- {
- if (Area == NativeRect.Empty)
- {
- return Bitmap.Height;
- }
-
- return Area.Height;
- }
- }
+ public int Height => Area == NativeRect.Empty ? Bitmap.Height : Area.Height;
private int _left;
@@ -460,8 +415,8 @@ namespace Greenshot.Base.Core
///
public int Left
{
- get { return 0; }
- set { _left = value; }
+ get => 0;
+ set => _left = value;
}
///
@@ -469,8 +424,8 @@ namespace Greenshot.Base.Core
///
int IFastBitmapWithOffset.Left
{
- get { return _left; }
- set { _left = value; }
+ get => _left;
+ set => _left = value;
}
private int _top;
@@ -480,8 +435,8 @@ namespace Greenshot.Base.Core
///
public int Top
{
- get { return 0; }
- set { _top = value; }
+ get => 0;
+ set => _top = value;
}
///
@@ -489,8 +444,8 @@ namespace Greenshot.Base.Core
///
int IFastBitmapWithOffset.Top
{
- get { return _top; }
- set { _top = value; }
+ get => _top;
+ set => _top = value;
}
///
@@ -547,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;
@@ -574,7 +526,7 @@ namespace Greenshot.Base.Core
BitsLocked = true;
IntPtr scan0 = BmData.Scan0;
- Pointer = (byte*) (void*) scan0;
+ Pointer = (byte*)(void*)scan0;
Stride = BmData.Stride;
}
@@ -595,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
@@ -624,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);
@@ -637,14 +583,7 @@ namespace Greenshot.Base.Core
bool IFastBitmapWithClip.Contains(int x, int y)
{
bool contains = Clip.Contains(x, y);
- if (InvertClip)
- {
- return !contains;
- }
- else
- {
- return contains;
- }
+ return InvertClip ? !contains : contains;
}
void IFastBitmapWithClip.SetColorAt(int x, int y, byte[] color)
@@ -675,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)
{
@@ -716,12 +652,9 @@ namespace Greenshot.Base.Core
{
// Used for indexed images
private readonly Color[] _colorEntries;
- private readonly Dictionary _colorCache = new Dictionary();
+ 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
@@ -742,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
@@ -753,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
@@ -956,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
@@ -1039,9 +963,9 @@ namespace Greenshot.Base.Core
{
// As the request is to get without alpha, we blend.
int rem = 255 - a;
- red = (red * a + BackgroundBlendColor.R * rem) / 255;
- green = (green * a + BackgroundBlendColor.G * rem) / 255;
- blue = (blue * a + BackgroundBlendColor.B * rem) / 255;
+ red = ((red * a) + (BackgroundBlendColor.R * rem)) / 255;
+ green = ((green * a) + (BackgroundBlendColor.G * rem)) / 255;
+ blue = ((blue * a) + (BackgroundBlendColor.B * rem)) / 255;
}
return Color.FromArgb(255, red, green, blue);
diff --git a/src/Greenshot.Base/Core/FileDescriptorReader.cs b/src/Greenshot.Base/Core/FileDescriptorReader.cs
index 69ad0af7d..e895e8d40 100644
--- a/src/Greenshot.Base/Core/FileDescriptorReader.cs
+++ b/src/Greenshot.Base/Core/FileDescriptorReader.cs
@@ -29,7 +29,7 @@ namespace Greenshot.Base.Core
{
///
/// Specifies which fields are valid in a FileDescriptor Structure
- ///
+ ///
[Flags]
public enum FileDescriptorFlags : uint
{
@@ -67,7 +67,7 @@ namespace Greenshot.Base.Core
var count = reader.ReadUInt32();
while (count > 0)
{
- FileDescriptor descriptor = new FileDescriptor(reader);
+ FileDescriptor descriptor = new(reader);
yield return descriptor.FileName;
@@ -78,7 +78,7 @@ namespace Greenshot.Base.Core
internal static MemoryStream GetFileContents(System.Windows.Forms.IDataObject dataObject, int index)
{
//cast the default IDataObject to a com IDataObject
- var comDataObject = (IDataObject) dataObject;
+ var comDataObject = (IDataObject)dataObject;
var format = System.Windows.DataFormats.GetDataFormat("FileContents");
if (format == null)
@@ -87,13 +87,13 @@ namespace Greenshot.Base.Core
}
//create STGMEDIUM to output request results into
- var medium = new STGMEDIUM();
-
+ _ = new STGMEDIUM();
+ STGMEDIUM medium;
unchecked
{
var formatetc = new FORMATETC
{
- cfFormat = (short) format.Id,
+ cfFormat = (short)format.Id,
dwAspect = DVASPECT.DVASPECT_CONTENT,
lindex = index,
tymed = TYMED.TYMED_ISTREAM | TYMED.TYMED_HGLOBAL
@@ -113,13 +113,13 @@ namespace Greenshot.Base.Core
private static MemoryStream GetIStream(STGMEDIUM medium)
{
//marshal the returned pointer to a IStream object
- IStream iStream = (IStream) Marshal.GetObjectForIUnknown(medium.unionmember);
+ IStream iStream = (IStream)Marshal.GetObjectForIUnknown(medium.unionmember);
Marshal.Release(medium.unionmember);
//get the STATSTG of the IStream to determine how many bytes are in it
- var iStreamStat = new System.Runtime.InteropServices.ComTypes.STATSTG();
- iStream.Stat(out iStreamStat, 0);
- int iStreamSize = (int) iStreamStat.cbSize;
+ _ = new System.Runtime.InteropServices.ComTypes.STATSTG();
+ iStream.Stat(out System.Runtime.InteropServices.ComTypes.STATSTG iStreamStat, 0);
+ int iStreamSize = (int)iStreamStat.cbSize;
//read the data from the IStream into a managed byte array
byte[] iStreamContent = new byte[iStreamSize];
diff --git a/src/Greenshot.Base/Core/FileFormatHandlers/FileFormatHandlerExtensions.cs b/src/Greenshot.Base/Core/FileFormatHandlers/FileFormatHandlerExtensions.cs
index 8941c7184..618e20c17 100644
--- a/src/Greenshot.Base/Core/FileFormatHandlers/FileFormatHandlerExtensions.cs
+++ b/src/Greenshot.Base/Core/FileFormatHandlers/FileFormatHandlerExtensions.cs
@@ -39,7 +39,7 @@ namespace Greenshot.Base.Core.FileFormatHandlers
///
/// string
/// string
- public static string NormalizeExtension(string extension)
+ public static string NormalizeExtension(string extension)
{
if (string.IsNullOrEmpty(extension))
{
@@ -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
@@ -93,17 +90,16 @@ namespace Greenshot.Base.Core.FileFormatHandlers
.Where(ffh => ffh.Supports(FileFormatHandlerActions.LoadFromStream, extension))
.OrderBy(ffh => ffh.PriorityFor(FileFormatHandlerActions.LoadFromStream, extension)).ToList();
- if (!saveFileFormatHandlers.Any())
+ if (saveFileFormatHandlers.Count == 0)
{
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;
@@ -126,12 +122,9 @@ namespace Greenshot.Base.Core.FileFormatHandlers
.OrderBy(ffh => ffh.PriorityFor(FileFormatHandlerActions.LoadDrawableFromStream, extension))
.FirstOrDefault();
- if (loadfileFormatHandler != null)
- {
- return loadfileFormatHandler.LoadDrawablesFromStream(stream, extension, parentSurface);
- }
-
- return Enumerable.Empty();
+ return loadfileFormatHandler != null
+ ? loadfileFormatHandler.LoadDrawablesFromStream(stream, extension, parentSurface)
+ : Enumerable.Empty();
}
///
diff --git a/src/Greenshot.Base/Core/FilenameHelper.cs b/src/Greenshot.Base/Core/FilenameHelper.cs
index 4c6864547..09ad85fc0 100644
--- a/src/Greenshot.Base/Core/FilenameHelper.cs
+++ b/src/Greenshot.Base/Core/FilenameHelper.cs
@@ -42,15 +42,15 @@ namespace Greenshot.Base.Core
// If a parameters needs to be supplied, than a ":" should follow the name... everything from the : until the } is considered to be part of the parameters.
// The parameter format is a single alpha followed by the value belonging to the parameter, e.g. :
// ${capturetime:d"yyyy-MM-dd HH_mm_ss"}
- private static readonly Regex VarRegexp = new Regex(@"\${(?[^:}]+)[:]?(?[^}]*)}", RegexOptions.Compiled);
- private static readonly Regex CmdVarRegexp = new Regex(@"%(?[^%]+)%", RegexOptions.Compiled);
+ private static readonly Regex VarRegexp = new(@"\${(?[^:}]+)[:]?(?[^}]*)}", RegexOptions.Compiled);
+ private static readonly Regex CmdVarRegexp = new("%(?[^%]+)%", RegexOptions.Compiled);
- private static readonly Regex SplitRegexp = new Regex(";(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", RegexOptions.Compiled);
+ private static readonly Regex SplitRegexp = new(";(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", RegexOptions.Compiled);
private const int MaxTitleLength = 80;
private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection();
private const string UnsafeReplacement = "_";
- private static readonly Random RandomNumberGen = new Random();
- private static readonly Regex RandRegexp = new Regex("^R+$", RegexOptions.Compiled);
+ private static readonly Random RandomNumberGen = new();
+ private static readonly Regex RandRegexp = new("^R+$", RegexOptions.Compiled);
///
/// Remove invalid characters from the fully qualified filename
@@ -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
@@ -141,7 +129,6 @@ namespace Greenshot.Base.Core
return GetFilenameFromPattern(pattern, format, captureDetails);
}
-
///
/// This method will be called by the regexp.replace as a MatchEvaluator delegate!
/// Will delegate this to the MatchVarEvaluatorInternal and catch any exceptions
@@ -191,7 +178,7 @@ namespace Greenshot.Base.Core
string replaceValue = string.Empty;
string variable = match.Groups["variable"].Value;
string parameters = match.Groups["parameters"].Value;
- string randomChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
+ const string randomChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
if (parameters.Length > 0)
{
@@ -222,7 +209,7 @@ namespace Greenshot.Base.Core
// r,
case "r":
string[] replaceParameters = parameter.Substring(1).Split(',');
- if (replaceParameters != null && replaceParameters.Length == 2)
+ if (replaceParameters?.Length == 2)
{
replacements.Add(replaceParameters[0], replaceParameters[1]);
}
@@ -277,25 +264,25 @@ namespace Greenshot.Base.Core
}
}
- if (processVars != null && processVars.Contains(variable))
+ if (processVars?.Contains(variable) == true)
{
- replaceValue = (string) processVars[variable];
+ replaceValue = (string)processVars[variable];
if (filenameSafeMode)
{
replaceValue = MakePathSafe(replaceValue);
}
}
- else if (userVars != null && userVars.Contains(variable))
+ else if (userVars?.Contains(variable) == true)
{
- replaceValue = (string) userVars[variable];
+ replaceValue = (string)userVars[variable];
if (filenameSafeMode)
{
replaceValue = MakePathSafe(replaceValue);
}
}
- else if (machineVars != null && machineVars.Contains(variable))
+ else if (machineVars?.Contains(variable) == true)
{
- replaceValue = (string) machineVars[variable];
+ replaceValue = (string)machineVars[variable];
if (filenameSafeMode)
{
replaceValue = MakePathSafe(replaceValue);
@@ -675,7 +662,7 @@ namespace Greenshot.Base.Core
var forbiddenChars = Path.GetInvalidPathChars();
foreach (var forbiddenChar in forbiddenChars)
{
- if (directoryName == null || directoryName.Contains(forbiddenChar.ToString()))
+ if (directoryName?.Contains(forbiddenChar.ToString()) != false)
{
return false;
}
@@ -694,7 +681,7 @@ namespace Greenshot.Base.Core
var forbiddenChars = Path.GetInvalidFileNameChars();
foreach (var forbiddenChar in forbiddenChars)
{
- if (filename == null || filename.Contains(forbiddenChar.ToString()))
+ if (filename?.Contains(forbiddenChar.ToString()) != false)
{
return false;
}
diff --git a/src/Greenshot.Base/Core/Fraction.cs b/src/Greenshot.Base/Core/Fraction.cs
index e7d999445..a538b5211 100644
--- a/src/Greenshot.Base/Core/Fraction.cs
+++ b/src/Greenshot.Base/Core/Fraction.cs
@@ -31,11 +31,11 @@ namespace Greenshot.Base.Core
}
public Fraction Inverse()
- => new Fraction(Denominator, Numerator);
+ => new(Denominator, Numerator);
#region Parse
- private static readonly Regex PARSE_REGEX = new Regex(@"^([1-9][0-9]*)\/([1-9][0-9]*)$", RegexOptions.Compiled);
+ private static readonly Regex PARSE_REGEX = new(@"^([1-9][0-9]*)\/([1-9][0-9]*)$", RegexOptions.Compiled);
public static bool TryParse(string str, out Fraction result)
{
@@ -75,14 +75,14 @@ namespace Greenshot.Base.Core
unchecked
{
int hashCode = -1534900553;
- hashCode = hashCode * -1521134295 + Numerator.GetHashCode();
- hashCode = hashCode * -1521134295 + Denominator.GetHashCode();
+ hashCode = (hashCode * -1521134295) + Numerator.GetHashCode();
+ hashCode = (hashCode * -1521134295) + Denominator.GetHashCode();
return hashCode;
}
}
public int CompareTo(Fraction other)
- => (int) (Numerator * other.Denominator) - (int) (other.Numerator * Denominator);
+ => (int)(Numerator * other.Denominator) - (int)(other.Numerator * Denominator);
#endregion
@@ -115,22 +115,22 @@ namespace Greenshot.Base.Core
#region Scale operators
public static Fraction operator *(Fraction left, Fraction right)
- => new Fraction(left.Numerator * right.Numerator, left.Denominator * right.Denominator);
+ => new(left.Numerator * right.Numerator, left.Denominator * right.Denominator);
public static Fraction operator *(Fraction left, uint right)
- => new Fraction(left.Numerator * right, left.Denominator);
+ => new(left.Numerator * right, left.Denominator);
public static Fraction operator *(uint left, Fraction right)
- => new Fraction(left * right.Numerator, right.Denominator);
+ => new(left * right.Numerator, right.Denominator);
public static Fraction operator /(Fraction left, Fraction right)
- => new Fraction(left.Numerator * right.Denominator, left.Denominator * right.Numerator);
+ => new(left.Numerator * right.Denominator, left.Denominator * right.Numerator);
public static Fraction operator /(Fraction left, uint right)
- => new Fraction(left.Numerator, left.Denominator * right);
+ => new(left.Numerator, left.Denominator * right);
public static Fraction operator /(uint left, Fraction right)
- => new Fraction(left * right.Denominator, right.Numerator);
+ => new(left * right.Denominator, right.Numerator);
#endregion
@@ -143,10 +143,10 @@ namespace Greenshot.Base.Core
=> 1.0f * fraction.Numerator / fraction.Denominator;
public static implicit operator Fraction(uint number)
- => new Fraction(number, 1u);
+ => new(number, 1u);
public static implicit operator Fraction((uint numerator, uint demoninator) tuple)
- => new Fraction(tuple.numerator, tuple.demoninator);
+ => new(tuple.numerator, tuple.demoninator);
#endregion
diff --git a/src/Greenshot.Base/Core/GreenshotResources.cs b/src/Greenshot.Base/Core/GreenshotResources.cs
index 1276ee3f6..17dbcd23f 100644
--- a/src/Greenshot.Base/Core/GreenshotResources.cs
+++ b/src/Greenshot.Base/Core/GreenshotResources.cs
@@ -29,21 +29,12 @@ namespace Greenshot.Base.Core
///
public static class GreenshotResources
{
- private static readonly ComponentResourceManager GreenshotResourceManager = new ComponentResourceManager(typeof(GreenshotResources));
+ 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 f7fa3242b..8de4f07a4 100644
--- a/src/Greenshot.Base/Core/IEHelper.cs
+++ b/src/Greenshot.Base/Core/IEHelper.cs
@@ -85,15 +85,10 @@ namespace Greenshot.Base.Core
if (ieVersion > 9)
{
- return ieVersion * 1000 + (ignoreDoctype ? 1 : 0);
+ return (ieVersion * 1000) + (ignoreDoctype ? 1 : 0);
}
- if (ieVersion > 7)
- {
- return ieVersion * 1111;
- }
-
- return 7000;
+ return ieVersion > 7 ? ieVersion * 1111 : 7000;
}
///
@@ -111,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
@@ -128,7 +120,7 @@ namespace Greenshot.Base.Core
{
ModifyRegistry("HKEY_CURRENT_USER", applicationName + ".exe", ieVersion);
#if DEBUG
- ModifyRegistry("HKEY_CURRENT_USER", applicationName + ".vshost.exe", ieVersion);
+ ModifyRegistry("HKEY_CURRENT_USER", applicationName + ".vshost.exe", ieVersion);
#endif
}
@@ -191,7 +183,7 @@ namespace Greenshot.Base.Core
WindowDetails directUIWD = GetDirectUI(ieWindow);
if (directUIWD != null)
{
- Accessible ieAccessible = new Accessible(directUIWD.Handle);
+ Accessible ieAccessible = new(directUIWD.Handle);
foreach (string url in ieAccessible.IETabUrls)
{
yield return url;
diff --git a/src/Greenshot.Base/Core/ImageHelper.cs b/src/Greenshot.Base/Core/ImageHelper.cs
index f75cc9def..6c49c119b 100644
--- a/src/Greenshot.Base/Core/ImageHelper.cs
+++ b/src/Greenshot.Base/Core/ImageHelper.cs
@@ -51,7 +51,6 @@ namespace Greenshot.Base.Core
private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection();
private const int ExifOrientationId = 0x0112;
-
///
/// Make sure the image is orientated correctly
///
@@ -75,7 +74,7 @@ namespace Greenshot.Base.Core
PropertyItem item = image.GetPropertyItem(ExifOrientationId);
- ExifOrientations orientation = (ExifOrientations) item.Value[0];
+ ExifOrientations orientation = (ExifOrientations)item.Value[0];
// Orient the image.
switch (orientation)
{
@@ -106,7 +105,7 @@ namespace Greenshot.Base.Core
}
// Set the orientation to be normal, as we rotated the image.
- item.Value[0] = (byte) ExifOrientations.TopLeft;
+ item.Value[0] = (byte)ExifOrientations.TopLeft;
image.SetPropertyItem(item);
}
catch (Exception orientEx)
@@ -130,34 +129,34 @@ namespace Greenshot.Base.Core
int srcHeight = image.Height;
if (thumbHeight < 0)
{
- thumbHeight = (int) (thumbWidth * (srcHeight / (float) srcWidth));
+ thumbHeight = (int)(thumbWidth * (srcHeight / (float)srcWidth));
}
if (thumbWidth < 0)
{
- thumbWidth = (int) (thumbHeight * (srcWidth / (float) srcHeight));
+ thumbWidth = (int)(thumbHeight * (srcWidth / (float)srcHeight));
}
if (maxWidth > 0 && thumbWidth > maxWidth)
{
thumbWidth = Math.Min(thumbWidth, maxWidth);
- thumbHeight = (int) (thumbWidth * (srcHeight / (float) srcWidth));
+ thumbHeight = (int)(thumbWidth * (srcHeight / (float)srcWidth));
}
if (maxHeight > 0 && thumbHeight > maxHeight)
{
thumbHeight = Math.Min(thumbHeight, maxHeight);
- thumbWidth = (int) (thumbHeight * (srcWidth / (float) srcHeight));
+ thumbWidth = (int)(thumbHeight * (srcWidth / (float)srcHeight));
}
- Bitmap bmp = new Bitmap(thumbWidth, thumbHeight);
+ Bitmap bmp = new(thumbWidth, thumbHeight);
using (Graphics graphics = Graphics.FromImage(bmp))
{
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
- NativeRect rectDestination = new NativeRect(0, 0, thumbWidth, thumbHeight);
+ NativeRect rectDestination = new(0, 0, thumbWidth, thumbHeight);
graphics.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);
}
@@ -200,8 +199,8 @@ namespace Greenshot.Base.Core
area ??= new NativeRect(0, 0, fastBitmap.Width, fastBitmap.Height);
NativeRect cropNativeRect = NativeRect.Empty;
Color referenceColor = fastBitmap.GetColorAt(colorPoint.X, colorPoint.Y);
- NativePoint min = new NativePoint(int.MaxValue, int.MaxValue);
- NativePoint max = new NativePoint(int.MinValue, int.MinValue);
+ NativePoint min = new(int.MaxValue, int.MaxValue);
+ NativePoint max = new(int.MinValue, int.MinValue);
if (cropDifference > 0)
{
@@ -245,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;
@@ -279,7 +275,7 @@ namespace Greenshot.Base.Core
// Bottom Left
// Top Right
// Bottom Right
- using (IFastBitmap fastBitmap = FastBitmap.Create((Bitmap) image))
+ using (IFastBitmap fastBitmap = FastBitmap.Create((Bitmap)image))
{
// find biggest area
foreach (var checkPoint in checkPoints)
@@ -369,9 +365,9 @@ namespace Greenshot.Base.Core
Image returnImage = CreateEmpty(sourceImage.Width, sourceImage.Height, PixelFormat.Format32bppArgb, Color.Empty, sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
using (var path = new GraphicsPath())
{
- Random random = new Random();
- int horizontalRegions = (int) Math.Round((float) sourceImage.Width / horizontalToothRange);
- int verticalRegions = (int) Math.Round((float) sourceImage.Height / verticalToothRange);
+ Random random = new();
+ int horizontalRegions = (int)Math.Round((float)sourceImage.Width / horizontalToothRange);
+ int verticalRegions = (int)Math.Round((float)sourceImage.Height / verticalToothRange);
var topLeft = new NativePoint(0, 0);
var topRight = new NativePoint(sourceImage.Width, 0);
@@ -429,7 +425,7 @@ namespace Greenshot.Base.Core
{
for (int i = 1; i < horizontalRegions - 1; i++)
{
- points.Add(new NativePoint(sourceImage.Width - i * horizontalToothRange, sourceImage.Height - random.Next(1, toothHeight)));
+ points.Add(new NativePoint(sourceImage.Width - (i * horizontalToothRange), sourceImage.Height - random.Next(1, toothHeight)));
}
points.Add(new NativePoint(random.Next(1, toothHeight), sourceImage.Height - random.Next(1, toothHeight)));
@@ -575,7 +571,7 @@ namespace Greenshot.Base.Core
if (x >= targetFastBitmap.Left)
{
- newColors[x - targetFastBitmap.Left] = Color.FromArgb(255, (byte) (r / hits), (byte) (g / hits), (byte) (b / hits));
+ newColors[x - targetFastBitmap.Left] = Color.FromArgb(255, (byte)(r / hits), (byte)(g / hits), (byte)(b / hits));
}
}
@@ -634,7 +630,7 @@ namespace Greenshot.Base.Core
if (x >= targetFastBitmap.Left)
{
- newColors[x - targetFastBitmap.Left] = Color.FromArgb((byte) (a / hits), (byte) (r / hits), (byte) (g / hits), (byte) (b / hits));
+ newColors[x - targetFastBitmap.Left] = Color.FromArgb((byte)(a / hits), (byte)(r / hits), (byte)(g / hits), (byte)(b / hits));
}
}
@@ -690,7 +686,7 @@ namespace Greenshot.Base.Core
if (y >= targetFastBitmap.Top)
{
- newColors[y - targetFastBitmap.Top] = Color.FromArgb(255, (byte) (r / hits), (byte) (g / hits), (byte) (b / hits));
+ newColors[y - targetFastBitmap.Top] = Color.FromArgb(255, (byte)(r / hits), (byte)(g / hits), (byte)(b / hits));
}
}
@@ -750,7 +746,7 @@ namespace Greenshot.Base.Core
if (y >= targetFastBitmap.Top)
{
- newColors[y - targetFastBitmap.Top] = Color.FromArgb((byte) (a / hits), (byte) (r / hits), (byte) (g / hits), (byte) (b / hits));
+ newColors[y - targetFastBitmap.Top] = Color.FromArgb((byte)(a / hits), (byte)(r / hits), (byte)(g / hits), (byte)(b / hits));
}
}
@@ -772,18 +768,15 @@ namespace Greenshot.Base.Core
/// NativeRect
public static NativeRect CreateIntersectRectangle(NativeSize applySize, NativeRect rect, bool invert)
{
- NativeRect myRect;
if (invert)
{
- myRect = new NativeRect(0, 0, applySize.Width, applySize.Height);
+ return new NativeRect(0, 0, applySize.Width, applySize.Height);
}
else
{
- NativeRect applyRect = new NativeRect(0, 0, applySize.Width, applySize.Height);
- myRect = new NativeRect(rect.X, rect.Y, rect.Width, rect.Height).Intersect(applyRect);
+ NativeRect applyRect = new(0, 0, applySize.Width, applySize.Height);
+ return new NativeRect(rect.X, rect.Y, rect.Width, rect.Height).Intersect(applyRect);
}
-
- return myRect;
}
///
@@ -801,7 +794,7 @@ namespace Greenshot.Base.Core
NativePoint offset = shadowOffset.Offset(shadowSize - 1, shadowSize - 1);
matrix.Translate(offset.X, offset.Y, MatrixOrder.Append);
// Create a new "clean" image
- Bitmap returnImage = CreateEmpty(sourceBitmap.Width + shadowSize * 2, sourceBitmap.Height + shadowSize * 2, targetPixelformat, Color.Empty,
+ Bitmap returnImage = CreateEmpty(sourceBitmap.Width + (shadowSize * 2), sourceBitmap.Height + (shadowSize * 2), targetPixelformat, Color.Empty,
sourceBitmap.HorizontalResolution, sourceBitmap.VerticalResolution);
// Make sure the shadow is odd, there is no reason for an even blur!
if ((shadowSize & 1) == 0)
@@ -811,29 +804,22 @@ namespace Greenshot.Base.Core
bool useGdiBlur = GdiPlusApi.IsBlurPossible(shadowSize);
// Create "mask" for the shadow
- ColorMatrix maskMatrix = new ColorMatrix
+ ColorMatrix maskMatrix = new()
{
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 NativeRect(new NativePoint(shadowSize, shadowSize), sourceBitmap.Size);
- ApplyColorMatrix((Bitmap) sourceBitmap, NativeRect.Empty, returnImage, shadowNativeRect, maskMatrix);
+ NativeRect shadowNativeRect = new(new NativePoint(shadowSize, shadowSize), sourceBitmap.Size);
+ ApplyColorMatrix((Bitmap)sourceBitmap, NativeRect.Empty, returnImage, shadowNativeRect, maskMatrix);
// blur "shadow", apply to whole new image
if (useGdiBlur)
{
// Use GDI Blur
- NativeRect newImageNativeRect = new NativeRect(0, 0, returnImage.Width, returnImage.Height);
+ NativeRect newImageNativeRect = new(0, 0, returnImage.Width, returnImage.Height);
GdiPlusApi.ApplyBlur(returnImage, newImageNativeRect, shadowSize + 1, false);
}
else
@@ -868,8 +854,8 @@ namespace Greenshot.Base.Core
/// Negative bitmap
public static Bitmap CreateNegative(Image sourceImage)
{
- Bitmap clone = (Bitmap) Clone(sourceImage);
- ColorMatrix invertMatrix = new ColorMatrix(new[]
+ Bitmap clone = (Bitmap)Clone(sourceImage);
+ ColorMatrix invertMatrix = new(new[]
{
new float[]
{
@@ -901,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
@@ -916,7 +899,7 @@ namespace Greenshot.Base.Core
/// ColorMatrix to apply
public static void ApplyColorMatrix(Bitmap source, NativeRect sourceRect, Bitmap dest, NativeRect destRect, ColorMatrix colorMatrix)
{
- using ImageAttributes imageAttributes = new ImageAttributes();
+ using ImageAttributes imageAttributes = new();
imageAttributes.ClearColorMatrix();
imageAttributes.SetColorMatrix(colorMatrix);
ApplyImageAttributes(source, sourceRect, dest, destRect, imageAttributes);
@@ -993,11 +976,11 @@ namespace Greenshot.Base.Core
public static Image CreateBorder(Image sourceImage, int borderSize, Color borderColor, PixelFormat targetPixelformat, Matrix matrix)
{
// "return" the shifted offset, so the caller can e.g. move elements
- NativePoint offset = new NativePoint(borderSize, borderSize);
+ NativePoint offset = new(borderSize, borderSize);
matrix.Translate(offset.X, offset.Y, MatrixOrder.Append);
// Create a new "clean" image
- Bitmap newImage = CreateEmpty(sourceImage.Width + borderSize * 2, sourceImage.Height + borderSize * 2, targetPixelformat, Color.Empty, sourceImage.HorizontalResolution,
+ Bitmap newImage = CreateEmpty(sourceImage.Width + (borderSize * 2), sourceImage.Height + (borderSize * 2), targetPixelformat, Color.Empty, sourceImage.HorizontalResolution,
sourceImage.VerticalResolution);
using (Graphics graphics = Graphics.FromImage(newImage))
{
@@ -1006,10 +989,10 @@ namespace Greenshot.Base.Core
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
- using (GraphicsPath path = new GraphicsPath())
+ using (GraphicsPath path = new())
{
path.AddRectangle(new NativeRect(borderSize >> 1, borderSize >> 1, newImage.Width - borderSize, newImage.Height - borderSize));
- using Pen pen = new Pen(borderColor, borderSize)
+ using Pen pen = new(borderColor, borderSize)
{
LineJoin = LineJoin.Round,
StartCap = LineCap.Round,
@@ -1038,7 +1021,7 @@ namespace Greenshot.Base.Core
public static ImageAttributes CreateAdjustAttributes(float brightness, float contrast, float gamma)
{
float adjustedBrightness = brightness - 1.0f;
- ColorMatrix applyColorMatrix = new ColorMatrix(
+ ColorMatrix applyColorMatrix = new(
new[]
{
new[]
@@ -1064,7 +1047,7 @@ namespace Greenshot.Base.Core
});
//create some image attributes
- ImageAttributes attributes = new ImageAttributes();
+ ImageAttributes attributes = new();
attributes.ClearColorMatrix();
attributes.SetColorMatrix(applyColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
attributes.SetGamma(gamma, ColorAdjustType.Bitmap);
@@ -1088,7 +1071,7 @@ namespace Greenshot.Base.Core
sourceImage.VerticalResolution);
using (ImageAttributes adjustAttributes = CreateAdjustAttributes(brightness, contrast, gamma))
{
- ApplyImageAttributes((Bitmap) sourceImage, NativeRect.Empty, newBitmap, NativeRect.Empty, adjustAttributes);
+ ApplyImageAttributes((Bitmap)sourceImage, NativeRect.Empty, newBitmap, NativeRect.Empty, adjustAttributes);
}
return newBitmap;
@@ -1101,8 +1084,8 @@ namespace Greenshot.Base.Core
/// Bitmap with grayscale
public static Image CreateGrayscale(Image sourceImage)
{
- Bitmap clone = (Bitmap) Clone(sourceImage);
- ColorMatrix grayscaleMatrix = new ColorMatrix(new[]
+ Bitmap clone = (Bitmap)Clone(sourceImage);
+ ColorMatrix grayscaleMatrix = new(new[]
{
new[]
{
@@ -1134,28 +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)
- {
- if (sourceImage is Metafile)
- {
- return (Image) sourceImage.Clone();
- }
-
- return 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
@@ -1163,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:
@@ -1182,17 +1151,12 @@ namespace Greenshot.Base.Core
public static Bitmap CloneArea(Image sourceImage, NativeRect sourceRect, PixelFormat targetFormat)
{
Bitmap newImage;
- NativeRect bitmapRect = new NativeRect(0, 0, sourceImage.Width, sourceImage.Height);
+ 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)
@@ -1201,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;
}
}
@@ -1322,7 +1282,7 @@ namespace Greenshot.Base.Core
public static Bitmap CreateEmpty(int width, int height, PixelFormat format, Color backgroundColor, float horizontalResolution = 96f, float verticalResolution = 96f)
{
// Create a new "clean" image
- Bitmap newImage = new Bitmap(width, height, format);
+ Bitmap newImage = new(width, height, format);
newImage.SetResolution(horizontalResolution, verticalResolution);
if (format != PixelFormat.Format8bppIndexed)
{
@@ -1378,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
@@ -1399,7 +1356,7 @@ namespace Greenshot.Base.Core
toCount &= 0xffffff;
}
- using IFastBitmap bb = FastBitmap.Create((Bitmap) sourceImage);
+ using IFastBitmap bb = FastBitmap.Create((Bitmap)sourceImage);
for (int y = 0; y < bb.Height; y++)
{
for (int x = 0; x < bb.Width; x++)
@@ -1436,32 +1393,32 @@ namespace Greenshot.Base.Core
int destX = 0;
int destY = 0;
- var nPercentW = newWidth / (float) sourceImage.Width;
- var nPercentH = newHeight / (float) sourceImage.Height;
+ var nPercentW = newWidth / (float)sourceImage.Width;
+ var nPercentH = newHeight / (float)sourceImage.Height;
if (maintainAspectRatio)
{
- if ((int) nPercentW == 1)
+ if ((int)nPercentW == 1)
{
nPercentW = nPercentH;
if (canvasUseNewSize)
{
- destX = Math.Max(0, Convert.ToInt32((newWidth - sourceImage.Width * nPercentW) / 2));
+ destX = Math.Max(0, Convert.ToInt32((newWidth - (sourceImage.Width * nPercentW)) / 2));
}
}
- else if ((int) nPercentH == 1)
+ else if ((int)nPercentH == 1)
{
nPercentH = nPercentW;
if (canvasUseNewSize)
{
- destY = Math.Max(0, Convert.ToInt32((newHeight - sourceImage.Height * nPercentH) / 2));
+ destY = Math.Max(0, Convert.ToInt32((newHeight - (sourceImage.Height * nPercentH)) / 2));
}
}
- else if ((int) nPercentH != 0 && nPercentH < nPercentW)
+ else if ((int)nPercentH != 0 && nPercentH < nPercentW)
{
nPercentW = nPercentH;
if (canvasUseNewSize)
{
- destX = Math.Max(0, Convert.ToInt32((newWidth - sourceImage.Width * nPercentW) / 2));
+ destX = Math.Max(0, Convert.ToInt32((newWidth - (sourceImage.Width * nPercentW)) / 2));
}
}
else
@@ -1469,13 +1426,13 @@ namespace Greenshot.Base.Core
nPercentH = nPercentW;
if (canvasUseNewSize)
{
- destY = Math.Max(0, Convert.ToInt32((newHeight - sourceImage.Height * nPercentH) / 2));
+ destY = Math.Max(0, Convert.ToInt32((newHeight - (sourceImage.Height * nPercentH)) / 2));
}
}
}
- int destWidth = (int) (sourceImage.Width * nPercentW);
- int destHeight = (int) (sourceImage.Height * nPercentH);
+ int destWidth = (int)(sourceImage.Width * nPercentW);
+ int destHeight = (int)(sourceImage.Height * nPercentH);
if (newWidth == 0)
{
newWidth = destWidth;
@@ -1490,25 +1447,25 @@ namespace Greenshot.Base.Core
if (maintainAspectRatio && canvasUseNewSize)
{
newImage = CreateEmpty(newWidth, newHeight, sourceImage.PixelFormat, backgroundColor, sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
- matrix?.Scale((float) newWidth / sourceImage.Width, (float) newHeight / sourceImage.Height, MatrixOrder.Append);
+ matrix?.Scale((float)newWidth / sourceImage.Width, (float)newHeight / sourceImage.Height, MatrixOrder.Append);
}
else
{
newImage = CreateEmpty(destWidth, destHeight, sourceImage.PixelFormat, backgroundColor, sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
- matrix?.Scale((float) destWidth / sourceImage.Width, (float) destHeight / sourceImage.Height, MatrixOrder.Append);
+ matrix?.Scale((float)destWidth / sourceImage.Width, (float)destHeight / sourceImage.Height, MatrixOrder.Append);
}
using (Graphics graphics = Graphics.FromImage(newImage))
{
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
- using ImageAttributes wrapMode = new ImageAttributes();
+ using ImageAttributes wrapMode = new();
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(sourceImage, new NativeRect(destX, destY, destWidth, destHeight), 0, 0, sourceImage.Width, sourceImage.Height, GraphicsUnit.Pixel, wrapMode);
}
return newImage;
}
-
+
///
/// Rotate the image
///
@@ -1562,12 +1519,7 @@ namespace Greenshot.Base.Core
{
return PixelFormat.Format24bppRgb;
}
- if (pixelFormat == PixelFormats.Bgr32)
- {
- return PixelFormat.Format32bppRgb;
- }
-
- throw new NotSupportedException($"Can't map {pixelFormat}.");
+ return pixelFormat == PixelFormats.Bgr32 ? PixelFormat.Format32bppRgb : throw new NotSupportedException($"Can't map {pixelFormat}.");
}
///
@@ -1605,7 +1557,7 @@ namespace Greenshot.Base.Core
{
var pixelFormat = bitmapSource.Format.Map();
- Bitmap bitmap = new Bitmap(bitmapSource.PixelWidth, bitmapSource.PixelHeight, pixelFormat);
+ Bitmap bitmap = new(bitmapSource.PixelWidth, bitmapSource.PixelHeight, pixelFormat);
BitmapData data = bitmap.LockBits(new NativeRect(NativePoint.Empty, bitmap.Size), ImageLockMode.WriteOnly, pixelFormat);
bitmapSource.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
bitmap.UnlockBits(data);
diff --git a/src/Greenshot.Base/Core/ImageIO.cs b/src/Greenshot.Base/Core/ImageIO.cs
index 9d6bbf1cd..260f886f9 100644
--- a/src/Greenshot.Base/Core/ImageIO.cs
+++ b/src/Greenshot.Base/Core/ImageIO.cs
@@ -48,7 +48,7 @@ namespace Greenshot.Base.Core
private static readonly ILog Log = LogManager.GetLogger(typeof(ImageIO));
private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection();
private static readonly int PROPERTY_TAG_SOFTWARE_USED = 0x0131;
- private static readonly Cache TmpFileCache = new Cache(10 * 60 * 60, RemoveExpiredTmpFile);
+ private static readonly Cache TmpFileCache = new(10 * 60 * 60, RemoveExpiredTmpFile);
///
/// Creates a PropertyItem (Metadata) to store with the image.
@@ -66,7 +66,7 @@ namespace Greenshot.Base.Core
ConstructorInfo ci = typeof(PropertyItem).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, new Type[]
{
}, null);
- propertyItem = (PropertyItem) ci.Invoke(null);
+ propertyItem = (PropertyItem)ci.Invoke(null);
// Make sure it's of type string
propertyItem.Type = 2;
// Set the ID
@@ -182,10 +182,10 @@ namespace Greenshot.Base.Core
}
Image tmpImage;
- if (outputSettings.Effects != null && outputSettings.Effects.Count > 0)
+ if (outputSettings.Effects?.Count > 0)
{
// apply effects, if there are any
- using (Matrix matrix = new Matrix())
+ using (Matrix matrix = new())
{
tmpImage = ImageHelper.ApplyEffects(imageToSave, outputSettings.Effects, matrix);
}
@@ -211,7 +211,7 @@ namespace Greenshot.Base.Core
bool isAlpha = Image.IsAlphaPixelFormat(imageToSave.PixelFormat);
if (outputSettings.ReduceColors || (!isAlpha && CoreConfig.OutputFileAutoReduceColors))
{
- using var quantizer = new WuQuantizer((Bitmap) imageToSave);
+ using var quantizer = new WuQuantizer((Bitmap)imageToSave);
int colorCount = quantizer.GetColorCount();
Log.InfoFormat("Image with format {0} has {1} colors", imageToSave.PixelFormat, colorCount);
if (!outputSettings.ReduceColors && colorCount >= 256)
@@ -304,7 +304,7 @@ namespace Greenshot.Base.Core
// check whether path exists - if not create it
if (path != null)
{
- DirectoryInfo di = new DirectoryInfo(path);
+ DirectoryInfo di = new(path);
if (!di.Exists)
{
Directory.CreateDirectory(di.FullName);
@@ -313,14 +313,14 @@ namespace Greenshot.Base.Core
if (!allowOverwrite && File.Exists(fullPath))
{
- ArgumentException throwingException = new ArgumentException("File '" + fullPath + "' already exists.");
+ ArgumentException throwingException = new("File '" + fullPath + "' already exists.");
throwingException.Data.Add("fullPath", fullPath);
throw throwingException;
}
Log.DebugFormat("Saving surface to {0}", fullPath);
// Create the stream and call SaveToStream
- using (FileStream stream = new FileStream(fullPath, FileMode.Create, FileAccess.Write))
+ using (FileStream stream = new(fullPath, FileMode.Create, FileAccess.Write))
{
SaveToStream(surface, stream, outputSettings);
}
@@ -343,7 +343,7 @@ namespace Greenshot.Base.Core
OutputFormat format = OutputFormat.png;
try
{
- format = (OutputFormat) Enum.Parse(typeof(OutputFormat), extension.ToLower());
+ format = (OutputFormat)Enum.Parse(typeof(OutputFormat), extension.ToLower());
}
catch (ArgumentException ae)
{
@@ -362,17 +362,17 @@ namespace Greenshot.Base.Core
public static string SaveWithDialog(ISurface surface, ICaptureDetails captureDetails)
{
string returnValue = null;
- using (SaveImageFileDialog saveImageFileDialog = new SaveImageFileDialog(captureDetails))
+ using (SaveImageFileDialog saveImageFileDialog = new(captureDetails))
{
DialogResult dialogResult = saveImageFileDialog.ShowDialog();
if (!dialogResult.Equals(DialogResult.OK)) return returnValue;
try
{
string fileNameWithExtension = saveImageFileDialog.FileNameWithExtension;
- SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(FormatForFilename(fileNameWithExtension));
+ SurfaceOutputSettings outputSettings = new(FormatForFilename(fileNameWithExtension));
if (CoreConfig.OutputFilePromptQuality)
{
- QualityDialog qualityDialog = new QualityDialog(outputSettings);
+ QualityDialog qualityDialog = new(outputSettings);
qualityDialog.ShowDialog();
}
@@ -410,7 +410,7 @@ namespace Greenshot.Base.Core
// Prevent problems with "other characters", which causes a problem in e.g. Outlook 2007 or break our HTML
filename = Regex.Replace(filename, @"[^\d\w\.]", "_");
// Remove multiple "_"
- filename = Regex.Replace(filename, @"_+", "_");
+ filename = Regex.Replace(filename, "_+", "_");
string tmpFile = Path.Combine(Path.GetTempPath(), filename);
Log.Debug("Creating TMP File: " + tmpFile);
@@ -495,7 +495,7 @@ namespace Greenshot.Base.Core
///
/// Cleanup all created tmpfiles
- ///
+ ///
public static void RemoveTmpFiles()
{
foreach (string tmpFile in TmpFileCache.Elements)
@@ -625,7 +625,7 @@ namespace Greenshot.Base.Core
// Start at -14 read "GreenshotXX.YY" (XX=Major, YY=Minor)
const int markerSize = 14;
surfaceFileStream.Seek(-markerSize, SeekOrigin.End);
- using (StreamReader streamReader = new StreamReader(surfaceFileStream))
+ using (StreamReader streamReader = new(surfaceFileStream))
{
var greenshotMarker = streamReader.ReadToEnd();
if (!greenshotMarker.StartsWith("Greenshot"))
@@ -636,7 +636,7 @@ namespace Greenshot.Base.Core
Log.InfoFormat("Greenshot file format: {0}", greenshotMarker);
const int filesizeLocation = 8 + markerSize;
surfaceFileStream.Seek(-filesizeLocation, SeekOrigin.End);
- using BinaryReader reader = new BinaryReader(surfaceFileStream);
+ using BinaryReader reader = new(surfaceFileStream);
long bytesWritten = reader.ReadInt64();
surfaceFileStream.Seek(-(bytesWritten + filesizeLocation), SeekOrigin.End);
returnSurface.LoadElementsFromStream(surfaceFileStream);
diff --git a/src/Greenshot.Base/Core/JSONHelper.cs b/src/Greenshot.Base/Core/JSONHelper.cs
index 7e7ac97eb..22d018305 100644
--- a/src/Greenshot.Base/Core/JSONHelper.cs
+++ b/src/Greenshot.Base/Core/JSONHelper.cs
@@ -17,10 +17,10 @@ namespace Greenshot.Base.Core
///
/// This parses a JSON response, a modified version of the code found at:
/// See: https://techblog.procurios.nl/k/n618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
- ///
+ ///
/// This file is under the MIT License, which is GPL Compatible and according to: https://en.wikipedia.org/wiki/MIT_License
/// can be used under the GPL "umbrella".
- ///
+ ///
/// TODO: code should be replaced when upgrading to .NET 3.5 or higher!!
///
public class JSONHelper
@@ -80,55 +80,54 @@ namespace Greenshot.Base.Core
// {
NextToken(json, ref index);
- bool done = false;
+ const bool done = false;
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
- public class Language
+ public static class Language
{
private static readonly ILog Log = LogManager.GetLogger(typeof(Language));
private static readonly List LanguagePaths = new();
private static readonly Dictionary> LanguageFiles = new();
private static readonly Dictionary HelpFiles = new();
private const string DefaultLanguage = "en-US";
- private const string HelpFilenamePattern = @"help-*.html";
- private const string LanguageFilenamePattern = @"language*.xml";
- private static readonly Regex PrefixRegexp = new(@"language_([a-zA-Z0-9]+).*");
- private static readonly Regex IetfRegexp = new(@"^.*([a-zA-Z]{2,3}-([a-zA-Z]{1,2})|[a-zA-Z]{2,3}-x-[a-zA-Z]+)$");
+ private const string HelpFilenamePattern = "help-*.html";
+ private const string LanguageFilenamePattern = "language*.xml";
+ private static readonly Regex PrefixRegexp = new("language_([a-zA-Z0-9]+).*");
+ private static readonly Regex IetfRegexp = new("^.*([a-zA-Z]{2,3}-([a-zA-Z]{1,2})|[a-zA-Z]{2,3}-x-[a-zA-Z]+)$");
private const string LanguageGroupsKey = @"SYSTEM\CurrentControlSet\Control\Nls\Language Groups";
private static readonly List UnsupportedLanguageGroups = new();
private static readonly Dictionary Resources = new();
@@ -88,7 +88,7 @@ namespace Greenshot.Base.Core
// Startup path
if (applicationFolder != null)
{
- AddPath(Path.Combine(applicationFolder, @"Languages"));
+ AddPath(Path.Combine(applicationFolder, "Languages"));
}
}
catch (Exception pathException)
@@ -104,7 +104,7 @@ namespace Greenshot.Base.Core
string[] groups = languageGroupsKey.GetValueNames();
foreach (string group in groups)
{
- string groupValue = (string) languageGroupsKey.GetValue(group);
+ string groupValue = (string)languageGroupsKey.GetValue(group);
bool isGroupNotInstalled = "0".Equals(groupValue);
if (isGroupNotInstalled)
{
@@ -218,7 +218,7 @@ namespace Greenshot.Base.Core
{
Resources.Clear();
LoadFiles(DefaultLanguage);
- if (_currentLanguage != null && !_currentLanguage.Equals(DefaultLanguage))
+ if (_currentLanguage?.Equals(DefaultLanguage) == false)
{
LoadFiles(_currentLanguage);
}
@@ -239,7 +239,7 @@ namespace Greenshot.Base.Core
}
else
{
- if (_currentLanguage == null || !_currentLanguage.Equals(ietf))
+ if (_currentLanguage?.Equals(ietf) != true)
{
_currentLanguage = ietf;
Reload();
@@ -328,18 +328,7 @@ namespace Greenshot.Base.Core
///
/// Return the path to the help-file
///
- public static string HelpFilePath
- {
- get
- {
- if (HelpFiles.ContainsKey(_currentLanguage))
- {
- return HelpFiles[_currentLanguage];
- }
-
- return HelpFiles[DefaultLanguage];
- }
- }
+ public static string HelpFilePath => HelpFiles.ContainsKey(_currentLanguage) ? HelpFiles[_currentLanguage] : HelpFiles[DefaultLanguage];
///
/// Load the resources from the language file
@@ -350,7 +339,7 @@ namespace Greenshot.Base.Core
Log.InfoFormat("Loading language file {0}", languageFile.Filepath);
try
{
- XmlDocument xmlDocument = new XmlDocument();
+ XmlDocument xmlDocument = new();
xmlDocument.Load(languageFile.Filepath);
XmlNodeList resourceNodes = xmlDocument.GetElementsByTagName("resource");
foreach (XmlNode resourceNode in resourceNodes)
@@ -571,32 +560,21 @@ namespace Greenshot.Base.Core
}
return null;
}
-
+
///
/// Check if a resource with prefix.key exists
///
///
///
/// 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)
- {
- if (key == null)
- {
- return false;
- }
-
- return Resources.ContainsKey(key);
- }
+ public static bool HasKey(string key) => key != null && Resources.ContainsKey(key);
///
/// TryGet method which combines HasKey & GetString
@@ -604,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
@@ -616,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
@@ -628,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
@@ -642,12 +611,7 @@ namespace Greenshot.Base.Core
{
string typename = key.GetType().Name;
string enumKey = typename + "." + key;
- if (HasKey(enumKey))
- {
- return GetString(enumKey);
- }
-
- return key.ToString();
+ return HasKey(enumKey) ? GetString(enumKey) : key.ToString();
}
///
@@ -655,15 +619,7 @@ namespace Greenshot.Base.Core
///
/// Enum
/// resource or a "string ###key### not found"
- public static string GetString(Enum key)
- {
- if (key == null)
- {
- return null;
- }
-
- return GetString(key.ToString());
- }
+ public static string GetString(Enum key) => key == null ? null : GetString(key.ToString());
///
/// Get the resource for prefix.key
@@ -671,15 +627,7 @@ namespace Greenshot.Base.Core
/// string
/// Enum
/// resource or a "string ###prefix.key### not found"
- public static string GetString(string prefix, Enum key)
- {
- if (key == null)
- {
- return null;
- }
-
- return GetString(prefix + "." + key);
- }
+ public static string GetString(string prefix, Enum key) => key == null ? null : GetString(prefix + "." + key);
///
/// Get the resource for prefix.key
@@ -687,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
@@ -704,63 +649,41 @@ namespace Greenshot.Base.Core
return null;
}
- if (!Resources.TryGetValue(key, out var returnValue))
- {
- return "string ###" + key + "### not found";
- }
-
- return returnValue;
+ return !Resources.TryGetValue(key, out var returnValue) ? "string ###" + key + "### not found" : returnValue;
}
///
- /// Get the resource for key, format with with string.format an supply the parameters
+ /// Get the resource for key, format with string.format an supply the parameters
///
/// 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
+ /// Get the resource for prefix.key, format with string.format an supply the parameters
///
/// string
/// 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
+ /// Get the resource for prefix.key, format with string.format an supply the parameters
///
/// string
/// 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
+ /// Get the resource for key, format with string.format an supply the parameters
///
/// string
/// object
/// formatted resource or a "string ###key### not found"
- public static string GetFormattedString(string key, object param)
- {
- if (!Resources.TryGetValue(key, out var returnValue))
- {
- return "string ###" + key + "### not found";
- }
-
- return 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/LanguageFile.cs b/src/Greenshot.Base/Core/LanguageFile.cs
index b9f8a57c4..5b362d032 100644
--- a/src/Greenshot.Base/Core/LanguageFile.cs
+++ b/src/Greenshot.Base/Core/LanguageFile.cs
@@ -57,7 +57,7 @@ namespace Greenshot.Base.Core
return false;
}
}
- else if (other != null && other.Version != null)
+ else if (other?.Version != null)
{
return false;
}
diff --git a/src/Greenshot.Base/Core/LogHelper.cs b/src/Greenshot.Base/Core/LogHelper.cs
index 42cabddd4..290431a47 100644
--- a/src/Greenshot.Base/Core/LogHelper.cs
+++ b/src/Greenshot.Base/Core/LogHelper.cs
@@ -88,12 +88,11 @@ namespace Greenshot.Base.Core
// Get the logfile name
try
{
- if (((Hierarchy) LogManager.GetRepository()).Root.Appenders.Count > 0)
+ if (((Hierarchy)LogManager.GetRepository()).Root.Appenders.Count > 0)
{
- foreach (IAppender appender in ((Hierarchy) LogManager.GetRepository()).Root.Appenders)
+ foreach (IAppender appender in ((Hierarchy)LogManager.GetRepository()).Root.Appenders)
{
- var fileAppender = appender as FileAppender;
- if (fileAppender != null)
+ if (appender is FileAppender fileAppender)
{
return fileAppender.File;
}
@@ -117,7 +116,7 @@ namespace Greenshot.Base.Core
{
protected override void Convert(TextWriter writer, object state)
{
- Environment.SpecialFolder specialFolder = (Environment.SpecialFolder) Enum.Parse(typeof(Environment.SpecialFolder), Option, true);
+ Environment.SpecialFolder specialFolder = (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), Option, true);
writer.Write(Environment.GetFolderPath(specialFolder));
}
}
diff --git a/src/Greenshot.Base/Core/NetworkHelper.cs b/src/Greenshot.Base/Core/NetworkHelper.cs
index 88cfff569..fbdb82de1 100644
--- a/src/Greenshot.Base/Core/NetworkHelper.cs
+++ b/src/Greenshot.Base/Core/NetworkHelper.cs
@@ -77,7 +77,7 @@ namespace Greenshot.Base.Core
public static MemoryStream GetAsMemoryStream(string url)
{
var request = CreateWebRequest(url);
- using var response = (HttpWebResponse) request.GetResponse();
+ using var response = (HttpWebResponse)request.GetResponse();
var memoryStream = new MemoryStream();
using (var responseStream = response.GetResponseStream())
{
@@ -99,7 +99,7 @@ namespace Greenshot.Base.Core
var fileFormatHandlers = SimpleServiceProvider.Current.GetAllInstances();
var extensions = string.Join("|", fileFormatHandlers.ExtensionsFor(FileFormatHandlerActions.LoadFromStream));
- var imageUrlRegex = new Regex($@"(http|https)://.*(?{extensions})");
+ var imageUrlRegex = new Regex($"(http|https)://.*(?{extensions})");
var match = imageUrlRegex.Match(url);
try
{
@@ -162,7 +162,7 @@ namespace Greenshot.Base.Core
var extensions = string.Join("|", fileFormatHandlers.ExtensionsFor(FileFormatHandlerActions.LoadFromStream));
- var imageUrlRegex = new Regex($@"(http|https)://.*(?{extensions})");
+ var imageUrlRegex = new Regex($"(http|https)://.*(?{extensions})");
var match = imageUrlRegex.Match(url);
try
{
@@ -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
@@ -250,7 +244,7 @@ namespace Greenshot.Base.Core
/// WebRequest
public static HttpWebRequest CreateWebRequest(Uri uri)
{
- var webRequest = (HttpWebRequest) WebRequest.Create(uri);
+ var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Proxy = Config.UseProxy ? CreateProxy(uri) : null;
// Make sure the default credentials are available
webRequest.Credentials = CredentialCache.DefaultCredentials;
@@ -352,7 +346,6 @@ namespace Greenshot.Base.Core
}
return result.ToString();
-
}
///
@@ -594,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
@@ -617,7 +607,7 @@ namespace Greenshot.Base.Core
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
- using StreamReader reader = new StreamReader(responseStream, true);
+ using StreamReader reader = new(responseStream, true);
responseData = reader.ReadToEnd();
}
}
@@ -638,9 +628,9 @@ namespace Greenshot.Base.Core
bool isHttpError = false;
try
{
- response = (HttpWebResponse) webRequest.GetResponse();
+ response = (HttpWebResponse)webRequest.GetResponse();
Log.InfoFormat("Response status: {0}", response.StatusCode);
- isHttpError = (int) response.StatusCode >= 300;
+ isHttpError = (int)response.StatusCode >= 300;
if (isHttpError)
{
Log.ErrorFormat("HTTP error {0}", response.StatusCode);
@@ -655,7 +645,7 @@ namespace Greenshot.Base.Core
}
catch (WebException e)
{
- response = (HttpWebResponse) e.Response;
+ response = (HttpWebResponse)e.Response;
HttpStatusCode statusCode = HttpStatusCode.Unused;
if (response != null)
{
@@ -731,9 +721,9 @@ namespace Greenshot.Base.Core
/// string
public string ToBase64String(Base64FormattingOptions formattingOptions)
{
- using MemoryStream stream = new MemoryStream();
+ using MemoryStream stream = new();
ImageIO.SaveToStream(_surface, stream, _outputSettings);
- return Convert.ToBase64String(stream.GetBuffer(), 0, (int) stream.Length, formattingOptions);
+ return Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length, formattingOptions);
}
///
@@ -743,7 +733,7 @@ namespace Greenshot.Base.Core
/// byte[]
public byte[] ToByteArray()
{
- using MemoryStream stream = new MemoryStream();
+ using MemoryStream stream = new();
ImageIO.SaveToStream(_surface, stream, _outputSettings);
return stream.ToArray();
}
@@ -767,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/LocalJsonReceiver.cs b/src/Greenshot.Base/Core/OAuth/LocalJsonReceiver.cs
index ffb6867bf..41c6bfc81 100644
--- a/src/Greenshot.Base/Core/OAuth/LocalJsonReceiver.cs
+++ b/src/Greenshot.Base/Core/OAuth/LocalJsonReceiver.cs
@@ -39,7 +39,7 @@ namespace Greenshot.Base.Core.OAuth
public class LocalJsonReceiver
{
private static readonly ILog Log = LogManager.GetLogger(typeof(LocalJsonReceiver));
- private readonly ManualResetEvent _ready = new ManualResetEvent(true);
+ private readonly ManualResetEvent _ready = new(true);
private IDictionary _returnValues;
///
@@ -121,7 +121,7 @@ namespace Greenshot.Base.Core.OAuth
/// IAsyncResult
private void ListenerCallback(IAsyncResult result)
{
- HttpListener listener = (HttpListener) result.AsyncState;
+ HttpListener listener = (HttpListener)result.AsyncState;
//If not listening return immediately as this method is called one last time after Close()
if (!listener.IsListening)
@@ -192,7 +192,7 @@ namespace Greenshot.Base.Core.OAuth
try
{
listener.Start();
- return ((IPEndPoint) listener.LocalEndpoint).Port;
+ return ((IPEndPoint)listener.LocalEndpoint).Port;
}
finally
{
diff --git a/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs b/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs
index f079598a3..2f855f2d3 100644
--- a/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs
+++ b/src/Greenshot.Base/Core/OAuth/LocalServerCodeReceiver.cs
@@ -38,7 +38,7 @@ namespace Greenshot.Base.Core.OAuth
public class LocalServerCodeReceiver
{
private static readonly ILog Log = LogManager.GetLogger(typeof(LocalServerCodeReceiver));
- private readonly ManualResetEvent _ready = new ManualResetEvent(true);
+ private readonly ManualResetEvent _ready = new(true);
///
/// The call back format. Expects one port parameter.
@@ -47,7 +47,7 @@ namespace Greenshot.Base.Core.OAuth
public string LoopbackCallbackUrl { get; set; } = "http://localhost:{0}/authorize/";
///
- /// HTML code to to return the _browser, default it will try to close the _browser / tab, this won't always work.
+ /// HTML code to return the _browser, default it will try to close the _browser / tab, this won't always work.
/// You can use CloudServiceName where you want to show the CloudServiceName from your OAuth2 settings
///
public string ClosePageResponse { get; set; } = @"
@@ -71,24 +71,12 @@ Greenshot received information from CloudServiceName. You can close this browser
///
/// The URL to redirect to
///
- protected string RedirectUri
- {
- get
- {
- if (!string.IsNullOrEmpty(_redirectUri))
- {
- return _redirectUri;
- }
-
- return _redirectUri = string.Format(LoopbackCallbackUrl, GetRandomUnusedPort());
- }
- }
+ protected string RedirectUri => !string.IsNullOrEmpty(_redirectUri) ? _redirectUri : (_redirectUri = string.Format(LoopbackCallbackUrl, GetRandomUnusedPort()));
private string _cloudServiceName;
private readonly IDictionary _returnValues = new Dictionary();
-
///
/// The OAuth code receiver
///
@@ -142,7 +130,7 @@ Greenshot received information from CloudServiceName. You can close this browser
/// IAsyncResult
private void ListenerCallback(IAsyncResult result)
{
- HttpListener listener = (HttpListener) result.AsyncState;
+ HttpListener listener = (HttpListener)result.AsyncState;
//If not listening return immediately as this method is called one last time after Close()
if (!listener.IsListening)
@@ -153,7 +141,6 @@ Greenshot received information from CloudServiceName. You can close this browser
// Use EndGetContext to complete the asynchronous operation.
HttpListenerContext context = listener.EndGetContext(result);
-
// Handle request
HttpListenerRequest request = context.Request;
try
@@ -199,7 +186,7 @@ Greenshot received information from CloudServiceName. You can close this browser
try
{
listener.Start();
- return ((IPEndPoint) listener.LocalEndpoint).Port;
+ return ((IPEndPoint)listener.LocalEndpoint).Port;
}
finally
{
diff --git a/src/Greenshot.Base/Core/OAuth/OAuth2Helper.cs b/src/Greenshot.Base/Core/OAuth/OAuth2Helper.cs
index 8c77a0fff..137009a89 100644
--- a/src/Greenshot.Base/Core/OAuth/OAuth2Helper.cs
+++ b/src/Greenshot.Base/Core/OAuth/OAuth2Helper.cs
@@ -82,7 +82,7 @@ namespace Greenshot.Base.Core.OAuth
throw new Exception($"{refreshTokenResult["error"]} - {refreshTokenResult["error_description"]}");
}
- throw new Exception((string) refreshTokenResult["error"]);
+ throw new Exception((string)refreshTokenResult["error"]);
}
// gives as described here: https://developers.google.com/identity/protocols/OAuth2InstalledApp
@@ -92,12 +92,12 @@ namespace Greenshot.Base.Core.OAuth
// "refresh_token":"1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
if (refreshTokenResult.ContainsKey(AccessToken))
{
- settings.AccessToken = (string) refreshTokenResult[AccessToken];
+ settings.AccessToken = (string)refreshTokenResult[AccessToken];
}
if (refreshTokenResult.ContainsKey(RefreshToken))
{
- settings.RefreshToken = (string) refreshTokenResult[RefreshToken];
+ settings.RefreshToken = (string)refreshTokenResult[RefreshToken];
}
if (refreshTokenResult.ContainsKey(ExpiresIn))
@@ -105,7 +105,7 @@ namespace Greenshot.Base.Core.OAuth
object seconds = refreshTokenResult[ExpiresIn];
if (seconds != null)
{
- settings.AccessTokenExpires = DateTimeOffset.Now.AddSeconds((double) seconds);
+ settings.AccessTokenExpires = DateTimeOffset.Now.AddSeconds((double)seconds);
}
}
@@ -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);
}
}
@@ -187,7 +184,7 @@ namespace Greenshot.Base.Core.OAuth
IDictionary accessTokenResult = JSONHelper.JsonDecode(accessTokenJsonResult);
if (accessTokenResult.ContainsKey("error"))
{
- if ("invalid_grant" == (string) accessTokenResult["error"])
+ if ((string)accessTokenResult["error"] == "invalid_grant")
{
// Refresh token has also expired, we need a new one!
settings.RefreshToken = null;
@@ -202,19 +199,19 @@ namespace Greenshot.Base.Core.OAuth
throw new Exception($"{accessTokenResult["error"]} - {accessTokenResult["error_description"]}");
}
- throw new Exception((string) accessTokenResult["error"]);
+ throw new Exception((string)accessTokenResult["error"]);
}
if (accessTokenResult.ContainsKey(AccessToken))
{
- settings.AccessToken = (string) accessTokenResult[AccessToken];
+ settings.AccessToken = (string)accessTokenResult[AccessToken];
settings.AccessTokenExpires = DateTimeOffset.MaxValue;
}
if (accessTokenResult.ContainsKey(RefreshToken))
{
// Refresh the refresh token :)
- settings.RefreshToken = (string) accessTokenResult[RefreshToken];
+ settings.RefreshToken = (string)accessTokenResult[RefreshToken];
}
if (accessTokenResult.ContainsKey(ExpiresIn))
@@ -222,7 +219,7 @@ namespace Greenshot.Base.Core.OAuth
object seconds = accessTokenResult[ExpiresIn];
if (seconds != null)
{
- settings.AccessTokenExpires = DateTimeOffset.Now.AddSeconds((double) seconds);
+ settings.AccessTokenExpires = DateTimeOffset.Now.AddSeconds((double)seconds);
}
}
}
@@ -288,7 +285,7 @@ namespace Greenshot.Base.Core.OAuth
throw new Exception(errorDescription);
}
- if ("access_denied" == error)
+ if (error == "access_denied")
{
throw new UnauthorizedAccessException("Access denied");
}
@@ -324,7 +321,7 @@ namespace Greenshot.Base.Core.OAuth
throw new ArgumentNullException(nameof(settings.BrowserSize));
}
- OAuthLoginForm loginForm = new OAuthLoginForm($"Authorize {settings.CloudServiceName}", settings.BrowserSize, settings.FormattedAuthUrl, settings.RedirectUrl);
+ OAuthLoginForm loginForm = new($"Authorize {settings.CloudServiceName}", settings.BrowserSize, settings.FormattedAuthUrl, settings.RedirectUrl);
loginForm.ShowDialog();
if (!loginForm.IsOk) return false;
if (loginForm.CallbackParameters.TryGetValue(Code, out var code) && !string.IsNullOrEmpty(code))
@@ -362,7 +359,7 @@ namespace Greenshot.Base.Core.OAuth
throw new Exception(errorDescription);
}
- if ("access_denied" == error)
+ if (error == "access_denied")
{
throw new UnauthorizedAccessException("Access denied");
}
@@ -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/OAuth2Settings.cs b/src/Greenshot.Base/Core/OAuth/OAuth2Settings.cs
index 42345c49c..0a06d7462 100644
--- a/src/Greenshot.Base/Core/OAuth/OAuth2Settings.cs
+++ b/src/Greenshot.Base/Core/OAuth/OAuth2Settings.cs
@@ -96,7 +96,7 @@ namespace Greenshot.Base.Core.OAuth
public string AccessToken { get; set; }
///
- /// Expire time for the AccessToken, this this time (-60 seconds) is passed a new AccessToken needs to be generated with the RefreshToken
+ /// Expire time for the AccessToken, this time (-60 seconds) is passed a new AccessToken needs to be generated with the RefreshToken
///
public DateTimeOffset AccessTokenExpires { get; set; }
diff --git a/src/Greenshot.Base/Core/OAuth/OAuthSession.cs b/src/Greenshot.Base/Core/OAuth/OAuthSession.cs
index d0cc833d8..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
{
@@ -58,11 +59,9 @@ namespace Greenshot.Base.Core.OAuth
protected const string HMACSHA1SignatureType = "HMAC-SHA1";
protected const string PlainTextSignatureType = "PLAINTEXT";
- protected static Random random = new Random();
+ protected static Random random = new();
protected const string UnreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
-
- private string _userAgent = "Greenshot";
private IDictionary _requestTokenResponseParameters;
public IDictionary RequestTokenParameters { get; } = new Dictionary();
@@ -94,11 +93,7 @@ namespace Greenshot.Base.Core.OAuth
public bool UseMultipartFormData { get; set; }
- public string UserAgent
- {
- get { return _userAgent; }
- set { _userAgent = value; }
- }
+ public string UserAgent { get; set; } = "Greenshot";
public string CallbackUrl { get; set; } = "https://getgreenshot.org";
@@ -166,7 +161,7 @@ namespace Greenshot.Base.Core.OAuth
queryParameters = new SortedDictionary(queryParameters);
- StringBuilder sb = new StringBuilder();
+ StringBuilder sb = new();
foreach (string key in queryParameters.Keys)
{
if (queryParameters[key] is string)
@@ -189,7 +184,7 @@ namespace Greenshot.Base.Core.OAuth
/// Returns a Url encoded string (unicode) with UTF-8 encoded % values
public static string UrlEncode3986(string value)
{
- StringBuilder result = new StringBuilder();
+ StringBuilder result = new();
foreach (char symbol in value)
{
@@ -225,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
@@ -269,37 +262,29 @@ namespace Greenshot.Base.Core.OAuth
{
if (string.IsNullOrEmpty(Token))
{
- Exception e = new Exception("The request token is not set, service responded with: " + requestTokenResponse);
+ Exception e = new("The request token is not set, service responded with: " + requestTokenResponse);
throw e;
}
Log.DebugFormat("Opening AuthorizationLink: {0}", AuthorizationLink);
- OAuthLoginForm oAuthLoginForm = new OAuthLoginForm(LoginTitle, BrowserSize, AuthorizationLink, CallbackUrl);
+ 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;
}
}
if (CheckVerifier)
{
- if (!string.IsNullOrEmpty(Verifier))
- {
- return Token;
- }
-
- return null;
+ return !string.IsNullOrEmpty(Verifier) ? Token : null;
}
return Token;
@@ -313,7 +298,7 @@ namespace Greenshot.Base.Core.OAuth
{
if (string.IsNullOrEmpty(Token) || (CheckVerifier && string.IsNullOrEmpty(Verifier)))
{
- Exception e = new Exception("The request token and verifier were not set");
+ Exception e = new("The request token and verifier were not set");
throw e;
}
@@ -394,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.
@@ -410,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.
@@ -426,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.
@@ -455,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
@@ -490,15 +463,10 @@ namespace Greenshot.Base.Core.OAuth
Token = null;
TokenSecret = null;
// Remove oauth keys, so they aren't added double
- List keysToDelete = new List();
- foreach (string parameterKey in parametersToSign.Keys)
- {
- if (parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX))
- {
- keysToDelete.Add(parameterKey);
- }
- }
-
+ List keysToDelete = new();
+ keysToDelete.AddRange(from string parameterKey in parametersToSign.Keys
+ where parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX)
+ select parameterKey);
foreach (string keyToDelete in keysToDelete)
{
parametersToSign.Remove(keyToDelete);
@@ -529,13 +497,13 @@ namespace Greenshot.Base.Core.OAuth
}
// Build the signature base
- StringBuilder signatureBase = new StringBuilder();
+ StringBuilder signatureBase = new();
// Add Method to signature base
signatureBase.Append(method).Append("&");
// Add normalized URL
- Uri url = new Uri(requestUrl);
+ Uri url = new(requestUrl);
string normalizedUrl = string.Format(CultureInfo.InvariantCulture, "{0}://{1}", url.Scheme, url.Host);
if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443)))
{
@@ -586,7 +554,7 @@ namespace Greenshot.Base.Core.OAuth
break;
default:
// Generate Signature and add it to the parameters
- HMACSHA1 hmacsha1 = new HMACSHA1
+ HMACSHA1 hmacsha1 = new()
{
Key = Encoding.UTF8.GetBytes(key)
};
@@ -643,19 +611,16 @@ 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
HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(requestUrl, method);
webRequest.ServicePoint.Expect100Continue = false;
- webRequest.UserAgent = _userAgent;
+ webRequest.UserAgent = UserAgent;
if (UseHttpHeadersForAuthorization && authHeader != null)
{
@@ -679,12 +644,11 @@ namespace Greenshot.Base.Core.OAuth
}
else
{
- StringBuilder form = new StringBuilder();
+ StringBuilder form = new();
foreach (string parameterKey in requestParameters.Keys)
{
- var binaryParameter = parameters[parameterKey] as IBinaryContainer;
form.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey),
- binaryParameter != null ? UrlEncode3986(binaryParameter.ToBase64String(Base64FormattingOptions.None)) : UrlEncode3986($"{parameters[parameterKey]}"));
+ parameters[parameterKey] is IBinaryContainer binaryParameter ? UrlEncode3986(binaryParameter.ToBase64String(Base64FormattingOptions.None)) : UrlEncode3986($"{parameters[parameterKey]}"));
}
// Remove trailing &
diff --git a/src/Greenshot.Base/Core/ObjectExtensions.cs b/src/Greenshot.Base/Core/ObjectExtensions.cs
index 45f0585b1..22bfa00f3 100644
--- a/src/Greenshot.Base/Core/ObjectExtensions.cs
+++ b/src/Greenshot.Base/Core/ObjectExtensions.cs
@@ -57,7 +57,7 @@ namespace Greenshot.Base.Core
using var stream = new MemoryStream();
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
- return (T) formatter.Deserialize(stream);
+ return (T)formatter.Deserialize(stream);
}
///
diff --git a/src/Greenshot.Base/Core/PluginUtils.cs b/src/Greenshot.Base/Core/PluginUtils.cs
index d41e545a5..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
@@ -84,7 +81,7 @@ namespace Greenshot.Base.Core
if (key != null)
{
// "" is the default key, which should point to the requested location
- return (string) key.GetValue(string.Empty);
+ return (string)key.GetValue(string.Empty);
}
}
diff --git a/src/Greenshot.Base/Core/QuantizerHelper.cs b/src/Greenshot.Base/Core/QuantizerHelper.cs
index ec414968b..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;
}
}
@@ -130,7 +127,7 @@ namespace Greenshot.Base.Core
{
this.sourceBitmap = sourceBitmap;
// Make sure the color count variables are reset
- BitArray bitArray = new BitArray((int) Math.Pow(2, 24));
+ BitArray bitArray = new((int)Math.Pow(2, 24));
colorCount = 0;
// creates all the cubes
@@ -167,7 +164,6 @@ namespace Greenshot.Base.Core
// Use a bitmap to store the initial match, which is just as good as an array and saves us 2x the storage
using IFastBitmap sourceFastBitmap = FastBitmap.Create(sourceBitmap);
- IFastBitmapWithBlend sourceFastBitmapWithBlend = sourceFastBitmap as IFastBitmapWithBlend;
sourceFastBitmap.Lock();
using FastChunkyBitmap destinationFastBitmap = FastBitmap.CreateEmpty(sourceBitmap.Size, PixelFormat.Format8bppIndexed, Color.White) as FastChunkyBitmap;
destinationFastBitmap.Lock();
@@ -175,15 +171,9 @@ namespace Greenshot.Base.Core
{
for (int x = 0; x < sourceFastBitmap.Width; x++)
{
- Color color;
- if (sourceFastBitmapWithBlend == null)
- {
- 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;
@@ -207,7 +197,7 @@ namespace Greenshot.Base.Core
// Store the initial "match"
int paletteIndex = (indexRed << 10) + (indexRed << 6) + indexRed + (indexGreen << 5) + indexGreen + indexBlue;
- destinationFastBitmap.SetColorIndexAt(x, y, (byte) (paletteIndex & 0xff));
+ destinationFastBitmap.SetColorIndexAt(x, y, (byte)(paletteIndex & 0xff));
}
}
@@ -217,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
@@ -228,13 +215,12 @@ namespace Greenshot.Base.Core
/// Bitmap
public Bitmap SimpleReindex()
{
- List colors = new List();
- Dictionary lookup = new Dictionary();
+ List colors = new();
+ Dictionary lookup = new();
using (FastChunkyBitmap bbbDest = FastBitmap.Create(resultBitmap) as FastChunkyBitmap)
{
bbbDest.Lock();
using IFastBitmap bbbSrc = FastBitmap.Create(sourceBitmap);
- IFastBitmapWithBlend bbbSrcBlend = bbbSrc as IFastBitmapWithBlend;
bbbSrc.Lock();
byte index;
@@ -242,16 +228,7 @@ namespace Greenshot.Base.Core
{
for (int x = 0; x < bbbSrc.Width; x++)
{
- Color color;
- if (bbbSrcBlend != null)
- {
- 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];
@@ -259,7 +236,7 @@ namespace Greenshot.Base.Core
else
{
colors.Add(color);
- index = (byte) (colors.Count - 1);
+ index = (byte)(colors.Count - 1);
lookup.Add(color, index);
}
@@ -273,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;
@@ -364,9 +334,9 @@ namespace Greenshot.Base.Core
if (weight > 0)
{
- lookupRed[k] = (int) (Volume(cubes[k], momentsRed) / weight);
- lookupGreen[k] = (int) (Volume(cubes[k], momentsGreen) / weight);
- lookupBlue[k] = (int) (Volume(cubes[k], momentsBlue) / weight);
+ lookupRed[k] = (int)(Volume(cubes[k], momentsRed) / weight);
+ lookupGreen[k] = (int)(Volume(cubes[k], momentsGreen) / weight);
+ lookupBlue[k] = (int)(Volume(cubes[k], momentsBlue) / weight);
}
else
{
@@ -386,14 +356,13 @@ namespace Greenshot.Base.Core
using (FastChunkyBitmap dest = FastBitmap.Create(resultBitmap) as FastChunkyBitmap)
{
using IFastBitmap src = FastBitmap.Create(sourceBitmap);
- IFastBitmapWithBlend srcBlend = src as IFastBitmapWithBlend;
- Dictionary lookup = new Dictionary();
+ Dictionary lookup = new();
for (int y = 0; y < src.Height; y++)
{
for (int x = 0; x < src.Width; x++)
{
Color color;
- if (srcBlend != null)
+ if (src is IFastBitmapWithBlend srcBlend)
{
// WithoutAlpha, this makes it possible to ignore the alpha
color = srcBlend.GetBlendedColorAt(x, y);
@@ -423,12 +392,12 @@ namespace Greenshot.Base.Core
int deltaGreen = color.G - foundGreen;
int deltaBlue = color.B - foundBlue;
- int distance = deltaRed * deltaRed + deltaGreen * deltaGreen + deltaBlue * deltaBlue;
+ int distance = (deltaRed * deltaRed) + (deltaGreen * deltaGreen) + (deltaBlue * deltaBlue);
if (distance < bestDistance)
{
bestDistance = distance;
- bestMatch = (byte) lookupIndex;
+ bestMatch = (byte)lookupIndex;
}
}
@@ -450,7 +419,6 @@ namespace Greenshot.Base.Core
}
}
-
// generates palette
ColorPalette imagePalette = resultBitmap.Palette;
Color[] entries = imagePalette.Entries;
@@ -531,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] -
@@ -541,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] -
@@ -556,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.
@@ -615,7 +571,7 @@ namespace Greenshot.Base.Core
float volumeMoment = VolumeFloat(cube, moments);
float volumeWeight = Volume(cube, weights);
- float distance = volumeRed * volumeRed + volumeGreen * volumeGreen + volumeBlue * volumeBlue;
+ float distance = (volumeRed * volumeRed) + (volumeGreen * volumeGreen) + (volumeBlue * volumeBlue);
return volumeMoment - (distance / volumeWeight);
}
@@ -644,7 +600,7 @@ namespace Greenshot.Base.Core
// the cube cannot be cut at bottom (this would lead to empty cube)
if (halfWeight != 0)
{
- float halfDistance = (float) halfRed * halfRed + (float) halfGreen * halfGreen + (float) halfBlue * halfBlue;
+ float halfDistance = ((float)halfRed * halfRed) + ((float)halfGreen * halfGreen) + ((float)halfBlue * halfBlue);
float temp = halfDistance / halfWeight;
halfRed = wholeRed - halfRed;
@@ -654,7 +610,7 @@ namespace Greenshot.Base.Core
if (halfWeight != 0)
{
- halfDistance = (float) halfRed * halfRed + (float) halfGreen * halfGreen + (float) halfBlue * halfBlue;
+ halfDistance = ((float)halfRed * halfRed) + ((float)halfGreen * halfGreen) + ((float)halfBlue * halfBlue);
temp += halfDistance / halfWeight;
if (temp > result)
@@ -707,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;
@@ -762,7 +711,7 @@ namespace Greenshot.Base.Core
{
for (int blueIndex = cube.BlueMinimum + 1; blueIndex <= cube.BlueMaximum; ++blueIndex)
{
- tag[(redIndex << 10) + (redIndex << 6) + redIndex + (greenIndex << 5) + greenIndex + blueIndex] = (byte) label;
+ tag[(redIndex << 10) + (redIndex << 6) + redIndex + (greenIndex << 5) + greenIndex + blueIndex] = (byte)label;
}
}
}
diff --git a/src/Greenshot.Base/Core/RegistryKeyExtensions.cs b/src/Greenshot.Base/Core/RegistryKeyExtensions.cs
index 7b5567ce1..0a15f0483 100644
--- a/src/Greenshot.Base/Core/RegistryKeyExtensions.cs
+++ b/src/Greenshot.Base/Core/RegistryKeyExtensions.cs
@@ -50,7 +50,7 @@ namespace Greenshot.Base.Core
if (key != null)
{
- result = (string) key.GetValue(value);
+ result = (string)key.GetValue(value);
}
if (string.IsNullOrEmpty(result))
@@ -67,7 +67,7 @@ namespace Greenshot.Base.Core
{
if (key != null)
{
- result = (string) key.GetValue(value);
+ result = (string)key.GetValue(value);
}
if (!string.IsNullOrEmpty(result)) return result;
@@ -78,7 +78,7 @@ namespace Greenshot.Base.Core
{
if (key != null)
{
- result = (string) key.GetValue(value);
+ result = (string)key.GetValue(value);
}
}
diff --git a/src/Greenshot.Base/Core/SimpleServiceProvider.cs b/src/Greenshot.Base/Core/SimpleServiceProvider.cs
index 084f5b1fd..fe9441e91 100644
--- a/src/Greenshot.Base/Core/SimpleServiceProvider.cs
+++ b/src/Greenshot.Base/Core/SimpleServiceProvider.cs
@@ -17,18 +17,10 @@ namespace Greenshot.Base.Core
public IReadOnlyList GetAllInstances()
{
var typeOfService = typeof(TService);
- if (!_services.TryGetValue(typeOfService, out var results))
- {
- return Array.Empty();
- }
-
- return results.Cast().ToArray();
+ 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)
{
@@ -50,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 73f7d5169..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
@@ -72,7 +69,7 @@ namespace Greenshot.Base.Core
}
else
{
- IDictionary dictionary = (IDictionary) value;
+ IDictionary dictionary = (IDictionary)value;
foreach (var propertyKey in dictionary.Keys)
{
properties.Add(propertyKey, dictionary[propertyKey]);
@@ -81,11 +78,11 @@ namespace Greenshot.Base.Core
}
}
- Regex r = new Regex(@"(?\{)+(?[\w\.\[\]]+)(?:[^}]+)?(?\})+",
+ Regex r = new(@"(?\{)+(?[\w\.\[\]]+)(?:[^}]+)?(?\})+",
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
- List