This commit is contained in:
Michael Adams 2022-07-14 15:10:57 -07:00 committed by GitHub
commit 891133dd63
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
304 changed files with 3591 additions and 6346 deletions

View file

@ -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]
@ -71,3 +77,76 @@ 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
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

View file

@ -54,22 +54,15 @@ namespace Greenshot.Base.Controls
/// </summary>
/// <param name="milliseconds"></param>
/// <returns>Number of frames, 1 if in Terminal Server Session</returns>
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;
/// <summary>
/// Calculate the interval for the timer to animate the frames
/// </summary>
/// <returns>Milliseconds for the interval</returns>
protected int Interval() => (int)1000 / VRefresh;
protected int Interval() => 1000 / VRefresh;
/// <summary>
/// Initialize the animation
@ -119,9 +112,6 @@ namespace Greenshot.Base.Controls
/// <summary>
/// This method will be called every frame, so implement your animation/redraw logic here.
/// </summary>
protected virtual void Animate()
{
throw new NotImplementedException();
}
protected virtual void Animate() => throw new NotImplementedException();
}
}

View file

@ -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)
{
if (screen.Bounds.Contains(Cursor.Position))
foreach (var screen in from Screen screen in Screen.AllScreens
where screen.Bounds.Contains(Cursor.Position)
select screen)
{
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();
}
}

View file

@ -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 (nCmdID == OLECMDID_SHOWSCRIPTERROR)
if (pguidCmdGroup == CGID_DocHostCommandHandler && nCmdID == OLECMDID_SHOWSCRIPTERROR)
{
// 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);
}
}

View file

@ -28,9 +28,6 @@ namespace Greenshot.Base.Controls
/// </summary>
public class FormWithoutActivation : Form
{
protected override bool ShowWithoutActivation
{
get { return true; }
}
protected override bool ShowWithoutActivation => true;
}
}

View file

@ -29,16 +29,6 @@ namespace Greenshot.Base.Controls
/// </summary>
public class GreenshotColumnSorter : IComparer
{
/// <summary>
/// Specifies the column to be sorted
/// </summary>
private int _columnToSort;
/// <summary>
/// Specifies the order in which to sort (i.e. 'Ascending').
/// </summary>
private SortOrder _orderOfSort;
/// <summary>
/// Case insensitive comparer object
/// </summary>
@ -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
/// <summary>
/// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0').
/// </summary>
public int SortColumn
{
set { _columnToSort = value; }
get { return _columnToSort; }
}
public int SortColumn { set; get; }
/// <summary>
/// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending').
/// </summary>
public SortOrder Order
{
set { _orderOfSort = value; }
get { return _orderOfSort; }
}
public SortOrder Order { set; get; }
}
}

View file

@ -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;
}
/// <summary>
/// Get the selected enum value from the combobox, uses generics
/// </summary>
/// <returns>The enum value of the combobox</returns>
public Enum GetSelectedEnum()
{
return _selectedEnum;
}
public Enum GetSelectedEnum() => _selectedEnum;
}
}

View file

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

View file

@ -19,7 +19,6 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#if DEBUG
using System.ComponentModel;
using System.ComponentModel.Design;
@ -48,9 +47,8 @@ namespace Greenshot.Base.Controls
private bool _isDesignModeLanguageSet;
private IDictionary<string, Control> _designTimeControls;
private IDictionary<string, ToolStripItem> _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
/// </summary>
/// <returns></returns>
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; }
/// <summary>
/// When this is set, the form will be brought to the foreground as soon as it is shown.
/// </summary>
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);
/// <summary>
/// This is the basic DpiChangedHandler responsible for all the DPI relative changes
@ -127,14 +108,12 @@ namespace Greenshot.Base.Controls
_designTimeToolStripItems = new Dictionary<string, ToolStripItem>();
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,9 +139,7 @@ namespace Greenshot.Base.Controls
/// <param name="e"></param>
protected override void OnPaint(PaintEventArgs e)
{
if (DesignMode)
{
if (!_isDesignModeLanguageSet)
if (DesignMode && !_isDesignModeLanguageSet)
{
_isDesignModeLanguageSet = true;
try
@ -174,7 +151,6 @@ namespace Greenshot.Base.Controls
// ignored
}
}
}
base.OnPaint(e);
}
@ -189,7 +165,7 @@ namespace Greenshot.Base.Controls
if (!DesignMode)
{
#endif
if (!_applyLanguageManually)
if (!ManualLanguageApply)
{
ApplyLanguage();
}
@ -227,14 +203,11 @@ namespace Greenshot.Base.Controls
/// <param name="e"></param>
protected override void OnClosed(EventArgs e)
{
if (!DesignMode && !_storeFieldsManually)
{
if (DialogResult == DialogResult.OK)
if (!DesignMode && !ManualStoreFields && DialogResult == DialogResult.OK)
{
LOG.Info("Form was closed with OK: storing field values.");
StoreFields();
}
}
base.OnClosed(e);
}
@ -246,7 +219,7 @@ namespace Greenshot.Base.Controls
/// </summary>
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
/// <param name="ce"></param>
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;
}
}

View file

@ -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<int> _needNonShiftModifier = new List<int>();
private readonly IList<int> _needNonAltGrModifier = new List<int>();
private readonly ContextMenuStrip _dummy = new ContextMenuStrip();
private readonly ContextMenuStrip _dummy = new();
/// <summary>
/// Used to make sure that there is no right-click menu available
/// </summary>
public override ContextMenuStrip ContextMenuStrip
{
get { return _dummy; }
set { base.ContextMenuStrip = _dummy; }
get => _dummy;
set => base.ContextMenuStrip = _dummy;
}
/// <summary>
@ -118,13 +118,11 @@ namespace Greenshot.Base.Controls
/// </summary>
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;
}
}
/// <summary>
/// Creates a new HotkeyControl
@ -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"
/// </summary>
private void HotkeyControl_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
private void HotkeyControl_KeyPress(object sender, KeyPressEventArgs e) => e.Handled = true;
/// <summary>
/// Handles some misc keys, such as Ctrl+Delete and Shift+Insert
@ -284,7 +279,7 @@ namespace Greenshot.Base.Controls
/// </summary>
public Keys Hotkey
{
get { return _hotkey; }
get => _hotkey;
set
{
_hotkey = value;
@ -307,7 +302,7 @@ namespace Greenshot.Base.Controls
/// </summary>
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+<key> 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;
/// <summary>
/// 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)

View file

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

View file

@ -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();
}
}

View file

@ -51,15 +51,12 @@ namespace Greenshot.Base.Controls
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (SaveFileDialog != null)
if (disposing && SaveFileDialog != null)
{
SaveFileDialog.Dispose();
SaveFileDialog = null;
}
}
}
public SaveImageFileDialog(ICaptureDetails captureDetails)
{
@ -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
/// </summary>
public string FileName
{
get { return SaveFileDialog.FileName; }
set { SaveFileDialog.FileName = value; }
get => SaveFileDialog.FileName;
set => SaveFileDialog.FileName = value;
}
/// <summary>
@ -150,8 +147,8 @@ namespace Greenshot.Base.Controls
/// </summary>
public string InitialDirectory
{
get { return SaveFileDialog.InitialDirectory; }
set { SaveFileDialog.InitialDirectory = value; }
get => SaveFileDialog.InitialDirectory;
set => SaveFileDialog.InitialDirectory = value;
}
/// <summary>
@ -181,7 +178,7 @@ namespace Greenshot.Base.Controls
/// </summary>
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
/// <summary>
/// sets InitialDirectory and FileName property of a SaveFileDialog smartly, considering default pattern and last used path
/// </summary>
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;

View file

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

View file

@ -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
/// <param name="surface"></param>
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;
/// <summary>
/// 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<IDestination> 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")
};
@ -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<NotifyIcon>().ContextMenuStrip.Handle);
@ -374,7 +350,7 @@ namespace Greenshot.Base.Core
{
if (basisMenuItem.DropDownItems.Count == 0)
{
List<IDestination> subDestinations = new List<IDestination>();
List<IDestination> subDestinations = new();
// Fixing Bug #3536968 by catching the COMException (every exception) and not displaying the "subDestinations"
try
{

View file

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

View file

@ -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<Accessible> list = new List<Accessible>(res.Length);
List<Accessible> 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,22 +177,20 @@ namespace Greenshot.Base.Core
}
}
public IEnumerable<string> 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)
{
foreach (var tab in child.Children)
{
object tabIndex = tab.accessible.get_accState(CHILDID_SELF);
_ = tab.accessible.get_accState(CHILDID_SELF);
var description = tab.accessible.get_accDescription(CHILDID_SELF);
if (!string.IsNullOrEmpty(description))
{
if (description.Contains(Environment.NewLine))
if (!string.IsNullOrEmpty(description) && description.Contains(Environment.NewLine))
{
var url = description.Substring(description.IndexOf(Environment.NewLine)).Trim();
yield return url;
@ -205,19 +198,10 @@ namespace Greenshot.Base.Core
}
}
}
}
}
}
private Accessible(IAccessible acc)
{
accessible = acc ?? throw new Exception();
}
private Accessible(IAccessible acc) => accessible = acc ?? throw new Exception();
private void Activate()
{
accessible.accDoDefaultAction(CHILDID_SELF);
}
private void Activate() => accessible.accDoDefaultAction(CHILDID_SELF);
private static object[] GetAccessibleChildren(IAccessible ao, out int childs)
{

View file

@ -67,7 +67,7 @@ namespace Greenshot.Base.Core
/// <typeparam name="T">Type for the animation, like Point/Rectangle/Size</typeparam>
public abstract class AnimatorBase<T> : IAnimator
{
private readonly Queue<AnimationLeg<T>> _queue = new Queue<AnimationLeg<T>>();
private readonly Queue<AnimationLeg<T>> _queue = new();
/// <summary>
/// Constructor
@ -77,7 +77,7 @@ namespace Greenshot.Base.Core
/// <param name="frames"></param>
/// <param name="easingType"></param>
/// <param name="easingMode"></param>
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
/// <summary>
/// Final animation value, this is including the legs
/// </summary>
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;
/// <summary>
/// This restarts the current animation and changes the last frame
/// </summary>
/// <param name="newDestination"></param>
public void ChangeDestination(T newDestination)
{
ChangeDestination(newDestination, Frames);
}
public void ChangeDestination(T newDestination) => ChangeDestination(newDestination, Frames);
/// <summary>
/// This restarts the current animation and changes the last frame
@ -151,20 +137,14 @@ namespace Greenshot.Base.Core
/// All values will stay the same
/// </summary>
/// <param name="queuedDestination"></param>
public void QueueDestinationLeg(T queuedDestination)
{
QueueDestinationLeg(queuedDestination, Frames, EasingType, EasingMode);
}
public void QueueDestinationLeg(T queuedDestination) => QueueDestinationLeg(queuedDestination, Frames, EasingType, EasingMode);
/// <summary>
/// Queue the destination, it will be used to continue at the last frame
/// </summary>
/// <param name="queuedDestination"></param>
/// <param name="frames"></param>
public void QueueDestinationLeg(T queuedDestination, int frames)
{
QueueDestinationLeg(queuedDestination, frames, EasingType, EasingMode);
}
public void QueueDestinationLeg(T queuedDestination, int frames) => QueueDestinationLeg(queuedDestination, frames, EasingType, EasingMode);
/// <summary>
/// Queue the destination, it will be used to continue at the last frame
@ -172,10 +152,7 @@ namespace Greenshot.Base.Core
/// <param name="queuedDestination"></param>
/// <param name="frames"></param>
/// <param name="easingType">EasingType</param>
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);
/// <summary>
/// Queue the destination, it will be used to continue at the last frame
@ -186,7 +163,7 @@ namespace Greenshot.Base.Core
/// <param name="easingMode"></param>
public void QueueDestinationLeg(T queuedDestination, int frames, EasingType easingType, EasingMode easingMode)
{
AnimationLeg<T> leg = new AnimationLeg<T>
AnimationLeg<T> leg = new()
{
Destination = queuedDestination,
Frames = frames,
@ -209,17 +186,13 @@ namespace Greenshot.Base.Core
/// <summary>
/// Get the easing value, which is from 0-1 and depends on the frame
/// </summary>
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)
};
}
/// <summary>
/// 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;
}
}
/// <summary>
/// Are there more frames to animate?
/// </summary>
public virtual bool HasNext
{
get
{
if (CurrentFrameNr < Frames)
{
return true;
}
return _queue.Count > 0;
}
}
public virtual bool HasNext => CurrentFrameNr < Frames || _queue.Count > 0;
/// <summary>
/// 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));
}
}
}

View file

@ -63,7 +63,7 @@ namespace Greenshot.Base.Core
public static T FromIntPtr<T>(IntPtr intPtr) where T : struct
{
object obj = Marshal.PtrToStructure(intPtr, typeof(T));
return (T) obj;
return (T)obj;
}
/// <summary>

View file

@ -35,7 +35,7 @@ namespace Greenshot.Base.Core
{
private static readonly ILog Log = LogManager.GetLogger(typeof(Cache<TK, TV>));
private readonly IDictionary<TK, TV> _internalCache = new Dictionary<TK, TV>();
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
/// </summary>
/// <param name="expiredCallback"></param>
public Cache(CacheObjectExpired expiredCallback) : this()
{
_expiredCallback = expiredCallback;
}
public Cache(CacheObjectExpired expiredCallback) : this() => _expiredCallback = expiredCallback;
/// <summary>
/// Initialize the cache with a expire setting
/// </summary>
/// <param name="secondsToExpire"></param>
public Cache(int secondsToExpire) : this()
{
_secondsToExpire = secondsToExpire;
}
public Cache(int secondsToExpire) : this() => _secondsToExpire = secondsToExpire;
/// <summary>
/// Initialize the cache with a expire setting
/// </summary>
/// <param name="secondsToExpire"></param>
/// <param name="expiredCallback"></param>
public Cache(int secondsToExpire, CacheObjectExpired expiredCallback) : this(expiredCallback)
{
_secondsToExpire = secondsToExpire;
}
public Cache(int secondsToExpire, CacheObjectExpired expiredCallback) : this(expiredCallback) => _secondsToExpire = secondsToExpire;
/// <summary>
/// Enumerable for the values in the cache
@ -83,14 +74,11 @@ namespace Greenshot.Base.Core
{
get
{
List<TV> elements = new List<TV>();
List<TV> 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
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void Add(TK key, TV value)
{
Add(key, value, null);
}
public void Add(TK key, TV value) => Add(key, value, null);
/// <summary>
/// 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; }

View file

@ -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
/// </summary>
public bool CursorVisible { get; set; }
private NativePoint _cursorLocation = NativePoint.Empty;
/// <summary>
/// Get/Set the CursorLocation
/// </summary>
public NativePoint CursorLocation
{
get => _cursorLocation;
set => _cursorLocation = value;
}
private NativePoint _location = NativePoint.Empty;
public NativePoint CursorLocation { get; set; } = NativePoint.Empty;
/// <summary>
/// Get/set the Location
/// </summary>
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;
}
/// <summary>
@ -174,10 +159,7 @@ namespace Greenshot.Base.Core
/// Note: the supplied bitmap can be disposed immediately or when constructor is called.
/// </summary>
/// <param name="newImage">Image</param>
public Capture(Image newImage) : this()
{
Image = newImage;
}
public Capture(Image newImage) : this() => Image = newImage;
/// <summary>
/// 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
/// </summary>
/// <param name="x">x coordinates to move the mouse</param>
/// <param name="y">y coordinates to move the mouse</param>
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.
///// <summary>

View file

@ -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<string, string> MetaData { get; } = new Dictionary<string, string>();
/// <inheritdoc />
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;
/// <inheritdoc />
public CaptureMode CaptureMode { get; set; }
@ -73,10 +64,7 @@ namespace Greenshot.Base.Core
public List<IDestination> CaptureDestinations { get; set; } = new List<IDestination>();
/// <inheritdoc />
public void ClearDestinations()
{
CaptureDestinations.Clear();
}
public void ClearDestinations() => CaptureDestinations.Clear();
/// <inheritdoc />
public void RemoveDestination(IDestination destination)
@ -99,20 +87,16 @@ namespace Greenshot.Base.Core
/// <inheritdoc />
public bool HasDestination(string designation)
{
foreach (IDestination destination in CaptureDestinations)
{
if (designation.Equals(destination.Designation))
foreach (var _ in from IDestination destination in CaptureDestinations
where designation.Equals(destination.Designation)
select new { })
{
return true;
}
}
return false;
}
public CaptureDetails()
{
DateTime = DateTime.Now;
}
public CaptureDetails() => DateTime = DateTime.Now;
}
}

View file

@ -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<CoreConfiguration>();
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,13 +244,10 @@ EndSelection:<<<<<<<4
/// <returns></returns>
public static bool ContainsText(IDataObject dataObject)
{
if (dataObject != null)
{
if (dataObject.GetDataPresent(DataFormats.Text) || dataObject.GetDataPresent(DataFormats.UnicodeText))
if (dataObject != null && (dataObject.GetDataPresent(DataFormats.Text) || dataObject.GetDataPresent(DataFormats.UnicodeText)))
{
return true;
}
}
return false;
}
@ -384,7 +371,7 @@ EndSelection:<<<<<<<4
/// </summary>
/// <param name="dataObject">IDataObject</param>
/// <returns>IEnumerable{(MemoryStream,string)}</returns>
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
/// <returns>IEnumerable{FileDescriptor}</returns>
private static IEnumerable<FileDescriptor> 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
/// </summary>
/// <param name="memoryStream"></param>
/// <returns>true if there is a valid stream</returns>
private static bool IsValidStream(MemoryStream memoryStream)
{
return memoryStream?.Length > 0;
}
private static bool IsValidStream(MemoryStream memoryStream) => memoryStream?.Length > 0;
/// <summary>
/// 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<IDrawableContainer> 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
/// <returns>Bitmap or null</returns>
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<IFileFormatHandler>();
// 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;
}
/// <summary>
@ -835,8 +813,6 @@ EndSelection:<<<<<<<4
/// <returns>IDrawableContainer or null</returns>
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
/// </summary>
/// <returns>string if there is text on the clipboard</returns>
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;
/// <summary>
/// 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("<HTML>", StringComparison.Ordinal) + "<HTML>".Length).ToString("D8"));
sb.Replace("<<<<<<<2", (utf8EncodedHtmlString.IndexOf("</HTML>", StringComparison.Ordinal)).ToString("D8"));
sb.Replace("<<<<<<<2", utf8EncodedHtmlString.IndexOf("</HTML>", StringComparison.Ordinal).ToString("D8"));
sb.Replace("<<<<<<<3", (utf8EncodedHtmlString.IndexOf("<!--StartFragment -->", StringComparison.Ordinal) + "<!--StartFragment -->".Length).ToString("D8"));
sb.Replace("<<<<<<<4", (utf8EncodedHtmlString.IndexOf("<!--EndFragment -->", StringComparison.Ordinal)).ToString("D8"));
sb.Replace("<<<<<<<4", utf8EncodedHtmlString.IndexOf("<!--EndFragment -->", 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("<HTML>", StringComparison.Ordinal) + "<HTML>".Length).ToString("D8"));
sb.Replace("<<<<<<<2", (utf8EncodedHtmlString.IndexOf("</HTML>", StringComparison.Ordinal)).ToString("D8"));
sb.Replace("<<<<<<<2", utf8EncodedHtmlString.IndexOf("</HTML>", StringComparison.Ordinal).ToString("D8"));
sb.Replace("<<<<<<<3", (utf8EncodedHtmlString.IndexOf("<!--StartFragment -->", StringComparison.Ordinal) + "<!--StartFragment -->".Length).ToString("D8"));
sb.Replace("<<<<<<<4", (utf8EncodedHtmlString.IndexOf("<!--EndFragment -->", StringComparison.Ordinal)).ToString("D8"));
sb.Replace("<<<<<<<4", utf8EncodedHtmlString.IndexOf("<!--EndFragment -->", StringComparison.Ordinal).ToString("D8"));
return sb.ToString();
}
@ -956,7 +924,7 @@ EndSelection:<<<<<<<4
/// </summary>
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
/// <param name="dataObject">IDataObject</param>
/// <param name="format">string with format</param>
/// <returns>true if one the format is found</returns>
public static bool ContainsFormat(IDataObject dataObject, string format)
{
return ContainsFormat(dataObject, new[]
public static bool ContainsFormat(IDataObject dataObject, string format) => ContainsFormat(dataObject, new[]
{
format
});
}
/// <summary>
/// Check if there is currently something on the clipboard which has one of the supplied formats
/// </summary>
/// <param name="formats">string[] with formats</param>
/// <returns>true if one of the formats was found</returns>
public static bool ContainsFormat(string[] formats)
{
return ContainsFormat(GetDataObject(), formats);
}
public static bool ContainsFormat(string[] formats) => ContainsFormat(GetDataObject(), formats);
/// <summary>
/// Check if there is currently something on the clipboard which has one of the supplied formats
@ -1223,14 +1185,13 @@ EndSelection:<<<<<<<4
return false;
}
foreach (string format in formats)
{
if (currentFormats.Contains(format))
foreach (var _ in from string format in formats
where currentFormats.Contains(format)
select new { })
{
formatFound = true;
break;
}
}
return formatFound;
}
@ -1241,15 +1202,7 @@ EndSelection:<<<<<<<4
/// <param name="dataObj">IDataObject</param>
/// <param name="type">Type to get</param>
/// <returns>object from IDataObject</returns>
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;
/// <summary>
/// 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)));
}
/// <summary>

View file

@ -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,13 +359,13 @@ 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)));
}
}
}
@ -383,10 +383,7 @@ namespace Greenshot.Base.Core
/// </summary>
/// <param name="experimentalFeature"></param>
/// <returns></returns>
public bool IsExperimentalFeatureEnabled(string experimentalFeature)
{
return ExperimentalFeatures != null && ExperimentalFeatures.Contains(experimentalFeature);
}
public bool IsExperimentalFeatureEnabled(string experimentalFeature) => ExperimentalFeatures?.Contains(experimentalFeature) == true;
private string CreateOutputFilePath()
{
@ -456,21 +453,15 @@ 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 (propertyValue != null)
if ("Destinations".Equals(propertyName) && propertyValue != null)
{
return propertyValue.Replace('|', ',');
}
}
if ("OutputFilePath".Equals(propertyName))
{
if (string.IsNullOrEmpty(propertyValue))
if ("OutputFilePath".Equals(propertyName) && string.IsNullOrEmpty(propertyValue))
{
return null;
}
}
return base.PreCheckValue(propertyName, propertyValue);
}
@ -528,13 +519,10 @@ namespace Greenshot.Base.Core
}
// Enable OneNote if upgrading from 1.1
if (ExcludeDestinations != null && ExcludeDestinations.Contains("OneNote"))
{
if (LastSaveWithVersion != null && LastSaveWithVersion.StartsWith("1.1"))
if (ExcludeDestinations?.Contains("OneNote") == true && LastSaveWithVersion?.StartsWith("1.1") == true)
{
ExcludeDestinations.Remove("OneNote");
}
}
if (OutputDestinations == null)
{
@ -568,15 +556,12 @@ namespace Greenshot.Base.Core
if (NoGDICaptureForProduct != null)
{
// Fix error in configuration
if (NoGDICaptureForProduct.Count >= 2)
{
if ("intellij".Equals(NoGDICaptureForProduct[0]) && "idea".Equals(NoGDICaptureForProduct[1]))
if (NoGDICaptureForProduct.Count >= 2 && "intellij".Equals(NoGDICaptureForProduct[0]) && "idea".Equals(NoGDICaptureForProduct[1]))
{
NoGDICaptureForProduct.RemoveRange(0, 2);
NoGDICaptureForProduct.Add("Intellij Idea");
IsDirty = true;
}
}
for (int i = 0; i < NoGDICaptureForProduct.Count; i++)
{
@ -587,15 +572,12 @@ namespace Greenshot.Base.Core
if (NoDWMCaptureForProduct != null)
{
// Fix error in configuration
if (NoDWMCaptureForProduct.Count >= 3)
{
if ("citrix".Equals(NoDWMCaptureForProduct[0]) && "ica".Equals(NoDWMCaptureForProduct[1]) && "client".Equals(NoDWMCaptureForProduct[2]))
if (NoDWMCaptureForProduct.Count >= 3 && "citrix".Equals(NoDWMCaptureForProduct[0]) && "ica".Equals(NoDWMCaptureForProduct[1]) && "client".Equals(NoDWMCaptureForProduct[2]))
{
NoDWMCaptureForProduct.RemoveRange(0, 3);
NoDWMCaptureForProduct.Add("Citrix ICA Client");
IsDirty = true;
}
}
for (int i = 0; i < NoDWMCaptureForProduct.Count; i++)
{

View file

@ -132,7 +132,7 @@ namespace Greenshot.Base.Core
/// <summary>Gets or sets the name for the credentials.</summary>
public string Name
{
get { return _name; }
get => _name;
set
{
if (value?.Length > CredUi.MAX_USERNAME_LENGTH)
@ -153,7 +153,7 @@ namespace Greenshot.Base.Core
/// <summary>Gets or sets the password for the credentials.</summary>
public string Password
{
get { return _password; }
get => _password;
set
{
if (value?.Length > CredUi.MAX_PASSWORD_LENGTH)
@ -181,7 +181,7 @@ namespace Greenshot.Base.Core
/// <summary>Gets or sets the name of the target for the credentials, typically a server name.</summary>
public string Target
{
get { return _target; }
get => _target;
set
{
if (value == null)
@ -208,7 +208,7 @@ namespace Greenshot.Base.Core
/// <remarks>A null value will cause a system default caption to be used.</remarks>
public string Caption
{
get { return _caption; }
get => _caption;
set
{
if (value?.Length > CredUi.MAX_CAPTION_LENGTH)
@ -230,7 +230,7 @@ namespace Greenshot.Base.Core
/// <remarks>A null value will cause a system default message to be used.</remarks>
public string Message
{
get { return _message; }
get => _message;
set
{
if (value?.Length > CredUi.MAX_MESSAGE_LENGTH)
@ -252,7 +252,7 @@ namespace Greenshot.Base.Core
/// <remarks>A null value will cause a system default image to be used.</remarks>
public Image Banner
{
get { return _banner; }
get => _banner;
set
{
if (value != null)
@ -275,10 +275,7 @@ namespace Greenshot.Base.Core
/// <summary>Shows the credentials dialog with the specified name.</summary>
/// <param name="name">The name for the credentials.</param>
/// <returns>Returns a DialogResult indicating the user action.</returns>
public DialogResult Show(string name)
{
return Show(null, name, Password, SaveChecked);
}
public DialogResult Show(string name) => Show(null, name, Password, SaveChecked);
/// <summary>Shows the credentials dialog with the specified owner, name, password and save checkbox status.</summary>
/// <param name="owner">The System.Windows.Forms.IWin32Window the dialog will display in front of.</param>
@ -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
/// <param name="owner">The System.Windows.Forms.IWin32Window the dialog will display in front of.</param>
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;

View file

@ -37,13 +37,8 @@ namespace Greenshot.Base.Core
/// Method to get all the destinations from the plugins
/// </summary>
/// <returns>List of IDestination</returns>
public static IEnumerable<IDestination> GetAllDestinations()
{
return SimpleServiceProvider.Current.GetAllInstances<IDestination>()
.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<IDestination> GetAllDestinations() => SimpleServiceProvider.Current.GetAllInstances<IDestination>()
.Where(destination => destination.IsActive && CoreConfig.ExcludeDestinations?.Contains(destination.Designation) != true).OrderBy(p => p.Priority).ThenBy(p => p.Description);
/// <summary>
/// Get a destination by a designation
@ -57,13 +52,12 @@ namespace Greenshot.Base.Core
return null;
}
foreach (IDestination destination in GetAllDestinations())
{
if (designation.Equals(destination.Designation))
foreach (var destination in from IDestination destination in GetAllDestinations()
where designation.Equals(destination.Designation)
select destination)
{
return destination;
}
}
return null;
}
@ -75,10 +69,7 @@ namespace Greenshot.Base.Core
/// <param name="designation">WellKnownDestinations</param>
/// <param name="surface">ISurface</param>
/// <param name="captureDetails">ICaptureDetails</param>
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);
/// <summary>
/// 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;
}
}
}

View file

@ -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()
{

View file

@ -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,13 +105,10 @@ 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 (darkness <= 1.0)
if (pair[1] != null && float.TryParse(pair[1], NumberStyles.Float, _numberFormatInfo, out var darkness) && darkness <= 1.0)
{
effect.Darkness = darkness;
}
}
break;
case "ShadowSize":
@ -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]);
}
}
}

View file

@ -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,8 +302,9 @@ namespace Greenshot.Base.Core
var productType = osVersionInfo.ProductType;
var suiteMask = osVersionInfo.SuiteMask;
if (majorVersion == 4)
switch (majorVersion)
{
case 4:
if (productType == WindowsProductTypes.VER_NT_WORKSTATION)
{
// Windows NT 4.0 Workstation
@ -315,10 +314,8 @@ namespace Greenshot.Base.Core
{
edition = (suiteMask & WindowsSuites.Enterprise) != 0 ? "Enterprise Server" : "Standard Server";
}
}
else if (majorVersion == 5)
{
break;
case 5:
if (productType == WindowsProductTypes.VER_NT_WORKSTATION)
{
if ((suiteMask & WindowsSuites.Personal) != 0)
@ -334,8 +331,9 @@ namespace Greenshot.Base.Core
}
else if (productType == WindowsProductTypes.VER_NT_SERVER)
{
if (minorVersion == 0)
switch (minorVersion)
{
case 0:
if ((suiteMask & WindowsSuites.DataCenter) != 0)
{
// Windows 2000 Datacenter Server
@ -351,9 +349,8 @@ namespace Greenshot.Base.Core
// Windows 2000 Server
edition = "Server";
}
}
else
{
break;
default:
if ((suiteMask & WindowsSuites.DataCenter) != 0)
{
// Windows Server 2003 Datacenter Edition
@ -374,16 +371,13 @@ namespace Greenshot.Base.Core
// 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}";
}
}
}

View file

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

View file

@ -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);
/// <summary>
/// Factory for creating a FastBitmap depending on the pixelformat of the source
@ -324,10 +318,7 @@ namespace Greenshot.Base.Core
/// <param name="source">Bitmap to clone</param>
/// <param name="pixelFormat">new PixelFormat</param>
/// <returns>IFastBitmap</returns>
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);
/// <summary>
/// Factory for creating a FastBitmap as a destination for the source
@ -335,10 +326,7 @@ namespace Greenshot.Base.Core
/// <param name="source">Bitmap to clone</param>
/// <param name="area">Area of the bitmap to access, can be NativeRect.Empty for the whole</param>
/// <returns>IFastBitmap</returns>
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);
/// <summary>
/// Factory for creating a FastBitmap as a destination for the source
@ -408,50 +396,17 @@ namespace Greenshot.Base.Core
/// <summary>
/// Return the size of the image
/// </summary>
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;
/// <summary>
/// Return the width of the image
/// </summary>
public int Width
{
get
{
if (Area == NativeRect.Empty)
{
return Bitmap.Width;
}
return Area.Width;
}
}
public int Width => Area == NativeRect.Empty ? Bitmap.Width : Area.Width;
/// <summary>
/// Return the height of the image
/// </summary>
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
/// </summary>
public int Left
{
get { return 0; }
set { _left = value; }
get => 0;
set => _left = value;
}
/// <summary>
@ -469,8 +424,8 @@ namespace Greenshot.Base.Core
/// </summary>
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
/// </summary>
public int Top
{
get { return 0; }
set { _top = value; }
get => 0;
set => _top = value;
}
/// <summary>
@ -489,8 +444,8 @@ namespace Greenshot.Base.Core
/// </summary>
int IFastBitmapWithOffset.Top
{
get { return _top; }
set { _top = value; }
get => _top;
set => _top = value;
}
/// <summary>
@ -547,13 +502,10 @@ namespace Greenshot.Base.Core
protected virtual void Dispose(bool disposing)
{
Unlock();
if (disposing)
{
if (Bitmap != null && NeedsDispose)
if (disposing && Bitmap != null && NeedsDispose)
{
Bitmap.Dispose();
}
}
Bitmap = null;
BmData = 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
/// </summary>
/// <param name="graphics"></param>
/// <param name="destination"></param>
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));
/// <summary>
/// Draw the stored Bitmap on the Destination bitmap with the specified rectangle
@ -624,10 +573,7 @@ namespace Greenshot.Base.Core
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>true if x & y are inside the FastBitmap</returns>
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
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>true if x & y are inside the FastBitmap</returns>
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<Color, byte> _colorCache = new Dictionary<Color, byte>();
private readonly Dictionary<Color, byte> _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;
/// <summary>
/// Get the color from the specified location
@ -742,10 +675,7 @@ namespace Greenshot.Base.Core
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="color">byte[4] as reference</param>
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!");
/// <summary>
/// Set the color at the specified location from the specified array
@ -753,10 +683,7 @@ namespace Greenshot.Base.Core
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="color">byte[4] as reference</param>
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!");
/// <summary>
/// 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;
/// <summary>
/// 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);

View file

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

View file

@ -56,10 +56,7 @@ namespace Greenshot.Base.Core.FileFormatHandlers
/// <param name="fileFormatHandlers">IEnumerable{IFileFormatHandler}</param>
/// <param name="fileFormatHandlerAction"></param>
/// <returns></returns>
public static IEnumerable<string> ExtensionsFor(this IEnumerable<IFileFormatHandler> fileFormatHandlers, FileFormatHandlerActions fileFormatHandlerAction)
{
return fileFormatHandlers.Where(ffh => ffh.SupportedExtensions.ContainsKey(fileFormatHandlerAction)).SelectMany(ffh => ffh.SupportedExtensions[fileFormatHandlerAction]).Distinct().OrderBy(e => e);
}
public static IEnumerable<string> ExtensionsFor(this IEnumerable<IFileFormatHandler> fileFormatHandlers, FileFormatHandlerActions fileFormatHandlerAction) => fileFormatHandlers.Where(ffh => ffh.SupportedExtensions.ContainsKey(fileFormatHandlerAction)).SelectMany(ffh => ffh.SupportedExtensions[fileFormatHandlerAction]).Distinct().OrderBy(e => e);
/// <summary>
/// Extension method to check if a certain IFileFormatHandler supports a certain action with a specific extension
@ -93,18 +90,17 @@ 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)
{
if (fileFormatHandler.TrySaveToStream(bitmap, destination, extension, surface))
foreach (var _ in from fileFormatHandler in saveFileFormatHandlers
where fileFormatHandler.TrySaveToStream(bitmap, destination, extension, surface)
select new { })
{
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<IDrawableContainer>();
return loadfileFormatHandler != null
? loadfileFormatHandler.LoadDrawablesFromStream(stream, extension, parentSurface)
: Enumerable.Empty<IDrawableContainer>();
}
/// <summary>

View file

@ -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(@"\${(?<variable>[^:}]+)[:]?(?<parameters>[^}]*)}", RegexOptions.Compiled);
private static readonly Regex CmdVarRegexp = new Regex(@"%(?<variable>[^%]+)%", RegexOptions.Compiled);
private static readonly Regex VarRegexp = new(@"\${(?<variable>[^:}]+)[:]?(?<parameters>[^}]*)}", RegexOptions.Compiled);
private static readonly Regex CmdVarRegexp = new("%(?<variable>[^%]+)%", 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<CoreConfiguration>();
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);
/// <summary>
/// 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();
/// <summary>
/// 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);
}
/// <summary>
/// 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<old string>,<new string>
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;
}

View file

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

View file

@ -29,21 +29,12 @@ namespace Greenshot.Base.Core
/// </summary>
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");
}
}

View file

@ -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;
}
/// <summary>
@ -111,10 +106,7 @@ namespace Greenshot.Base.Core
/// </summary>
/// <param name="applicationName">Name of the process</param>
/// <param name="ignoreDoctype">true to ignore the doctype when loading a page</param>
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));
/// <summary>
/// Fix the browser version for the specified application
@ -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;

View file

@ -51,7 +51,6 @@ namespace Greenshot.Base.Core
private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>();
private const int ExifOrientationId = 0x0112;
/// <summary>
/// Make sure the image is orientated correctly
/// </summary>
@ -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,13 +244,10 @@ namespace Greenshot.Base.Core
}
}
if (!(NativePoint.Empty.Equals(min) && max.Equals(new NativePoint(area.Value.Width - 1, area.Value.Height - 1))))
{
if (!(min.X == int.MaxValue || min.Y == int.MaxValue || max.X == int.MinValue || min.X == int.MinValue))
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))
{
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
/// <returns>NativeRect</returns>
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;
}
/// <summary>
@ -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
/// <returns>Negative bitmap</returns>
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
/// </summary>
/// <param name="source">Image to apply matrix to</param>
/// <param name="colorMatrix">ColorMatrix to apply</param>
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);
/// <summary>
/// Apply a color matrix by copying from the source to the destination
@ -916,7 +899,7 @@ namespace Greenshot.Base.Core
/// <param name="colorMatrix">ColorMatrix to apply</param>
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
/// <returns>Bitmap with grayscale</returns>
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
/// </summary>
/// <param name="pixelformat">PixelFormat to check</param>
/// <returns>bool if we support it</returns>
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);
}
/// <summary>
/// Wrapper for just cloning which calls the CloneArea
/// </summary>
/// <param name="sourceImage">Image to clone</param>
/// <returns>Bitmap with clone image data</returns>
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);
/// <summary>
/// Wrapper for just cloning & TargetFormat which calls the CloneArea
@ -1163,10 +1135,7 @@ namespace Greenshot.Base.Core
/// <param name="sourceBitmap">Image to clone</param>
/// <param name="targetFormat">Target Format, use PixelFormat.DontCare if you want the original (or a default if the source PixelFormat is not supported)</param>
/// <returns>Bitmap with clone image data</returns>
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);
/// <summary>
/// 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
/// <param name="newHeight"></param>
/// <param name="matrix"></param>
/// <returns></returns>
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);
/// <summary>
/// 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,18 +1447,18 @@ 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);
}
@ -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}.");
}
/// <summary>
@ -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);

View file

@ -48,7 +48,7 @@ namespace Greenshot.Base.Core
private static readonly ILog Log = LogManager.GetLogger(typeof(ImageIO));
private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>();
private static readonly int PROPERTY_TAG_SOFTWARE_USED = 0x0131;
private static readonly Cache<string, string> TmpFileCache = new Cache<string, string>(10 * 60 * 60, RemoveExpiredTmpFile);
private static readonly Cache<string, string> TmpFileCache = new(10 * 60 * 60, RemoveExpiredTmpFile);
/// <summary>
/// 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);
@ -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);

View file

@ -80,25 +80,22 @@ 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)
{
case TOKEN_NONE:
success = false;
return null;
}
else if (token == TOKEN_COMMA)
{
case TOKEN_COMMA:
NextToken(json, ref index);
}
else if (token == TOKEN_CURLY_CLOSE)
{
break;
case TOKEN_CURLY_CLOSE:
NextToken(json, ref index);
return table;
}
else
default:
{
// name
string name = ParseString(json, ref index, ref success);
@ -125,10 +122,12 @@ namespace Greenshot.Base.Core
}
table.Add(name, value);
break;
}
}
}
return table;
// return table;
}
protected static IList<object> ParseArray(char[] json, ref int index, ref bool success)
@ -138,7 +137,7 @@ namespace Greenshot.Base.Core
// [
NextToken(json, ref index);
bool done = false;
const bool done = false;
while (!done)
{
int token = LookAhead(json, index);
@ -202,12 +201,12 @@ namespace Greenshot.Base.Core
protected static string ParseString(char[] json, ref int index, ref bool success)
{
StringBuilder s = new StringBuilder(BUILDER_CAPACITY);
StringBuilder s = new(BUILDER_CAPACITY);
EatWhitespace(json, ref index);
// "
var c = json[index++];
_ = json[index++];
bool complete = false;
while (!complete)
@ -217,7 +216,7 @@ namespace Greenshot.Base.Core
break;
}
c = json[index++];
char c = json[index++];
if (c == '"')
{
complete = true;
@ -275,7 +274,7 @@ namespace Greenshot.Base.Core
}
// convert the integer codepoint to a unicode char and add to string
s.Append(char.ConvertFromUtf32((int) codePoint));
s.Append(char.ConvertFromUtf32((int)codePoint));
// skip 4 chars
index += 4;
}
@ -305,7 +304,7 @@ namespace Greenshot.Base.Core
EatWhitespace(json, ref index);
int lastIndex = GetLastIndexOfNumber(json, index);
int charLength = (lastIndex - index) + 1;
int charLength = lastIndex - index + 1;
success = double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out var number);
@ -391,9 +390,7 @@ namespace Greenshot.Base.Core
int remainingLength = json.Length - index;
// false
if (remainingLength >= 5)
{
if (json[index] == 'f' &&
if (remainingLength >= 5 && json[index] == 'f' &&
json[index + 1] == 'a' &&
json[index + 2] == 'l' &&
json[index + 3] == 's' &&
@ -402,12 +399,9 @@ namespace Greenshot.Base.Core
index += 5;
return TOKEN_FALSE;
}
}
// true
if (remainingLength >= 4)
{
if (json[index] == 't' &&
if (remainingLength >= 4 && json[index] == 't' &&
json[index + 1] == 'r' &&
json[index + 2] == 'u' &&
json[index + 3] == 'e')
@ -415,12 +409,9 @@ namespace Greenshot.Base.Core
index += 4;
return TOKEN_TRUE;
}
}
// null
if (remainingLength >= 4)
{
if (json[index] == 'n' &&
if (remainingLength >= 4 && json[index] == 'n' &&
json[index + 1] == 'u' &&
json[index + 2] == 'l' &&
json[index + 3] == 'l')
@ -428,7 +419,6 @@ namespace Greenshot.Base.Core
index += 4;
return TOKEN_NULL;
}
}
return TOKEN_NONE;
}

View file

@ -36,17 +36,17 @@ namespace Greenshot.Base.Core
/// This class supplies the GUI with translations, based upon keys.
/// The language resources are loaded from the language files found on fixed or supplied paths
/// </summary>
public class Language
public static class Language
{
private static readonly ILog Log = LogManager.GetLogger(typeof(Language));
private static readonly List<string> LanguagePaths = new();
private static readonly Dictionary<string, List<LanguageFile>> LanguageFiles = new();
private static readonly Dictionary<string, string> 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<string> UnsupportedLanguageGroups = new();
private static readonly Dictionary<string, string> 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
/// <summary>
/// Return the path to the help-file
/// </summary>
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];
/// <summary>
/// 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)
@ -578,25 +567,14 @@ namespace Greenshot.Base.Core
/// <param name="prefix"></param>
/// <param name="key"></param>
/// <returns>true if available</returns>
public static bool HasKey(string prefix, string key)
{
return HasKey(prefix + "." + key);
}
public static bool HasKey(string prefix, string key) => HasKey(prefix + "." + key);
/// <summary>
/// Check if a resource with key exists
/// </summary>
/// <param name="key"></param>
/// <returns>true if available</returns>
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);
/// <summary>
/// TryGet method which combines HasKey & GetString
@ -604,10 +582,7 @@ namespace Greenshot.Base.Core
/// <param name="key"></param>
/// <param name="languageString">out string</param>
/// <returns></returns>
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);
/// <summary>
/// TryGet method which combines HasKey & GetString
@ -616,10 +591,7 @@ namespace Greenshot.Base.Core
/// <param name="key">string with key</param>
/// <param name="languageString">out string</param>
/// <returns></returns>
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);
/// <summary>
/// TryGet method which combines HasKey & GetString
@ -628,10 +600,7 @@ namespace Greenshot.Base.Core
/// <param name="key">Enum with key</param>
/// <param name="languageString">out string</param>
/// <returns></returns>
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);
/// <summary>
/// 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();
}
/// <summary>
@ -655,15 +619,7 @@ namespace Greenshot.Base.Core
/// </summary>
/// <param name="key">Enum</param>
/// <returns>resource or a "string ###key### not found"</returns>
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());
/// <summary>
/// Get the resource for prefix.key
@ -671,15 +627,7 @@ namespace Greenshot.Base.Core
/// <param name="prefix">string</param>
/// <param name="key">Enum</param>
/// <returns>resource or a "string ###prefix.key### not found"</returns>
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);
/// <summary>
/// Get the resource for prefix.key
@ -687,10 +635,7 @@ namespace Greenshot.Base.Core
/// <param name="prefix">string</param>
/// <param name="key">string</param>
/// <returns>resource or a "string ###prefix.key### not found"</returns>
public static string GetString(string prefix, string key)
{
return GetString(prefix + "." + key);
}
public static string GetString(string prefix, string key) => GetString(prefix + "." + key);
/// <summary>
/// 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;
}
/// <summary>
/// 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
/// </summary>
/// <param name="key">Enum</param>
/// <param name="param">object</param>
/// <returns>formatted resource or a "string ###key### not found"</returns>
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);
/// <summary>
/// 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
/// </summary>
/// <param name="prefix">string</param>
/// <param name="key">Enum</param>
/// <param name="param">object</param>
/// <returns>formatted resource or a "string ###prefix.key### not found"</returns>
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);
/// <summary>
/// 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
/// </summary>
/// <param name="prefix">string</param>
/// <param name="key">string</param>
/// <param name="param">object</param>
/// <returns>formatted resource or a "string ###prefix.key### not found"</returns>
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);
/// <summary>
/// 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
/// </summary>
/// <param name="key">string</param>
/// <param name="param">object</param>
/// <returns>formatted resource or a "string ###key### not found"</returns>
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);
}
}

View file

@ -57,7 +57,7 @@ namespace Greenshot.Base.Core
return false;
}
}
else if (other != null && other.Version != null)
else if (other?.Version != null)
{
return false;
}

View file

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

View file

@ -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<IFileFormatHandler>();
var extensions = string.Join("|", fileFormatHandlers.ExtensionsFor(FileFormatHandlerActions.LoadFromStream));
var imageUrlRegex = new Regex($@"(http|https)://.*(?<extension>{extensions})");
var imageUrlRegex = new Regex($"(http|https)://.*(?<extension>{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)://.*(?<extension>{extensions})");
var imageUrlRegex = new Regex($"(http|https)://.*(?<extension>{extensions})");
var match = imageUrlRegex.Match(url);
try
{
@ -214,10 +214,7 @@ namespace Greenshot.Base.Core
/// </summary>
/// <param name="uri">string with uri to connect to</param>
/// <returns>WebRequest</returns>
public static HttpWebRequest CreateWebRequest(string uri)
{
return CreateWebRequest(new Uri(uri));
}
public static HttpWebRequest CreateWebRequest(string uri) => CreateWebRequest(new Uri(uri));
/// <summary>
/// Helper method to create a web request with a lot of default settings
@ -225,10 +222,7 @@ namespace Greenshot.Base.Core
/// <param name="uri">string with uri to connect to</param>
/// /// <param name="method">Method to use</param>
/// <returns>WebRequest</returns>
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);
/// <summary>
/// Helper method to create a web request with a lot of default settings
@ -250,7 +244,7 @@ namespace Greenshot.Base.Core
/// <returns>WebRequest</returns>
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();
}
/// <summary>
@ -594,10 +587,7 @@ namespace Greenshot.Base.Core
/// <param name="webRequest">The request object.</param>
/// <returns>The response data.</returns>
/// 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);
/// <summary>
/// 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
/// <returns>string</returns>
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);
}
/// <summary>
@ -743,7 +733,7 @@ namespace Greenshot.Base.Core
/// <returns>byte[]</returns>
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"
/// </summary>
/// <param name="dataStream"></param>
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);
}
/// <summary>
/// Upload the Surface as image to the webrequest

View file

@ -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<string, string> _returnValues;
/// <summary>
@ -121,7 +121,7 @@ namespace Greenshot.Base.Core.OAuth
/// <param name="result">IAsyncResult</param>
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
{

View file

@ -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);
/// <summary>
/// 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/";
/// <summary>
/// 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
/// </summary>
public string ClosePageResponse { get; set; } = @"<html>
@ -71,24 +71,12 @@ Greenshot received information from CloudServiceName. You can close this browser
/// <summary>
/// The URL to redirect to
/// </summary>
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<string, string> _returnValues = new Dictionary<string, string>();
/// <summary>
/// The OAuth code receiver
/// </summary>
@ -142,7 +130,7 @@ Greenshot received information from CloudServiceName. You can close this browser
/// <param name="result">IAsyncResult</param>
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
{

View file

@ -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,14 +135,11 @@ namespace Greenshot.Base.Core.OAuth
{
var expiresIn = callbackParameters[ExpiresIn];
settings.AccessTokenExpires = DateTimeOffset.MaxValue;
if (expiresIn != null)
{
if (double.TryParse(expiresIn, out var seconds))
if (expiresIn != null && double.TryParse(expiresIn, out var seconds))
{
settings.AccessTokenExpires = DateTimeOffset.Now.AddSeconds(seconds);
}
}
}
settings.AccessToken = callbackParameters[AccessToken];
return true;
@ -187,7 +184,7 @@ namespace Greenshot.Base.Core.OAuth
IDictionary<string, object> 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,13 +390,10 @@ namespace Greenshot.Base.Core.OAuth
public static void CheckAndAuthenticateOrRefresh(OAuth2Settings settings)
{
// Get Refresh / Access token
if (string.IsNullOrEmpty(settings.RefreshToken))
{
if (!Authorize(settings))
if (string.IsNullOrEmpty(settings.RefreshToken) && !Authorize(settings))
{
throw new Exception("Authentication cancelled");
}
}
if (settings.IsAccessTokenExpired)
{

View file

@ -96,7 +96,7 @@ namespace Greenshot.Base.Core.OAuth
public string AccessToken { get; set; }
/// <summary>
/// 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
/// </summary>
public DateTimeOffset AccessTokenExpires { get; set; }

View file

@ -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<string, string> _requestTokenResponseParameters;
public IDictionary<string, object> RequestTokenParameters { get; } = new Dictionary<string, object>();
@ -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<string, object>(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>Returns a Url encoded string (unicode) with UTF-8 encoded % values</returns>
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
/// </summary>
/// <returns></returns>
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();
/// <summary>
/// Get the request token using the consumer key and secret. Also initializes tokensecret
@ -269,16 +262,14 @@ 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.CallbackParameters != null)
if (oAuthLoginForm.IsOk && oAuthLoginForm.CallbackParameters != null)
{
if (oAuthLoginForm.CallbackParameters.TryGetValue(OAUTH_TOKEN_KEY, out var tokenValue))
{
@ -290,16 +281,10 @@ namespace Greenshot.Base.Core.OAuth
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
/// <param name="postData">Data to post (MemoryStream)</param>
/// <returns>The web server response.</returns>
public string MakeOAuthRequest(HTTPMethod method, string requestUrl, IDictionary<string, object> parametersToSign, IDictionary<string, object> additionalParameters,
IBinaryContainer postData)
{
return MakeOAuthRequest(method, requestUrl, requestUrl, null, parametersToSign, additionalParameters, postData);
}
IBinaryContainer postData) => MakeOAuthRequest(method, requestUrl, requestUrl, null, parametersToSign, additionalParameters, postData);
/// <summary>
/// Submit a web request using oAuth.
@ -410,10 +392,7 @@ namespace Greenshot.Base.Core.OAuth
/// <param name="postData">Data to post (MemoryStream)</param>
/// <returns>The web server response.</returns>
public string MakeOAuthRequest(HTTPMethod method, string requestUrl, IDictionary<string, string> headers, IDictionary<string, object> parametersToSign,
IDictionary<string, object> additionalParameters, IBinaryContainer postData)
{
return MakeOAuthRequest(method, requestUrl, requestUrl, headers, parametersToSign, additionalParameters, postData);
}
IDictionary<string, object> additionalParameters, IBinaryContainer postData) => MakeOAuthRequest(method, requestUrl, requestUrl, headers, parametersToSign, additionalParameters, postData);
/// <summary>
/// Submit a web request using oAuth.
@ -426,10 +405,7 @@ namespace Greenshot.Base.Core.OAuth
/// <param name="postData">Data to post (MemoryStream)</param>
/// <returns>The web server response.</returns>
public string MakeOAuthRequest(HTTPMethod method, string signUrl, string requestUrl, IDictionary<string, object> parametersToSign,
IDictionary<string, object> additionalParameters, IBinaryContainer postData)
{
return MakeOAuthRequest(method, signUrl, requestUrl, null, parametersToSign, additionalParameters, postData);
}
IDictionary<string, object> additionalParameters, IBinaryContainer postData) => MakeOAuthRequest(method, signUrl, requestUrl, null, parametersToSign, additionalParameters, postData);
/// <summary>
/// Submit a web request using oAuth.
@ -455,13 +431,10 @@ 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 (!AutoLogin || !Authorize())
if (string.IsNullOrEmpty(Token) && (!AutoLogin || !Authorize()))
{
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<string> keysToDelete = new List<string>();
foreach (string parameterKey in parametersToSign.Keys)
{
if (parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX))
{
keysToDelete.Add(parameterKey);
}
}
List<string> 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 (requestParameters.Count > 0)
if ((HTTPMethod.GET == method || postData != null) && requestParameters.Count > 0)
{
// 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 &

View file

@ -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);
}
/// <summary>

View file

@ -42,10 +42,7 @@ namespace Greenshot.Base.Core
private const string PathKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\";
private static readonly IDictionary<string, Image> ExeIconCache = new Dictionary<string, Image>();
static PluginUtils()
{
CoreConfig.PropertyChanged += OnIconSizeChanged;
}
static PluginUtils() => CoreConfig.PropertyChanged += OnIconSizeChanged;
/// <summary>
/// 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);
}
}

View file

@ -113,15 +113,12 @@ namespace Greenshot.Base.Core
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (resultBitmap != null)
if (disposing && resultBitmap != null)
{
resultBitmap.Dispose();
resultBitmap = null;
}
}
}
/// <summary>
/// See <see cref="IColorQuantizer.Prepare"/> for more details.
@ -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
/// <summary>
/// See <see cref="IColorQuantizer.Prepare"/> for more details.
/// </summary>
public int GetColorCount()
{
return colorCount;
}
public int GetColorCount() => colorCount;
/// <summary>
/// Reindex the 24/32 BPP (A)RGB image to a 8BPP
@ -228,13 +215,12 @@ namespace Greenshot.Base.Core
/// <returns>Bitmap</returns>
public Bitmap SimpleReindex()
{
List<Color> colors = new List<Color>();
Dictionary<Color, byte> lookup = new Dictionary<Color, byte>();
List<Color> colors = new();
Dictionary<Color, byte> 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<Color, byte> lookup = new Dictionary<Color, byte>();
Dictionary<Color, byte> 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
/// <summary>
/// Computes the volume of the cube in a specific moment.
/// </summary>
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];
}
/// <summary>
/// Computes the volume of the cube in a specific moment. For the floating-point values.
/// </summary>
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];
}
/// <summary>
/// Splits the cube in given position, and color direction.
/// </summary>
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] -
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[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.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]),
moment[cube.RedMinimum, cube.GreenMinimum, position],
_ => 0,
};
}
/// <summary>
/// Splits the cube in a given color direction at its minimum.
/// </summary>
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] +
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.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.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]),
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum],
_ => 0
};
}
/// <summary>
/// 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;
}
}
}

View file

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

View file

@ -17,18 +17,10 @@ namespace Greenshot.Base.Core
public IReadOnlyList<TService> GetAllInstances<TService>()
{
var typeOfService = typeof(TService);
if (!_services.TryGetValue(typeOfService, out var results))
{
return Array.Empty<TService>();
return !_services.TryGetValue(typeOfService, out var results) ? Array.Empty<TService>() : (IReadOnlyList<TService>)results.Cast<TService>().ToArray();
}
return results.Cast<TService>().ToArray();
}
public TService GetInstance<TService>()
{
return GetAllInstances<TService>().SingleOrDefault();
}
public TService GetInstance<TService>() => GetAllInstances<TService>().SingleOrDefault();
public void AddService<TService>(IEnumerable<TService> services)
{
@ -50,9 +42,6 @@ namespace Greenshot.Base.Core
}
}
public void AddService<TService>(params TService[] services)
{
AddService(services.AsEnumerable());
}
public void AddService<TService>(params TService[] services) => AddService(services.AsEnumerable());
}
}

View file

@ -41,10 +41,7 @@ namespace Greenshot.Base.Core
/// <param name="format">String with formatting, like {name}</param>
/// <param name="source">Object used for the formatting</param>
/// <returns>Formatted string</returns>
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);
/// <summary>
/// Format the string "format" with the source
@ -72,7 +69,7 @@ namespace Greenshot.Base.Core
}
else
{
IDictionary<string, string> dictionary = (IDictionary<string, string>) value;
IDictionary<string, string> dictionary = (IDictionary<string, string>)value;
foreach (var propertyKey in dictionary.Keys)
{
properties.Add(propertyKey, dictionary[propertyKey]);
@ -81,11 +78,11 @@ namespace Greenshot.Base.Core
}
}
Regex r = new Regex(@"(?<start>\{)+(?<property>[\w\.\[\]]+)(?<format>:[^}]+)?(?<end>\})+",
Regex r = new(@"(?<start>\{)+(?<property>[\w\.\[\]]+)(?<format>:[^}]+)?(?<end>\})+",
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
List<object> values = new List<object>();
string rewrittenFormat = r.Replace(format, delegate(Match m)
List<object> values = new();
string rewrittenFormat = r.Replace(format, (Match m) =>
{
Group startGroup = m.Groups["start"];
Group propertyGroup = m.Groups["property"];
@ -112,10 +109,10 @@ namespace Greenshot.Base.Core
byte[] clearTextBytes = Encoding.ASCII.GetBytes(clearText);
SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();
using MemoryStream ms = new MemoryStream();
using MemoryStream ms = new();
byte[] rgbIV = Encoding.ASCII.GetBytes(RGBIV);
byte[] key = Encoding.ASCII.GetBytes(KEY);
using CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write);
using CryptoStream cs = new(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write);
cs.Write(clearTextBytes, 0, clearTextBytes.Length);
cs.FlushFinalBlock();
@ -140,14 +137,13 @@ namespace Greenshot.Base.Core
try
{
byte[] encryptedTextBytes = Convert.FromBase64String(encryptedText);
using MemoryStream ms = new MemoryStream();
using MemoryStream ms = new();
SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();
byte[] rgbIV = Encoding.ASCII.GetBytes(RGBIV);
byte[] key = Encoding.ASCII.GetBytes(KEY);
using CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write);
using CryptoStream cs = new(ms, rijn.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write);
cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);
cs.FlushFinalBlock();
returnValue = Encoding.ASCII.GetString(ms.ToArray());

View file

@ -41,6 +41,7 @@ using Dapplo.Windows.User32.Structs;
using Greenshot.Base.IniFile;
using Greenshot.Base.Interfaces;
using log4net;
using System.Linq;
namespace Greenshot.Base.Core
{
@ -59,10 +60,7 @@ namespace Greenshot.Base.Core
/// <returns>
/// Point with cursor location, relative to the top left corner of the monitor setup (which itself might actually not be on any screen)
/// </returns>
public static NativePoint GetCursorLocationRelativeToScreenBounds()
{
return GetLocationRelativeToScreenBounds(User32Api.GetCursorLocation());
}
public static NativePoint GetCursorLocationRelativeToScreenBounds() => GetLocationRelativeToScreenBounds(User32Api.GetCursorLocation());
/// <summary>
/// Converts locationRelativeToScreenOrigin to be relative to top left corner of all screen bounds, which might
@ -153,7 +151,7 @@ namespace Greenshot.Base.Core
{
if (process == null) return true;
if (Configuration.NoDWMCaptureForProduct == null ||
Configuration.NoDWMCaptureForProduct.Count <= 0) return true;
Configuration.NoDWMCaptureForProduct.Count == 0) return true;
try
{
@ -180,7 +178,7 @@ namespace Greenshot.Base.Core
{
if (process == null) return true;
if (Configuration.NoGDICaptureForProduct == null ||
Configuration.NoGDICaptureForProduct.Count <= 0) return true;
Configuration.NoGDICaptureForProduct.Count == 0) return true;
try
{
@ -337,18 +335,14 @@ namespace Greenshot.Base.Core
try
{
// Collect all screens inside this capture
List<Screen> screensInsideCapture = new List<Screen>();
foreach (Screen screen in Screen.AllScreens)
{
if (screen.Bounds.IntersectsWith(captureBounds))
{
screensInsideCapture.Add(screen);
}
}
List<Screen> screensInsideCapture = new();
screensInsideCapture.AddRange(from Screen screen in Screen.AllScreens
where screen.Bounds.IntersectsWith(captureBounds)
select screen);
// Check all all screens are of an equal size
bool offscreenContent;
using (Region captureRegion = new Region(captureBounds))
using (Region captureRegion = new(captureBounds))
{
// Exclude every visible part
foreach (Screen screen in screensInsideCapture)

View file

@ -78,10 +78,7 @@ namespace Greenshot.Base.Core
}
}
internal static bool IsIgnoreHandle(IntPtr handle)
{
return IgnoreHandles.Contains(handle);
}
internal static bool IsIgnoreHandle(IntPtr handle) => IgnoreHandles.Contains(handle);
private IList<WindowDetails> _childWindows;
private IntPtr _parentHandle = IntPtr.Zero;
@ -100,22 +97,15 @@ namespace Greenshot.Base.Core
public bool IsBackgroundWin10App => WindowsVersion.IsWindows10OrLater && AppFrameWindowClass.Equals(ClassName) &&
!Children.Any(window => string.Equals(window.ClassName, AppWindowClass));
/// <summary>
/// To allow items to be compared, the hash code
/// is set to the Window handle, so two EnumWindowsItem
/// objects for the same Window will be equal.
/// </summary>
/// <returns>The Window Handle for this window</returns>
public override int GetHashCode()
{
return Handle.ToInt32();
}
public override int GetHashCode() => Handle.ToInt32();
public override bool Equals(object right)
{
return Equals(right as WindowDetails);
}
public override bool Equals(object right) => Equals(right as WindowDetails);
/// <summary>
/// Compare two windows details
@ -134,34 +124,23 @@ namespace Greenshot.Base.Core
return true;
}
if (GetType() != other.GetType())
{
return false;
}
return other.Handle == Handle;
return GetType() == other.GetType() && other.Handle == Handle;
}
/// <summary>
/// Check if the window has children
/// </summary>
public bool HasChildren => (_childWindows != null) && (_childWindows.Count > 0);
public bool HasChildren => _childWindows?.Count > 0;
/// <summary>
/// Freeze information updates
/// </summary>
public void FreezeDetails()
{
_frozen = true;
}
public void FreezeDetails() => _frozen = true;
/// <summary>
/// Make the information update again.
/// </summary>
public void UnfreezeDetails()
{
_frozen = false;
}
public void UnfreezeDetails() => _frozen = false;
/// <summary>
/// Get the file path to the exe for the process which owns this window
@ -182,7 +161,6 @@ namespace Greenshot.Base.Core
}
}
/// <summary>
/// Get the icon belonging to the process
/// </summary>
@ -226,8 +204,8 @@ namespace Greenshot.Base.Core
private static Icon GetAppIcon(IntPtr hWnd)
{
IntPtr iconSmall = IntPtr.Zero;
IntPtr iconBig = new IntPtr(1);
IntPtr iconSmall2 = new IntPtr(2);
IntPtr iconBig = new(1);
IntPtr iconSmall2 = new(2);
IntPtr iconHandle;
if (Conf.UseLargeIcons)
@ -277,19 +255,13 @@ namespace Greenshot.Base.Core
/// Use this to make remove internal windows, like the mainform and the captureforms, invisible
/// </summary>
/// <param name="ignoreHandle"></param>
public static void RegisterIgnoreHandle(IntPtr ignoreHandle)
{
IgnoreHandles.Add(ignoreHandle);
}
public static void RegisterIgnoreHandle(IntPtr ignoreHandle) => IgnoreHandles.Add(ignoreHandle);
/// <summary>
/// Use this to remove the with RegisterIgnoreHandle registered handle
/// </summary>
/// <param name="ignoreHandle"></param>
public static void UnregisterIgnoreHandle(IntPtr ignoreHandle)
{
IgnoreHandles.Remove(ignoreHandle);
}
public static void UnregisterIgnoreHandle(IntPtr ignoreHandle) => IgnoreHandles.Remove(ignoreHandle);
public IList<WindowDetails> Children
{
@ -309,13 +281,12 @@ namespace Greenshot.Base.Core
/// </summary>
public WindowDetails GetChild(string childClassname)
{
foreach (var child in Children)
{
if (childClassname.Equals(child.ClassName))
foreach (var child in from child in Children
where childClassname.Equals(child.ClassName)
select child)
{
return child;
}
}
return null;
}
@ -368,15 +339,7 @@ namespace Greenshot.Base.Core
/// Retrieve all the children, this only stores the children internally.
/// One should normally use the getter "Children"
/// </summary>
public IList<WindowDetails> GetChildren()
{
if (_childWindows == null)
{
return GetChildren(0);
}
return _childWindows;
}
public IList<WindowDetails> GetChildren() => _childWindows ?? GetChildren(0);
/// <summary>
/// Retrieve all the children, this only stores the children internally, use the "Children" property for the value
@ -437,10 +400,7 @@ namespace Greenshot.Base.Core
/// </summary>
public bool Iconic
{
get
{
return User32Api.IsIconic(Handle) || Location.X <= -32000;
}
get => User32Api.IsIconic(Handle) || Location.X <= -32000;
set
{
if (value)
@ -459,10 +419,7 @@ namespace Greenshot.Base.Core
/// </summary>
public bool Maximised
{
get
{
return User32Api.IsZoomed(Handle);
}
get => User32Api.IsZoomed(Handle);
set
{
if (value)
@ -479,27 +436,14 @@ namespace Greenshot.Base.Core
/// <summary>
/// Returns if this window is cloaked
/// </summary>
public bool IsCloaked
{
get => DwmApi.IsWindowCloaked(Handle);
}
public bool IsCloaked => DwmApi.IsWindowCloaked(Handle);
/// <summary>
/// Gets whether the window is visible.
/// </summary>
public bool Visible
{
get
{
public bool Visible =>
// Tip from Raymond Chen https://devblogs.microsoft.com/oldnewthing/20200302-00/?p=103507
if (IsCloaked)
{
return false;
}
return User32Api.IsWindowVisible(Handle);
}
}
!IsCloaked && User32Api.IsWindowVisible(Handle);
public bool HasParent
{
@ -560,15 +504,12 @@ namespace Greenshot.Base.Core
if (DwmApi.IsDwmEnabled)
{
bool gotFrameBounds = GetExtendedFrameBounds(out windowRect);
if (IsWin10App)
{
// Pre-Cache for maximized call, this is only on Windows 8 apps (full screen)
if (gotFrameBounds)
if (IsWin10App && gotFrameBounds)
{
_previousWindowRectangle = windowRect;
_lastWindowRectangleRetrieveTime = now;
}
}
if (gotFrameBounds && WindowsVersion.IsWindows10OrLater && !Maximised)
{
@ -581,14 +522,11 @@ namespace Greenshot.Base.Core
}
}
if (windowRect.IsEmpty)
{
if (!GetWindowRect(out windowRect))
if (windowRect.IsEmpty && !GetWindowRect(out windowRect))
{
Win32Error error = Win32.GetLastErrorCode();
Log.WarnFormat("Couldn't retrieve the windows rectangle: {0}", Win32.GetMessage(error));
}
}
_lastWindowRectangleRetrieveTime = now;
// Try to return something valid, by getting returning the previous size if the window doesn't have a NativeRect anymore
@ -599,25 +537,18 @@ namespace Greenshot.Base.Core
_previousWindowRectangle = windowRect;
return windowRect;
}
}
/// <summary>
/// Gets the location of the window relative to the screen.
/// </summary>
public NativePoint Location
{
get => WindowRectangle.Location;
}
public NativePoint Location => WindowRectangle.Location;
/// <summary>
/// Gets the size of the window.
/// </summary>
public NativeSize Size
{
get => WindowRectangle.Size;
}
public NativeSize Size => WindowRectangle.Size;
/// <summary>
/// Get the client rectangle, this is the part of the window inside the borders (drawable area)
@ -641,10 +572,7 @@ namespace Greenshot.Base.Core
/// </summary>
/// <param name="p">Point with the coordinates to check</param>
/// <returns>true if the point lies within</returns>
public bool Contains(NativePoint p)
{
return WindowRectangle.Contains(p);
}
public bool Contains(NativePoint p) => WindowRectangle.Contains(p);
/// <summary>
/// Restores and Brings the window to the front,
@ -675,7 +603,7 @@ namespace Greenshot.Base.Core
get => unchecked(
(WindowStyleFlags)User32Api.GetWindowLongWrapper(Handle, WindowLongIndex.GWL_STYLE).ToInt64()
);
set => User32Api.SetWindowLongWrapper(Handle, WindowLongIndex.GWL_STYLE, new IntPtr((long) value));
set => User32Api.SetWindowLongWrapper(Handle, WindowLongIndex.GWL_STYLE, new IntPtr((long)value));
}
/// <summary>
@ -689,7 +617,7 @@ namespace Greenshot.Base.Core
User32Api.GetWindowPlacement(Handle, ref placement);
return placement;
}
set { User32Api.SetWindowPlacement(Handle, ref value); }
set => User32Api.SetWindowPlacement(Handle, ref value);
}
/// <summary>
@ -697,8 +625,8 @@ namespace Greenshot.Base.Core
/// </summary>
public ExtendedWindowStyleFlags ExtendedWindowStyle
{
get => (ExtendedWindowStyleFlags) User32Api.GetWindowLongWrapper(Handle, WindowLongIndex.GWL_EXSTYLE);
set => User32Api.SetWindowLongWrapper(Handle, WindowLongIndex.GWL_EXSTYLE, new IntPtr((uint) value));
get => (ExtendedWindowStyleFlags)User32Api.GetWindowLongWrapper(Handle, WindowLongIndex.GWL_EXSTYLE);
set => User32Api.SetWindowLongWrapper(Handle, WindowLongIndex.GWL_EXSTYLE, new IntPtr((uint)value));
}
/// <summary>
@ -713,7 +641,6 @@ namespace Greenshot.Base.Core
capture.Image = capturedImage;
capture.Location = Location;
return capture;
}
/// <summary>
@ -751,14 +678,14 @@ namespace Greenshot.Base.Core
// Calculate the location of the temp form
NativeRect windowRectangle = WindowRectangle;
NativePoint formLocation = windowRectangle.Location;
NativeSize borderSize = new NativeSize();
NativeSize borderSize = new();
bool doesCaptureFit = false;
if (!Maximised)
{
// Assume using it's own location
formLocation = windowRectangle.Location;
// TODO: Use Rectangle.Union!
using Region workingArea = new Region(Screen.PrimaryScreen.Bounds);
using Region workingArea = new(Screen.PrimaryScreen.Bounds);
// Find the screen where the window is and check if it fits
foreach (Screen screen in Screen.AllScreens)
{
@ -815,10 +742,8 @@ namespace Greenshot.Base.Core
captureRectangle = captureRectangle.Inflate(Conf.Win10BorderCrop);
}
if (autoMode)
{
// check if the capture fits
if (!doesCaptureFit)
if (autoMode && !doesCaptureFit)
{
// if GDI is allowed.. (a screenshot won't be better than we comes if we continue)
using Process thisWindowProcess = Process;
@ -829,7 +754,6 @@ namespace Greenshot.Base.Core
}
}
}
}
// Prepare the displaying of the Thumbnail
var props = new DwmThumbnailProperties()
@ -913,13 +837,9 @@ namespace Greenshot.Base.Core
capturedBitmap = WindowCapture.CaptureRectangle(captureRectangle);
}
if (capturedBitmap != null)
{
// Not needed for Windows 8
if (!WindowsVersion.IsWindows8OrLater)
{
// Only if the Inivalue is set, not maximized and it's not a tool window.
if (Conf.WindowCaptureRemoveCorners && !Maximised && (ExtendedWindowStyle & ExtendedWindowStyleFlags.WS_EX_TOOLWINDOW) == 0)
// Not needed for Windows 8
if (capturedBitmap != null && !WindowsVersion.IsWindows8OrLater && Conf.WindowCaptureRemoveCorners && !Maximised && (ExtendedWindowStyle & ExtendedWindowStyleFlags.WS_EX_TOOLWINDOW) == 0)
{
// Remove corners
if (!Image.IsAlphaPixelFormat(capturedBitmap.PixelFormat))
@ -933,8 +853,6 @@ namespace Greenshot.Base.Core
RemoveCorners(capturedBitmap);
}
}
}
}
finally
{
// Make sure to ALWAYS unfreeze!!
@ -1025,12 +943,12 @@ namespace Greenshot.Base.Core
else
{
// Calculate original color
byte originalAlpha = (byte) Math.Min(255, alpha);
byte originalAlpha = (byte)Math.Min(255, alpha);
var alphaFactor = alpha / 255d;
//LOG.DebugFormat("Alpha {0} & c0 {1} & c1 {2}", alpha, c0, c1);
byte originalRed = (byte) Math.Min(255, c0.R / alphaFactor);
byte originalGreen = (byte) Math.Min(255, c0.G / alphaFactor);
byte originalBlue = (byte) Math.Min(255, c0.B / alphaFactor);
byte originalRed = (byte)Math.Min(255, c0.R / alphaFactor);
byte originalGreen = (byte)Math.Min(255, c0.G / alphaFactor);
byte originalBlue = (byte)Math.Min(255, c0.B / alphaFactor);
Color originalColor = Color.FromArgb(originalAlpha, originalRed, originalGreen, originalBlue);
//Color originalColor = Color.FromArgb(originalAlpha, originalRed, c0.G, c0.B);
targetBuffer.SetColorAt(x, y, originalColor);
@ -1095,14 +1013,7 @@ namespace Greenshot.Base.Core
var windowInfo = new WindowInfo();
// Get the Window Info for this window
bool result = User32Api.GetWindowInfo(Handle, ref windowInfo);
if (IsHidden(windowInfo.Bounds))
{
rectangle = NativeRect.Empty;
}
else
{
rectangle = result ? windowInfo.Bounds : NativeRect.Empty;
}
rectangle = IsHidden(windowInfo.Bounds) ? NativeRect.Empty : result ? windowInfo.Bounds : NativeRect.Empty;
return result;
}
@ -1165,10 +1076,7 @@ namespace Greenshot.Base.Core
/// <summary>
/// Set the window as foreground window
/// </summary>
public void ToForeground()
{
ToForeground(Handle);
}
public void ToForeground() => ToForeground(Handle);
/// <summary>
/// Get the region for a window
@ -1197,18 +1105,17 @@ namespace Greenshot.Base.Core
return false;
}
if (titleOrProcessname.ToLower().Contains("greenshot"))
if (titleOrProcessname.IndexOf("greenshot", StringComparison.CurrentCultureIgnoreCase) >= 0)
{
return false;
}
foreach (string excludeProcess in ExcludeProcessesFromFreeze)
{
if (titleOrProcessname.ToLower().Contains(excludeProcess))
foreach (var _ in from string excludeProcess in ExcludeProcessesFromFreeze
where titleOrProcessname.ToLower().Contains(excludeProcess)
select new { })
{
return false;
}
}
return true;
}
@ -1237,10 +1144,9 @@ namespace Greenshot.Base.Core
Log.DebugFormat("Freezing process: {0}", processName);
foreach (ProcessThread pT in proc.Threads)
{
IntPtr pOpenThread = Kernel32Api.OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint) pT.Id);
IntPtr pOpenThread = Kernel32Api.OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);
if (pOpenThread == IntPtr.Zero)
{
@ -1279,7 +1185,7 @@ namespace Greenshot.Base.Core
foreach (ProcessThread pT in proc.Threads)
{
IntPtr pOpenThread = Kernel32Api.OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint) pT.Id);
IntPtr pOpenThread = Kernel32Api.OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);
if (pOpenThread == IntPtr.Zero)
{
@ -1312,7 +1218,7 @@ namespace Greenshot.Base.Core
backgroundColor = Color.Transparent;
}
returnImage = ImageHelper.CreateEmpty(windowRect.Width, windowRect.Height, pixelFormat, backgroundColor, 96,96);
returnImage = ImageHelper.CreateEmpty(windowRect.Width, windowRect.Height, pixelFormat, backgroundColor, 96, 96);
using Graphics graphics = Graphics.FromImage(returnImage);
using (SafeGraphicsDcHandle graphicsDc = graphics.GetSafeDeviceContext())
{
@ -1326,7 +1232,7 @@ namespace Greenshot.Base.Core
}
// Apply the region "transparency"
if (region != null && !region.IsEmpty(graphics))
if (region?.IsEmpty(graphics) == false)
{
graphics.ExcludeClip(region);
graphics.Clear(Color.Transparent);
@ -1347,7 +1253,7 @@ namespace Greenshot.Base.Core
{
Log.Debug("Correcting for maximized window");
GetBorderSize(out var borderSize);
NativeRect borderRectangle = new NativeRect(borderSize.Width, borderSize.Height, windowRect.Width - (2 * borderSize.Width), windowRect.Height - (2 * borderSize.Height));
NativeRect borderRectangle = new(borderSize.Width, borderSize.Height, windowRect.Width - (2 * borderSize.Width), windowRect.Height - (2 * borderSize.Height));
ImageHelper.Crop(ref returnImage, ref borderRectangle);
}
@ -1359,10 +1265,7 @@ namespace Greenshot.Base.Core
/// the specified Window Handle.
/// </summary>
/// <param name="hWnd">The Window Handle</param>
public WindowDetails(IntPtr hWnd)
{
Handle = hWnd;
}
public WindowDetails(IntPtr hWnd) => Handle = hWnd;
/// <summary>
/// Gets an instance of the current active foreground window
@ -1378,14 +1281,9 @@ namespace Greenshot.Base.Core
return GetDesktopWindow();
}
WindowDetails activeWindow = new WindowDetails(hWnd);
WindowDetails activeWindow = new(hWnd);
// Invisible Windows should not be active
if (!activeWindow.Visible)
{
return GetDesktopWindow();
}
return activeWindow;
return !activeWindow.Visible ? GetDesktopWindow() : activeWindow;
}
return null;
@ -1395,28 +1293,19 @@ namespace Greenshot.Base.Core
/// Gets the Desktop window
/// </summary>
/// <returns>WindowDetails for the desktop window</returns>
public static WindowDetails GetDesktopWindow()
{
return new WindowDetails(User32Api.GetDesktopWindow());
}
public static WindowDetails GetDesktopWindow() => new(User32Api.GetDesktopWindow());
/// <summary>
/// Get all the top level windows
/// </summary>
/// <returns>List of WindowDetails with all the top level windows</returns>
public static IList<WindowDetails> GetAllWindows()
{
return GetAllWindows(null);
}
public static IList<WindowDetails> GetAllWindows() => GetAllWindows(null);
/// <summary>
/// Get all the top level windows, with matching classname
/// </summary>
/// <returns>List WindowDetails with all the top level windows</returns>
public static IList<WindowDetails> GetAllWindows(string classname)
{
return new WindowsEnumerator().GetWindows(IntPtr.Zero, classname).Items;
}
public static IList<WindowDetails> GetAllWindows(string classname) => new WindowsEnumerator().GetWindows(IntPtr.Zero, classname).Items;
/// <summary>
/// Recursive "find children which"
@ -1437,14 +1326,14 @@ namespace Greenshot.Base.Core
return this;
}
foreach (var childWindow in
// Look into the child windows
foreach (var childWindow in Children)
{
if (childWindow.Contains(point))
from childWindow in Children
where childWindow.Contains(point)
select childWindow)
{
return childWindow.FindChildUnderPoint(point);
}
}
return this;
}
@ -1483,12 +1372,7 @@ namespace Greenshot.Base.Core
// Skip everything which is not rendered "normally", trying to fix BUG-2017
var exWindowStyle = window.ExtendedWindowStyle;
if (!window.IsWin10App && (exWindowStyle & ExtendedWindowStyleFlags.WS_EX_NOREDIRECTIONBITMAP) != 0)
{
return false;
}
return true;
return window.IsWin10App || (exWindowStyle & ExtendedWindowStyleFlags.WS_EX_NOREDIRECTIONBITMAP) == 0;
}
/// <summary>
@ -1498,14 +1382,9 @@ namespace Greenshot.Base.Core
public static IEnumerable<WindowDetails> GetVisibleWindows()
{
var screenBounds = DisplayInfo.ScreenBounds;
foreach (var window in GetAllWindows())
{
if (IsVisible(window, screenBounds))
{
yield return window;
}
}
return from window in GetAllWindows()
where IsVisible(window, screenBounds)
select window;
}
/// <summary>
@ -1560,12 +1439,7 @@ namespace Greenshot.Base.Core
return false;
}
if (!(window.Visible || window.Iconic))
{
return false;
}
return !window.IsBackgroundWin10App;
return (window.Visible || window.Iconic) && !window.IsBackgroundWin10App;
}
/// <summary>
@ -1574,13 +1448,9 @@ namespace Greenshot.Base.Core
/// <returns>List WindowDetails with all the top level windows</returns>
public static IEnumerable<WindowDetails> GetTopLevelWindows()
{
foreach (var possibleTopLevel in GetAllWindows())
{
if (IsTopLevel(possibleTopLevel))
{
yield return possibleTopLevel;
}
}
return from possibleTopLevel in GetAllWindows()
where IsTopLevel(possibleTopLevel)
select possibleTopLevel;
}
/// <summary>
@ -1653,18 +1523,7 @@ namespace Greenshot.Base.Core
/// Return true if the metro-app-launcher is visible
/// </summary>
/// <returns></returns>
public static bool IsAppLauncherVisible
{
get
{
if (AppVisibility != null)
{
return AppVisibility.IsLauncherVisible;
}
return false;
}
}
public static bool IsAppLauncherVisible => AppVisibility?.IsLauncherVisible == true;
/// <summary>
/// Make a string representation of the window details
@ -1673,21 +1532,21 @@ namespace Greenshot.Base.Core
public override string ToString()
{
var result = new StringBuilder();
result.AppendLine($"Text: {Text}");
result.AppendLine($"ClassName: {ClassName}");
result.AppendLine($"ExtendedWindowStyle: {ExtendedWindowStyle}");
result.AppendLine($"WindowStyle: {WindowStyle}");
result.AppendLine($"Size: {WindowRectangle.Size}");
result.AppendLine($"HasParent: {HasParent}");
result.AppendLine($"IsWin10App: {IsWin10App}");
result.AppendLine($"Visible: {Visible}");
result.AppendLine($"IsWindowVisible: {User32Api.IsWindowVisible(Handle)}");
result.AppendLine($"IsCloaked: {IsCloaked}");
result.AppendLine($"Iconic: {Iconic}");
result.AppendLine($"IsBackgroundWin10App: {IsBackgroundWin10App}");
result.Append("Text: ").AppendLine(Text);
result.Append("ClassName: ").AppendLine(ClassName);
result.Append("ExtendedWindowStyle: ").Append(ExtendedWindowStyle).AppendLine();
result.Append("WindowStyle: ").Append(WindowStyle).AppendLine();
result.Append("Size: ").Append(WindowRectangle.Size).AppendLine();
result.Append("HasParent: ").Append(HasParent).AppendLine();
result.Append("IsWin10App: ").Append(IsWin10App).AppendLine();
result.Append("Visible: ").Append(Visible).AppendLine();
result.Append("IsWindowVisible: ").Append(User32Api.IsWindowVisible(Handle)).AppendLine();
result.Append("IsCloaked: ").Append(IsCloaked).AppendLine();
result.Append("Iconic: ").Append(Iconic).AppendLine();
result.Append("IsBackgroundWin10App: ").Append(IsBackgroundWin10App).AppendLine();
if (HasChildren)
{
result.AppendLine($"Children classes: {string.Join(",", Children.Select(c => c.ClassName))}");
result.Append("Children classes: ").AppendLine(string.Join(",", Children.Select(c => c.ClassName)));
}
return result.ToString();

View file

@ -37,13 +37,13 @@ namespace Greenshot.Base.Core
/// Test if the current OS is Windows 8.1 or later
/// </summary>
/// <returns>true if we are running on Windows 8.1 or later</returns>
public static bool IsWindows81OrLater { get; } = WinVersion.Major == 6 && WinVersion.Minor >= 3 || WinVersion.Major > 6;
public static bool IsWindows81OrLater { get; } = (WinVersion.Major == 6 && WinVersion.Minor >= 3) || WinVersion.Major > 6;
/// <summary>
/// Test if the current OS is Windows 8 or later
/// </summary>
/// <returns>true if we are running on Windows 8 or later</returns>
public static bool IsWindows8OrLater { get; } = WinVersion.Major == 6 && WinVersion.Minor >= 2 || WinVersion.Major > 6;
public static bool IsWindows8OrLater { get; } = (WinVersion.Major == 6 && WinVersion.Minor >= 2) || WinVersion.Major > 6;
/// <summary>
/// Test if the current OS is Windows Vista or later
@ -62,9 +62,6 @@ namespace Greenshot.Base.Core
/// </summary>
/// <param name="minimalBuildNumber">int</param>
/// <returns>bool</returns>
public static bool IsWindows10BuildOrLater(int minimalBuildNumber)
{
return IsWindows10 && WinVersion.Build >= minimalBuildNumber;
}
public static bool IsWindows10BuildOrLater(int minimalBuildNumber) => IsWindows10 && WinVersion.Build >= minimalBuildNumber;
}
}

View file

@ -38,10 +38,7 @@ namespace Greenshot.Base.Core
/// </summary>
/// <param name="m">Message</param>
/// <returns>true if the message should be filtered</returns>
public bool PreFilterMessage(ref Message m)
{
return PreFilterMessageExternal(ref m);
}
public bool PreFilterMessage(ref Message m) => PreFilterMessageExternal(ref m);
/// <summary>
/// Also used in the MainForm WndProc
@ -50,7 +47,7 @@ namespace Greenshot.Base.Core
/// <returns>true if the message should be filtered</returns>
public static bool PreFilterMessageExternal(ref Message m)
{
WindowsMessages message = (WindowsMessages) m.Msg;
WindowsMessages message = (WindowsMessages)m.Msg;
if (message != WindowsMessages.WM_INPUTLANGCHANGEREQUEST && message != WindowsMessages.WM_INPUTLANGCHANGE) return false;
LOG.DebugFormat("Filtering: {0}, {1:X} - {2:X} - {3:X}", message, m.LParam.ToInt64(), m.WParam.ToInt64(), m.HWnd.ToInt64());

View file

@ -30,10 +30,7 @@ namespace Greenshot.Base.Effects
/// </summary>
public class AdjustEffect : IEffect
{
public AdjustEffect()
{
Reset();
}
public AdjustEffect() => Reset();
public float Contrast { get; set; }
public float Brightness { get; set; }
@ -46,9 +43,6 @@ namespace Greenshot.Base.Effects
Gamma = 1f;
}
public Image Apply(Image sourceImage, Matrix matrix)
{
return ImageHelper.Adjust(sourceImage, Brightness, Contrast, Gamma);
}
public Image Apply(Image sourceImage, Matrix matrix) => ImageHelper.Adjust(sourceImage, Brightness, Contrast, Gamma);
}
}

View file

@ -30,10 +30,7 @@ namespace Greenshot.Base.Effects
/// </summary>
public class BorderEffect : IEffect
{
public BorderEffect()
{
Reset();
}
public BorderEffect() => Reset();
public Color Color { get; set; }
public int Width { get; set; }
@ -44,9 +41,6 @@ namespace Greenshot.Base.Effects
Color = Color.Black;
}
public Image Apply(Image sourceImage, Matrix matrix)
{
return ImageHelper.CreateBorder(sourceImage, Width, Color, sourceImage.PixelFormat, matrix);
}
public Image Apply(Image sourceImage, Matrix matrix) => ImageHelper.CreateBorder(sourceImage, Width, Color, sourceImage.PixelFormat, matrix);
}
}

View file

@ -34,10 +34,7 @@ namespace Greenshot.Base.Effects
[TypeConverter(typeof(EffectConverter))]
public class DropShadowEffect : IEffect
{
public DropShadowEffect()
{
Reset();
}
public DropShadowEffect() => Reset();
public float Darkness { get; set; }
@ -52,9 +49,6 @@ namespace Greenshot.Base.Effects
ShadowOffset = new Point(-1, -1);
}
public virtual Image Apply(Image sourceImage, Matrix matrix)
{
return ImageHelper.CreateShadow(sourceImage, Darkness, ShadowSize, ShadowOffset, matrix, PixelFormat.Format32bppArgb);
}
public virtual Image Apply(Image sourceImage, Matrix matrix) => ImageHelper.CreateShadow(sourceImage, Darkness, ShadowSize, ShadowOffset, matrix, PixelFormat.Format32bppArgb);
}
}

View file

@ -30,10 +30,7 @@ namespace Greenshot.Base.Effects
/// </summary>
public class GrayscaleEffect : IEffect
{
public Image Apply(Image sourceImage, Matrix matrix)
{
return ImageHelper.CreateGrayscale(sourceImage);
}
public Image Apply(Image sourceImage, Matrix matrix) => ImageHelper.CreateGrayscale(sourceImage);
public void Reset()
{

View file

@ -30,10 +30,7 @@ namespace Greenshot.Base.Effects
/// </summary>
public class InvertEffect : IEffect
{
public Image Apply(Image sourceImage, Matrix matrix)
{
return ImageHelper.CreateNegative(sourceImage);
}
public Image Apply(Image sourceImage, Matrix matrix) => ImageHelper.CreateNegative(sourceImage);
public void Reset()
{

View file

@ -33,19 +33,13 @@ namespace Greenshot.Base.Effects
private readonly byte _threshold;
/// <param name="threshold">Threshold for monochrome filter (0 - 255), lower value means less black</param>
public MonochromeEffect(byte threshold)
{
_threshold = threshold;
}
public MonochromeEffect(byte threshold) => _threshold = threshold;
public void Reset()
{
// TODO: Modify the threshold to have a default, which is reset here
}
public Image Apply(Image sourceImage, Matrix matrix)
{
return ImageHelper.CreateMonochrome(sourceImage, _threshold);
}
public Image Apply(Image sourceImage, Matrix matrix) => ImageHelper.CreateMonochrome(sourceImage, _threshold);
}
}

View file

@ -34,21 +34,15 @@ namespace Greenshot.Base.Effects
{
private static readonly ILog Log = LogManager.GetLogger(typeof(ReduceColorsEffect));
public ReduceColorsEffect()
{
Reset();
}
public ReduceColorsEffect() => Reset();
public int Colors { get; set; }
public void Reset()
{
Colors = 256;
}
public void Reset() => Colors = 256;
public Image Apply(Image sourceImage, Matrix matrix)
{
using (WuQuantizer quantizer = new WuQuantizer((Bitmap) sourceImage))
using (WuQuantizer quantizer = new((Bitmap)sourceImage))
{
int colorCount = quantizer.GetColorCount();
if (colorCount > Colors)

View file

@ -50,9 +50,6 @@ namespace Greenshot.Base.Effects
// values don't have a default value
}
public Image Apply(Image sourceImage, Matrix matrix)
{
return ImageHelper.ResizeCanvas(sourceImage, BackgroundColor, Left, Right, Top, Bottom, matrix);
}
public Image Apply(Image sourceImage, Matrix matrix) => ImageHelper.ResizeCanvas(sourceImage, BackgroundColor, Left, Right, Top, Bottom, matrix);
}
}

View file

@ -46,9 +46,6 @@ namespace Greenshot.Base.Effects
// values don't have a default value
}
public Image Apply(Image sourceImage, Matrix matrix)
{
return ImageHelper.ResizeImage(sourceImage, MaintainAspectRatio, Width, Height, matrix);
}
public Image Apply(Image sourceImage, Matrix matrix) => ImageHelper.ResizeImage(sourceImage, MaintainAspectRatio, Width, Height, matrix);
}
}

View file

@ -31,10 +31,7 @@ namespace Greenshot.Base.Effects
/// </summary>
public class RotateEffect : IEffect
{
public RotateEffect(int angle)
{
Angle = angle;
}
public RotateEffect(int angle) => Angle = angle;
public int Angle { get; set; }

View file

@ -33,10 +33,7 @@ namespace Greenshot.Base.Effects
[TypeConverter(typeof(EffectConverter))]
public sealed class TornEdgeEffect : DropShadowEffect
{
public TornEdgeEffect()
{
Reset();
}
public TornEdgeEffect() => Reset();
public int ToothHeight { get; set; }
public int HorizontalToothRange { get; set; }

View file

@ -14,6 +14,14 @@
<PackageReference Include="Dapplo.Windows.Multimedia" Version="1.0.26" />
<PackageReference Include="HtmlAgilityPack" Version="1.11.43" />
<PackageReference Include="log4net" version="2.0.14" />
<PackageReference Include="Roslynator.Analyzers" Version="4.1.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="SonarAnalyzer.CSharp" Version="8.41.0.50478">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Svg" Version="3.4.2" />
<Reference Include="Accessibility" />
<Reference Include="CustomMarshalers" />
@ -21,4 +29,10 @@
<ItemGroup>
<EmbeddedResource Include="log4net-embedded.xml" />
</ItemGroup>
<ItemGroup>
<PackageReference Update="Nerdbank.GitVersioning" Version="3.5.108">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>

View file

@ -33,7 +33,7 @@ namespace Greenshot.Base.Help
{
private static readonly ILog Log = LogManager.GetLogger(typeof(HelpFileLoader));
private const string ExtHelpUrl = @"https://getgreenshot.org/help/";
private const string ExtHelpUrl = "https://getgreenshot.org/help/";
public static void LoadHelp()
{
@ -89,12 +89,12 @@ namespace Greenshot.Base.Help
try
{
HttpWebRequest req = NetworkHelper.CreateWebRequest(url);
using HttpWebResponse res = (HttpWebResponse) req.GetResponse();
using HttpWebResponse res = (HttpWebResponse)req.GetResponse();
return res.StatusCode;
}
catch (WebException e)
{
return ((HttpWebResponse) e.Response)?.StatusCode;
return ((HttpWebResponse)e.Response)?.StatusCode;
}
}
}

View file

@ -79,7 +79,8 @@ namespace Greenshot.Base.IEInterop
[DispId(1014)]
[return: MarshalAs(UnmanagedType.BStr)]
get;
[DispId(1014)] set;
[DispId(1014)]
set;
}
}
}

View file

@ -28,47 +28,47 @@ namespace Greenshot.Base.IEInterop
InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IHTMLFrameBase
{
//dispinterface IHTMLFrameBase {
// properties:
// methods:
// [id(0x80010bb8), propput]
// void src([in] BSTR rhs);
// [id(0x80010bb8), propget]
// BSTR src();
// [id(0x80010000), propput]
// void name([in] BSTR rhs);
// [id(0x80010000), propget]
// BSTR name();
// [id(0x80010bba), propput]
// void border([in] VARIANT rhs);
// [id(0x80010bba), propget]
// VARIANT border();
// [id(0x80010bbb), propput]
// void frameBorder([in] BSTR rhs);
// [id(0x80010bbb), propget]
// BSTR frameBorder();
// [id(0x80010bbc), propput]
// void frameSpacing([in] VARIANT rhs);
// [id(0x80010bbc), propget]
// VARIANT frameSpacing();
// [id(0x80010bbd), propput]
// void marginWidth([in] VARIANT rhs);
// [id(0x80010bbd), propget]
// VARIANT marginWidth();
// [id(0x80010bbe), propput]
// void marginHeight([in] VARIANT rhs);
// [id(0x80010bbe), propget]
// VARIANT marginHeight();
// [id(0x80010bbf), propput]
// void noResize([in] VARIANT_BOOL rhs);
// [id(0x80010bbf), propget]
// VARIANT_BOOL noResize();
// [id(0x80010bc0), propput]
// void scrolling([in] BSTR rhs);
// [id(0x80010bc0), propget]
// BSTR scrolling();
//};
// [DispId(HTMLDispIDs.DISPID_IHTMLFRAMEBASE_SRC)]
//dispinterface IHTMLFrameBase {
// properties:
// methods:
// [id(0x80010bb8), propput]
// void src([in] BSTR rhs);
// [id(0x80010bb8), propget]
// BSTR src();
// [id(0x80010000), propput]
// void name([in] BSTR rhs);
// [id(0x80010000), propget]
// BSTR name();
// [id(0x80010bba), propput]
// void border([in] VARIANT rhs);
// [id(0x80010bba), propget]
// VARIANT border();
// [id(0x80010bbb), propput]
// void frameBorder([in] BSTR rhs);
// [id(0x80010bbb), propget]
// BSTR frameBorder();
// [id(0x80010bbc), propput]
// void frameSpacing([in] VARIANT rhs);
// [id(0x80010bbc), propget]
// VARIANT frameSpacing();
// [id(0x80010bbd), propput]
// void marginWidth([in] VARIANT rhs);
// [id(0x80010bbd), propget]
// VARIANT marginWidth();
// [id(0x80010bbe), propput]
// void marginHeight([in] VARIANT rhs);
// [id(0x80010bbe), propget]
// VARIANT marginHeight();
// [id(0x80010bbf), propput]
// void noResize([in] VARIANT_BOOL rhs);
// [id(0x80010bbf), propget]
// VARIANT_BOOL noResize();
// [id(0x80010bc0), propput]
// void scrolling([in] BSTR rhs);
// [id(0x80010bc0), propget]
// BSTR scrolling();
//};
// [DispId(HTMLDispIDs.DISPID_IHTMLFRAMEBASE_SRC)]
string src
{
[return: MarshalAs(UnmanagedType.BStr)]

View file

@ -71,7 +71,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT background (BSTR value);
// VB6: Sub background (ByVal value As String)
[DispId(-2147413080)] set;
[DispId(-2147413080)]
set;
}
/// <summary><para><c>backgroundAttachment</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -87,7 +88,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT backgroundAttachment (BSTR value);
// VB6: Sub backgroundAttachment (ByVal value As String)
[DispId(-2147413067)] set;
[DispId(-2147413067)]
set;
}
/// <summary><para><c>backgroundColor</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -98,10 +100,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT backgroundColor ([out, retval] VARIANT* ReturnValue);
// VB6: Function backgroundColor As Any
[DispId(-501)] get;
[DispId(-501)]
get;
// IDL: HRESULT backgroundColor (VARIANT value);
// VB6: Sub backgroundColor (ByVal value As Any)
[DispId(-501)] set;
[DispId(-501)]
set;
}
/// <summary><para><c>backgroundImage</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -117,7 +121,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT backgroundImage (BSTR value);
// VB6: Sub backgroundImage (ByVal value As String)
[DispId(-2147413111)] set;
[DispId(-2147413111)]
set;
}
/// <summary><para><c>backgroundPosition</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -133,7 +138,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT backgroundPosition (BSTR value);
// VB6: Sub backgroundPosition (ByVal value As String)
[DispId(-2147413066)] set;
[DispId(-2147413066)]
set;
}
/// <summary><para><c>backgroundPositionX</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -144,10 +150,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT backgroundPositionX ([out, retval] VARIANT* ReturnValue);
// VB6: Function backgroundPositionX As Any
[DispId(-2147413079)] get;
[DispId(-2147413079)]
get;
// IDL: HRESULT backgroundPositionX (VARIANT value);
// VB6: Sub backgroundPositionX (ByVal value As Any)
[DispId(-2147413079)] set;
[DispId(-2147413079)]
set;
}
/// <summary><para><c>backgroundPositionY</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -158,10 +166,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT backgroundPositionY ([out, retval] VARIANT* ReturnValue);
// VB6: Function backgroundPositionY As Any
[DispId(-2147413078)] get;
[DispId(-2147413078)]
get;
// IDL: HRESULT backgroundPositionY (VARIANT value);
// VB6: Sub backgroundPositionY (ByVal value As Any)
[DispId(-2147413078)] set;
[DispId(-2147413078)]
set;
}
/// <summary><para><c>backgroundRepeat</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -177,7 +187,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT backgroundRepeat (BSTR value);
// VB6: Sub backgroundRepeat (ByVal value As String)
[DispId(-2147413068)] set;
[DispId(-2147413068)]
set;
}
/// <summary><para><c>border</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -193,7 +204,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT border (BSTR value);
// VB6: Sub border (ByVal value As String)
[DispId(-2147413063)] set;
[DispId(-2147413063)]
set;
}
/// <summary><para><c>borderBottom</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -209,7 +221,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT borderBottom (BSTR value);
// VB6: Sub borderBottom (ByVal value As String)
[DispId(-2147413060)] set;
[DispId(-2147413060)]
set;
}
/// <summary><para><c>borderBottomColor</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -220,10 +233,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT borderBottomColor ([out, retval] VARIANT* ReturnValue);
// VB6: Function borderBottomColor As Any
[DispId(-2147413055)] get;
[DispId(-2147413055)]
get;
// IDL: HRESULT borderBottomColor (VARIANT value);
// VB6: Sub borderBottomColor (ByVal value As Any)
[DispId(-2147413055)] set;
[DispId(-2147413055)]
set;
}
/// <summary><para><c>borderBottomStyle</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -239,7 +254,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT borderBottomStyle (BSTR value);
// VB6: Sub borderBottomStyle (ByVal value As String)
[DispId(-2147413045)] set;
[DispId(-2147413045)]
set;
}
/// <summary><para><c>borderBottomWidth</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -250,10 +266,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT borderBottomWidth ([out, retval] VARIANT* ReturnValue);
// VB6: Function borderBottomWidth As Any
[DispId(-2147413050)] get;
[DispId(-2147413050)]
get;
// IDL: HRESULT borderBottomWidth (VARIANT value);
// VB6: Sub borderBottomWidth (ByVal value As Any)
[DispId(-2147413050)] set;
[DispId(-2147413050)]
set;
}
/// <summary><para><c>borderColor</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -269,7 +287,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT borderColor (BSTR value);
// VB6: Sub borderColor (ByVal value As String)
[DispId(-2147413058)] set;
[DispId(-2147413058)]
set;
}
/// <summary><para><c>borderLeft</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -285,7 +304,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT borderLeft (BSTR value);
// VB6: Sub borderLeft (ByVal value As String)
[DispId(-2147413059)] set;
[DispId(-2147413059)]
set;
}
/// <summary><para><c>borderLeftColor</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -296,10 +316,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT borderLeftColor ([out, retval] VARIANT* ReturnValue);
// VB6: Function borderLeftColor As Any
[DispId(-2147413054)] get;
[DispId(-2147413054)]
get;
// IDL: HRESULT borderLeftColor (VARIANT value);
// VB6: Sub borderLeftColor (ByVal value As Any)
[DispId(-2147413054)] set;
[DispId(-2147413054)]
set;
}
/// <summary><para><c>borderLeftStyle</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -315,7 +337,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT borderLeftStyle (BSTR value);
// VB6: Sub borderLeftStyle (ByVal value As String)
[DispId(-2147413044)] set;
[DispId(-2147413044)]
set;
}
/// <summary><para><c>borderLeftWidth</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -326,10 +349,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT borderLeftWidth ([out, retval] VARIANT* ReturnValue);
// VB6: Function borderLeftWidth As Any
[DispId(-2147413049)] get;
[DispId(-2147413049)]
get;
// IDL: HRESULT borderLeftWidth (VARIANT value);
// VB6: Sub borderLeftWidth (ByVal value As Any)
[DispId(-2147413049)] set;
[DispId(-2147413049)]
set;
}
/// <summary><para><c>borderRight</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -345,7 +370,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT borderRight (BSTR value);
// VB6: Sub borderRight (ByVal value As String)
[DispId(-2147413061)] set;
[DispId(-2147413061)]
set;
}
/// <summary><para><c>borderRightColor</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -356,10 +382,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT borderRightColor ([out, retval] VARIANT* ReturnValue);
// VB6: Function borderRightColor As Any
[DispId(-2147413056)] get;
[DispId(-2147413056)]
get;
// IDL: HRESULT borderRightColor (VARIANT value);
// VB6: Sub borderRightColor (ByVal value As Any)
[DispId(-2147413056)] set;
[DispId(-2147413056)]
set;
}
/// <summary><para><c>borderRightStyle</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -375,7 +403,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT borderRightStyle (BSTR value);
// VB6: Sub borderRightStyle (ByVal value As String)
[DispId(-2147413046)] set;
[DispId(-2147413046)]
set;
}
/// <summary><para><c>borderRightWidth</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -386,10 +415,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT borderRightWidth ([out, retval] VARIANT* ReturnValue);
// VB6: Function borderRightWidth As Any
[DispId(-2147413051)] get;
[DispId(-2147413051)]
get;
// IDL: HRESULT borderRightWidth (VARIANT value);
// VB6: Sub borderRightWidth (ByVal value As Any)
[DispId(-2147413051)] set;
[DispId(-2147413051)]
set;
}
/// <summary><para><c>borderStyle</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -405,7 +436,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT borderStyle (BSTR value);
// VB6: Sub borderStyle (ByVal value As String)
[DispId(-2147413048)] set;
[DispId(-2147413048)]
set;
}
/// <summary><para><c>borderTop</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -421,7 +453,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT borderTop (BSTR value);
// VB6: Sub borderTop (ByVal value As String)
[DispId(-2147413062)] set;
[DispId(-2147413062)]
set;
}
/// <summary><para><c>borderTopColor</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -432,10 +465,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT borderTopColor ([out, retval] VARIANT* ReturnValue);
// VB6: Function borderTopColor As Any
[DispId(-2147413057)] get;
[DispId(-2147413057)]
get;
// IDL: HRESULT borderTopColor (VARIANT value);
// VB6: Sub borderTopColor (ByVal value As Any)
[DispId(-2147413057)] set;
[DispId(-2147413057)]
set;
}
/// <summary><para><c>borderTopStyle</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -451,7 +486,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT borderTopStyle (BSTR value);
// VB6: Sub borderTopStyle (ByVal value As String)
[DispId(-2147413047)] set;
[DispId(-2147413047)]
set;
}
/// <summary><para><c>borderTopWidth</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -462,10 +498,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT borderTopWidth ([out, retval] VARIANT* ReturnValue);
// VB6: Function borderTopWidth As Any
[DispId(-2147413052)] get;
[DispId(-2147413052)]
get;
// IDL: HRESULT borderTopWidth (VARIANT value);
// VB6: Sub borderTopWidth (ByVal value As Any)
[DispId(-2147413052)] set;
[DispId(-2147413052)]
set;
}
/// <summary><para><c>borderWidth</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -481,7 +519,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT borderWidth (BSTR value);
// VB6: Sub borderWidth (ByVal value As String)
[DispId(-2147413053)] set;
[DispId(-2147413053)]
set;
}
/// <summary><para><c>clear</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -497,7 +536,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT clear (BSTR value);
// VB6: Sub clear (ByVal value As String)
[DispId(-2147413096)] set;
[DispId(-2147413096)]
set;
}
/// <summary><para><c>clip</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -513,7 +553,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT clip (BSTR value);
// VB6: Sub clip (ByVal value As String)
[DispId(-2147413020)] set;
[DispId(-2147413020)]
set;
}
/// <summary><para><c>color</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -524,10 +565,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT color ([out, retval] VARIANT* ReturnValue);
// VB6: Function color As Any
[DispId(-2147413110)] get;
[DispId(-2147413110)]
get;
// IDL: HRESULT color (VARIANT value);
// VB6: Sub color (ByVal value As Any)
[DispId(-2147413110)] set;
[DispId(-2147413110)]
set;
}
/// <summary><para><c>cssText</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -543,7 +586,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT cssText (BSTR value);
// VB6: Sub cssText (ByVal value As String)
[DispId(-2147413013)] set;
[DispId(-2147413013)]
set;
}
/// <summary><para><c>cursor</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -559,7 +603,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT cursor (BSTR value);
// VB6: Sub cursor (ByVal value As String)
[DispId(-2147413010)] set;
[DispId(-2147413010)]
set;
}
/// <summary><para><c>display</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -575,7 +620,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT display (BSTR value);
// VB6: Sub display (ByVal value As String)
[DispId(-2147413041)] set;
[DispId(-2147413041)]
set;
}
/// <summary><para><c>filter</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -591,7 +637,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT filter (BSTR value);
// VB6: Sub filter (ByVal value As String)
[DispId(-2147413030)] set;
[DispId(-2147413030)]
set;
}
/// <summary><para><c>font</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -607,7 +654,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT font (BSTR value);
// VB6: Sub font (ByVal value As String)
[DispId(-2147413071)] set;
[DispId(-2147413071)]
set;
}
/// <summary><para><c>fontFamily</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -623,7 +671,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT fontFamily (BSTR value);
// VB6: Sub fontFamily (ByVal value As String)
[DispId(-2147413094)] set;
[DispId(-2147413094)]
set;
}
/// <summary><para><c>fontSize</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -634,10 +683,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT fontSize ([out, retval] VARIANT* ReturnValue);
// VB6: Function fontSize As Any
[DispId(-2147413093)] get;
[DispId(-2147413093)]
get;
// IDL: HRESULT fontSize (VARIANT value);
// VB6: Sub fontSize (ByVal value As Any)
[DispId(-2147413093)] set;
[DispId(-2147413093)]
set;
}
/// <summary><para><c>fontStyle</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -653,7 +704,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT fontStyle (BSTR value);
// VB6: Sub fontStyle (ByVal value As String)
[DispId(-2147413088)] set;
[DispId(-2147413088)]
set;
}
/// <summary><para><c>fontVariant</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -669,7 +721,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT fontVariant (BSTR value);
// VB6: Sub fontVariant (ByVal value As String)
[DispId(-2147413087)] set;
[DispId(-2147413087)]
set;
}
/// <summary><para><c>fontWeight</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -685,7 +738,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT fontWeight (BSTR value);
// VB6: Sub fontWeight (ByVal value As String)
[DispId(-2147413085)] set;
[DispId(-2147413085)]
set;
}
/// <summary><para><c>height</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -696,10 +750,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT height ([out, retval] VARIANT* ReturnValue);
// VB6: Function height As Any
[DispId(-2147418106)] get;
[DispId(-2147418106)]
get;
// IDL: HRESULT height (VARIANT value);
// VB6: Sub height (ByVal value As Any)
[DispId(-2147418106)] set;
[DispId(-2147418106)]
set;
}
/// <summary><para><c>left</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -710,10 +766,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT left ([out, retval] VARIANT* ReturnValue);
// VB6: Function left As Any
[DispId(-2147418109)] get;
[DispId(-2147418109)]
get;
// IDL: HRESULT left (VARIANT value);
// VB6: Sub left (ByVal value As Any)
[DispId(-2147418109)] set;
[DispId(-2147418109)]
set;
}
/// <summary><para><c>letterSpacing</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -724,10 +782,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT letterSpacing ([out, retval] VARIANT* ReturnValue);
// VB6: Function letterSpacing As Any
[DispId(-2147413104)] get;
[DispId(-2147413104)]
get;
// IDL: HRESULT letterSpacing (VARIANT value);
// VB6: Sub letterSpacing (ByVal value As Any)
[DispId(-2147413104)] set;
[DispId(-2147413104)]
set;
}
/// <summary><para><c>lineHeight</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -738,10 +798,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT lineHeight ([out, retval] VARIANT* ReturnValue);
// VB6: Function lineHeight As Any
[DispId(-2147413106)] get;
[DispId(-2147413106)]
get;
// IDL: HRESULT lineHeight (VARIANT value);
// VB6: Sub lineHeight (ByVal value As Any)
[DispId(-2147413106)] set;
[DispId(-2147413106)]
set;
}
/// <summary><para><c>listStyle</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -757,7 +819,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT listStyle (BSTR value);
// VB6: Sub listStyle (ByVal value As String)
[DispId(-2147413037)] set;
[DispId(-2147413037)]
set;
}
/// <summary><para><c>listStyleImage</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -773,7 +836,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT listStyleImage (BSTR value);
// VB6: Sub listStyleImage (ByVal value As String)
[DispId(-2147413038)] set;
[DispId(-2147413038)]
set;
}
/// <summary><para><c>listStylePosition</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -789,7 +853,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT listStylePosition (BSTR value);
// VB6: Sub listStylePosition (ByVal value As String)
[DispId(-2147413039)] set;
[DispId(-2147413039)]
set;
}
/// <summary><para><c>listStyleType</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -805,7 +870,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT listStyleType (BSTR value);
// VB6: Sub listStyleType (ByVal value As String)
[DispId(-2147413040)] set;
[DispId(-2147413040)]
set;
}
/// <summary><para><c>margin</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -821,7 +887,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT margin (BSTR value);
// VB6: Sub margin (ByVal value As String)
[DispId(-2147413076)] set;
[DispId(-2147413076)]
set;
}
/// <summary><para><c>marginBottom</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -832,10 +899,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT marginBottom ([out, retval] VARIANT* ReturnValue);
// VB6: Function marginBottom As Any
[DispId(-2147413073)] get;
[DispId(-2147413073)]
get;
// IDL: HRESULT marginBottom (VARIANT value);
// VB6: Sub marginBottom (ByVal value As Any)
[DispId(-2147413073)] set;
[DispId(-2147413073)]
set;
}
/// <summary><para><c>marginLeft</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -846,10 +915,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT marginLeft ([out, retval] VARIANT* ReturnValue);
// VB6: Function marginLeft As Any
[DispId(-2147413072)] get;
[DispId(-2147413072)]
get;
// IDL: HRESULT marginLeft (VARIANT value);
// VB6: Sub marginLeft (ByVal value As Any)
[DispId(-2147413072)] set;
[DispId(-2147413072)]
set;
}
/// <summary><para><c>marginRight</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -860,10 +931,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT marginRight ([out, retval] VARIANT* ReturnValue);
// VB6: Function marginRight As Any
[DispId(-2147413074)] get;
[DispId(-2147413074)]
get;
// IDL: HRESULT marginRight (VARIANT value);
// VB6: Sub marginRight (ByVal value As Any)
[DispId(-2147413074)] set;
[DispId(-2147413074)]
set;
}
/// <summary><para><c>marginTop</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -874,10 +947,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT marginTop ([out, retval] VARIANT* ReturnValue);
// VB6: Function marginTop As Any
[DispId(-2147413075)] get;
[DispId(-2147413075)]
get;
// IDL: HRESULT marginTop (VARIANT value);
// VB6: Sub marginTop (ByVal value As Any)
[DispId(-2147413075)] set;
[DispId(-2147413075)]
set;
}
/// <summary><para><c>overflow</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -893,7 +968,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT overflow (BSTR value);
// VB6: Sub overflow (ByVal value As String)
[DispId(-2147413102)] set;
[DispId(-2147413102)]
set;
}
/// <summary><para><c>padding</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -909,7 +985,8 @@ namespace Greenshot.Base.IEInterop
get;
// IDL: HRESULT padding (BSTR value);
// VB6: Sub padding (ByVal value As String)
[DispId(-2147413101)] set;
[DispId(-2147413101)]
set;
}
/// <summary><para><c>paddingBottom</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -920,10 +997,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT paddingBottom ([out, retval] VARIANT* ReturnValue);
// VB6: Function paddingBottom As Any
[DispId(-2147413098)] get;
[DispId(-2147413098)]
get;
// IDL: HRESULT paddingBottom (VARIANT value);
// VB6: Sub paddingBottom (ByVal value As Any)
[DispId(-2147413098)] set;
[DispId(-2147413098)]
set;
}
/// <summary><para><c>paddingLeft</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -934,10 +1013,12 @@ namespace Greenshot.Base.IEInterop
{
// IDL: HRESULT paddingLeft ([out, retval] VARIANT* ReturnValue);
// VB6: Function paddingLeft As Any
[DispId(-2147413097)] get;
[DispId(-2147413097)]
get;
// IDL: HRESULT paddingLeft (VARIANT value);
// VB6: Sub paddingLeft (ByVal value As Any)
[DispId(-2147413097)] set;
[DispId(-2147413097)]
set;
}
/// <summary><para><c>paddingRight</c> property of <c>IHTMLStyle</c> interface.</para></summary>

View file

@ -137,7 +137,8 @@ namespace Greenshot.Base.IEInterop
[DispId(1004)]
[return: MarshalAs(UnmanagedType.BStr)]
get;
[DispId(1004)] set;
[DispId(1004)]
set;
}
}
}

View file

@ -24,16 +24,16 @@ using System.Runtime.InteropServices;
namespace Greenshot.Base.IEInterop
{
// IWebBrowser: EAB22AC1-30C1-11CF-A7EB-0000C05BAE0B
// [ComVisible(true), ComImport(), Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E"),
// TypeLibType(TypeLibTypeFlags.FDual),
// InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
// public interface IWebBrowser2 {
// [DispId(203)]
// object Document {
// [return: MarshalAs(UnmanagedType.IDispatch)]
// get;
// }
// }
// [ComVisible(true), ComImport(), Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E"),
// TypeLibType(TypeLibTypeFlags.FDual),
// InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
// public interface IWebBrowser2 {
// [DispId(203)]
// object Document {
// [return: MarshalAs(UnmanagedType.IDispatch)]
// get;
// }
// }
[ComImport, /*SuppressUnmanagedCodeSecurity,*/
TypeLibType(TypeLibTypeFlags.FOleAutomation |
TypeLibTypeFlags.FDual |

View file

@ -29,13 +29,9 @@ namespace Greenshot.Base.IniFile
[AttributeUsage(AttributeTargets.Class)]
public class IniSectionAttribute : Attribute
{
public IniSectionAttribute(string name)
{
Name = name;
}
public string Description;
public IniSectionAttribute(string name) => Name = name;
public string Name { get; set; }
public string Description { get; set; }
}
/// <summary>
@ -44,15 +40,9 @@ namespace Greenshot.Base.IniFile
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class IniPropertyAttribute : Attribute
{
public IniPropertyAttribute()
{
Separator = ",";
}
public IniPropertyAttribute() => Separator = ",";
public IniPropertyAttribute(string name) : this()
{
Name = name;
}
public IniPropertyAttribute(string name) : this() => Name = name;
public string Description { get; set; }
public string Separator { get; set; }

View file

@ -26,6 +26,7 @@ using System.Reflection;
using System.Text;
using System.Threading;
using log4net;
using System.Linq;
namespace Greenshot.Base.IniFile
{
@ -39,7 +40,7 @@ namespace Greenshot.Base.IniFile
/// <summary>
/// A lock object for the ini file saving
/// </summary>
private static readonly object IniLock = new object();
private static readonly object IniLock = new();
/// <summary>
/// As the ini implementation is kept someone generic, for reusing, this holds the name of the application
@ -152,18 +153,9 @@ namespace Greenshot.Base.IniFile
/// <summary>
/// Get the location of the configuration
/// </summary>
public static string ConfigLocation
{
get
{
if (IsInitialized)
{
return CreateIniLocation(_configName + IniExtension, false);
}
throw new InvalidOperationException("Ini configuration was not initialized!");
}
}
public static string ConfigLocation => IsInitialized
? CreateIniLocation(_configName + IniExtension, false)
: throw new InvalidOperationException("Ini configuration was not initialized!");
/// <summary>
/// Create the location of the configuration file
@ -210,7 +202,7 @@ namespace Greenshot.Base.IniFile
catch (Exception exception)
{
Log.WarnFormat("Problem retrieving the AssemblyLocation: {0} (Designer mode?)", exception.Message);
applicationStartupPath = @".";
applicationStartupPath = ".";
}
if (applicationStartupPath != null)
@ -328,14 +320,13 @@ namespace Greenshot.Base.IniFile
return;
}
foreach (string fixedPropertyKey in fixedPropertiesForSection.Keys)
{
if (section.Values.ContainsKey(fixedPropertyKey))
foreach (var fixedPropertyKey in from string fixedPropertyKey in fixedPropertiesForSection.Keys
where section.Values.ContainsKey(fixedPropertyKey)
select fixedPropertyKey)
{
section.Values[fixedPropertyKey].IsFixed = true;
}
}
}
/// <summary>
/// Read the ini file into the Dictionary
@ -412,10 +403,7 @@ namespace Greenshot.Base.IniFile
/// </summary>
/// <typeparam name="T">IniSection Type to get the configuration for</typeparam>
/// <returns>Filled instance of IniSection type which was supplied</returns>
public static T GetIniSection<T>() where T : IniSection
{
return GetIniSection<T>(true);
}
public static T GetIniSection<T>() where T : IniSection => GetIniSection<T>(true);
/// <summary>
///
@ -432,12 +420,12 @@ namespace Greenshot.Base.IniFile
if (SectionMap.ContainsKey(sectionName))
{
//LOG.Debug("Returning pre-mapped section " + sectionName);
section = (T) SectionMap[sectionName];
section = (T)SectionMap[sectionName];
}
else
{
// Create instance of this type
section = (T) Activator.CreateInstance(iniSectionType);
section = (T)Activator.CreateInstance(iniSectionType);
// Store for later save & retrieval
SectionMap.Add(sectionName, section);
@ -463,18 +451,15 @@ namespace Greenshot.Base.IniFile
{
string sectionName = section.IniSectionAttribute.Name;
// Get the properties for the section
IDictionary<string, string> properties;
if (_sections.ContainsKey(sectionName))
{
properties = _sections[sectionName];
return _sections[sectionName];
}
else
{
_sections.Add(sectionName, new Dictionary<string, string>());
properties = _sections[sectionName];
return _sections[sectionName];
}
return properties;
}
/// <summary>
@ -567,7 +552,7 @@ namespace Greenshot.Base.IniFile
// Don't forget to flush the buffer
writer.Flush();
// Now write the created .ini string to the real file
using FileStream fileStream = new FileStream(iniLocation, FileMode.Create, FileAccess.Write);
using FileStream fileStream = new(iniLocation, FileMode.Create, FileAccess.Write);
memoryStream.WriteTo(fileStream);
}
}

View file

@ -25,6 +25,7 @@ using System.IO;
using System.Reflection;
using Greenshot.Base.Core;
using log4net;
using System.Linq;
namespace Greenshot.Base.IniFile
{
@ -39,26 +40,12 @@ namespace Greenshot.Base.IniFile
[NonSerialized] private readonly IDictionary<string, IniValue> values = new Dictionary<string, IniValue>();
[NonSerialized] private IniSectionAttribute iniSectionAttribute;
public IniSectionAttribute IniSectionAttribute
{
get
{
if (iniSectionAttribute == null)
{
iniSectionAttribute = GetIniSectionAttribute(GetType());
}
return iniSectionAttribute;
}
}
public IniSectionAttribute IniSectionAttribute => iniSectionAttribute ??= GetIniSectionAttribute(GetType());
/// <summary>
/// Get the dictionary with all the IniValues
/// </summary>
public IDictionary<string, IniValue> Values
{
get { return values; }
}
public IDictionary<string, IniValue> Values => values;
/// <summary>
/// Flag to specify if values have been changed
@ -70,10 +57,7 @@ namespace Greenshot.Base.IniFile
/// </summary>
/// <param name="property">The property to return a default for</param>
/// <returns>object with the default value for the supplied property</returns>
public virtual object GetDefault(string property)
{
return null;
}
public virtual object GetDefault(string property) => null;
/// <summary>
/// This method will be called before converting the property, making to possible to correct a certain value
@ -82,10 +66,7 @@ namespace Greenshot.Base.IniFile
/// <param name="propertyName">The name of the property</param>
/// <param name="propertyValue">The string value of the property</param>
/// <returns>string with the propertyValue, modified or not...</returns>
public virtual string PreCheckValue(string propertyName, string propertyValue)
{
return propertyValue;
}
public virtual string PreCheckValue(string propertyName, string propertyValue) => propertyValue;
/// <summary>
/// This method will be called after reading the configuration, so eventually some corrections can be made
@ -118,9 +99,9 @@ namespace Greenshot.Base.IniFile
Attribute[] classAttributes = Attribute.GetCustomAttributes(iniSectionType);
foreach (Attribute attribute in classAttributes)
{
if (attribute is IniSectionAttribute)
if (attribute is IniSectionAttribute iniSectionAttribute2)
{
return (IniSectionAttribute) attribute;
return iniSectionAttribute2;
}
}
@ -134,31 +115,25 @@ namespace Greenshot.Base.IniFile
public void Fill(IDictionary<string, string> properties)
{
Type iniSectionType = GetType();
// Iterate over the members and create IniValueContainers
foreach (FieldInfo fieldInfo in iniSectionType.GetFields())
{
if (Attribute.IsDefined(fieldInfo, typeof(IniPropertyAttribute)))
{
IniPropertyAttribute iniPropertyAttribute = (IniPropertyAttribute) fieldInfo.GetCustomAttributes(typeof(IniPropertyAttribute), false)[0];
if (!Values.ContainsKey(iniPropertyAttribute.Name))
foreach (var (fieldInfo, iniPropertyAttribute) in
from FieldInfo fieldInfo in iniSectionType.GetFields()
where Attribute.IsDefined(fieldInfo, typeof(IniPropertyAttribute))
let iniPropertyAttribute = (IniPropertyAttribute)fieldInfo.GetCustomAttributes(typeof(IniPropertyAttribute), false)[0]
where !Values.ContainsKey(iniPropertyAttribute.Name)
select (fieldInfo, iniPropertyAttribute))
{
Values[iniPropertyAttribute.Name] = new IniValue(this, fieldInfo, iniPropertyAttribute);
}
}
}
foreach (PropertyInfo propertyInfo in iniSectionType.GetProperties())
{
if (Attribute.IsDefined(propertyInfo, typeof(IniPropertyAttribute)))
if (Attribute.IsDefined(propertyInfo, typeof(IniPropertyAttribute)) && !Values.ContainsKey(propertyInfo.Name))
{
if (!Values.ContainsKey(propertyInfo.Name))
{
IniPropertyAttribute iniPropertyAttribute = (IniPropertyAttribute) propertyInfo.GetCustomAttributes(typeof(IniPropertyAttribute), false)[0];
IniPropertyAttribute iniPropertyAttribute = (IniPropertyAttribute)propertyInfo.GetCustomAttributes(typeof(IniPropertyAttribute), false)[0];
Values[iniPropertyAttribute.Name] = new IniValue(this, propertyInfo, iniPropertyAttribute);
}
}
}
foreach (string fieldName in Values.Keys)
{
@ -166,14 +141,11 @@ namespace Greenshot.Base.IniFile
try
{
iniValue.SetValueFromProperties(properties);
if (iniValue.Attributes.Encrypted)
{
if (iniValue.Value is string stringValue && stringValue.Length > 2)
if (iniValue.Attributes.Encrypted && iniValue.Value is string stringValue && stringValue.Length > 2)
{
iniValue.Value = stringValue.Decrypt();
}
}
}
catch (Exception ex)
{
LOG.Error(ex);
@ -207,22 +179,16 @@ namespace Greenshot.Base.IniFile
foreach (IniValue value in Values.Values)
{
if (value.Attributes.Encrypted)
{
if (value.Value is string stringValue && stringValue.Length > 2)
if (value.Attributes.Encrypted && value.Value is string stringValue && stringValue.Length > 2)
{
value.Value = stringValue.Encrypt();
}
}
// Write the value
value.Write(writer, onlyProperties);
if (value.Attributes.Encrypted)
if (value.Attributes.Encrypted && value.Value is string stringValue2 && stringValue2.Length > 2)
{
if (value.Value is string stringValue && stringValue.Length > 2)
{
value.Value = stringValue.Decrypt();
}
value.Value = stringValue2.Decrypt();
}
}
}

View file

@ -37,21 +37,19 @@ namespace Greenshot.Base.IniFile
private static readonly ILog Log = LogManager.GetLogger(typeof(IniValue));
private readonly PropertyInfo _propertyInfo;
private readonly FieldInfo _fieldInfo;
private readonly IniSection _containingIniSection;
private readonly IniPropertyAttribute _attributes;
public IniValue(IniSection containingIniSection, PropertyInfo propertyInfo, IniPropertyAttribute iniPropertyAttribute)
{
_containingIniSection = containingIniSection;
ContainingIniSection = containingIniSection;
_propertyInfo = propertyInfo;
_attributes = iniPropertyAttribute;
Attributes = iniPropertyAttribute;
}
public IniValue(IniSection containingIniSection, FieldInfo fieldInfo, IniPropertyAttribute iniPropertyAttribute)
{
_containingIniSection = containingIniSection;
ContainingIniSection = containingIniSection;
_fieldInfo = fieldInfo;
_attributes = iniPropertyAttribute;
Attributes = iniPropertyAttribute;
}
/// <summary>
@ -59,20 +57,12 @@ namespace Greenshot.Base.IniFile
/// </summary>
public bool IsFixed
{
get
{
if (_attributes != null)
{
return _attributes.FixedValue;
}
return false;
}
get => Attributes?.FixedValue == true;
set
{
if (_attributes != null)
if (Attributes != null)
{
_attributes.FixedValue = value;
Attributes.FixedValue = value;
}
}
}
@ -82,25 +72,16 @@ namespace Greenshot.Base.IniFile
/// </summary>
public bool IsExpert
{
get
{
if (_attributes != null)
{
return _attributes.Expert;
}
return false;
}
get => Attributes?.Expert == true;
set
{
if (_attributes != null)
if (Attributes != null)
{
_attributes.Expert = value;
Attributes.Expert = value;
}
}
}
/// <summary>
/// Return true when the value is can be changed by the GUI
/// </summary>
@ -111,52 +92,33 @@ namespace Greenshot.Base.IniFile
/// </summary>
public bool IsVisible => !IsExpert;
public MemberInfo MemberInfo
{
get
{
if (_propertyInfo == null)
{
return _fieldInfo;
}
return _propertyInfo;
}
}
public MemberInfo MemberInfo => _propertyInfo == null ? _fieldInfo : _propertyInfo;
/// <summary>
/// Returns the IniSection this value is contained in
/// </summary>
public IniSection ContainingIniSection => _containingIniSection;
public IniSection ContainingIniSection { get; }
/// <summary>
/// Get the in the ini file defined attributes
/// </summary>
public IniPropertyAttribute Attributes => _attributes;
public IniPropertyAttribute Attributes { get; }
/// <summary>
/// Get the value for this IniValue
/// </summary>
public object Value
{
get
{
if (_propertyInfo == null)
{
return _fieldInfo.GetValue(_containingIniSection);
}
return _propertyInfo.GetValue(_containingIniSection, null);
}
get => _propertyInfo == null ? _fieldInfo.GetValue(ContainingIniSection) : _propertyInfo.GetValue(ContainingIniSection, null);
set
{
if (_propertyInfo == null)
{
_fieldInfo.SetValue(_containingIniSection, value);
_fieldInfo.SetValue(ContainingIniSection, value);
}
else
{
_propertyInfo.SetValue(_containingIniSection, value, null);
_propertyInfo.SetValue(ContainingIniSection, value, null);
}
}
}
@ -196,19 +158,19 @@ namespace Greenshot.Base.IniFile
Type valueType = ValueType;
if (myValue == null)
{
if (_attributes.ExcludeIfNull)
if (Attributes.ExcludeIfNull)
{
return;
}
if (_attributes.DefaultValue != null)
if (Attributes.DefaultValue != null)
{
myValue = _attributes.DefaultValue;
myValue = Attributes.DefaultValue;
valueType = typeof(string);
}
else
{
myValue = _containingIniSection.GetDefault(_attributes.Name);
myValue = ContainingIniSection.GetDefault(Attributes.Name);
if (myValue != null)
{
valueType = myValue.GetType();
@ -216,22 +178,19 @@ namespace Greenshot.Base.IniFile
}
}
if (myValue == null)
{
if (_attributes.ExcludeIfNull)
if (myValue == null && Attributes.ExcludeIfNull)
{
return;
}
}
if (!onlyProperties)
{
writer.WriteLine("; {0}", _attributes.Description);
writer.WriteLine("; {0}", Attributes.Description);
}
if (myValue == null)
{
writer.WriteLine("{0}=", _attributes.Name);
writer.WriteLine("{0}=", Attributes.Name);
return;
}
@ -247,7 +206,7 @@ namespace Greenshot.Base.IniFile
var moveNext = enumerator.GetType().GetMethod("MoveNext");
var current = enumerator.GetType().GetProperty("Current").GetGetMethod();
// Get all the values.
while ((bool) moveNext.Invoke(enumerator, null))
while ((bool)moveNext.Invoke(enumerator, null))
{
var key = current.Invoke(enumerator, null);
var valueObject = item.GetValue(myValue, new[]
@ -255,13 +214,13 @@ namespace Greenshot.Base.IniFile
key
});
// Write to ini file!
writer.WriteLine("{0}.{1}={2}", _attributes.Name, ConvertValueToString(valueType1, key, _attributes.Separator),
ConvertValueToString(valueType2, valueObject, _attributes.Separator));
writer.WriteLine("{0}.{1}={2}", Attributes.Name, ConvertValueToString(valueType1, key, Attributes.Separator),
ConvertValueToString(valueType2, valueObject, Attributes.Separator));
}
}
else
{
writer.WriteLine("{0}={1}", _attributes.Name, ConvertValueToString(valueType, myValue, _attributes.Separator));
writer.WriteLine("{0}={1}", Attributes.Name, ConvertValueToString(valueType, myValue, Attributes.Separator));
}
}
@ -271,11 +230,11 @@ namespace Greenshot.Base.IniFile
/// <returns></returns>
public void SetValueFromProperties(IDictionary<string, string> properties)
{
string propertyName = _attributes.Name;
string propertyName = Attributes.Name;
string propertyValue = null;
if (properties.ContainsKey(propertyName) && properties[propertyName] != null)
{
propertyValue = _containingIniSection.PreCheckValue(propertyName, properties[propertyName]);
propertyValue = ContainingIniSection.PreCheckValue(propertyName, properties[propertyName]);
}
UseValueOrDefault(propertyValue);
@ -288,10 +247,10 @@ namespace Greenshot.Base.IniFile
public void UseValueOrDefault(string propertyValue)
{
Type valueType = ValueType;
string propertyName = _attributes.Name;
string defaultValue = _attributes.DefaultValue;
string propertyName = Attributes.Name;
string defaultValue = Attributes.DefaultValue;
bool defaultUsed = false;
object defaultValueFromConfig = _containingIniSection.GetDefault(propertyName);
object defaultValueFromConfig = ContainingIniSection.GetDefault(propertyName);
if (string.IsNullOrEmpty(propertyValue))
{
@ -306,7 +265,7 @@ namespace Greenshot.Base.IniFile
}
else
{
if (_attributes.ExcludeIfNull)
if (Attributes.ExcludeIfNull)
{
Value = null;
return;
@ -326,10 +285,10 @@ namespace Greenshot.Base.IniFile
object dictionary = Activator.CreateInstance(valueType);
MethodInfo addMethodInfo = valueType.GetMethod("Add");
bool addedElements = false;
IDictionary<string, string> properties = IniConfig.PropertiesForSection(_containingIniSection);
IDictionary<string, string> properties = IniConfig.PropertiesForSection(ContainingIniSection);
foreach (string key in properties.Keys)
{
if (key != null && key.StartsWith(propertyName + "."))
if (key?.StartsWith(propertyName + ".") == true)
{
// What "key" do we need to store it under?
string subPropertyName = key.Substring(propertyName.Length + 1);
@ -338,7 +297,7 @@ namespace Greenshot.Base.IniFile
object newValue2 = null;
try
{
newValue1 = ConvertStringToValueType(type1, subPropertyName, _attributes.Separator);
newValue1 = ConvertStringToValueType(type1, subPropertyName, Attributes.Separator);
}
catch (Exception ex)
{
@ -348,7 +307,7 @@ namespace Greenshot.Base.IniFile
try
{
newValue2 = ConvertStringToValueType(type2, stringValue, _attributes.Separator);
newValue2 = ConvertStringToValueType(type2, stringValue, Attributes.Separator);
}
catch (Exception ex)
{
@ -388,7 +347,7 @@ namespace Greenshot.Base.IniFile
object newValue;
try
{
newValue = ConvertStringToValueType(valueType, propertyValue, _attributes.Separator);
newValue = ConvertStringToValueType(valueType, propertyValue, Attributes.Separator);
}
catch (Exception ex1)
{
@ -398,7 +357,7 @@ namespace Greenshot.Base.IniFile
try
{
Log.WarnFormat("Problem '{0}' while converting {1} to type {2} trying fallback...", ex1.Message, propertyValue, valueType.FullName);
newValue = ConvertStringToValueType(valueType, defaultValue, _attributes.Separator);
newValue = ConvertStringToValueType(valueType, defaultValue, Attributes.Separator);
ContainingIniSection.IsDirty = true;
Log.InfoFormat("Used default value {0} for property {1}", defaultValue, propertyName);
}
@ -432,7 +391,7 @@ namespace Greenshot.Base.IniFile
}
catch (Exception)
{
Log.WarnFormat("Couldn't create instance of {0} for {1}, using default value.", ValueType.FullName, _attributes.Name);
Log.WarnFormat("Couldn't create instance of {0} for {1}, using default value.", ValueType.FullName, Attributes.Name);
Value = default(ValueType);
}
}
@ -543,10 +502,7 @@ namespace Greenshot.Base.IniFile
/// Override of ToString which calls the ConvertValueToString
/// </summary>
/// <returns>string representation of this</returns>
public override string ToString()
{
return ConvertValueToString(ValueType, Value, _attributes.Separator);
}
public override string ToString() => ConvertValueToString(ValueType, Value, Attributes.Separator);
/// <summary>
/// Convert the supplied value to a string
@ -565,9 +521,9 @@ namespace Greenshot.Base.IniFile
if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(List<>))
{
StringBuilder stringBuilder = new StringBuilder();
StringBuilder stringBuilder = new();
Type specificValueType = valueType.GetGenericArguments()[0];
int listCount = (int) valueType.GetProperty("Count").GetValue(valueObject, null);
int listCount = (int)valueType.GetProperty("Count").GetValue(valueObject, null);
// Loop though generic list
for (int index = 0; index < listCount; index++)
{

View file

@ -57,9 +57,6 @@ namespace Greenshot.Base.Interfaces.Drawing
{
public IField Field { get; private set; }
public FieldChangedEventArgs(IField field)
{
Field = field;
}
public FieldChangedEventArgs(IField field) => Field = field;
}
}

View file

@ -34,10 +34,7 @@ namespace Greenshot.Base.Interfaces
DestinationDescription = destinationDescription;
}
public ExportInformation(string destinationDesignation, string destinationDescription, bool exportMade) : this(destinationDesignation, destinationDescription)
{
ExportMade = exportMade;
}
public ExportInformation(string destinationDesignation, string destinationDescription, bool exportMade) : this(destinationDesignation, destinationDescription) => ExportMade = exportMade;
public string DestinationDesignation { get; }

View file

@ -77,10 +77,7 @@ namespace Greenshot.Base.Interfaces.Ocr
/// <summary>
/// Return the calculated bounds for the whole line
/// </summary>
public NativeRect CalculatedBounds
{
get { return _calculatedBounds ??= CalculateBounds(); }
}
public NativeRect CalculatedBounds => _calculatedBounds ??= CalculateBounds();
/// <summary>
/// Offset the words with the specified x and y coordinates

View file

@ -33,7 +33,7 @@ namespace Greenshot.Base.Interfaces.Ocr
/// <summary>
/// Check if there is any content
/// </summary>
public bool HasContent => Lines.Any();
public bool HasContent => Lines.Count > 0;
/// <summary>
/// The complete text

View file

@ -41,20 +41,11 @@ namespace Greenshot.Base.Interfaces.Plugin
ReduceColors = CoreConfig.OutputFileReduceColors;
}
public SurfaceOutputSettings(OutputFormat format) : this()
{
Format = format;
}
public SurfaceOutputSettings(OutputFormat format) : this() => Format = format;
public SurfaceOutputSettings(OutputFormat format, int quality) : this(format)
{
JPGQuality = quality;
}
public SurfaceOutputSettings(OutputFormat format, int quality) : this(format) => JPGQuality = quality;
public SurfaceOutputSettings(OutputFormat format, int quality, bool reduceColors) : this(format, quality)
{
ReduceColors = reduceColors;
}
public SurfaceOutputSettings(OutputFormat format, int quality, bool reduceColors) : this(format, quality) => ReduceColors = reduceColors;
/// <summary>
/// BUG-2056 reported a logical issue, using greenshot format as the default causes issues with the external commands.
@ -81,17 +72,10 @@ namespace Greenshot.Base.Interfaces.Plugin
public bool ReduceColors
{
get
{
get =>
// Fix for Bug #3468436, force quantizing when output format is gif as this has only 256 colors!
if (OutputFormat.gif.Equals(Format))
{
return true;
}
return _reduceColors;
}
set { _reduceColors = value; }
!(!OutputFormat.gif.Equals(Format) && !_reduceColors);
set => _reduceColors = value;
}
/// <summary>
@ -99,7 +83,7 @@ namespace Greenshot.Base.Interfaces.Plugin
/// </summary>
public bool DisableReduceColors
{
get { return _disableReduceColors; }
get => _disableReduceColors;
set
{
// Quantizing os needed when output format is gif as this has only 256 colors!

View file

@ -21,5 +21,5 @@
namespace Greenshot.Base.Interfaces
{
public delegate void SurfaceBackgroundColorEventHandler (object sender, SurfaceBackgroundColorEventArgs e);
public delegate void SurfaceBackgroundColorEventHandler(object sender, SurfaceBackgroundColorEventArgs e);
}

View file

@ -21,5 +21,5 @@
namespace Greenshot.Base.Interfaces
{
public delegate void SurfaceForegroundColorEventHandler (object sender, SurfaceForegroundColorEventArgs e);
public delegate void SurfaceForegroundColorEventHandler(object sender, SurfaceForegroundColorEventArgs e);
}

View file

@ -21,5 +21,5 @@
namespace Greenshot.Base.Interfaces
{
public delegate void SurfaceLineThicknessEventHandler (object sender, SurfaceLineThicknessEventArgs e);
public delegate void SurfaceLineThicknessEventHandler(object sender, SurfaceLineThicknessEventArgs e);
}

View file

@ -21,5 +21,5 @@
namespace Greenshot.Base.Interfaces
{
public delegate void SurfaceShadowEventHandler (object sender, SurfaceShadowEventArgs e);
public delegate void SurfaceShadowEventHandler(object sender, SurfaceShadowEventArgs e);
}

View file

@ -37,8 +37,8 @@ namespace Greenshot.Base.Interop
public sealed class COMWrapper : RealProxy, IDisposable, IRemotingTypeInfo
{
private static readonly ILog Log = LogManager.GetLogger(typeof(COMWrapper));
public const int RPC_E_CALL_REJECTED = unchecked((int) 0x80010001);
public const int RPC_E_FAIL = unchecked((int) 0x80004005);
public const int RPC_E_CALL_REJECTED = unchecked((int)0x80010001);
public const int RPC_E_FAIL = unchecked((int)0x80004005);
/// <summary>
/// Holds reference to the actual COM object which is wrapped by this proxy
@ -67,7 +67,7 @@ namespace Greenshot.Base.Interop
public static T CreateInstance<T>()
{
Type type = typeof(T);
if (null == type)
if (type == null)
{
throw new ArgumentNullException(nameof(T));
}
@ -87,7 +87,7 @@ namespace Greenshot.Base.Interop
Type comType = null;
if (progId.StartsWith("clsid:"))
{
Guid guid = new Guid(progId.Substring(6));
Guid guid = new(progId.Substring(6));
try
{
comType = Type.GetTypeFromCLSID(guid);
@ -127,12 +127,7 @@ namespace Greenshot.Base.Interop
}
}
if (comObject != null)
{
return (T) comObject;
}
return default;
return comObject != null ? (T)comObject : default;
}
/// <summary>
@ -144,17 +139,17 @@ namespace Greenshot.Base.Interop
/// <returns>Transparent proxy to the real proxy for the object</returns>
private static object Wrap(object comObject, Type type, string targetName)
{
if (null == comObject)
if (comObject == null)
{
throw new ArgumentNullException(nameof(comObject));
}
if (null == type)
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
COMWrapper wrapper = new COMWrapper(comObject, type, targetName);
COMWrapper wrapper = new(comObject, type, targetName);
return wrapper.GetTransparentProxy();
}
@ -204,7 +199,7 @@ namespace Greenshot.Base.Interop
/// </param>
private void Dispose(bool disposing)
{
if (null != _comObject)
if (_comObject != null)
{
Log.DebugFormat("Disposing {0}", _interceptType);
if (Marshal.IsComObject(_comObject))
@ -237,10 +232,7 @@ namespace Greenshot.Base.Interop
/// <returns>
/// The full name of the intercepted type.
/// </returns>
public override string ToString()
{
return _interceptType.FullName;
}
public override string ToString() => _interceptType.FullName;
/// <summary>
/// Returns the hash code of the wrapped object.
@ -248,10 +240,7 @@ namespace Greenshot.Base.Interop
/// <returns>
/// The hash code of the wrapped object.
/// </returns>
public override int GetHashCode()
{
return _comObject.GetHashCode();
}
public override int GetHashCode() => _comObject.GetHashCode();
/// <summary>
/// Compares this object to another.
@ -264,14 +253,10 @@ namespace Greenshot.Base.Interop
/// </returns>
public override bool Equals(object value)
{
if (null != value && RemotingServices.IsTransparentProxy(value))
{
COMWrapper wrapper = RemotingServices.GetRealProxy(value) as COMWrapper;
if (null != wrapper)
if (value != null && RemotingServices.IsTransparentProxy(value) && RemotingServices.GetRealProxy(value) is COMWrapper wrapper)
{
return _comObject == wrapper._comObject;
}
}
return base.Equals(value);
}
@ -290,7 +275,7 @@ namespace Greenshot.Base.Interop
/// </exception>
private static Type GetByValType(Type byRefType)
{
if (null == byRefType)
if (byRefType == null)
{
throw new ArgumentNullException(nameof(byRefType));
}
@ -316,14 +301,14 @@ namespace Greenshot.Base.Interop
/// </returns>
public override IMessage Invoke(IMessage myMessage)
{
if (!(myMessage is IMethodCallMessage callMessage))
if (myMessage is not IMethodCallMessage callMessage)
{
Log.DebugFormat("Message type not implemented: {0}", myMessage.GetType());
return null;
}
MethodInfo method = callMessage.MethodBase as MethodInfo;
if (null == method)
if (method == null)
{
Log.DebugFormat("Unrecognized Invoke call: {0}", callMessage.MethodBase);
return null;
@ -341,33 +326,34 @@ namespace Greenshot.Base.Interop
ParameterModifier[] argModifiers = null;
ParameterInfo[] parameters = null;
if ("Dispose" == methodName && 0 == argCount && typeof(void) == returnType)
if (methodName == "Dispose" && argCount == 0 && typeof(void) == returnType)
{
Dispose();
}
else if ("ToString" == methodName && 0 == argCount && typeof(string) == returnType)
else if (methodName == "ToString" && argCount == 0 && typeof(string) == returnType)
{
returnValue = ToString();
}
else if ("GetType" == methodName && 0 == argCount && typeof(Type) == returnType)
else if (methodName == "GetType" && argCount == 0 && typeof(Type) == returnType)
{
returnValue = _interceptType;
}
else if ("GetHashCode" == methodName && 0 == argCount && typeof(int) == returnType)
else if (methodName == "GetHashCode" && argCount == 0 && typeof(int) == returnType)
{
returnValue = GetHashCode();
}
else if ("Equals" == methodName && 1 == argCount && typeof(bool) == returnType)
else if (methodName == "Equals" && argCount == 1 && typeof(bool) == returnType)
{
returnValue = Equals(callMessage.Args[0]);
}
else if (1 == argCount && typeof(void) == returnType && (methodName.StartsWith("add_") || methodName.StartsWith("remove_")))
else if (argCount == 1 && typeof(void) == returnType && (methodName.StartsWith("add_") || methodName.StartsWith("remove_")))
{
bool removeHandler = methodName.StartsWith("remove_");
methodName = methodName.Substring(removeHandler ? 7 : 4);
_ = methodName.Substring(removeHandler ? 7 : 4);
// TODO: Something is missing here
if (!(callMessage.InArgs[0] is Delegate handler))
if (callMessage.InArgs[0] is not Delegate)
{
Delegate handler;
return new ReturnMessage(new ArgumentNullException(nameof(handler)), callMessage);
}
}
@ -395,7 +381,7 @@ namespace Greenshot.Base.Interop
else
{
args = callMessage.Args;
if (null != args && 0 != args.Length)
if (args != null && args.Length != 0)
{
// Modifiers for ref / out parameters
argModifiers = new ParameterModifier[1];
@ -412,7 +398,7 @@ namespace Greenshot.Base.Interop
}
}
if (0 == outArgsCount)
if (outArgsCount == 0)
{
argModifiers = null;
}
@ -423,7 +409,7 @@ namespace Greenshot.Base.Interop
Type byValType;
COMWrapper wrapper;
COMWrapper[] originalArgs;
if (null == args || 0 == args.Length)
if (args == null || args.Length == 0)
{
originalArgs = null;
}
@ -432,16 +418,16 @@ namespace Greenshot.Base.Interop
originalArgs = new COMWrapper[args.Length];
for (int i = 0; i < args.Length; i++)
{
if (null != args[i] && RemotingServices.IsTransparentProxy(args[i]))
if (args[i] != null && RemotingServices.IsTransparentProxy(args[i]))
{
wrapper = RemotingServices.GetRealProxy(args[i]) as COMWrapper;
if (null != wrapper)
if (wrapper != null)
{
originalArgs[i] = wrapper;
args[i] = wrapper._comObject;
}
}
else if (0 != outArgsCount && argModifiers[0][i])
else if (outArgsCount != 0 && argModifiers[0][i])
{
byValType = GetByValType(parameters[i].ParameterType);
if (byValType.IsInterface)
@ -449,7 +435,7 @@ namespace Greenshot.Base.Interop
// If we're passing a COM object by reference, and
// the parameter is null, we need to pass a
// DispatchWrapper to avoid a type mismatch exception.
if (null == args[i])
if (args[i] == null)
{
args[i] = new DispatchWrapper(null);
}
@ -466,7 +452,7 @@ namespace Greenshot.Base.Interop
}
}
do
while (true)
{
try
{
@ -482,7 +468,7 @@ namespace Greenshot.Base.Interop
catch (Exception ex)
{
// Test for rejected
if (!(ex is COMException comEx))
if (ex is not COMException comEx)
{
comEx = ex.InnerException as COMException;
}
@ -491,7 +477,7 @@ namespace Greenshot.Base.Interop
{
string destinationName = _targetName;
// Try to find a "catchy" name for the rejecting application
if (destinationName != null && destinationName.Contains("."))
if (destinationName?.Contains(".") == true)
{
destinationName = destinationName.Substring(0, destinationName.IndexOf(".", StringComparison.Ordinal));
}
@ -514,10 +500,10 @@ namespace Greenshot.Base.Interop
// Not rejected OR pressed cancel
return new ReturnMessage(ex, callMessage);
}
} while (true);
}
// Handle enum and interface return types
if (null != returnValue)
if (returnValue != null)
{
if (returnType.IsInterface)
{
@ -535,7 +521,7 @@ namespace Greenshot.Base.Interop
}
// Handle out args
if (0 != outArgsCount)
if (outArgsCount != 0)
{
outArgs = new object[args.Length];
for (int i = 0; i < parameters.Length; i++)
@ -546,45 +532,40 @@ namespace Greenshot.Base.Interop
}
var arg = args[i];
if (null == arg)
if (arg == null)
{
continue;
}
parameter = parameters[i];
wrapper = null;
byValType = GetByValType(parameter.ParameterType);
if (typeof(decimal) == byValType)
{
if (arg is CurrencyWrapper)
if (arg is CurrencyWrapper wrapper1)
{
arg = ((CurrencyWrapper) arg).WrappedObject;
arg = wrapper1.WrappedObject;
}
}
else if (byValType.IsEnum)
{
arg = Enum.Parse(byValType, arg.ToString());
}
else if (byValType.IsInterface)
{
if (Marshal.IsComObject(arg))
else if (byValType.IsInterface && Marshal.IsComObject(arg))
{
wrapper = originalArgs[i];
if (null != wrapper && wrapper._comObject != arg)
if (wrapper != null && wrapper._comObject != arg)
{
wrapper.Dispose();
wrapper = null;
}
if (null == wrapper)
if (wrapper == null)
{
wrapper = new COMWrapper(arg, byValType, _targetName);
}
arg = wrapper.GetTransparentProxy();
}
}
outArgs[i] = arg;
}
@ -612,8 +593,8 @@ namespace Greenshot.Base.Interop
/// </summary>
public string TypeName
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
}
}

View file

@ -43,7 +43,7 @@ namespace Greenshot.Base.Interop
/// </exception>
public static ComProgIdAttribute GetAttribute(Type interfaceType)
{
if (null == interfaceType)
if (interfaceType == null)
{
throw new ArgumentNullException(nameof(interfaceType));
}
@ -51,34 +51,26 @@ namespace Greenshot.Base.Interop
Type attributeType = typeof(ComProgIdAttribute);
object[] attributes = interfaceType.GetCustomAttributes(attributeType, false);
if (0 == attributes.Length)
if (attributes.Length == 0)
{
Type[] interfaces = interfaceType.GetInterfaces();
foreach (Type t in interfaces)
{
interfaceType = t;
attributes = interfaceType.GetCustomAttributes(attributeType, false);
if (0 != attributes.Length)
if (attributes.Length != 0)
{
break;
}
}
}
if (0 == attributes.Length)
{
return null;
}
return (ComProgIdAttribute) attributes[0];
return attributes.Length == 0 ? null : (ComProgIdAttribute)attributes[0];
}
/// <summary>Constructor</summary>
/// <param name="value">The COM ProgID.</param>
public ComProgIdAttribute(string value)
{
Value = value;
}
public ComProgIdAttribute(string value) => Value = value;
/// <summary>
/// Returns the COM ProgID

View file

@ -80,7 +80,6 @@ namespace Greenshot.Editor.Configuration
[IniProperty("DefaultEditorSize", Description = "The size for the editor when it's opened without a capture", DefaultValue = "500,500")]
public NativeSize DefaultEditorSize { get; set; }
public override void AfterLoad()
{
base.AfterLoad();
@ -140,15 +139,8 @@ namespace Greenshot.Editor.Configuration
LastUsedFieldValues ??= new Dictionary<string, object>();
// check if settings for the requesting type exist, if not create!
if (LastUsedFieldValues.ContainsKey(requestedField))
{
LastUsedFieldValues[requestedField] = field.Value;
}
else
{
LastUsedFieldValues.Add(requestedField, field.Value);
}
}
public void ResetEditorPlacement()
{

View file

@ -36,14 +36,8 @@ namespace Greenshot.Editor.Controls
[Category("Greenshot"), DefaultValue(null), Description("Specifies key of the language file to use when displaying the text.")]
public string LanguageKey { get; set; }
public BindableToolStripButton()
{
CheckedChanged += BindableToolStripButton_CheckedChanged;
}
public BindableToolStripButton() => CheckedChanged += BindableToolStripButton_CheckedChanged;
private void BindableToolStripButton_CheckedChanged(object sender, EventArgs e)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Checked"));
}
private void BindableToolStripButton_CheckedChanged(object sender, EventArgs e) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Checked"));
}
}

View file

@ -36,14 +36,8 @@ namespace Greenshot.Editor.Controls
[Category("Greenshot"), DefaultValue(null), Description("Specifies key of the language file to use when displaying the text.")]
public string LanguageKey { get; set; }
public BindableToolStripComboBox()
{
SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged;
}
public BindableToolStripComboBox() => SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged;
private void BindableToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedItem"));
}
private void BindableToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedItem"));
}
}

View file

@ -44,13 +44,13 @@ namespace Greenshot.Editor.Controls
if (Tag == null && DropDownItems.Count > 0) Tag = DropDownItems[0].Tag;
return Tag;
}
set { AdoptFromTag(value); }
set => AdoptFromTag(value);
}
protected override void OnDropDownItemClicked(ToolStripItemClickedEventArgs e)
{
ToolStripItem clickedItem = e.ClickedItem;
if (Tag == null || !Tag.Equals(clickedItem.Tag))
if (Tag?.Equals(clickedItem.Tag) != true)
{
Tag = clickedItem.Tag;
Image = clickedItem.Image;
@ -62,12 +62,12 @@ namespace Greenshot.Editor.Controls
private void AdoptFromTag(object tag)
{
if (Tag == null || !Tag.Equals(tag))
if (Tag?.Equals(tag) != true)
{
Tag = tag;
foreach (ToolStripItem item in DropDownItems)
{
if (item.Tag != null && item.Tag.Equals(tag))
if (item.Tag?.Equals(tag) == true)
{
Image = item.Image;
break;

View file

@ -41,28 +41,16 @@ namespace Greenshot.Editor.Controls
[Category("Greenshot"), DefaultValue(null), Description("Specifies key of the language file to use when displaying the text.")]
public string LanguageKey { get; set; }
public ColorButton()
{
Click += ColorButtonClick;
}
public ColorButton() => Click += ColorButtonClick;
public Color SelectedColor
{
get { return _selectedColor; }
get => _selectedColor;
set
{
_selectedColor = value;
Brush brush;
if (value != Color.Transparent)
{
brush = new SolidBrush(value);
}
else
{
brush = new HatchBrush(HatchStyle.Percent50, Color.White, Color.Gray);
}
Brush brush = value != Color.Transparent ? new SolidBrush(value) : new HatchBrush(HatchStyle.Percent50, Color.White, Color.Gray);
if (Image != null)
{
using Graphics graphics = Graphics.FromImage(Image);

View file

@ -30,35 +30,17 @@ namespace Greenshot.Editor.Controls
/// </summary>
internal class CustomProfessionalColorTable : ProfessionalColorTable
{
public override Color ToolStripGradientBegin
{
get { return SystemColors.Control; }
}
public override Color ToolStripGradientBegin => SystemColors.Control;
public override Color ToolStripGradientMiddle
{
get { return SystemColors.Control; }
}
public override Color ToolStripGradientMiddle => SystemColors.Control;
public override Color ToolStripGradientEnd
{
get { return SystemColors.Control; }
}
public override Color ToolStripGradientEnd => SystemColors.Control;
public override Color OverflowButtonGradientBegin
{
get { return SystemColors.Control; }
}
public override Color OverflowButtonGradientBegin => SystemColors.Control;
public override Color OverflowButtonGradientMiddle
{
get { return SystemColors.Control; }
}
public override Color OverflowButtonGradientMiddle => SystemColors.Control;
public override Color OverflowButtonGradientEnd
{
get { return SystemColors.Control; }
}
public override Color OverflowButtonGradientEnd => SystemColors.Control;
}
/// <summary>
@ -67,10 +49,7 @@ namespace Greenshot.Editor.Controls
/// </summary>
public class CustomToolStripProfessionalRenderer : ToolStripProfessionalRenderer
{
public CustomToolStripProfessionalRenderer() : base(new CustomProfessionalColorTable())
{
RoundedEdges = false;
}
public CustomToolStripProfessionalRenderer() : base(new CustomProfessionalColorTable()) => RoundedEdges = false;
/// <summary>
/// By overriding the OnRenderToolStripBorder we can make the ToolStrip without border

View file

@ -37,7 +37,7 @@ namespace Greenshot.Editor.Controls
public FontFamily FontFamily
{
get { return (FontFamily) SelectedItem; }
get => (FontFamily)SelectedItem;
set
{
if (!SelectedItem.Equals(value))
@ -70,7 +70,7 @@ namespace Greenshot.Editor.Controls
{
FontFamily fontFamily = Items[e.Index] as FontFamily;
FontStyle fontStyle = FontStyle.Regular;
if (fontFamily != null && !fontFamily.IsStyleAvailable(FontStyle.Regular))
if (fontFamily?.IsStyleAvailable(FontStyle.Regular) == false)
{
if (fontFamily.IsStyleAvailable(FontStyle.Bold))
{
@ -121,9 +121,9 @@ namespace Greenshot.Editor.Controls
/// <param name="text">string</param>
private void DrawText(Graphics graphics, FontFamily fontFamily, FontStyle fontStyle, NativeRect bounds, string text)
{
using Font font = new Font(fontFamily, Font.Size + 5, fontStyle, GraphicsUnit.Pixel);
using Font font = new(fontFamily, Font.Size + 5, fontStyle, GraphicsUnit.Pixel);
// Make sure the text is visible by centering it in the line
using StringFormat stringFormat = new StringFormat
using StringFormat stringFormat = new()
{
LineAlignment = StringAlignment.Center
};

View file

@ -37,28 +37,21 @@ namespace Greenshot.Editor.Controls
MA_ACTIVATEANDEAT = 2,
}
private bool _clickThrough;
/// <summary>
/// Gets or sets whether the ToolStripEx honors item clicks when its containing form does not have input focus.
/// </summary>
/// <remarks>
/// Default value is false, which is the same behavior provided by the base ToolStrip class.
/// </remarks>
public bool ClickThrough
{
get { return _clickThrough; }
set { _clickThrough = value; }
}
public bool ClickThrough { get; set; }
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
var windowsMessage = (WindowsMessages) m.Msg;
if (_clickThrough && windowsMessage == WindowsMessages.WM_MOUSEACTIVATE && m.Result == (IntPtr) NativeConstants.MA_ACTIVATEANDEAT)
var windowsMessage = (WindowsMessages)m.Msg;
if (ClickThrough && windowsMessage == WindowsMessages.WM_MOUSEACTIVATE && m.Result == (IntPtr)NativeConstants.MA_ACTIVATEANDEAT)
{
m.Result = (IntPtr) NativeConstants.MA_ACTIVATE;
m.Result = (IntPtr)NativeConstants.MA_ACTIVATE;
}
}
}

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