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 # Xml project files
[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}] [*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}]
indent_size = 2 indent_size = 4
# Xml config files # Xml config files
[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}] [*.{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_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion dotnet_style_null_propagation = true:suggestion
dotnet_style_explicit_tuple_names = 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: # CSharp code style settings:
[*.cs] [*.cs]
@ -71,3 +77,76 @@ csharp_new_line_before_catch = true
csharp_new_line_before_finally = true csharp_new_line_before_finally = true
csharp_new_line_before_members_in_object_initializers = true csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_members_in_anonymous_types = 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> /// </summary>
/// <param name="milliseconds"></param> /// <param name="milliseconds"></param>
/// <returns>Number of frames, 1 if in Terminal Server Session</returns> /// <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 we are in a Terminal Server Session we return 1
if (IsTerminalServerSession) IsTerminalServerSession ? 1 : milliseconds / VRefresh;
{
return 1;
}
return milliseconds / VRefresh;
}
/// <summary> /// <summary>
/// Calculate the interval for the timer to animate the frames /// Calculate the interval for the timer to animate the frames
/// </summary> /// </summary>
/// <returns>Milliseconds for the interval</returns> /// <returns>Milliseconds for the interval</returns>
protected int Interval() => (int)1000 / VRefresh; protected int Interval() => 1000 / VRefresh;
/// <summary> /// <summary>
/// Initialize the animation /// Initialize the animation
@ -119,9 +112,6 @@ namespace Greenshot.Base.Controls
/// <summary> /// <summary>
/// This method will be called every frame, so implement your animation/redraw logic here. /// This method will be called every frame, so implement your animation/redraw logic here.
/// </summary> /// </summary>
protected virtual void Animate() protected virtual void Animate() => throw new NotImplementedException();
{
throw new NotImplementedException();
}
} }
} }

View file

@ -23,6 +23,7 @@ using System;
using System.Drawing; using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
using Greenshot.Base.Core; using Greenshot.Base.Core;
using System.Linq;
namespace Greenshot.Base.Controls namespace Greenshot.Base.Controls
{ {
@ -52,19 +53,18 @@ namespace Greenshot.Base.Controls
{ {
base.Show(); base.Show();
bool positioned = false; bool positioned = false;
foreach (Screen screen in Screen.AllScreens) foreach (var screen in from Screen screen in Screen.AllScreens
{ where screen.Bounds.Contains(Cursor.Position)
if (screen.Bounds.Contains(Cursor.Position)) select screen)
{ {
positioned = true; positioned = true;
Location = new Point(screen.Bounds.X + (screen.Bounds.Width / 2) - (Width / 2), screen.Bounds.Y + (screen.Bounds.Height / 2) - (Height / 2)); Location = new Point(screen.Bounds.X + (screen.Bounds.Width / 2) - (Width / 2), screen.Bounds.Y + (screen.Bounds.Height / 2) - (Height / 2));
break; break;
} }
}
if (!positioned) 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(); Application.DoEvents();
} }
private void BackgroundFormFormClosing(object sender, FormClosingEventArgs e) private void BackgroundFormFormClosing(object sender, FormClosingEventArgs e) => timer_checkforclose.Stop();
{
timer_checkforclose.Stop();
}
} }
} }

View file

@ -31,38 +31,29 @@ namespace Greenshot.Base.Controls
{ {
private const int OLECMDID_SHOWSCRIPTERROR = 40; 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 S_OK = 0;
private const int OLECMDERR_E_NOTSUPPORTED = (-2147221248); private const int OLECMDERR_E_NOTSUPPORTED = -2147221248;
public ExtendedWebBrowserSite(WebBrowser wb) : base(wb) public ExtendedWebBrowserSite(WebBrowser wb) : base(wb)
{ {
} }
public int QueryStatus(Guid pguidCmdGroup, int cCmds, IntPtr prgCmds, IntPtr pCmdText) public int QueryStatus(Guid pguidCmdGroup, int cCmds, IntPtr prgCmds, IntPtr pCmdText) => OLECMDERR_E_NOTSUPPORTED;
{
return OLECMDERR_E_NOTSUPPORTED;
}
public int Exec(Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) public int Exec(Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{ {
if (pguidCmdGroup == CGID_DocHostCommandHandler) if (pguidCmdGroup == CGID_DocHostCommandHandler && nCmdID == OLECMDID_SHOWSCRIPTERROR)
{
if (nCmdID == OLECMDID_SHOWSCRIPTERROR)
{ {
// do not need to alter pvaOut as the docs says, enough to return S_OK here // do not need to alter pvaOut as the docs says, enough to return S_OK here
return S_OK; return S_OK;
} }
}
return OLECMDERR_E_NOTSUPPORTED; return OLECMDERR_E_NOTSUPPORTED;
} }
} }
protected override WebBrowserSiteBase CreateWebBrowserSiteBase() protected override WebBrowserSiteBase CreateWebBrowserSiteBase() => new ExtendedWebBrowserSite(this);
{
return new ExtendedWebBrowserSite(this);
}
} }
} }

View file

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

View file

@ -29,16 +29,6 @@ namespace Greenshot.Base.Controls
/// </summary> /// </summary>
public class GreenshotColumnSorter : IComparer 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> /// <summary>
/// Case insensitive comparer object /// Case insensitive comparer object
/// </summary> /// </summary>
@ -50,10 +40,10 @@ namespace Greenshot.Base.Controls
public GreenshotColumnSorter() public GreenshotColumnSorter()
{ {
// Initialize the column to '0' // Initialize the column to '0'
_columnToSort = 0; SortColumn = 0;
// Initialize the sort order to 'none' // Initialize the sort order to 'none'
_orderOfSort = SortOrder.None; Order = SortOrder.None;
// Initialize the CaseInsensitiveComparer object // Initialize the CaseInsensitiveComparer object
_objectCompare = new CaseInsensitiveComparer(); _objectCompare = new CaseInsensitiveComparer();
@ -83,20 +73,20 @@ namespace Greenshot.Base.Controls
} }
// Cast the objects to be compared to ListViewItem objects // Cast the objects to be compared to ListViewItem objects
var listviewX = (ListViewItem) x; var listviewX = (ListViewItem)x;
var listviewY = (ListViewItem) y; var listviewY = (ListViewItem)y;
// Compare the two items // 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 // 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 // Ascending sort is selected, return normal result of compare operation
return compareResult; return compareResult;
} }
if (_orderOfSort == SortOrder.Descending) if (Order == SortOrder.Descending)
{ {
// Descending sort is selected, return negative result of compare operation // Descending sort is selected, return negative result of compare operation
return -compareResult; return -compareResult;
@ -109,19 +99,11 @@ namespace Greenshot.Base.Controls
/// <summary> /// <summary>
/// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0'). /// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0').
/// </summary> /// </summary>
public int SortColumn public int SortColumn { set; get; }
{
set { _columnToSort = value; }
get { return _columnToSort; }
}
/// <summary> /// <summary>
/// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending'). /// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending').
/// </summary> /// </summary>
public SortOrder Order public SortOrder Order { set; get; }
{
set { _orderOfSort = value; }
get { return _orderOfSort; }
}
} }
} }

View file

@ -37,10 +37,7 @@ namespace Greenshot.Base.Controls
[Category("Greenshot"), DefaultValue(null), Description("Specifies the property name to map the configuration.")] [Category("Greenshot"), DefaultValue(null), Description("Specifies the property name to map the configuration.")]
public string PropertyName { get; set; } public string PropertyName { get; set; }
public GreenshotComboBox() public GreenshotComboBox() => SelectedIndexChanged += delegate { StoreSelectedEnum(); };
{
SelectedIndexChanged += delegate { StoreSelectedEnum(); };
}
public void SetValue(Enum currentValue) public void SetValue(Enum currentValue)
{ {
@ -65,7 +62,7 @@ namespace Greenshot.Base.Controls
Items.Clear(); Items.Clear();
foreach (var enumValue in availableValues) 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> /// <summary>
/// Get the selected enum value from the combobox, uses generics /// Get the selected enum value from the combobox, uses generics
/// </summary> /// </summary>
/// <returns>The enum value of the combobox</returns> /// <returns>The enum value of the combobox</returns>
public Enum GetSelectedEnum() public Enum GetSelectedEnum() => _selectedEnum;
{
return _selectedEnum;
}
} }
} }

View file

@ -4,9 +4,6 @@ namespace Greenshot.Base.Controls
{ {
public class GreenshotDoubleClickButton : Button public class GreenshotDoubleClickButton : Button
{ {
public GreenshotDoubleClickButton() public GreenshotDoubleClickButton() => SetStyle(ControlStyles.StandardClick | ControlStyles.StandardDoubleClick, true);
{
SetStyle(ControlStyles.StandardClick | ControlStyles.StandardDoubleClick, true);
}
} }
} }

View file

@ -19,7 +19,6 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
#if DEBUG #if DEBUG
using System.ComponentModel; using System.ComponentModel;
using System.ComponentModel.Design; using System.ComponentModel.Design;
@ -48,9 +47,8 @@ namespace Greenshot.Base.Controls
private bool _isDesignModeLanguageSet; private bool _isDesignModeLanguageSet;
private IDictionary<string, Control> _designTimeControls; private IDictionary<string, Control> _designTimeControls;
private IDictionary<string, ToolStripItem> _designTimeToolStripItems; private IDictionary<string, ToolStripItem> _designTimeToolStripItems;
#endif #endif
private bool _applyLanguageManually;
private bool _storeFieldsManually;
static GreenshotForm() static GreenshotForm()
{ {
@ -74,38 +72,21 @@ namespace Greenshot.Base.Controls
/// Used to check the designmode during a constructor /// Used to check the designmode during a constructor
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
protected static bool IsInDesignMode protected static bool IsInDesignMode => (Application.ExecutablePath.IndexOf("devenv.exe", StringComparison.OrdinalIgnoreCase) > -1) ||
{ Application.ExecutablePath.IndexOf("sharpdevelop.exe", StringComparison.OrdinalIgnoreCase) > -1 ||
get (Application.ExecutablePath.IndexOf("wdexpress.exe", StringComparison.OrdinalIgnoreCase) > -1);
{
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));
}
}
#endif #endif
protected bool ManualLanguageApply protected bool ManualLanguageApply { get; set; }
{
get { return _applyLanguageManually; }
set { _applyLanguageManually = value; }
}
protected bool ManualStoreFields protected bool ManualStoreFields { get; set; }
{
get { return _storeFieldsManually; }
set { _storeFieldsManually = value; }
}
/// <summary> /// <summary>
/// When this is set, the form will be brought to the foreground as soon as it is shown. /// When this is set, the form will be brought to the foreground as soon as it is shown.
/// </summary> /// </summary>
protected bool ToFront { get; set; } protected bool ToFront { get; set; }
protected GreenshotForm() protected GreenshotForm() => DpiChanged += (sender, dpiChangedEventArgs) => DpiChangedHandler(dpiChangedEventArgs.DeviceDpiOld, dpiChangedEventArgs.DeviceDpiNew);
{
DpiChanged += (sender, dpiChangedEventArgs) => DpiChangedHandler(dpiChangedEventArgs.DeviceDpiOld, dpiChangedEventArgs.DeviceDpiNew);
}
/// <summary> /// <summary>
/// This is the basic DpiChangedHandler responsible for all the DPI relative changes /// 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>(); _designTimeToolStripItems = new Dictionary<string, ToolStripItem>();
try try
{ {
ITypeResolutionService typeResService = GetService(typeof(ITypeResolutionService)) as ITypeResolutionService;
// Add a hard-path if you are using SharpDevelop // Add a hard-path if you are using SharpDevelop
// Language.AddLanguageFilePath(@"C:\Greenshot\Greenshot\Languages"); // Language.AddLanguageFilePath(@"C:\Greenshot\Greenshot\Languages");
// this "type" // this "type"
Assembly currentAssembly = GetType().Assembly; Assembly currentAssembly = GetType().Assembly;
if (typeResService == null) return; if (GetService(typeof(ITypeResolutionService)) is not ITypeResolutionService typeResService) return;
string assemblyPath = typeResService.GetPathOfAssembly(currentAssembly.GetName()); string assemblyPath = typeResService.GetPathOfAssembly(currentAssembly.GetName());
string assemblyDirectory = Path.GetDirectoryName(assemblyPath); string assemblyDirectory = Path.GetDirectoryName(assemblyPath);
@ -160,9 +139,7 @@ namespace Greenshot.Base.Controls
/// <param name="e"></param> /// <param name="e"></param>
protected override void OnPaint(PaintEventArgs e) protected override void OnPaint(PaintEventArgs e)
{ {
if (DesignMode) if (DesignMode && !_isDesignModeLanguageSet)
{
if (!_isDesignModeLanguageSet)
{ {
_isDesignModeLanguageSet = true; _isDesignModeLanguageSet = true;
try try
@ -174,7 +151,6 @@ namespace Greenshot.Base.Controls
// ignored // ignored
} }
} }
}
base.OnPaint(e); base.OnPaint(e);
} }
@ -189,7 +165,7 @@ namespace Greenshot.Base.Controls
if (!DesignMode) if (!DesignMode)
{ {
#endif #endif
if (!_applyLanguageManually) if (!ManualLanguageApply)
{ {
ApplyLanguage(); ApplyLanguage();
} }
@ -227,14 +203,11 @@ namespace Greenshot.Base.Controls
/// <param name="e"></param> /// <param name="e"></param>
protected override void OnClosed(EventArgs e) protected override void OnClosed(EventArgs e)
{ {
if (!DesignMode && !_storeFieldsManually) if (!DesignMode && !ManualStoreFields && DialogResult == DialogResult.OK)
{
if (DialogResult == DialogResult.OK)
{ {
LOG.Info("Form was closed with OK: storing field values."); LOG.Info("Form was closed with OK: storing field values.");
StoreFields(); StoreFields();
} }
}
base.OnClosed(e); base.OnClosed(e);
} }
@ -246,7 +219,7 @@ namespace Greenshot.Base.Controls
/// </summary> /// </summary>
public override ISite Site public override ISite Site
{ {
get { return base.Site; } get => base.Site;
set set
{ {
// Clear any component change event handlers. // Clear any component change event handlers.
@ -255,7 +228,7 @@ namespace Greenshot.Base.Controls
// Set the new Site value. // Set the new Site value.
base.Site = value; base.Site = value;
m_changeService = (IComponentChangeService) GetService(typeof(IComponentChangeService)); m_changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService));
// Register event handlers for component change events. // Register event handlers for component change events.
RegisterChangeNotifications(); RegisterChangeNotifications();
@ -266,7 +239,7 @@ namespace Greenshot.Base.Controls
{ {
// The m_changeService value is null when not in design mode, // The m_changeService value is null when not in design mode,
// as the IComponentChangeService is only available at design time. // 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. // Clear our the component change events to prepare for re-siting.
if (m_changeService != null) if (m_changeService != null)
@ -293,19 +266,19 @@ namespace Greenshot.Base.Controls
/// <param name="ce"></param> /// <param name="ce"></param>
private void OnComponentChanged(object sender, ComponentChangedEventArgs ce) 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 (!"LanguageKey".Equals(ce.Member.Name)) return;
if (ce.Component is Control control) if (ce.Component is Control control)
{ {
LOG.InfoFormat("Changing LanguageKey for {0} to {1}", control.Name, ce.NewValue); LOG.InfoFormat("Changing LanguageKey for {0} to {1}", control.Name, ce.NewValue);
ApplyLanguage(control, (string) ce.NewValue); ApplyLanguage(control, (string)ce.NewValue);
} }
else else
{ {
if (ce.Component is ToolStripItem item) if (ce.Component is ToolStripItem item)
{ {
LOG.InfoFormat("Changing LanguageKey for {0} to {1}", item.Name, ce.NewValue); LOG.InfoFormat("Changing LanguageKey for {0} to {1}", item.Name, ce.NewValue);
ApplyLanguage(item, (string) ce.NewValue); ApplyLanguage(item, (string)ce.NewValue);
} }
else else
{ {
@ -556,14 +529,14 @@ namespace Greenshot.Base.Controls
if (controlObject is CheckBox checkBox) if (controlObject is CheckBox checkBox)
{ {
checkBox.Checked = (bool) iniValue.Value; checkBox.Checked = (bool)iniValue.Value;
checkBox.Enabled = !iniValue.IsFixed; checkBox.Enabled = !iniValue.IsFixed;
continue; continue;
} }
if (controlObject is RadioButton radíoButton) if (controlObject is RadioButton radíoButton)
{ {
radíoButton.Checked = (bool) iniValue.Value; radíoButton.Checked = (bool)iniValue.Value;
radíoButton.Enabled = !iniValue.IsFixed; radíoButton.Enabled = !iniValue.IsFixed;
continue; continue;
} }
@ -572,7 +545,7 @@ namespace Greenshot.Base.Controls
{ {
if (controlObject is HotkeyControl hotkeyControl) if (controlObject is HotkeyControl hotkeyControl)
{ {
string hotkeyValue = (string) iniValue.Value; string hotkeyValue = (string)iniValue.Value;
if (!string.IsNullOrEmpty(hotkeyValue)) if (!string.IsNullOrEmpty(hotkeyValue))
{ {
hotkeyControl.SetHotkey(hotkeyValue); hotkeyControl.SetHotkey(hotkeyValue);
@ -590,7 +563,7 @@ namespace Greenshot.Base.Controls
if (controlObject is GreenshotComboBox comboxBox) if (controlObject is GreenshotComboBox comboxBox)
{ {
comboxBox.Populate(iniValue.ValueType); comboxBox.Populate(iniValue.ValueType);
comboxBox.SetValue((Enum) iniValue.Value); comboxBox.SetValue((Enum)iniValue.Value);
comboxBox.Enabled = !iniValue.IsFixed; 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 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; private static readonly bool IsWindows7OrOlder = Environment.OSVersion.Version.Major >= 6 && Environment.OSVersion.Version.Minor >= 1;
// Holds the list of hotkeys // 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> _needNonShiftModifier = new List<int>();
private readonly IList<int> _needNonAltGrModifier = new List<int>(); private readonly IList<int> _needNonAltGrModifier = new List<int>();
private readonly ContextMenuStrip _dummy = new ContextMenuStrip(); private readonly ContextMenuStrip _dummy = new();
/// <summary> /// <summary>
/// Used to make sure that there is no right-click menu available /// Used to make sure that there is no right-click menu available
/// </summary> /// </summary>
public override ContextMenuStrip ContextMenuStrip public override ContextMenuStrip ContextMenuStrip
{ {
get { return _dummy; } get => _dummy;
set { base.ContextMenuStrip = _dummy; } set => base.ContextMenuStrip = _dummy;
} }
/// <summary> /// <summary>
@ -118,13 +118,11 @@ namespace Greenshot.Base.Controls
/// </summary> /// </summary>
public override bool Multiline public override bool Multiline
{ {
get { return base.Multiline; } get => base.Multiline;
set set =>
{
// Ignore what the user wants; force Multiline to false // Ignore what the user wants; force Multiline to false
base.Multiline = false; base.Multiline = false;
} }
}
/// <summary> /// <summary>
/// Creates a new HotkeyControl /// Creates a new HotkeyControl
@ -151,43 +149,43 @@ namespace Greenshot.Base.Controls
// Shift + 0 - 9, A - Z // Shift + 0 - 9, A - Z
for (Keys k = Keys.D0; k <= Keys.Z; k++) for (Keys k = Keys.D0; k <= Keys.Z; k++)
{ {
_needNonShiftModifier.Add((int) k); _needNonShiftModifier.Add((int)k);
} }
// Shift + Numpad keys // Shift + Numpad keys
for (Keys k = Keys.NumPad0; k <= Keys.NumPad9; k++) for (Keys k = Keys.NumPad0; k <= Keys.NumPad9; k++)
{ {
_needNonShiftModifier.Add((int) k); _needNonShiftModifier.Add((int)k);
} }
// Shift + Misc (,;<./ etc) // Shift + Misc (,;<./ etc)
for (Keys k = Keys.Oem1; k <= Keys.OemBackslash; k++) for (Keys k = Keys.Oem1; k <= Keys.OemBackslash; k++)
{ {
_needNonShiftModifier.Add((int) k); _needNonShiftModifier.Add((int)k);
} }
// Shift + Space, PgUp, PgDn, End, Home // Shift + Space, PgUp, PgDn, End, Home
for (Keys k = Keys.Space; k <= Keys.Home; k++) 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 // Misc keys that we can't loop through
_needNonShiftModifier.Add((int) Keys.Insert); _needNonShiftModifier.Add((int)Keys.Insert);
_needNonShiftModifier.Add((int) Keys.Help); _needNonShiftModifier.Add((int)Keys.Help);
_needNonShiftModifier.Add((int) Keys.Multiply); _needNonShiftModifier.Add((int)Keys.Multiply);
_needNonShiftModifier.Add((int) Keys.Add); _needNonShiftModifier.Add((int)Keys.Add);
_needNonShiftModifier.Add((int) Keys.Subtract); _needNonShiftModifier.Add((int)Keys.Subtract);
_needNonShiftModifier.Add((int) Keys.Divide); _needNonShiftModifier.Add((int)Keys.Divide);
_needNonShiftModifier.Add((int) Keys.Decimal); _needNonShiftModifier.Add((int)Keys.Decimal);
_needNonShiftModifier.Add((int) Keys.Return); _needNonShiftModifier.Add((int)Keys.Return);
_needNonShiftModifier.Add((int) Keys.Escape); _needNonShiftModifier.Add((int)Keys.Escape);
_needNonShiftModifier.Add((int) Keys.NumLock); _needNonShiftModifier.Add((int)Keys.NumLock);
// Ctrl+Alt + 0 - 9 // Ctrl+Alt + 0 - 9
for (Keys k = Keys.D0; k <= Keys.D9; k++) 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 /// Prevents the letter/whatever entered to show up in the TextBox
/// Without this, a "A" key press would appear as "aControl, Alt + A" /// Without this, a "A" key press would appear as "aControl, Alt + A"
/// </summary> /// </summary>
private void HotkeyControl_KeyPress(object sender, KeyPressEventArgs e) private void HotkeyControl_KeyPress(object sender, KeyPressEventArgs e) => e.Handled = true;
{
e.Handled = true;
}
/// <summary> /// <summary>
/// Handles some misc keys, such as Ctrl+Delete and Shift+Insert /// Handles some misc keys, such as Ctrl+Delete and Shift+Insert
@ -284,7 +279,7 @@ namespace Greenshot.Base.Controls
/// </summary> /// </summary>
public Keys Hotkey public Keys Hotkey
{ {
get { return _hotkey; } get => _hotkey;
set set
{ {
_hotkey = value; _hotkey = value;
@ -307,7 +302,7 @@ namespace Greenshot.Base.Controls
/// </summary> /// </summary>
public Keys HotkeyModifiers public Keys HotkeyModifiers
{ {
get { return _modifiers; } get => _modifiers;
set set
{ {
_modifiers = value; _modifiers = value;
@ -336,15 +331,15 @@ namespace Greenshot.Base.Controls
} }
// Only validate input if it comes from the user // 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 // 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) if (_modifiers == Keys.None)
{ {
// Set Ctrl+Alt as the modifier unless Ctrl+Alt+<key> won't work... // 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; _modifiers = Keys.Alt | Keys.Control;
} }
@ -365,7 +360,7 @@ namespace Greenshot.Base.Controls
} }
// Check all Ctrl+Alt keys // 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 // Ctrl+Alt+4 etc won't work; reset hotkey and tell the user
_hotkey = Keys.None; _hotkey = Keys.None;
@ -384,10 +379,7 @@ namespace Greenshot.Base.Controls
Text = HotkeyToLocalizedString(_modifiers, _hotkey); Text = HotkeyToLocalizedString(_modifiers, _hotkey);
} }
public override string ToString() public override string ToString() => HotkeyToString(HotkeyModifiers, Hotkey);
{
return HotkeyToString(HotkeyModifiers, Hotkey);
}
public static string GetLocalizedHotkeyStringFromString(string hotkeyString) public static string GetLocalizedHotkeyStringFromString(string hotkeyString)
{ {
@ -396,14 +388,11 @@ namespace Greenshot.Base.Controls
return HotkeyToLocalizedString(modifiers, virtualKeyCode); return HotkeyToLocalizedString(modifiers, virtualKeyCode);
} }
public static string HotkeyToString(Keys modifierKeyCode, Keys virtualKeyCode) public static string HotkeyToString(Keys modifierKeyCode, Keys virtualKeyCode) => HotkeyModifiersToString(modifierKeyCode) + virtualKeyCode;
{
return HotkeyModifiersToString(modifierKeyCode) + virtualKeyCode;
}
public static string HotkeyModifiersToString(Keys modifierKeyCode) public static string HotkeyModifiersToString(Keys modifierKeyCode)
{ {
StringBuilder hotkeyString = new StringBuilder(); StringBuilder hotkeyString = new();
if ((modifierKeyCode & Keys.Alt) > 0) if ((modifierKeyCode & Keys.Alt) > 0)
{ {
hotkeyString.Append("Alt").Append(" + "); hotkeyString.Append("Alt").Append(" + ");
@ -427,15 +416,11 @@ namespace Greenshot.Base.Controls
return hotkeyString.ToString(); return hotkeyString.ToString();
} }
public static string HotkeyToLocalizedString(Keys modifierKeyCode, Keys virtualKeyCode) => HotkeyModifiersToLocalizedString(modifierKeyCode) + GetKeyName(virtualKeyCode);
public static string HotkeyToLocalizedString(Keys modifierKeyCode, Keys virtualKeyCode)
{
return HotkeyModifiersToLocalizedString(modifierKeyCode) + GetKeyName(virtualKeyCode);
}
public static string HotkeyModifiersToLocalizedString(Keys modifierKeyCode) public static string HotkeyModifiersToLocalizedString(Keys modifierKeyCode)
{ {
StringBuilder hotkeyString = new StringBuilder(); StringBuilder hotkeyString = new();
if ((modifierKeyCode & Keys.Alt) > 0) if ((modifierKeyCode & Keys.Alt) > 0)
{ {
hotkeyString.Append(GetKeyName(Keys.Alt)).Append(" + "); hotkeyString.Append(GetKeyName(Keys.Alt)).Append(" + ");
@ -459,28 +444,27 @@ namespace Greenshot.Base.Controls
return hotkeyString.ToString(); return hotkeyString.ToString();
} }
public static Keys HotkeyModifiersFromString(string modifiersString) public static Keys HotkeyModifiersFromString(string modifiersString)
{ {
Keys modifiers = Keys.None; Keys modifiers = Keys.None;
if (!string.IsNullOrEmpty(modifiersString)) if (!string.IsNullOrEmpty(modifiersString))
{ {
if (modifiersString.ToLower().Contains("alt")) if (modifiersString.IndexOf("alt", StringComparison.CurrentCultureIgnoreCase) >= 0)
{ {
modifiers |= Keys.Alt; modifiers |= Keys.Alt;
} }
if (modifiersString.ToLower().Contains("ctrl")) if (modifiersString.IndexOf("ctrl", StringComparison.CurrentCultureIgnoreCase) >= 0)
{ {
modifiers |= Keys.Control; modifiers |= Keys.Control;
} }
if (modifiersString.ToLower().Contains("shift")) if (modifiersString.IndexOf("shift", StringComparison.CurrentCultureIgnoreCase) >= 0)
{ {
modifiers |= Keys.Shift; modifiers |= Keys.Shift;
} }
if (modifiersString.ToLower().Contains("win")) if (modifiersString.IndexOf("win", StringComparison.CurrentCultureIgnoreCase) >= 0)
{ {
modifiers |= Keys.LWin; modifiers |= Keys.LWin;
} }
@ -499,16 +483,13 @@ namespace Greenshot.Base.Controls
hotkey = hotkey.Remove(0, hotkey.LastIndexOf('+') + 1).Trim(); hotkey = hotkey.Remove(0, hotkey.LastIndexOf('+') + 1).Trim();
} }
key = (Keys) Enum.Parse(typeof(Keys), hotkey); key = (Keys)Enum.Parse(typeof(Keys), hotkey);
} }
return key; return key;
} }
public static void RegisterHotkeyHwnd(IntPtr hWnd) public static void RegisterHotkeyHwnd(IntPtr hWnd) => _hotkeyHwnd = hWnd;
{
_hotkeyHwnd = hWnd;
}
/// <summary> /// <summary>
/// Register a hotkey /// Register a hotkey
@ -529,31 +510,31 @@ namespace Greenshot.Base.Controls
uint modifiers = 0; uint modifiers = 0;
if ((modifierKeyCode & Keys.Alt) > 0) if ((modifierKeyCode & Keys.Alt) > 0)
{ {
modifiers |= (uint) Modifiers.ALT; modifiers |= (uint)Modifiers.ALT;
} }
if ((modifierKeyCode & Keys.Control) > 0) if ((modifierKeyCode & Keys.Control) > 0)
{ {
modifiers |= (uint) Modifiers.CTRL; modifiers |= (uint)Modifiers.CTRL;
} }
if ((modifierKeyCode & Keys.Shift) > 0) if ((modifierKeyCode & Keys.Shift) > 0)
{ {
modifiers |= (uint) Modifiers.SHIFT; modifiers |= (uint)Modifiers.SHIFT;
} }
if (modifierKeyCode == Keys.LWin || modifierKeyCode == Keys.RWin) 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 // Disable repeating hotkey for Windows 7 and beyond, as described in #1559
if (IsWindows7OrOlder) 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); KeyHandlers.Add(_hotKeyCounter, handler);
return _hotKeyCounter++; return _hotKeyCounter++;
@ -592,7 +573,7 @@ namespace Greenshot.Base.Controls
return true; return true;
} }
if (KeyHandlers.TryGetValue((int) m.WParam, out var handler)) if (KeyHandlers.TryGetValue((int)m.WParam, out var handler))
{ {
handler(); handler();
} }
@ -602,7 +583,7 @@ namespace Greenshot.Base.Controls
public static string GetKeyName(Keys givenKey) public static string GetKeyName(Keys givenKey)
{ {
StringBuilder keyName = new StringBuilder(); StringBuilder keyName = new();
const uint numpad = 55; const uint numpad = 55;
Keys virtualKey = givenKey; Keys virtualKey = givenKey;
@ -641,7 +622,7 @@ namespace Greenshot.Base.Controls
return keyString + " /"; 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 // because MapVirtualKey strips the extended bit for some keys
switch (virtualKey) 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 //Cancel the key press so the user can't enter a new url
e.Handled = true; e.Handled = true;
} }
}
} }

View file

@ -64,9 +64,6 @@ namespace Greenshot.Base.Controls
} }
} }
private void TrackBarJpegQualityScroll(object sender, EventArgs e) private void TrackBarJpegQualityScroll(object sender, EventArgs e) => textBoxJpegQuality.Text = trackBarJpegQuality.Value.ToString();
{
textBoxJpegQuality.Text = trackBarJpegQuality.Value.ToString();
}
} }
} }

View file

@ -51,15 +51,12 @@ namespace Greenshot.Base.Controls
protected virtual void Dispose(bool disposing) protected virtual void Dispose(bool disposing)
{ {
if (disposing) if (disposing && SaveFileDialog != null)
{
if (SaveFileDialog != null)
{ {
SaveFileDialog.Dispose(); SaveFileDialog.Dispose();
SaveFileDialog = null; SaveFileDialog = null;
} }
} }
}
public SaveImageFileDialog(ICaptureDetails captureDetails) public SaveImageFileDialog(ICaptureDetails captureDetails)
{ {
@ -121,13 +118,13 @@ namespace Greenshot.Base.Controls
private void PrepareFilterOptions() private void PrepareFilterOptions()
{ {
// TODO: Change to the FileFormatHandlerRegistry to look for all the supported extensions // 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]; _filterOptions = new FilterOption[supportedImageFormats.Length];
for (int i = 0; i < _filterOptions.Length; i++) for (int i = 0; i < _filterOptions.Length; i++)
{ {
string ifo = supportedImageFormats[i].ToString(); string ifo = supportedImageFormats[i].ToString();
if (ifo.ToLower().Equals("jpeg")) ifo = "Jpg"; // we dont want no jpeg files, so let the dialog check for jpg if (ifo.Equals("jpeg", StringComparison.CurrentCultureIgnoreCase)) ifo = "Jpg"; // we dont want no jpeg files, so let the dialog check for jpg
FilterOption fo = new FilterOption FilterOption fo = new()
{ {
Label = ifo.ToUpper(), Label = ifo.ToUpper(),
Extension = ifo.ToLower() Extension = ifo.ToLower()
@ -141,8 +138,8 @@ namespace Greenshot.Base.Controls
/// </summary> /// </summary>
public string FileName public string FileName
{ {
get { return SaveFileDialog.FileName; } get => SaveFileDialog.FileName;
set { SaveFileDialog.FileName = value; } set => SaveFileDialog.FileName = value;
} }
/// <summary> /// <summary>
@ -150,8 +147,8 @@ namespace Greenshot.Base.Controls
/// </summary> /// </summary>
public string InitialDirectory public string InitialDirectory
{ {
get { return SaveFileDialog.InitialDirectory; } get => SaveFileDialog.InitialDirectory;
set { SaveFileDialog.InitialDirectory = value; } set => SaveFileDialog.InitialDirectory = value;
} }
/// <summary> /// <summary>
@ -181,7 +178,7 @@ namespace Greenshot.Base.Controls
/// </summary> /// </summary>
public string Extension public string Extension
{ {
get { return _filterOptions[SaveFileDialog.FilterIndex - 1].Extension; } get => _filterOptions[SaveFileDialog.FilterIndex - 1].Extension;
set set
{ {
for (int i = 0; i < _filterOptions.Length; i++) for (int i = 0; i < _filterOptions.Length; i++)
@ -204,11 +201,9 @@ namespace Greenshot.Base.Controls
/// <summary> /// <summary>
/// sets InitialDirectory and FileName property of a SaveFileDialog smartly, considering default pattern and last used path /// sets InitialDirectory and FileName property of a SaveFileDialog smartly, considering default pattern and last used path
/// </summary> /// </summary>
private void ApplySuggestedValues() private void ApplySuggestedValues() =>
{
// build the full path and set dialog properties // build the full path and set dialog properties
FileName = FilenameHelper.GetFilenameWithoutExtensionFromPattern(conf.OutputFileFilenamePattern, _captureDetails); FileName = FilenameHelper.GetFilenameWithoutExtensionFromPattern(conf.OutputFileFilenamePattern, _captureDetails);
}
private class FilterOption private class FilterOption
{ {
@ -221,7 +216,7 @@ namespace Greenshot.Base.Controls
// fix for bug #3379053 // fix for bug #3379053
try try
{ {
if (_eagerlyCreatedDirectory != null && _eagerlyCreatedDirectory.GetFiles().Length == 0 && _eagerlyCreatedDirectory.GetDirectories().Length == 0) if (_eagerlyCreatedDirectory?.GetFiles().Length == 0 && _eagerlyCreatedDirectory.GetDirectories().Length == 0)
{ {
_eagerlyCreatedDirectory.Delete(); _eagerlyCreatedDirectory.Delete();
_eagerlyCreatedDirectory = null; _eagerlyCreatedDirectory = null;

View file

@ -50,14 +50,9 @@ namespace Greenshot.Base.Controls
FormBorderStyle = FormBorderStyle.None; FormBorderStyle = FormBorderStyle.None;
TopMost = false; TopMost = false;
Enabled = false; Enabled = false;
if (conf.WindowCaptureMode == WindowCaptureMode.Auto || conf.WindowCaptureMode == WindowCaptureMode.Aero) BackColor = conf.WindowCaptureMode == WindowCaptureMode.Auto || conf.WindowCaptureMode == WindowCaptureMode.Aero
{ ? Color.FromArgb(255, conf.DWMBackgroundColor.R, conf.DWMBackgroundColor.G, conf.DWMBackgroundColor.B)
BackColor = Color.FromArgb(255, conf.DWMBackgroundColor.R, conf.DWMBackgroundColor.G, conf.DWMBackgroundColor.B); : Color.White;
}
else
{
BackColor = Color.White;
}
// cleanup at close // cleanup at close
FormClosing += delegate { UnregisterThumbnail(); }; FormClosing += delegate { UnregisterThumbnail(); };
@ -103,11 +98,11 @@ namespace Greenshot.Base.Controls
} }
int thumbnailHeight = 200; 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) if (parentControl != null && thumbnailWidth > parentControl.Width)
{ {
thumbnailWidth = parentControl.Width; thumbnailWidth = parentControl.Width;
thumbnailHeight = (int) (thumbnailWidth * (sourceSize.Height / (float) sourceSize.Width)); thumbnailHeight = (int)(thumbnailWidth * (sourceSize.Height / (float)sourceSize.Width));
} }
Width = thumbnailWidth; Width = thumbnailWidth;
@ -147,14 +142,9 @@ namespace Greenshot.Base.Controls
public void AlignToControl(Control alignTo) public void AlignToControl(Control alignTo)
{ {
var screenBounds = DisplayInfo.ScreenBounds; var screenBounds = DisplayInfo.ScreenBounds;
if (screenBounds.Contains(alignTo.Left, alignTo.Top - Height)) Location = screenBounds.Contains(alignTo.Left, alignTo.Top - Height)
{ ? new Point(alignTo.Left + (alignTo.Width / 2) - (Width / 2), alignTo.Top - Height)
Location = new Point(alignTo.Left + (alignTo.Width / 2) - (Width / 2), alignTo.Top - Height); : new Point(alignTo.Left + (alignTo.Width / 2) - (Width / 2), alignTo.Bottom);
}
else
{
Location = new Point(alignTo.Left + (alignTo.Width / 2) - (Width / 2), alignTo.Bottom);
}
} }
} }
} }

View file

@ -49,12 +49,9 @@ namespace Greenshot.Base.Core
return 1; return 1;
} }
if (Priority == other.Priority) return Priority == other.Priority
{ ? string.CompareOrdinal(Description, other.Description)
return string.Compare(Description, other.Description, StringComparison.Ordinal); : Priority - other.Priority;
}
return Priority - other.Priority;
} }
public abstract string Designation { get; } public abstract string Designation { get; }
@ -89,18 +86,7 @@ namespace Greenshot.Base.Core
public virtual bool IsLinkable => false; public virtual bool IsLinkable => false;
public virtual bool IsActive public virtual bool IsActive => (CoreConfig.ExcludeDestinations?.Contains(Designation)) != true;
{
get
{
if (CoreConfig.ExcludeDestinations != null && CoreConfig.ExcludeDestinations.Contains(Designation))
{
return false;
}
return true;
}
}
public abstract ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails); public abstract ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails);
@ -111,7 +97,7 @@ namespace Greenshot.Base.Core
/// <param name="surface"></param> /// <param name="surface"></param>
public void ProcessExport(ExportInformation exportInformation, ISurface surface) public void ProcessExport(ExportInformation exportInformation, ISurface surface)
{ {
if (exportInformation != null && exportInformation.ExportMade) if (exportInformation?.ExportMade == true)
{ {
if (!string.IsNullOrEmpty(exportInformation.Uri)) if (!string.IsNullOrEmpty(exportInformation.Uri))
{ {
@ -137,10 +123,7 @@ namespace Greenshot.Base.Core
} }
} }
public override string ToString() public override string ToString() => Description;
{
return Description;
}
/// <summary> /// <summary>
/// Helper method to add events which set the tag, this way we can see why there might be a close. /// 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) public ExportInformation ShowPickerMenu(bool addDynamics, ISurface surface, ICaptureDetails captureDetails, IEnumerable<IDestination> destinations)
{ {
// Generate an empty ExportInformation object, for when nothing was selected. // 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 var menu = new ContextMenuStrip
{ {
ImageScalingSize = CoreConfig.IconSize, ImageScalingSize = CoreConfig.IconSize,
@ -196,7 +179,7 @@ namespace Greenshot.Base.Core
menu.ResumeLayout(); menu.ResumeLayout();
}; };
menu.Closing += delegate(object source, ToolStripDropDownClosingEventArgs eventArgs) menu.Closing += (object source, ToolStripDropDownClosingEventArgs eventArgs) =>
{ {
Log.DebugFormat("Close reason: {0}", eventArgs.CloseReason); Log.DebugFormat("Close reason: {0}", eventArgs.CloseReason);
switch (eventArgs.CloseReason) switch (eventArgs.CloseReason)
@ -243,10 +226,10 @@ namespace Greenshot.Base.Core
{ {
// Fix foreach loop variable for the delegate // Fix foreach loop variable for the delegate
ToolStripMenuItem item = destination.GetMenuItem(addDynamics, menu, ToolStripMenuItem item = destination.GetMenuItem(addDynamics, menu,
delegate(object sender, EventArgs e) (object sender, EventArgs e) =>
{ {
ToolStripMenuItem toolStripMenuItem = sender as ToolStripMenuItem; ToolStripMenuItem toolStripMenuItem = sender as ToolStripMenuItem;
IDestination clickedDestination = (IDestination) toolStripMenuItem?.Tag; IDestination clickedDestination = (IDestination)toolStripMenuItem?.Tag;
if (clickedDestination == null) if (clickedDestination == null)
{ {
return; return;
@ -255,7 +238,7 @@ namespace Greenshot.Base.Core
menu.Tag = clickedDestination.Designation; menu.Tag = clickedDestination.Designation;
// Export // Export
exportInformation = clickedDestination.ExportCapture(true, surface, captureDetails); 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); Log.InfoFormat("Export to {0} success, closing menu", exportInformation.DestinationDescription);
// close menu if the destination wasn't the editor // close menu if the destination wasn't the editor
@ -288,7 +271,7 @@ namespace Greenshot.Base.Core
// Close // Close
menu.Items.Add(new ToolStripSeparator()); 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") Image = GreenshotResources.GetImage("Close.Image")
}; };
@ -319,14 +302,7 @@ namespace Greenshot.Base.Core
var menuRectangle = new NativeRect(location, menu.Size); var menuRectangle = new NativeRect(location, menu.Size);
menuRectangle = menuRectangle.Intersect(DisplayInfo.ScreenBounds); menuRectangle = menuRectangle.Intersect(DisplayInfo.ScreenBounds);
if (menuRectangle.Height < menu.Height) location = menuRectangle.Height < menu.Height ? location.Offset(-40, -(menuRectangle.Height - menu.Height)) : location.Offset(-40, -10);
{
location = location.Offset(-40, -(menuRectangle.Height - menu.Height));
}
else
{
location = location.Offset(-40, -10);
}
// This prevents the problem that the context menu shows in the task-bar // This prevents the problem that the context menu shows in the task-bar
User32Api.SetForegroundWindow(SimpleServiceProvider.Current.GetInstance<NotifyIcon>().ContextMenuStrip.Handle); User32Api.SetForegroundWindow(SimpleServiceProvider.Current.GetInstance<NotifyIcon>().ContextMenuStrip.Handle);
@ -374,7 +350,7 @@ namespace Greenshot.Base.Core
{ {
if (basisMenuItem.DropDownItems.Count == 0) 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" // Fixing Bug #3536968 by catching the COMException (every exception) and not displaying the "subDestinations"
try try
{ {

View file

@ -31,17 +31,14 @@ namespace Greenshot.Base.Core
{ {
public virtual int CompareTo(object obj) public virtual int CompareTo(object obj)
{ {
if (!(obj is IProcessor other)) if (obj is not IProcessor other)
{ {
return 1; return 1;
} }
if (Priority == other.Priority) return Priority == other.Priority
{ ? string.CompareOrdinal(Description, other.Description)
return string.Compare(Description, other.Description, StringComparison.Ordinal); : Priority - other.Priority;
}
return Priority - other.Priority;
} }
public abstract string Designation { get; } public abstract string Designation { get; }

View file

@ -23,6 +23,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using Accessibility; using Accessibility;
using System.Linq;
namespace Greenshot.Base.Core namespace Greenshot.Base.Core
{ {
@ -37,8 +38,8 @@ namespace Greenshot.Base.Core
{ {
var guid = new Guid("{618736e0-3c3d-11cf-810c-00aa00389b71}"); // IAccessible var guid = new Guid("{618736e0-3c3d-11cf-810c-00aa00389b71}"); // IAccessible
object obj = null; object obj = null;
int num = AccessibleObjectFromWindow(hWnd, (uint) idObject, ref guid, ref obj); int num = AccessibleObjectFromWindow(hWnd, (uint)idObject, ref guid, ref obj);
acc = (IAccessible) obj; acc = (IAccessible)obj;
return num; return num;
} }
@ -67,13 +68,13 @@ namespace Greenshot.Base.Core
{ {
get get
{ {
object[] res = GetAccessibleChildren(accessible, out var num); object[] res = GetAccessibleChildren(accessible, out _);
if (res == null) if (res == null)
{ {
return new Accessible[0]; return new Accessible[0];
} }
List<Accessible> list = new List<Accessible>(res.Length); List<Accessible> list = new(res.Length);
foreach (object obj in res) foreach (object obj in res)
{ {
if (obj is IAccessible acc) if (obj is IAccessible acc)
@ -86,15 +87,9 @@ namespace Greenshot.Base.Core
} }
} }
private string Name private string Name => accessible.get_accName(CHILDID_SELF);
{
get { return accessible.get_accName(CHILDID_SELF); }
}
private int ChildCount private int ChildCount => accessible.accChildCount;
{
get { return accessible.accChildCount; }
}
public Accessible(IntPtr hWnd) public Accessible(IntPtr hWnd)
{ {
@ -143,7 +138,7 @@ namespace Greenshot.Base.Core
{ {
object tabIndex = tab.accessible.get_accState(0); object tabIndex = tab.accessible.get_accState(0);
if ((int) tabIndex == IE_ACTIVE_TAB) if ((int)tabIndex == IE_ACTIVE_TAB)
{ {
return tab.Name; return tab.Name;
} }
@ -182,22 +177,20 @@ namespace Greenshot.Base.Core
} }
} }
public IEnumerable<string> IETabUrls public IEnumerable<string> IETabUrls
{ {
get get
{ {
foreach (Accessible accessor in Children) foreach (var tab in from Accessible accessor in Children
from tab in
from child in accessor.Children
from tab in child.Children
select tab
select tab)
{ {
foreach (var child in accessor.Children) _ = tab.accessible.get_accState(CHILDID_SELF);
{
foreach (var tab in child.Children)
{
object tabIndex = tab.accessible.get_accState(CHILDID_SELF);
var description = tab.accessible.get_accDescription(CHILDID_SELF); var description = tab.accessible.get_accDescription(CHILDID_SELF);
if (!string.IsNullOrEmpty(description)) if (!string.IsNullOrEmpty(description) && description.Contains(Environment.NewLine))
{
if (description.Contains(Environment.NewLine))
{ {
var url = description.Substring(description.IndexOf(Environment.NewLine)).Trim(); var url = description.Substring(description.IndexOf(Environment.NewLine)).Trim();
yield return url; yield return url;
@ -205,19 +198,10 @@ namespace Greenshot.Base.Core
} }
} }
} }
}
}
}
private Accessible(IAccessible acc) private Accessible(IAccessible acc) => accessible = acc ?? throw new Exception();
{
accessible = acc ?? throw new Exception();
}
private void Activate() private void Activate() => accessible.accDoDefaultAction(CHILDID_SELF);
{
accessible.accDoDefaultAction(CHILDID_SELF);
}
private static object[] GetAccessibleChildren(IAccessible ao, out int childs) 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> /// <typeparam name="T">Type for the animation, like Point/Rectangle/Size</typeparam>
public abstract class AnimatorBase<T> : IAnimator public abstract class AnimatorBase<T> : IAnimator
{ {
private readonly Queue<AnimationLeg<T>> _queue = new Queue<AnimationLeg<T>>(); private readonly Queue<AnimationLeg<T>> _queue = new();
/// <summary> /// <summary>
/// Constructor /// Constructor
@ -77,7 +77,7 @@ namespace Greenshot.Base.Core
/// <param name="frames"></param> /// <param name="frames"></param>
/// <param name="easingType"></param> /// <param name="easingType"></param>
/// <param name="easingMode"></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; First = first;
Last = last; Last = last;
@ -110,27 +110,13 @@ namespace Greenshot.Base.Core
/// <summary> /// <summary>
/// Final animation value, this is including the legs /// Final animation value, this is including the legs
/// </summary> /// </summary>
public T Final public T Final => _queue.Count == 0 ? Last : _queue.ToArray()[_queue.Count - 1].Destination;
{
get
{
if (_queue.Count == 0)
{
return Last;
}
return _queue.ToArray()[_queue.Count - 1].Destination;
}
}
/// <summary> /// <summary>
/// This restarts the current animation and changes the last frame /// This restarts the current animation and changes the last frame
/// </summary> /// </summary>
/// <param name="newDestination"></param> /// <param name="newDestination"></param>
public void ChangeDestination(T newDestination) public void ChangeDestination(T newDestination) => ChangeDestination(newDestination, Frames);
{
ChangeDestination(newDestination, Frames);
}
/// <summary> /// <summary>
/// This restarts the current animation and changes the last frame /// This restarts the current animation and changes the last frame
@ -151,20 +137,14 @@ namespace Greenshot.Base.Core
/// All values will stay the same /// All values will stay the same
/// </summary> /// </summary>
/// <param name="queuedDestination"></param> /// <param name="queuedDestination"></param>
public void QueueDestinationLeg(T queuedDestination) public void QueueDestinationLeg(T queuedDestination) => QueueDestinationLeg(queuedDestination, Frames, EasingType, EasingMode);
{
QueueDestinationLeg(queuedDestination, Frames, EasingType, EasingMode);
}
/// <summary> /// <summary>
/// Queue the destination, it will be used to continue at the last frame /// Queue the destination, it will be used to continue at the last frame
/// </summary> /// </summary>
/// <param name="queuedDestination"></param> /// <param name="queuedDestination"></param>
/// <param name="frames"></param> /// <param name="frames"></param>
public void QueueDestinationLeg(T queuedDestination, int frames) public void QueueDestinationLeg(T queuedDestination, int frames) => QueueDestinationLeg(queuedDestination, frames, EasingType, EasingMode);
{
QueueDestinationLeg(queuedDestination, frames, EasingType, EasingMode);
}
/// <summary> /// <summary>
/// Queue the destination, it will be used to continue at the last frame /// 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="queuedDestination"></param>
/// <param name="frames"></param> /// <param name="frames"></param>
/// <param name="easingType">EasingType</param> /// <param name="easingType">EasingType</param>
public void QueueDestinationLeg(T queuedDestination, int frames, EasingType easingType) public void QueueDestinationLeg(T queuedDestination, int frames, EasingType easingType) => QueueDestinationLeg(queuedDestination, frames, easingType, EasingMode);
{
QueueDestinationLeg(queuedDestination, frames, easingType, EasingMode);
}
/// <summary> /// <summary>
/// Queue the destination, it will be used to continue at the last frame /// 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> /// <param name="easingMode"></param>
public void QueueDestinationLeg(T queuedDestination, int frames, EasingType easingType, EasingMode easingMode) public void QueueDestinationLeg(T queuedDestination, int frames, EasingType easingType, EasingMode easingMode)
{ {
AnimationLeg<T> leg = new AnimationLeg<T> AnimationLeg<T> leg = new()
{ {
Destination = queuedDestination, Destination = queuedDestination,
Frames = frames, Frames = frames,
@ -209,17 +186,13 @@ namespace Greenshot.Base.Core
/// <summary> /// <summary>
/// Get the easing value, which is from 0-1 and depends on the frame /// Get the easing value, which is from 0-1 and depends on the frame
/// </summary> /// </summary>
protected double EasingValue protected double EasingValue => EasingMode switch
{ {
get => EasingMode.EaseOut => Easing.EaseOut(CurrentFrameNr / (double)Frames, EasingType),
EasingMode switch EasingMode.EaseInOut => Easing.EaseInOut(CurrentFrameNr / (double)Frames, EasingType),
{ EasingMode.EaseIn => Easing.EaseIn(CurrentFrameNr / (double)Frames, EasingType),
EasingMode.EaseOut => Easing.EaseOut(CurrentFrameNr / (double) Frames, EasingType), _ => Easing.EaseIn(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> /// <summary>
/// Get the current (previous) frame object /// Get the current (previous) frame object
@ -239,7 +212,7 @@ namespace Greenshot.Base.Core
return true; return true;
} }
if (_queue.Count <= 0) if (_queue.Count == 0)
{ {
return false; return false;
} }
@ -251,25 +224,13 @@ namespace Greenshot.Base.Core
EasingType = nextLeg.EasingType; EasingType = nextLeg.EasingType;
EasingMode = nextLeg.EasingMode; EasingMode = nextLeg.EasingMode;
return true; return true;
} }
} }
/// <summary> /// <summary>
/// Are there more frames to animate? /// Are there more frames to animate?
/// </summary> /// </summary>
public virtual bool HasNext public virtual bool HasNext => CurrentFrameNr < Frames || _queue.Count > 0;
{
get
{
if (CurrentFrameNr < Frames)
{
return true;
}
return _queue.Count > 0;
}
}
/// <summary> /// <summary>
/// Get the next animation frame value object /// Get the next animation frame value object
@ -312,12 +273,12 @@ namespace Greenshot.Base.Core
double dx = Last.X - First.X; double dx = Last.X - First.X;
double dy = Last.Y - First.Y; double dy = Last.Y - First.Y;
int x = First.X + (int) (easingValue * dx); int x = First.X + (int)(easingValue * dx);
int y = First.Y + (int) (easingValue * dy); int y = First.Y + (int)(easingValue * dy);
double dw = Last.Width - First.Width; double dw = Last.Width - First.Width;
double dh = Last.Height - First.Height; double dh = Last.Height - First.Height;
int width = First.Width + (int) (easingValue * dw); int width = First.Width + (int)(easingValue * dw);
int height = First.Height + (int) (easingValue * dh); int height = First.Height + (int)(easingValue * dh);
Current = new NativeRect(x, y, width, height); Current = new NativeRect(x, y, width, height);
return Current; return Current;
@ -356,8 +317,8 @@ namespace Greenshot.Base.Core
double dx = Last.X - First.X; double dx = Last.X - First.X;
double dy = Last.Y - First.Y; double dy = Last.Y - First.Y;
int x = First.X + (int) (easingValue * dx); int x = First.X + (int)(easingValue * dx);
int y = First.Y + (int) (easingValue * dy); int y = First.Y + (int)(easingValue * dy);
Current = new NativePoint(x, y); Current = new NativePoint(x, y);
} }
@ -396,8 +357,8 @@ namespace Greenshot.Base.Core
double easingValue = EasingValue; double easingValue = EasingValue;
double dw = Last.Width - First.Width; double dw = Last.Width - First.Width;
double dh = Last.Height - First.Height; double dh = Last.Height - First.Height;
int width = First.Width + (int) (easingValue * dw); int width = First.Width + (int)(easingValue * dw);
int height = First.Height + (int) (easingValue * dh); int height = First.Height + (int)(easingValue * dh);
Current = new NativeSize(width, height); Current = new NativeSize(width, height);
} }
@ -438,10 +399,10 @@ namespace Greenshot.Base.Core
double dr = Last.R - First.R; double dr = Last.R - First.R;
double dg = Last.G - First.G; double dg = Last.G - First.G;
double db = Last.B - First.B; double db = Last.B - First.B;
int a = First.A + (int) (easingValue * da); int a = First.A + (int)(easingValue * da);
int r = First.R + (int) (easingValue * dr); int r = First.R + (int)(easingValue * dr);
int g = First.G + (int) (easingValue * dg); int g = First.G + (int)(easingValue * dg);
int b = First.B + (int) (easingValue * db); int b = First.B + (int)(easingValue * db);
Current = Color.FromArgb(a, r, g, b); Current = Color.FromArgb(a, r, g, b);
} }
@ -479,7 +440,7 @@ namespace Greenshot.Base.Core
{ {
double easingValue = EasingValue; double easingValue = EasingValue;
double delta = Last - First; double delta = Last - First;
Current = First + (int) (easingValue * delta); Current = First + (int)(easingValue * delta);
} }
return Current; return Current;
@ -497,13 +458,13 @@ namespace Greenshot.Base.Core
{ {
double easedStep = acceleration > 0 ? EaseIn(linearStep, type) : acceleration < 0 ? EaseOut(linearStep, type) : linearStep; double easedStep = acceleration > 0 ? EaseIn(linearStep, type) : acceleration < 0 ? EaseOut(linearStep, type) : linearStep;
// Lerp: // Lerp:
return ((easedStep - linearStep) * Math.Abs(acceleration) + linearStep); return ((easedStep - linearStep) * Math.Abs(acceleration)) + linearStep;
} }
public static double EaseIn(double linearStep, EasingType type) => public static double EaseIn(double linearStep, EasingType type) =>
type switch type switch
{ {
EasingType.Step => (linearStep < 0.5 ? 0 : 1), EasingType.Step => linearStep < 0.5 ? 0 : 1,
EasingType.Linear => linearStep, EasingType.Linear => linearStep,
EasingType.Sine => Sine.EaseIn(linearStep), EasingType.Sine => Sine.EaseIn(linearStep),
EasingType.Quadratic => Power.EaseIn(linearStep, 2), EasingType.Quadratic => Power.EaseIn(linearStep, 2),
@ -516,7 +477,7 @@ namespace Greenshot.Base.Core
public static double EaseOut(double linearStep, EasingType type) => public static double EaseOut(double linearStep, EasingType type) =>
type switch type switch
{ {
EasingType.Step => (linearStep < 0.5 ? 0 : 1), EasingType.Step => linearStep < 0.5 ? 0 : 1,
EasingType.Linear => linearStep, EasingType.Linear => linearStep,
EasingType.Sine => Sine.EaseOut(linearStep), EasingType.Sine => Sine.EaseOut(linearStep),
EasingType.Quadratic => Power.EaseOut(linearStep, 2), EasingType.Quadratic => Power.EaseOut(linearStep, 2),
@ -526,15 +487,12 @@ namespace Greenshot.Base.Core
_ => throw new NotImplementedException() _ => throw new NotImplementedException()
}; };
public static double EaseInOut(double linearStep, EasingType easeInType, EasingType easeOutType) public static double EaseInOut(double linearStep, EasingType easeInType, EasingType easeOutType) => linearStep < 0.5 ? EaseInOut(linearStep, easeInType) : EaseInOut(linearStep, easeOutType);
{
return linearStep < 0.5 ? EaseInOut(linearStep, easeInType) : EaseInOut(linearStep, easeOutType);
}
public static double EaseInOut(double linearStep, EasingType type) => public static double EaseInOut(double linearStep, EasingType type) =>
type switch type switch
{ {
EasingType.Step => (linearStep < 0.5 ? 0 : 1), EasingType.Step => linearStep < 0.5 ? 0 : 1,
EasingType.Linear => linearStep, EasingType.Linear => linearStep,
EasingType.Sine => Sine.EaseInOut(linearStep), EasingType.Sine => Sine.EaseInOut(linearStep),
EasingType.Quadratic => Power.EaseInOut(linearStep, 2), EasingType.Quadratic => Power.EaseInOut(linearStep, 2),
@ -546,28 +504,16 @@ namespace Greenshot.Base.Core
private static class Sine private static class Sine
{ {
public static double EaseIn(double s) public static double EaseIn(double s) => Math.Sin((s * (Math.PI / 2)) - (Math.PI / 2)) + 1;
{
return Math.Sin(s * (Math.PI / 2) - (Math.PI / 2)) + 1;
}
public static double EaseOut(double s) public static double EaseOut(double s) => Math.Sin(s * (Math.PI / 2));
{
return Math.Sin(s * (Math.PI / 2));
}
public static double EaseInOut(double s) public static double EaseInOut(double s) => Math.Sin((s * Math.PI) - (Math.PI / 2) + 1) / 2;
{
return Math.Sin(s * Math.PI - (Math.PI / 2) + 1) / 2;
}
} }
private static class Power private static class Power
{ {
public static double EaseIn(double s, int power) public static double EaseIn(double s, int power) => Math.Pow(s, power);
{
return Math.Pow(s, power);
}
public static double EaseOut(double s, int power) public static double EaseOut(double s, int power)
{ {
@ -584,7 +530,7 @@ namespace Greenshot.Base.Core
} }
var sign = power % 2 == 0 ? -1 : 1; 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 public static T FromIntPtr<T>(IntPtr intPtr) where T : struct
{ {
object obj = Marshal.PtrToStructure(intPtr, typeof(T)); object obj = Marshal.PtrToStructure(intPtr, typeof(T));
return (T) obj; return (T)obj;
} }
/// <summary> /// <summary>

View file

@ -35,7 +35,7 @@ namespace Greenshot.Base.Core
{ {
private static readonly ILog Log = LogManager.GetLogger(typeof(Cache<TK, TV>)); private static readonly ILog Log = LogManager.GetLogger(typeof(Cache<TK, TV>));
private readonly IDictionary<TK, TV> _internalCache = new Dictionary<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 int _secondsToExpire = 10;
private readonly CacheObjectExpired _expiredCallback; private readonly CacheObjectExpired _expiredCallback;
@ -52,29 +52,20 @@ namespace Greenshot.Base.Core
/// Initialize the cache /// Initialize the cache
/// </summary> /// </summary>
/// <param name="expiredCallback"></param> /// <param name="expiredCallback"></param>
public Cache(CacheObjectExpired expiredCallback) : this() public Cache(CacheObjectExpired expiredCallback) : this() => _expiredCallback = expiredCallback;
{
_expiredCallback = expiredCallback;
}
/// <summary> /// <summary>
/// Initialize the cache with a expire setting /// Initialize the cache with a expire setting
/// </summary> /// </summary>
/// <param name="secondsToExpire"></param> /// <param name="secondsToExpire"></param>
public Cache(int secondsToExpire) : this() public Cache(int secondsToExpire) : this() => _secondsToExpire = secondsToExpire;
{
_secondsToExpire = secondsToExpire;
}
/// <summary> /// <summary>
/// Initialize the cache with a expire setting /// Initialize the cache with a expire setting
/// </summary> /// </summary>
/// <param name="secondsToExpire"></param> /// <param name="secondsToExpire"></param>
/// <param name="expiredCallback"></param> /// <param name="expiredCallback"></param>
public Cache(int secondsToExpire, CacheObjectExpired expiredCallback) : this(expiredCallback) public Cache(int secondsToExpire, CacheObjectExpired expiredCallback) : this(expiredCallback) => _secondsToExpire = secondsToExpire;
{
_secondsToExpire = secondsToExpire;
}
/// <summary> /// <summary>
/// Enumerable for the values in the cache /// Enumerable for the values in the cache
@ -83,14 +74,11 @@ namespace Greenshot.Base.Core
{ {
get get
{ {
List<TV> elements = new List<TV>(); List<TV> elements = new();
lock (_lockObject) lock (_lockObject)
{ {
foreach (TV element in _internalCache.Values) elements.AddRange(_internalCache.Values);
{
elements.Add(element);
}
} }
foreach (TV element in elements) foreach (TV element in elements)
@ -140,10 +128,7 @@ namespace Greenshot.Base.Core
/// </summary> /// </summary>
/// <param name="key"></param> /// <param name="key"></param>
/// <param name="value"></param> /// <param name="value"></param>
public void Add(TK key, TV value) public void Add(TK key, TV value) => Add(key, value, null);
{
Add(key, value, null);
}
/// <summary> /// <summary>
/// Add a value to the cache /// Add a value to the cache
@ -156,7 +141,7 @@ namespace Greenshot.Base.Core
lock (_lockObject) lock (_lockObject)
{ {
var cachedItem = new CachedItem(key, value, secondsToExpire ?? _secondsToExpire); 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)) if (_internalCache.ContainsKey(cacheKey))
{ {
@ -242,10 +227,7 @@ namespace Greenshot.Base.Core
} }
} }
private void timerEvent_Elapsed(object sender, ElapsedEventArgs e) private void timerEvent_Elapsed(object sender, ElapsedEventArgs e) => ExpireNow();
{
ExpireNow();
}
public TK Key { get; private set; } public TK Key { get; private set; }
public TV Item { get; private set; } public TV Item { get; private set; }

View file

@ -97,10 +97,7 @@ namespace Greenshot.Base.Core
} }
} }
public void NullImage() public void NullImage() => _image = null;
{
_image = null;
}
private Icon _cursor; private Icon _cursor;
@ -113,7 +110,7 @@ namespace Greenshot.Base.Core
set set
{ {
_cursor?.Dispose(); _cursor?.Dispose();
_cursor = (Icon) value.Clone(); _cursor = (Icon)value.Clone();
} }
} }
@ -127,27 +124,15 @@ namespace Greenshot.Base.Core
/// </summary> /// </summary>
public bool CursorVisible { get; set; } public bool CursorVisible { get; set; }
private NativePoint _cursorLocation = NativePoint.Empty;
/// <summary> /// <summary>
/// Get/Set the CursorLocation /// Get/Set the CursorLocation
/// </summary> /// </summary>
public NativePoint CursorLocation public NativePoint CursorLocation { get; set; } = NativePoint.Empty;
{
get => _cursorLocation;
set => _cursorLocation = value;
}
private NativePoint _location = NativePoint.Empty;
/// <summary> /// <summary>
/// Get/set the Location /// Get/set the Location
/// </summary> /// </summary>
public NativePoint Location public NativePoint Location { get; set; } = NativePoint.Empty;
{
get => _location;
set => _location = value;
}
private CaptureDetails _captureDetails; private CaptureDetails _captureDetails;
@ -157,7 +142,7 @@ namespace Greenshot.Base.Core
public ICaptureDetails CaptureDetails public ICaptureDetails CaptureDetails
{ {
get => _captureDetails; get => _captureDetails;
set => _captureDetails = (CaptureDetails) value; set => _captureDetails = (CaptureDetails)value;
} }
/// <summary> /// <summary>
@ -174,10 +159,7 @@ namespace Greenshot.Base.Core
/// Note: the supplied bitmap can be disposed immediately or when constructor is called. /// Note: the supplied bitmap can be disposed immediately or when constructor is called.
/// </summary> /// </summary>
/// <param name="newImage">Image</param> /// <param name="newImage">Image</param>
public Capture(Image newImage) : this() public Capture(Image newImage) : this() => Image = newImage;
{
Image = newImage;
}
/// <summary> /// <summary>
/// Destructor /// Destructor
@ -226,7 +208,7 @@ namespace Greenshot.Base.Core
return false; return false;
} }
_location = cropRectangle.Location; Location = cropRectangle.Location;
// Change mouse location according to the cropRectangle (including screenbounds) offset // Change mouse location according to the cropRectangle (including screenbounds) offset
MoveMouseLocation(-cropRectangle.Location.X, -cropRectangle.Location.Y); MoveMouseLocation(-cropRectangle.Location.X, -cropRectangle.Location.Y);
// Move all the elements // Move all the elements
@ -246,10 +228,7 @@ namespace Greenshot.Base.Core
/// </summary> /// </summary>
/// <param name="x">x coordinates to move the mouse</param> /// <param name="x">x coordinates to move the mouse</param>
/// <param name="y">y coordinates to move the mouse</param> /// <param name="y">y coordinates to move the mouse</param>
public void MoveMouseLocation(int x, int y) public void MoveMouseLocation(int x, int y) => CursorLocation = CursorLocation.Offset(x, y);
{
_cursorLocation = _cursorLocation.Offset(x, y);
}
// TODO: Enable when the elements are usable again. // TODO: Enable when the elements are usable again.
///// <summary> ///// <summary>

View file

@ -23,6 +23,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using Greenshot.Base.Interfaces; using Greenshot.Base.Interfaces;
using Greenshot.Base.Interfaces.Ocr; using Greenshot.Base.Interfaces.Ocr;
using System.Linq;
namespace Greenshot.Base.Core namespace Greenshot.Base.Core
{ {
@ -54,17 +55,7 @@ namespace Greenshot.Base.Core
public Dictionary<string, string> MetaData { get; } = new Dictionary<string, string>(); public Dictionary<string, string> MetaData { get; } = new Dictionary<string, string>();
/// <inheritdoc /> /// <inheritdoc />
public void AddMetaData(string key, string value) public void AddMetaData(string key, string value) => MetaData[key] = value;
{
if (MetaData.ContainsKey(key))
{
MetaData[key] = value;
}
else
{
MetaData.Add(key, value);
}
}
/// <inheritdoc /> /// <inheritdoc />
public CaptureMode CaptureMode { get; set; } public CaptureMode CaptureMode { get; set; }
@ -73,10 +64,7 @@ namespace Greenshot.Base.Core
public List<IDestination> CaptureDestinations { get; set; } = new List<IDestination>(); public List<IDestination> CaptureDestinations { get; set; } = new List<IDestination>();
/// <inheritdoc /> /// <inheritdoc />
public void ClearDestinations() public void ClearDestinations() => CaptureDestinations.Clear();
{
CaptureDestinations.Clear();
}
/// <inheritdoc /> /// <inheritdoc />
public void RemoveDestination(IDestination destination) public void RemoveDestination(IDestination destination)
@ -99,20 +87,16 @@ namespace Greenshot.Base.Core
/// <inheritdoc /> /// <inheritdoc />
public bool HasDestination(string designation) public bool HasDestination(string designation)
{ {
foreach (IDestination destination in CaptureDestinations) foreach (var _ in from IDestination destination in CaptureDestinations
{ where designation.Equals(destination.Designation)
if (designation.Equals(destination.Designation)) select new { })
{ {
return true; return true;
} }
}
return false; return false;
} }
public CaptureDetails() public CaptureDetails() => DateTime = DateTime.Now;
{
DateTime = DateTime.Now;
}
} }
} }

View file

@ -52,7 +52,7 @@ namespace Greenshot.Base.Core
public static class ClipboardHelper public static class ClipboardHelper
{ {
private static readonly ILog Log = LogManager.GetLogger(typeof(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 CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>();
private static readonly string FORMAT_FILECONTENTS = "FileContents"; private static readonly string FORMAT_FILECONTENTS = "FileContents";
private static readonly string FORMAT_HTML = "text/html"; private static readonly string FORMAT_HTML = "text/html";
@ -187,14 +187,9 @@ EndSelection:<<<<<<<4
{ {
string messageText; string messageText;
string clipboardOwner = GetClipboardOwner(); string clipboardOwner = GetClipboardOwner();
if (clipboardOwner != null) messageText = clipboardOwner != null
{ ? Language.GetFormattedString("clipboard_inuse", clipboardOwner)
messageText = Language.GetFormattedString("clipboard_inuse", clipboardOwner); : Language.GetString("clipboard_error");
}
else
{
messageText = Language.GetString("clipboard_error");
}
Log.Error(messageText, clipboardSetException); Log.Error(messageText, clipboardSetException);
} }
@ -221,14 +216,9 @@ EndSelection:<<<<<<<4
{ {
string messageText; string messageText;
string clipboardOwner = GetClipboardOwner(); string clipboardOwner = GetClipboardOwner();
if (clipboardOwner != null) messageText = clipboardOwner != null
{ ? Language.GetFormattedString("clipboard_inuse", clipboardOwner)
messageText = Language.GetFormattedString("clipboard_inuse", clipboardOwner); : Language.GetString("clipboard_error");
}
else
{
messageText = Language.GetString("clipboard_error");
}
Log.Error(messageText, ee); Log.Error(messageText, ee);
} }
@ -254,13 +244,10 @@ EndSelection:<<<<<<<4
/// <returns></returns> /// <returns></returns>
public static bool ContainsText(IDataObject dataObject) public static bool ContainsText(IDataObject dataObject)
{ {
if (dataObject != null) if (dataObject != null && (dataObject.GetDataPresent(DataFormats.Text) || dataObject.GetDataPresent(DataFormats.UnicodeText)))
{
if (dataObject.GetDataPresent(DataFormats.Text) || dataObject.GetDataPresent(DataFormats.UnicodeText))
{ {
return true; return true;
} }
}
return false; return false;
} }
@ -384,7 +371,7 @@ EndSelection:<<<<<<<4
/// </summary> /// </summary>
/// <param name="dataObject">IDataObject</param> /// <param name="dataObject">IDataObject</param>
/// <returns>IEnumerable{(MemoryStream,string)}</returns> /// <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); var fileDescriptors = AvailableFileDescriptors(dataObject);
if (fileDescriptors == null) yield break; if (fileDescriptors == null) yield break;
@ -402,7 +389,7 @@ EndSelection:<<<<<<<4
/// <returns>IEnumerable{FileDescriptor}</returns> /// <returns>IEnumerable{FileDescriptor}</returns>
private static IEnumerable<FileDescriptor> AvailableFileDescriptors(IDataObject dataObject) private static IEnumerable<FileDescriptor> AvailableFileDescriptors(IDataObject dataObject)
{ {
var fileDescriptor = (MemoryStream) dataObject.GetData("FileGroupDescriptorW"); var fileDescriptor = (MemoryStream)dataObject.GetData("FileGroupDescriptorW");
if (fileDescriptor != null) if (fileDescriptor != null)
{ {
try try
@ -487,10 +474,7 @@ EndSelection:<<<<<<<4
/// </summary> /// </summary>
/// <param name="memoryStream"></param> /// <param name="memoryStream"></param>
/// <returns>true if there is a valid stream</returns> /// <returns>true if there is a valid stream</returns>
private static bool IsValidStream(MemoryStream memoryStream) private static bool IsValidStream(MemoryStream memoryStream) => memoryStream?.Length > 0;
{
return memoryStream?.Length > 0;
}
/// <summary> /// <summary>
/// Wrapper for Clipboard.GetImage, Created for Bug #3432313 /// Wrapper for Clipboard.GetImage, Created for Bug #3432313
@ -544,7 +528,6 @@ EndSelection:<<<<<<<4
{ {
continue; continue;
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -569,7 +552,7 @@ EndSelection:<<<<<<<4
} }
Bitmap bitmap = null; 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 try
{ {
if (!fileFormatHandlers.TryLoadFromStream(fileStream, extension, out bitmap)) if (!fileFormatHandlers.TryLoadFromStream(fileStream, extension, out bitmap))
@ -643,7 +626,7 @@ EndSelection:<<<<<<<4
{ {
continue; 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; IEnumerable<IDrawableContainer> drawableContainers;
try try
{ {
@ -677,7 +660,7 @@ EndSelection:<<<<<<<4
// Found a weird bug, where PNG's from Outlook 2010 are clipped // Found a weird bug, where PNG's from Outlook 2010 are clipped
// So I build some special logic to get the best format: // 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 ?? // 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..."); 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) foreach (string currentFormat in retrieveFormats)
{ {
if (formats != null && formats.Contains(currentFormat)) if (formats?.Contains(currentFormat) == true)
{ {
Log.InfoFormat("Found {0}, trying to retrieve.", currentFormat); Log.InfoFormat("Found {0}, trying to retrieve.", currentFormat);
returnImage = GetImageForFormat(currentFormat, dataObject); returnImage = GetImageForFormat(currentFormat, dataObject);
@ -732,7 +715,7 @@ EndSelection:<<<<<<<4
// Found a weird bug, where PNG's from Outlook 2010 are clipped // Found a weird bug, where PNG's from Outlook 2010 are clipped
// So I build some special logic to get the best format: // 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 ?? // 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..."); 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) foreach (string currentFormat in retrieveFormats)
{ {
if (formats != null && formats.Contains(currentFormat)) if (formats?.Contains(currentFormat) == true)
{ {
Log.InfoFormat("Found {0}, trying to retrieve.", currentFormat); Log.InfoFormat("Found {0}, trying to retrieve.", currentFormat);
returnImage = GetDrawableForFormat(currentFormat, dataObject); returnImage = GetDrawableForFormat(currentFormat, dataObject);
@ -782,8 +765,7 @@ EndSelection:<<<<<<<4
/// <returns>Bitmap or null</returns> /// <returns>Bitmap or null</returns>
private static Bitmap GetImageForFormat(string format, IDataObject dataObject) private static Bitmap GetImageForFormat(string format, IDataObject dataObject)
{ {
Bitmap bitmap = null; Bitmap bitmap;
if (format == FORMAT_HTML) if (format == FORMAT_HTML)
{ {
var textObject = ContentAsString(dataObject, FORMAT_HTML, Encoding.UTF8); var textObject = ContentAsString(dataObject, FORMAT_HTML, Encoding.UTF8);
@ -818,11 +800,7 @@ EndSelection:<<<<<<<4
var fileFormatHandlers = SimpleServiceProvider.Current.GetAllInstances<IFileFormatHandler>(); var fileFormatHandlers = SimpleServiceProvider.Current.GetAllInstances<IFileFormatHandler>();
// From here, imageStream is a valid stream // From here, imageStream is a valid stream
if (fileFormatHandlers.TryLoadFromStream(imageStream, format, out bitmap)) return fileFormatHandlers.TryLoadFromStream(imageStream, format, out bitmap) ? bitmap : null;
{
return bitmap;
}
return null;
} }
/// <summary> /// <summary>
@ -835,8 +813,6 @@ EndSelection:<<<<<<<4
/// <returns>IDrawableContainer or null</returns> /// <returns>IDrawableContainer or null</returns>
private static IDrawableContainer GetDrawableForFormat(string format, IDataObject dataObject) private static IDrawableContainer GetDrawableForFormat(string format, IDataObject dataObject)
{ {
IDrawableContainer drawableContainer = null;
if (format == FORMAT_HTML) if (format == FORMAT_HTML)
{ {
var textObject = ContentAsString(dataObject, FORMAT_HTML, Encoding.UTF8); var textObject = ContentAsString(dataObject, FORMAT_HTML, Encoding.UTF8);
@ -852,7 +828,7 @@ EndSelection:<<<<<<<4
var srcAttribute = imgNode.Attributes["src"]; var srcAttribute = imgNode.Attributes["src"];
var imageUrl = srcAttribute.Value; var imageUrl = srcAttribute.Value;
Log.Debug(imageUrl); Log.Debug(imageUrl);
drawableContainer = NetworkHelper.DownloadImageAsDrawableContainer(imageUrl); IDrawableContainer drawableContainer = NetworkHelper.DownloadImageAsDrawableContainer(imageUrl);
if (drawableContainer != null) if (drawableContainer != null)
{ {
return drawableContainer; return drawableContainer;
@ -893,15 +869,7 @@ EndSelection:<<<<<<<4
/// Get Text from the DataObject /// Get Text from the DataObject
/// </summary> /// </summary>
/// <returns>string if there is text on the clipboard</returns> /// <returns>string if there is text on the clipboard</returns>
public static string GetText(IDataObject dataObject) public static string GetText(IDataObject dataObject) => ContainsText(dataObject) ? (string)dataObject.GetData(DataFormats.Text) : null;
{
if (ContainsText(dataObject))
{
return (string) dataObject.GetData(DataFormats.Text);
}
return null;
}
/// <summary> /// <summary>
/// Set text to the clipboard /// Set text to the clipboard
@ -920,12 +888,12 @@ EndSelection:<<<<<<<4
utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${width}", surface.Image.Width.ToString()); utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${width}", surface.Image.Width.ToString());
utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${height}", surface.Image.Height.ToString()); utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${height}", surface.Image.Height.ToString());
utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${file}", filename.Replace("\\", "/")); utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${file}", filename.Replace("\\", "/"));
StringBuilder sb = new StringBuilder(); StringBuilder sb = new();
sb.Append(utf8EncodedHtmlString); sb.Append(utf8EncodedHtmlString);
sb.Replace("<<<<<<<1", (utf8EncodedHtmlString.IndexOf("<HTML>", StringComparison.Ordinal) + "<HTML>".Length).ToString("D8")); 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("<<<<<<<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(); return sb.ToString();
} }
@ -935,13 +903,13 @@ EndSelection:<<<<<<<4
utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${width}", surface.Image.Width.ToString()); utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${width}", surface.Image.Width.ToString());
utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${height}", surface.Image.Height.ToString()); utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${height}", surface.Image.Height.ToString());
utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${format}", "png"); utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${format}", "png");
utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${data}", Convert.ToBase64String(pngStream.GetBuffer(), 0, (int) pngStream.Length)); utf8EncodedHtmlString = utf8EncodedHtmlString.Replace("${data}", Convert.ToBase64String(pngStream.GetBuffer(), 0, (int)pngStream.Length));
StringBuilder sb = new StringBuilder(); StringBuilder sb = new();
sb.Append(utf8EncodedHtmlString); sb.Append(utf8EncodedHtmlString);
sb.Replace("<<<<<<<1", (utf8EncodedHtmlString.IndexOf("<HTML>", StringComparison.Ordinal) + "<HTML>".Length).ToString("D8")); 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("<<<<<<<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(); return sb.ToString();
} }
@ -956,7 +924,7 @@ EndSelection:<<<<<<<4
/// </summary> /// </summary>
public static void SetClipboardData(ISurface surface) public static void SetClipboardData(ISurface surface)
{ {
DataObject dataObject = new DataObject(); DataObject dataObject = new();
// This will work for Office and most other applications // This will work for Office and most other applications
//ido.SetData(DataFormats.Bitmap, true, image); //ido.SetData(DataFormats.Bitmap, true, image);
@ -968,7 +936,7 @@ EndSelection:<<<<<<<4
bool disposeImage = false; bool disposeImage = false;
try 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 // Create the image which is going to be saved so we don't create it multiple times
disposeImage = ImageIO.CreateImageFromSurface(surface, outputSettings, out imageToSave); disposeImage = ImageIO.CreateImageFromSurface(surface, outputSettings, out imageToSave);
try try
@ -978,7 +946,7 @@ EndSelection:<<<<<<<4
{ {
pngStream = new MemoryStream(); pngStream = new MemoryStream();
// PNG works for e.g. Powerpoint // 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); ImageIO.SaveToStream(imageToSave, null, pngStream, pngOutputSettings);
pngStream.Seek(0, SeekOrigin.Begin); pngStream.Seek(0, SeekOrigin.Begin);
// Set the PNG stream // Set the PNG stream
@ -1034,7 +1002,7 @@ EndSelection:<<<<<<<4
// As we have specified BI_COMPRESSION.BI_BITFIELDS, the BitfieldColorMask needs to be added // As we have specified BI_COMPRESSION.BI_BITFIELDS, the BitfieldColorMask needs to be added
// This also makes sure the default values are set // This also makes sure the default values are set
BitfieldColorMask colorMask = new BitfieldColorMask(); BitfieldColorMask colorMask = new();
// Create the byte[] from the struct // Create the byte[] from the struct
byte[] colorMaskBytes = BinaryStructHelper.ToByteArray(colorMask); byte[] colorMaskBytes = BinaryStructHelper.ToByteArray(colorMask);
Array.Reverse(colorMaskBytes); Array.Reverse(colorMaskBytes);
@ -1042,7 +1010,7 @@ EndSelection:<<<<<<<4
dibV5Stream.Write(colorMaskBytes, 0, colorMaskBytes.Length); dibV5Stream.Write(colorMaskBytes, 0, colorMaskBytes.Length);
// Create the raw bytes for the pixels only // Create the raw bytes for the pixels only
byte[] bitmapBytes = BitmapToByteArray((Bitmap) imageToSave); byte[] bitmapBytes = BitmapToByteArray((Bitmap)imageToSave);
// Write to the stream // Write to the stream
dibV5Stream.Write(bitmapBytes, 0, bitmapBytes.Length); dibV5Stream.Write(bitmapBytes, 0, bitmapBytes.Length);
@ -1065,9 +1033,9 @@ EndSelection:<<<<<<<4
else if (CoreConfig.ClipboardFormats.Contains(ClipboardFormat.HTMLDATAURL)) else if (CoreConfig.ClipboardFormats.Contains(ClipboardFormat.HTMLDATAURL))
{ {
string html; 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 // Do not allow to reduce the colors, some applications dislike 256 color images
// reported with bug #3594681 // reported with bug #3594681
@ -1136,7 +1104,7 @@ EndSelection:<<<<<<<4
for (int i = 0; i < bitmap.Height; i++) 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); Marshal.Copy(pointer, rgbValues, absStride * (bitmap.Height - i - 1), absStride);
} }
@ -1190,23 +1158,17 @@ EndSelection:<<<<<<<4
/// <param name="dataObject">IDataObject</param> /// <param name="dataObject">IDataObject</param>
/// <param name="format">string with format</param> /// <param name="format">string with format</param>
/// <returns>true if one the format is found</returns> /// <returns>true if one the format is found</returns>
public static bool ContainsFormat(IDataObject dataObject, string format) public static bool ContainsFormat(IDataObject dataObject, string format) => ContainsFormat(dataObject, new[]
{
return ContainsFormat(dataObject, new[]
{ {
format format
}); });
}
/// <summary> /// <summary>
/// Check if there is currently something on the clipboard which has one of the supplied formats /// Check if there is currently something on the clipboard which has one of the supplied formats
/// </summary> /// </summary>
/// <param name="formats">string[] with formats</param> /// <param name="formats">string[] with formats</param>
/// <returns>true if one of the formats was found</returns> /// <returns>true if one of the formats was found</returns>
public static bool ContainsFormat(string[] formats) public static bool ContainsFormat(string[] formats) => ContainsFormat(GetDataObject(), formats);
{
return ContainsFormat(GetDataObject(), formats);
}
/// <summary> /// <summary>
/// Check if there is currently something on the clipboard which has one of the supplied formats /// Check if there is currently something on the clipboard which has one of the supplied formats
@ -1223,14 +1185,13 @@ EndSelection:<<<<<<<4
return false; return false;
} }
foreach (string format in formats) foreach (var _ in from string format in formats
{ where currentFormats.Contains(format)
if (currentFormats.Contains(format)) select new { })
{ {
formatFound = true; formatFound = true;
break; break;
} }
}
return formatFound; return formatFound;
} }
@ -1241,15 +1202,7 @@ EndSelection:<<<<<<<4
/// <param name="dataObj">IDataObject</param> /// <param name="dataObj">IDataObject</param>
/// <param name="type">Type to get</param> /// <param name="type">Type to get</param>
/// <returns>object from IDataObject</returns> /// <returns>object from IDataObject</returns>
public static object GetFromDataObject(IDataObject dataObj, Type type) public static object GetFromDataObject(IDataObject dataObj, Type type) => type != null ? GetFromDataObject(dataObj, type.FullName) : null;
{
if (type != null)
{
return GetFromDataObject(dataObj, type.FullName);
}
return null;
}
/// <summary> /// <summary>
/// Get ImageFilenames from the IDataObject /// Get ImageFilenames from the IDataObject
@ -1267,7 +1220,6 @@ EndSelection:<<<<<<<4
.Where(filename => !string.IsNullOrEmpty(filename)) .Where(filename => !string.IsNullOrEmpty(filename))
.Where(Path.HasExtension) .Where(Path.HasExtension)
.Where(filename => supportedExtensions.Contains(Path.GetExtension(filename))); .Where(filename => supportedExtensions.Contains(Path.GetExtension(filename)));
} }
/// <summary> /// <summary>

View file

@ -334,7 +334,7 @@ namespace Greenshot.Base.Core
DefaultValue = "16,16")] DefaultValue = "16,16")]
public NativeSize IconSize public NativeSize IconSize
{ {
get { return _iconSize; } get => _iconSize;
set set
{ {
Size newSize = value; Size newSize = value;
@ -349,7 +349,7 @@ namespace Greenshot.Base.Core
newSize.Width = 256; newSize.Width = 256;
} }
newSize.Width = (newSize.Width / 16) * 16; newSize.Width = newSize.Width / 16 * 16;
if (newSize.Height < 16) if (newSize.Height < 16)
{ {
newSize.Height = 16; newSize.Height = 16;
@ -359,13 +359,13 @@ namespace Greenshot.Base.Core
newSize.Height = 256; newSize.Height = 256;
} }
newSize.Height = (newSize.Height / 16) * 16; newSize.Height = newSize.Height / 16 * 16;
} }
if (_iconSize != newSize) if (_iconSize != newSize)
{ {
_iconSize = value; _iconSize = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IconSize")); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IconSize)));
} }
} }
} }
@ -383,10 +383,7 @@ namespace Greenshot.Base.Core
/// </summary> /// </summary>
/// <param name="experimentalFeature"></param> /// <param name="experimentalFeature"></param>
/// <returns></returns> /// <returns></returns>
public bool IsExperimentalFeatureEnabled(string experimentalFeature) public bool IsExperimentalFeatureEnabled(string experimentalFeature) => ExperimentalFeatures?.Contains(experimentalFeature) == true;
{
return ExperimentalFeatures != null && ExperimentalFeatures.Contains(experimentalFeature);
}
private string CreateOutputFilePath() private string CreateOutputFilePath()
{ {
@ -456,21 +453,15 @@ namespace Greenshot.Base.Core
public override string PreCheckValue(string propertyName, string propertyValue) public override string PreCheckValue(string propertyName, string propertyValue)
{ {
// Changed the separator, now we need to correct this // Changed the separator, now we need to correct this
if ("Destinations".Equals(propertyName)) if ("Destinations".Equals(propertyName) && propertyValue != null)
{
if (propertyValue != null)
{ {
return propertyValue.Replace('|', ','); return propertyValue.Replace('|', ',');
} }
}
if ("OutputFilePath".Equals(propertyName)) if ("OutputFilePath".Equals(propertyName) && string.IsNullOrEmpty(propertyValue))
{
if (string.IsNullOrEmpty(propertyValue))
{ {
return null; return null;
} }
}
return base.PreCheckValue(propertyName, propertyValue); return base.PreCheckValue(propertyName, propertyValue);
} }
@ -528,13 +519,10 @@ namespace Greenshot.Base.Core
} }
// Enable OneNote if upgrading from 1.1 // Enable OneNote if upgrading from 1.1
if (ExcludeDestinations != null && ExcludeDestinations.Contains("OneNote")) if (ExcludeDestinations?.Contains("OneNote") == true && LastSaveWithVersion?.StartsWith("1.1") == true)
{
if (LastSaveWithVersion != null && LastSaveWithVersion.StartsWith("1.1"))
{ {
ExcludeDestinations.Remove("OneNote"); ExcludeDestinations.Remove("OneNote");
} }
}
if (OutputDestinations == null) if (OutputDestinations == null)
{ {
@ -568,15 +556,12 @@ namespace Greenshot.Base.Core
if (NoGDICaptureForProduct != null) if (NoGDICaptureForProduct != null)
{ {
// Fix error in configuration // Fix error in configuration
if (NoGDICaptureForProduct.Count >= 2) if (NoGDICaptureForProduct.Count >= 2 && "intellij".Equals(NoGDICaptureForProduct[0]) && "idea".Equals(NoGDICaptureForProduct[1]))
{
if ("intellij".Equals(NoGDICaptureForProduct[0]) && "idea".Equals(NoGDICaptureForProduct[1]))
{ {
NoGDICaptureForProduct.RemoveRange(0, 2); NoGDICaptureForProduct.RemoveRange(0, 2);
NoGDICaptureForProduct.Add("Intellij Idea"); NoGDICaptureForProduct.Add("Intellij Idea");
IsDirty = true; IsDirty = true;
} }
}
for (int i = 0; i < NoGDICaptureForProduct.Count; i++) for (int i = 0; i < NoGDICaptureForProduct.Count; i++)
{ {
@ -587,15 +572,12 @@ namespace Greenshot.Base.Core
if (NoDWMCaptureForProduct != null) if (NoDWMCaptureForProduct != null)
{ {
// Fix error in configuration // Fix error in configuration
if (NoDWMCaptureForProduct.Count >= 3) if (NoDWMCaptureForProduct.Count >= 3 && "citrix".Equals(NoDWMCaptureForProduct[0]) && "ica".Equals(NoDWMCaptureForProduct[1]) && "client".Equals(NoDWMCaptureForProduct[2]))
{
if ("citrix".Equals(NoDWMCaptureForProduct[0]) && "ica".Equals(NoDWMCaptureForProduct[1]) && "client".Equals(NoDWMCaptureForProduct[2]))
{ {
NoDWMCaptureForProduct.RemoveRange(0, 3); NoDWMCaptureForProduct.RemoveRange(0, 3);
NoDWMCaptureForProduct.Add("Citrix ICA Client"); NoDWMCaptureForProduct.Add("Citrix ICA Client");
IsDirty = true; IsDirty = true;
} }
}
for (int i = 0; i < NoDWMCaptureForProduct.Count; i++) 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> /// <summary>Gets or sets the name for the credentials.</summary>
public string Name public string Name
{ {
get { return _name; } get => _name;
set set
{ {
if (value?.Length > CredUi.MAX_USERNAME_LENGTH) 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> /// <summary>Gets or sets the password for the credentials.</summary>
public string Password public string Password
{ {
get { return _password; } get => _password;
set set
{ {
if (value?.Length > CredUi.MAX_PASSWORD_LENGTH) 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> /// <summary>Gets or sets the name of the target for the credentials, typically a server name.</summary>
public string Target public string Target
{ {
get { return _target; } get => _target;
set set
{ {
if (value == null) 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> /// <remarks>A null value will cause a system default caption to be used.</remarks>
public string Caption public string Caption
{ {
get { return _caption; } get => _caption;
set set
{ {
if (value?.Length > CredUi.MAX_CAPTION_LENGTH) 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> /// <remarks>A null value will cause a system default message to be used.</remarks>
public string Message public string Message
{ {
get { return _message; } get => _message;
set set
{ {
if (value?.Length > CredUi.MAX_MESSAGE_LENGTH) 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> /// <remarks>A null value will cause a system default image to be used.</remarks>
public Image Banner public Image Banner
{ {
get { return _banner; } get => _banner;
set set
{ {
if (value != null) if (value != null)
@ -275,10 +275,7 @@ namespace Greenshot.Base.Core
/// <summary>Shows the credentials dialog with the specified name.</summary> /// <summary>Shows the credentials dialog with the specified name.</summary>
/// <param name="name">The name for the credentials.</param> /// <param name="name">The name for the credentials.</param>
/// <returns>Returns a DialogResult indicating the user action.</returns> /// <returns>Returns a DialogResult indicating the user action.</returns>
public DialogResult Show(string name) public DialogResult Show(string name) => Show(null, name, Password, SaveChecked);
{
return Show(null, name, Password, SaveChecked);
}
/// <summary>Shows the credentials dialog with the specified owner, name, password and save checkbox status.</summary> /// <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> /// <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) private DialogResult ShowDialog(IWin32Window owner)
{ {
// set the api call parameters // set the api call parameters
StringBuilder name = new StringBuilder(CredUi.MAX_USERNAME_LENGTH); StringBuilder name = new(CredUi.MAX_USERNAME_LENGTH);
name.Append(Name); name.Append(Name);
StringBuilder password = new StringBuilder(CredUi.MAX_PASSWORD_LENGTH); StringBuilder password = new(CredUi.MAX_PASSWORD_LENGTH);
password.Append(Password); password.Append(Password);
int saveChecked = Convert.ToInt32(SaveChecked); 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> /// <param name="owner">The System.Windows.Forms.IWin32Window the dialog will display in front of.</param>
private CredUi.INFO GetInfo(IWin32Window owner) private CredUi.INFO GetInfo(IWin32Window owner)
{ {
CredUi.INFO info = new CredUi.INFO(); CredUi.INFO info = new();
if (owner != null) info.hWndParent = owner.Handle; if (owner != null) info.hWndParent = owner.Handle;
info.pszCaptionText = Caption; info.pszCaptionText = Caption;
info.pszMessageText = Message; info.pszMessageText = Message;

View file

@ -37,13 +37,8 @@ namespace Greenshot.Base.Core
/// Method to get all the destinations from the plugins /// Method to get all the destinations from the plugins
/// </summary> /// </summary>
/// <returns>List of IDestination</returns> /// <returns>List of IDestination</returns>
public static IEnumerable<IDestination> GetAllDestinations() 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);
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);
}
/// <summary> /// <summary>
/// Get a destination by a designation /// Get a destination by a designation
@ -57,13 +52,12 @@ namespace Greenshot.Base.Core
return null; return null;
} }
foreach (IDestination destination in GetAllDestinations()) foreach (var destination in from IDestination destination in GetAllDestinations()
{ where designation.Equals(destination.Designation)
if (designation.Equals(destination.Designation)) select destination)
{ {
return destination; return destination;
} }
}
return null; return null;
} }
@ -75,10 +69,7 @@ namespace Greenshot.Base.Core
/// <param name="designation">WellKnownDestinations</param> /// <param name="designation">WellKnownDestinations</param>
/// <param name="surface">ISurface</param> /// <param name="surface">ISurface</param>
/// <param name="captureDetails">ICaptureDetails</param> /// <param name="captureDetails">ICaptureDetails</param>
public static ExportInformation ExportCapture(bool manuallyInitiated, WellKnownDestinations designation, ISurface surface, ICaptureDetails captureDetails) public static ExportInformation ExportCapture(bool manuallyInitiated, WellKnownDestinations designation, ISurface surface, ICaptureDetails captureDetails) => ExportCapture(manuallyInitiated, designation.ToString(), surface, captureDetails);
{
return ExportCapture(manuallyInitiated, designation.ToString(), surface, captureDetails);
}
/// <summary> /// <summary>
/// A simple helper method which will call ExportCapture for the destination with the specified designation /// 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) public static ExportInformation ExportCapture(bool manuallyInitiated, string designation, ISurface surface, ICaptureDetails captureDetails)
{ {
IDestination destination = GetDestination(designation); IDestination destination = GetDestination(designation);
if (destination != null && destination.IsActive) return destination?.IsActive == true ? destination.ExportCapture(manuallyInitiated, surface, captureDetails) : null;
{
return destination.ExportCapture(manuallyInitiated, surface, captureDetails);
}
return null;
} }
} }
} }

View file

@ -28,10 +28,7 @@ namespace Greenshot.Base.Core
{ {
public string Value { get; } public string Value { get; }
public DisplayKeyAttribute(string v) public DisplayKeyAttribute(string v) => Value = v;
{
Value = v;
}
public DisplayKeyAttribute() public DisplayKeyAttribute()
{ {

View file

@ -12,7 +12,7 @@ namespace Greenshot.Base.Core
public class EffectConverter : TypeConverter public class EffectConverter : TypeConverter
{ {
// Fix to prevent BUG-1753 // Fix to prevent BUG-1753
private readonly NumberFormatInfo _numberFormatInfo = new NumberFormatInfo(); private readonly NumberFormatInfo _numberFormatInfo = new();
public EffectConverter() public EffectConverter()
{ {
@ -20,15 +20,7 @@ namespace Greenshot.Base.Core
_numberFormatInfo.NumberGroupSeparator = ","; _numberFormatInfo.NumberGroupSeparator = ",";
} }
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) => sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{ {
@ -42,12 +34,7 @@ namespace Greenshot.Base.Core
return true; return true;
} }
if (destinationType == typeof(TornEdgeEffect)) return destinationType == typeof(TornEdgeEffect) || base.CanConvertTo(context, destinationType);
{
return true;
}
return base.CanConvertTo(context, destinationType);
} }
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
@ -55,7 +42,7 @@ namespace Greenshot.Base.Core
// to string // to string
if (destinationType == typeof(string)) if (destinationType == typeof(string))
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new();
if (value.GetType() == typeof(DropShadowEffect)) if (value.GetType() == typeof(DropShadowEffect))
{ {
DropShadowEffect effect = value as DropShadowEffect; DropShadowEffect effect = value as DropShadowEffect;
@ -63,7 +50,7 @@ namespace Greenshot.Base.Core
return sb.ToString(); return sb.ToString();
} }
if (value.GetType() == typeof(TornEdgeEffect)) if (value is TornEdgeEffect)
{ {
TornEdgeEffect effect = value as TornEdgeEffect; TornEdgeEffect effect = value as TornEdgeEffect;
RetrieveDropShadowEffectValues(effect, sb); RetrieveDropShadowEffectValues(effect, sb);
@ -79,14 +66,14 @@ namespace Greenshot.Base.Core
string settings = value as string; string settings = value as string;
if (destinationType == typeof(DropShadowEffect)) if (destinationType == typeof(DropShadowEffect))
{ {
DropShadowEffect effect = new DropShadowEffect(); DropShadowEffect effect = new();
ApplyDropShadowEffectValues(settings, effect); ApplyDropShadowEffectValues(settings, effect);
return effect; return effect;
} }
if (destinationType == typeof(TornEdgeEffect)) if (destinationType == typeof(TornEdgeEffect))
{ {
TornEdgeEffect effect = new TornEdgeEffect(); TornEdgeEffect effect = new();
ApplyDropShadowEffectValues(settings, effect); ApplyDropShadowEffectValues(settings, effect);
ApplyTornEdgeEffectValues(settings, effect); ApplyTornEdgeEffectValues(settings, effect);
return effect; return effect;
@ -100,12 +87,9 @@ namespace Greenshot.Base.Core
{ {
if (value is string settings) if (value is string settings)
{ {
if (settings.Contains("ToothHeight")) return settings.Contains("ToothHeight")
{ ? ConvertTo(context, culture, settings, typeof(TornEdgeEffect))
return ConvertTo(context, culture, settings, typeof(TornEdgeEffect)); : ConvertTo(context, culture, settings, typeof(DropShadowEffect));
}
return ConvertTo(context, culture, settings, typeof(DropShadowEffect));
} }
return base.ConvertFrom(context, culture, value); return base.ConvertFrom(context, culture, value);
@ -121,13 +105,10 @@ namespace Greenshot.Base.Core
{ {
case "Darkness": case "Darkness":
// Fix to prevent BUG-1753 // Fix to prevent BUG-1753
if (pair[1] != null && float.TryParse(pair[1], NumberStyles.Float, _numberFormatInfo, out var darkness)) if (pair[1] != null && float.TryParse(pair[1], NumberStyles.Float, _numberFormatInfo, out var darkness) && darkness <= 1.0)
{
if (darkness <= 1.0)
{ {
effect.Darkness = darkness; effect.Darkness = darkness;
} }
}
break; break;
case "ShadowSize": case "ShadowSize":
@ -138,7 +119,7 @@ namespace Greenshot.Base.Core
break; break;
case "ShadowOffset": case "ShadowOffset":
NativePoint shadowOffset = new NativePoint(); NativePoint shadowOffset = new();
string[] coordinates = pair[1].Split(','); string[] coordinates = pair[1].Split(',');
if (int.TryParse(coordinates[0], out var shadowOffsetX)) 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 // 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, sb.AppendFormat("Darkness:{0}|ShadowSize:{1}|ShadowOffset:{2},{3}", effect.Darkness.ToString("F2", _numberFormatInfo), effect.ShadowSize, effect.ShadowOffset.X,
effect.ShadowOffset.Y); effect.ShadowOffset.Y);
}
private void RetrieveTornEdgeEffectValues(TornEdgeEffect effect, StringBuilder sb) 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,
{
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]); 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. // 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) public static string GetGreenshotVersion(bool shortVersion = false)
{ {
@ -99,13 +97,13 @@ namespace Greenshot.Base.Core
public static string EnvironmentToString(bool newline) public static string EnvironmentToString(bool newline)
{ {
StringBuilder environment = new(); StringBuilder environment = new();
environment.Append("Software version: " + GetGreenshotVersion()); environment.Append("Software version: ").Append(GetGreenshotVersion());
if (IniConfig.IsPortable) if (IniConfig.IsPortable)
{ {
environment.Append(" Portable"); environment.Append(" Portable");
} }
environment.Append(" (" + OsInfo.Bits + " bit)"); environment.Append(" (").Append(OsInfo.Bits).Append(" bit)");
if (newline) if (newline)
{ {
@ -116,7 +114,7 @@ namespace Greenshot.Base.Core
environment.Append(", "); environment.Append(", ");
} }
environment.Append(".NET runtime version: " + Environment.Version); environment.Append(".NET runtime version: ").Append(Environment.Version);
if (IsNet45OrNewer()) if (IsNet45OrNewer())
{ {
environment.Append("+"); environment.Append("+");
@ -131,7 +129,7 @@ namespace Greenshot.Base.Core
environment.Append(", "); 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) if (IsWindows)
{ {
@ -144,19 +142,19 @@ namespace Greenshot.Base.Core
environment.Append(", "); environment.Append(", ");
} }
environment.Append($"OS: {OsInfo.Name}"); environment.Append("OS: ").Append(OsInfo.Name);
if (!string.IsNullOrEmpty(OsInfo.Edition)) if (!string.IsNullOrEmpty(OsInfo.Edition))
{ {
environment.Append($" {OsInfo.Edition}"); environment.Append(' ').Append(OsInfo.Edition);
} }
if (!string.IsNullOrEmpty(OsInfo.ServicePack)) if (!string.IsNullOrEmpty(OsInfo.ServicePack))
{ {
environment.Append($" {OsInfo.ServicePack}"); environment.Append(' ').Append(OsInfo.ServicePack);
} }
environment.Append($" x{OsInfo.Bits}"); environment.Append(" x").Append(OsInfo.Bits);
environment.Append($" {OsInfo.VersionString}"); environment.Append(' ').Append(OsInfo.VersionString);
if (newline) if (newline)
{ {
environment.AppendLine(); environment.AppendLine();
@ -214,8 +212,8 @@ namespace Greenshot.Base.Core
StringBuilder report = new(); StringBuilder report = new();
report.AppendLine("Exception: " + ex.GetType()); report.Append("Exception: ").Append(ex.GetType()).AppendLine();
report.AppendLine("Message: " + ex.Message); report.Append("Message: ").AppendLine(ex.Message);
if (ex.Data.Count > 0) if (ex.Data.Count > 0)
{ {
report.AppendLine(); report.AppendLine();
@ -225,7 +223,7 @@ namespace Greenshot.Base.Core
object data = ex.Data[key]; object data = ex.Data[key];
if (data != null) 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) if (ex is ExternalException externalException)
{ {
// e.g. COMException // 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); report.AppendLine().AppendLine("Stack:").AppendLine(ex.StackTrace);
@ -304,8 +302,9 @@ namespace Greenshot.Base.Core
var productType = osVersionInfo.ProductType; var productType = osVersionInfo.ProductType;
var suiteMask = osVersionInfo.SuiteMask; var suiteMask = osVersionInfo.SuiteMask;
if (majorVersion == 4) switch (majorVersion)
{ {
case 4:
if (productType == WindowsProductTypes.VER_NT_WORKSTATION) if (productType == WindowsProductTypes.VER_NT_WORKSTATION)
{ {
// Windows NT 4.0 Workstation // Windows NT 4.0 Workstation
@ -315,10 +314,8 @@ namespace Greenshot.Base.Core
{ {
edition = (suiteMask & WindowsSuites.Enterprise) != 0 ? "Enterprise Server" : "Standard Server"; edition = (suiteMask & WindowsSuites.Enterprise) != 0 ? "Enterprise Server" : "Standard Server";
} }
} break;
case 5:
else if (majorVersion == 5)
{
if (productType == WindowsProductTypes.VER_NT_WORKSTATION) if (productType == WindowsProductTypes.VER_NT_WORKSTATION)
{ {
if ((suiteMask & WindowsSuites.Personal) != 0) if ((suiteMask & WindowsSuites.Personal) != 0)
@ -334,8 +331,9 @@ namespace Greenshot.Base.Core
} }
else if (productType == WindowsProductTypes.VER_NT_SERVER) else if (productType == WindowsProductTypes.VER_NT_SERVER)
{ {
if (minorVersion == 0) switch (minorVersion)
{ {
case 0:
if ((suiteMask & WindowsSuites.DataCenter) != 0) if ((suiteMask & WindowsSuites.DataCenter) != 0)
{ {
// Windows 2000 Datacenter Server // Windows 2000 Datacenter Server
@ -351,9 +349,8 @@ namespace Greenshot.Base.Core
// Windows 2000 Server // Windows 2000 Server
edition = "Server"; edition = "Server";
} }
} break;
else default:
{
if ((suiteMask & WindowsSuites.DataCenter) != 0) if ((suiteMask & WindowsSuites.DataCenter) != 0)
{ {
// Windows Server 2003 Datacenter Edition // Windows Server 2003 Datacenter Edition
@ -374,16 +371,13 @@ namespace Greenshot.Base.Core
// Windows Server 2003 Standard Edition // Windows Server 2003 Standard Edition
edition = "Standard"; edition = "Standard";
} }
break;
} }
} }
} break;
case 6 when Kernel32Api.GetProductInfo(majorVersion, minorVersion, osVersionInfo.ServicePackMajor, osVersionInfo.ServicePackMinor, out var windowsProduct):
else if (majorVersion == 6)
{
if (Kernel32Api.GetProductInfo(majorVersion, minorVersion, osVersionInfo.ServicePackMajor, osVersionInfo.ServicePackMinor, out var windowsProduct))
{
edition = windowsProduct.GetEnumDescription(); edition = windowsProduct.GetEnumDescription();
} break;
} }
} }
@ -425,14 +419,7 @@ namespace Greenshot.Base.Core
switch (minorVersion) switch (minorVersion)
{ {
case 0: case 0:
if (csdVersion == "B" || csdVersion == "C") name = csdVersion == "B" || csdVersion == "C" ? "Windows 95 OSR2" : "Windows 95";
{
name = "Windows 95 OSR2";
}
else
{
name = "Windows 95";
}
break; break;
case 10: case 10:
@ -562,13 +549,9 @@ namespace Greenshot.Base.Core
return $"build {Environment.OSVersion.Version.Build}"; return $"build {Environment.OSVersion.Version.Build}";
} }
if (Environment.OSVersion.Version.Revision != 0) 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}"
return : $"{Environment.OSVersion.Version.Major}.{Environment.OSVersion.Version.Minor} build {Environment.OSVersion.Version.Build}";
$"{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}";
} }
} }
} }

View file

@ -28,14 +28,12 @@ namespace Greenshot.Base.Core
private long lastCheck; private long lastCheck;
private readonly long waitTime; private readonly long waitTime;
public EventDelay(long ticks) public EventDelay(long ticks) => waitTime = ticks;
{ private readonly object _lockObject = new(); // Prevent RCS1059
waitTime = ticks;
}
public bool Check() public bool Check()
{ {
lock (this) lock (_lockObject)
{ {
long now = DateTime.Now.Ticks; long now = DateTime.Now.Ticks;
bool isPassed = now - lastCheck > waitTime; bool isPassed = now - lastCheck > waitTime;

View file

@ -290,15 +290,9 @@ namespace Greenshot.Base.Core
protected bool BitsLocked; protected bool BitsLocked;
protected byte* Pointer; protected byte* Pointer;
public static IFastBitmap Create(Bitmap source) public static IFastBitmap Create(Bitmap source) => Create(source, NativeRect.Empty);
{
return Create(source, NativeRect.Empty);
}
public void SetResolution(float horizontal, float vertical) public void SetResolution(float horizontal, float vertical) => Bitmap.SetResolution(horizontal, vertical);
{
Bitmap.SetResolution(horizontal, vertical);
}
/// <summary> /// <summary>
/// Factory for creating a FastBitmap depending on the pixelformat of the source /// 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="source">Bitmap to clone</param>
/// <param name="pixelFormat">new PixelFormat</param> /// <param name="pixelFormat">new PixelFormat</param>
/// <returns>IFastBitmap</returns> /// <returns>IFastBitmap</returns>
public static IFastBitmap CreateCloneOf(Image source, PixelFormat pixelFormat) public static IFastBitmap CreateCloneOf(Image source, PixelFormat pixelFormat) => CreateCloneOf(source, pixelFormat, NativeRect.Empty);
{
return CreateCloneOf(source, pixelFormat, NativeRect.Empty);
}
/// <summary> /// <summary>
/// Factory for creating a FastBitmap as a destination for the source /// 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="source">Bitmap to clone</param>
/// <param name="area">Area of the bitmap to access, can be NativeRect.Empty for the whole</param> /// <param name="area">Area of the bitmap to access, can be NativeRect.Empty for the whole</param>
/// <returns>IFastBitmap</returns> /// <returns>IFastBitmap</returns>
public static IFastBitmap CreateCloneOf(Image source, NativeRect area) public static IFastBitmap CreateCloneOf(Image source, NativeRect area) => CreateCloneOf(source, PixelFormat.DontCare, area);
{
return CreateCloneOf(source, PixelFormat.DontCare, area);
}
/// <summary> /// <summary>
/// Factory for creating a FastBitmap as a destination for the source /// Factory for creating a FastBitmap as a destination for the source
@ -408,50 +396,17 @@ namespace Greenshot.Base.Core
/// <summary> /// <summary>
/// Return the size of the image /// Return the size of the image
/// </summary> /// </summary>
public NativeSize Size public NativeSize Size => Area == NativeRect.Empty ? (NativeSize)Bitmap.Size : Area.Size;
{
get
{
if (Area == NativeRect.Empty)
{
return Bitmap.Size;
}
return Area.Size;
}
}
/// <summary> /// <summary>
/// Return the width of the image /// Return the width of the image
/// </summary> /// </summary>
public int Width public int Width => Area == NativeRect.Empty ? Bitmap.Width : Area.Width;
{
get
{
if (Area == NativeRect.Empty)
{
return Bitmap.Width;
}
return Area.Width;
}
}
/// <summary> /// <summary>
/// Return the height of the image /// Return the height of the image
/// </summary> /// </summary>
public int Height public int Height => Area == NativeRect.Empty ? Bitmap.Height : Area.Height;
{
get
{
if (Area == NativeRect.Empty)
{
return Bitmap.Height;
}
return Area.Height;
}
}
private int _left; private int _left;
@ -460,8 +415,8 @@ namespace Greenshot.Base.Core
/// </summary> /// </summary>
public int Left public int Left
{ {
get { return 0; } get => 0;
set { _left = value; } set => _left = value;
} }
/// <summary> /// <summary>
@ -469,8 +424,8 @@ namespace Greenshot.Base.Core
/// </summary> /// </summary>
int IFastBitmapWithOffset.Left int IFastBitmapWithOffset.Left
{ {
get { return _left; } get => _left;
set { _left = value; } set => _left = value;
} }
private int _top; private int _top;
@ -480,8 +435,8 @@ namespace Greenshot.Base.Core
/// </summary> /// </summary>
public int Top public int Top
{ {
get { return 0; } get => 0;
set { _top = value; } set => _top = value;
} }
/// <summary> /// <summary>
@ -489,8 +444,8 @@ namespace Greenshot.Base.Core
/// </summary> /// </summary>
int IFastBitmapWithOffset.Top int IFastBitmapWithOffset.Top
{ {
get { return _top; } get => _top;
set { _top = value; } set => _top = value;
} }
/// <summary> /// <summary>
@ -547,13 +502,10 @@ namespace Greenshot.Base.Core
protected virtual void Dispose(bool disposing) protected virtual void Dispose(bool disposing)
{ {
Unlock(); Unlock();
if (disposing) if (disposing && Bitmap != null && NeedsDispose)
{
if (Bitmap != null && NeedsDispose)
{ {
Bitmap.Dispose(); Bitmap.Dispose();
} }
}
Bitmap = null; Bitmap = null;
BmData = null; BmData = null;
@ -574,7 +526,7 @@ namespace Greenshot.Base.Core
BitsLocked = true; BitsLocked = true;
IntPtr scan0 = BmData.Scan0; IntPtr scan0 = BmData.Scan0;
Pointer = (byte*) (void*) scan0; Pointer = (byte*)(void*)scan0;
Stride = BmData.Stride; Stride = BmData.Stride;
} }
@ -595,10 +547,7 @@ namespace Greenshot.Base.Core
/// </summary> /// </summary>
/// <param name="graphics"></param> /// <param name="graphics"></param>
/// <param name="destination"></param> /// <param name="destination"></param>
public void DrawTo(Graphics graphics, NativePoint destination) public void DrawTo(Graphics graphics, NativePoint destination) => DrawTo(graphics, new NativeRect(destination, Area.Size));
{
DrawTo(graphics, new NativeRect(destination, Area.Size));
}
/// <summary> /// <summary>
/// Draw the stored Bitmap on the Destination bitmap with the specified rectangle /// 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="x"></param>
/// <param name="y"></param> /// <param name="y"></param>
/// <returns>true if x & y are inside the FastBitmap</returns> /// <returns>true if x & y are inside the FastBitmap</returns>
public bool Contains(int x, int y) public bool Contains(int x, int y) => Area.Contains(x - Left, y - Top);
{
return Area.Contains(x - Left, y - Top);
}
public abstract Color GetColorAt(int x, int y); public abstract Color GetColorAt(int x, int y);
public abstract void SetColorAt(int x, int y, Color color); 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 IFastBitmapWithClip.Contains(int x, int y)
{ {
bool contains = Clip.Contains(x, y); bool contains = Clip.Contains(x, y);
if (InvertClip) return InvertClip ? !contains : contains;
{
return !contains;
}
else
{
return contains;
}
} }
void IFastBitmapWithClip.SetColorAt(int x, int y, byte[] color) void IFastBitmapWithClip.SetColorAt(int x, int y, byte[] color)
@ -675,10 +614,7 @@ namespace Greenshot.Base.Core
/// <param name="x"></param> /// <param name="x"></param>
/// <param name="y"></param> /// <param name="y"></param>
/// <returns>true if x & y are inside the FastBitmap</returns> /// <returns>true if x & y are inside the FastBitmap</returns>
bool IFastBitmapWithOffset.Contains(int x, int y) bool IFastBitmapWithOffset.Contains(int x, int y) => Area.Contains(x - Left, y - Top);
{
return Area.Contains(x - Left, y - Top);
}
Color IFastBitmapWithOffset.GetColorAt(int x, int y) Color IFastBitmapWithOffset.GetColorAt(int x, int y)
{ {
@ -716,12 +652,9 @@ namespace Greenshot.Base.Core
{ {
// Used for indexed images // Used for indexed images
private readonly Color[] _colorEntries; 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) public FastChunkyBitmap(Bitmap source, NativeRect area) : base(source, area) => _colorEntries = Bitmap.Palette.Entries;
{
_colorEntries = Bitmap.Palette.Entries;
}
/// <summary> /// <summary>
/// Get the color from the specified location /// Get the color from the specified location
@ -742,10 +675,7 @@ namespace Greenshot.Base.Core
/// <param name="x"></param> /// <param name="x"></param>
/// <param name="y"></param> /// <param name="y"></param>
/// <param name="color">byte[4] as reference</param> /// <param name="color">byte[4] as reference</param>
public override void GetColorAt(int x, int y, byte[] color) public override void GetColorAt(int x, int y, byte[] color) => throw new NotImplementedException("No performance gain!");
{
throw new NotImplementedException("No performance gain!");
}
/// <summary> /// <summary>
/// Set the color at the specified location from the specified array /// 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="x"></param>
/// <param name="y"></param> /// <param name="y"></param>
/// <param name="color">byte[4] as reference</param> /// <param name="color">byte[4] as reference</param>
public override void SetColorAt(int x, int y, byte[] color) public override void SetColorAt(int x, int y, byte[] color) => throw new NotImplementedException("No performance gain!");
{
throw new NotImplementedException("No performance gain!");
}
/// <summary> /// <summary>
/// Get the color-index from the specified location /// Get the color-index from the specified location
@ -956,10 +883,7 @@ namespace Greenshot.Base.Core
public Color BackgroundBlendColor { get; set; } public Color BackgroundBlendColor { get; set; }
public Fast32ArgbBitmap(Bitmap source, NativeRect area) : base(source, area) public Fast32ArgbBitmap(Bitmap source, NativeRect area) : base(source, area) => BackgroundBlendColor = Color.White;
{
BackgroundBlendColor = Color.White;
}
/// <summary> /// <summary>
/// Retrieve the color at location x,y /// 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. // As the request is to get without alpha, we blend.
int rem = 255 - a; int rem = 255 - a;
red = (red * a + BackgroundBlendColor.R * rem) / 255; red = ((red * a) + (BackgroundBlendColor.R * rem)) / 255;
green = (green * a + BackgroundBlendColor.G * rem) / 255; green = ((green * a) + (BackgroundBlendColor.G * rem)) / 255;
blue = (blue * a + BackgroundBlendColor.B * rem) / 255; blue = ((blue * a) + (BackgroundBlendColor.B * rem)) / 255;
} }
return Color.FromArgb(255, red, green, blue); return Color.FromArgb(255, red, green, blue);

View file

@ -67,7 +67,7 @@ namespace Greenshot.Base.Core
var count = reader.ReadUInt32(); var count = reader.ReadUInt32();
while (count > 0) while (count > 0)
{ {
FileDescriptor descriptor = new FileDescriptor(reader); FileDescriptor descriptor = new(reader);
yield return descriptor.FileName; yield return descriptor.FileName;
@ -78,7 +78,7 @@ namespace Greenshot.Base.Core
internal static MemoryStream GetFileContents(System.Windows.Forms.IDataObject dataObject, int index) internal static MemoryStream GetFileContents(System.Windows.Forms.IDataObject dataObject, int index)
{ {
//cast the default IDataObject to a com IDataObject //cast the default IDataObject to a com IDataObject
var comDataObject = (IDataObject) dataObject; var comDataObject = (IDataObject)dataObject;
var format = System.Windows.DataFormats.GetDataFormat("FileContents"); var format = System.Windows.DataFormats.GetDataFormat("FileContents");
if (format == null) if (format == null)
@ -87,13 +87,13 @@ namespace Greenshot.Base.Core
} }
//create STGMEDIUM to output request results into //create STGMEDIUM to output request results into
var medium = new STGMEDIUM(); _ = new STGMEDIUM();
STGMEDIUM medium;
unchecked unchecked
{ {
var formatetc = new FORMATETC var formatetc = new FORMATETC
{ {
cfFormat = (short) format.Id, cfFormat = (short)format.Id,
dwAspect = DVASPECT.DVASPECT_CONTENT, dwAspect = DVASPECT.DVASPECT_CONTENT,
lindex = index, lindex = index,
tymed = TYMED.TYMED_ISTREAM | TYMED.TYMED_HGLOBAL tymed = TYMED.TYMED_ISTREAM | TYMED.TYMED_HGLOBAL
@ -113,13 +113,13 @@ namespace Greenshot.Base.Core
private static MemoryStream GetIStream(STGMEDIUM medium) private static MemoryStream GetIStream(STGMEDIUM medium)
{ {
//marshal the returned pointer to a IStream object //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); Marshal.Release(medium.unionmember);
//get the STATSTG of the IStream to determine how many bytes are in it //get the STATSTG of the IStream to determine how many bytes are in it
var iStreamStat = new System.Runtime.InteropServices.ComTypes.STATSTG(); _ = new System.Runtime.InteropServices.ComTypes.STATSTG();
iStream.Stat(out iStreamStat, 0); iStream.Stat(out System.Runtime.InteropServices.ComTypes.STATSTG iStreamStat, 0);
int iStreamSize = (int) iStreamStat.cbSize; int iStreamSize = (int)iStreamStat.cbSize;
//read the data from the IStream into a managed byte array //read the data from the IStream into a managed byte array
byte[] iStreamContent = new byte[iStreamSize]; byte[] iStreamContent = new byte[iStreamSize];

View file

@ -56,10 +56,7 @@ namespace Greenshot.Base.Core.FileFormatHandlers
/// <param name="fileFormatHandlers">IEnumerable{IFileFormatHandler}</param> /// <param name="fileFormatHandlers">IEnumerable{IFileFormatHandler}</param>
/// <param name="fileFormatHandlerAction"></param> /// <param name="fileFormatHandlerAction"></param>
/// <returns></returns> /// <returns></returns>
public static IEnumerable<string> ExtensionsFor(this IEnumerable<IFileFormatHandler> fileFormatHandlers, FileFormatHandlerActions fileFormatHandlerAction) 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);
{
return fileFormatHandlers.Where(ffh => ffh.SupportedExtensions.ContainsKey(fileFormatHandlerAction)).SelectMany(ffh => ffh.SupportedExtensions[fileFormatHandlerAction]).Distinct().OrderBy(e => e);
}
/// <summary> /// <summary>
/// Extension method to check if a certain IFileFormatHandler supports a certain action with a specific extension /// 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)) .Where(ffh => ffh.Supports(FileFormatHandlerActions.LoadFromStream, extension))
.OrderBy(ffh => ffh.PriorityFor(FileFormatHandlerActions.LoadFromStream, extension)).ToList(); .OrderBy(ffh => ffh.PriorityFor(FileFormatHandlerActions.LoadFromStream, extension)).ToList();
if (!saveFileFormatHandlers.Any()) if (saveFileFormatHandlers.Count == 0)
{ {
return false; return false;
} }
foreach (var fileFormatHandler in saveFileFormatHandlers) foreach (var _ in from fileFormatHandler in saveFileFormatHandlers
{ where fileFormatHandler.TrySaveToStream(bitmap, destination, extension, surface)
if (fileFormatHandler.TrySaveToStream(bitmap, destination, extension, surface)) select new { })
{ {
return true; return true;
} }
}
return false; return false;
} }
@ -126,12 +122,9 @@ namespace Greenshot.Base.Core.FileFormatHandlers
.OrderBy(ffh => ffh.PriorityFor(FileFormatHandlerActions.LoadDrawableFromStream, extension)) .OrderBy(ffh => ffh.PriorityFor(FileFormatHandlerActions.LoadDrawableFromStream, extension))
.FirstOrDefault(); .FirstOrDefault();
if (loadfileFormatHandler != null) return loadfileFormatHandler != null
{ ? loadfileFormatHandler.LoadDrawablesFromStream(stream, extension, parentSurface)
return loadfileFormatHandler.LoadDrawablesFromStream(stream, extension, parentSurface); : Enumerable.Empty<IDrawableContainer>();
}
return Enumerable.Empty<IDrawableContainer>();
} }
/// <summary> /// <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. // 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. : // 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"} // ${capturetime:d"yyyy-MM-dd HH_mm_ss"}
private static readonly Regex VarRegexp = new Regex(@"\${(?<variable>[^:}]+)[:]?(?<parameters>[^}]*)}", RegexOptions.Compiled); private static readonly Regex VarRegexp = new(@"\${(?<variable>[^:}]+)[:]?(?<parameters>[^}]*)}", RegexOptions.Compiled);
private static readonly Regex CmdVarRegexp = new Regex(@"%(?<variable>[^%]+)%", 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 const int MaxTitleLength = 80;
private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>();
private const string UnsafeReplacement = "_"; private const string UnsafeReplacement = "_";
private static readonly Random RandomNumberGen = new Random(); private static readonly Random RandomNumberGen = new();
private static readonly Regex RandRegexp = new Regex("^R+$", RegexOptions.Compiled); private static readonly Regex RandRegexp = new("^R+$", RegexOptions.Compiled);
/// <summary> /// <summary>
/// Remove invalid characters from the fully qualified filename /// Remove invalid characters from the fully qualified filename
@ -103,25 +103,13 @@ namespace Greenshot.Base.Core
return path; return path;
} }
public static string GetFilenameWithoutExtensionFromPattern(string pattern) public static string GetFilenameWithoutExtensionFromPattern(string pattern) => GetFilenameWithoutExtensionFromPattern(pattern, null);
{
return GetFilenameWithoutExtensionFromPattern(pattern, null);
}
public static string GetFilenameWithoutExtensionFromPattern(string pattern, ICaptureDetails captureDetails) public static string GetFilenameWithoutExtensionFromPattern(string pattern, ICaptureDetails captureDetails) => FillPattern(pattern, captureDetails, true);
{
return FillPattern(pattern, captureDetails, true);
}
public static string GetFilenameFromPattern(string pattern, OutputFormat imageFormat) public static string GetFilenameFromPattern(string pattern, OutputFormat imageFormat) => GetFilenameFromPattern(pattern, imageFormat, null);
{
return GetFilenameFromPattern(pattern, imageFormat, null);
}
public static string GetFilenameFromPattern(string pattern, OutputFormat imageFormat, ICaptureDetails captureDetails) public static string GetFilenameFromPattern(string pattern, OutputFormat imageFormat, ICaptureDetails captureDetails) => FillPattern(pattern, captureDetails, true) + "." + imageFormat.ToString().ToLower();
{
return FillPattern(pattern, captureDetails, true) + "." + imageFormat.ToString().ToLower();
}
/// <summary> /// <summary>
/// Return a filename for the current image format (png,jpg etc) with the default file pattern /// 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); return GetFilenameFromPattern(pattern, format, captureDetails);
} }
/// <summary> /// <summary>
/// This method will be called by the regexp.replace as a MatchEvaluator delegate! /// This method will be called by the regexp.replace as a MatchEvaluator delegate!
/// Will delegate this to the MatchVarEvaluatorInternal and catch any exceptions /// Will delegate this to the MatchVarEvaluatorInternal and catch any exceptions
@ -191,7 +178,7 @@ namespace Greenshot.Base.Core
string replaceValue = string.Empty; string replaceValue = string.Empty;
string variable = match.Groups["variable"].Value; string variable = match.Groups["variable"].Value;
string parameters = match.Groups["parameters"].Value; string parameters = match.Groups["parameters"].Value;
string randomChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; const string randomChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
if (parameters.Length > 0) if (parameters.Length > 0)
{ {
@ -222,7 +209,7 @@ namespace Greenshot.Base.Core
// r<old string>,<new string> // r<old string>,<new string>
case "r": case "r":
string[] replaceParameters = parameter.Substring(1).Split(','); string[] replaceParameters = parameter.Substring(1).Split(',');
if (replaceParameters != null && replaceParameters.Length == 2) if (replaceParameters?.Length == 2)
{ {
replacements.Add(replaceParameters[0], replaceParameters[1]); 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) if (filenameSafeMode)
{ {
replaceValue = MakePathSafe(replaceValue); 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) if (filenameSafeMode)
{ {
replaceValue = MakePathSafe(replaceValue); 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) if (filenameSafeMode)
{ {
replaceValue = MakePathSafe(replaceValue); replaceValue = MakePathSafe(replaceValue);
@ -675,7 +662,7 @@ namespace Greenshot.Base.Core
var forbiddenChars = Path.GetInvalidPathChars(); var forbiddenChars = Path.GetInvalidPathChars();
foreach (var forbiddenChar in forbiddenChars) foreach (var forbiddenChar in forbiddenChars)
{ {
if (directoryName == null || directoryName.Contains(forbiddenChar.ToString())) if (directoryName?.Contains(forbiddenChar.ToString()) != false)
{ {
return false; return false;
} }
@ -694,7 +681,7 @@ namespace Greenshot.Base.Core
var forbiddenChars = Path.GetInvalidFileNameChars(); var forbiddenChars = Path.GetInvalidFileNameChars();
foreach (var forbiddenChar in forbiddenChars) foreach (var forbiddenChar in forbiddenChars)
{ {
if (filename == null || filename.Contains(forbiddenChar.ToString())) if (filename?.Contains(forbiddenChar.ToString()) != false)
{ {
return false; return false;
} }

View file

@ -31,11 +31,11 @@ namespace Greenshot.Base.Core
} }
public Fraction Inverse() public Fraction Inverse()
=> new Fraction(Denominator, Numerator); => new(Denominator, Numerator);
#region Parse #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) public static bool TryParse(string str, out Fraction result)
{ {
@ -75,14 +75,14 @@ namespace Greenshot.Base.Core
unchecked unchecked
{ {
int hashCode = -1534900553; int hashCode = -1534900553;
hashCode = hashCode * -1521134295 + Numerator.GetHashCode(); hashCode = (hashCode * -1521134295) + Numerator.GetHashCode();
hashCode = hashCode * -1521134295 + Denominator.GetHashCode(); hashCode = (hashCode * -1521134295) + Denominator.GetHashCode();
return hashCode; return hashCode;
} }
} }
public int CompareTo(Fraction other) public int CompareTo(Fraction other)
=> (int) (Numerator * other.Denominator) - (int) (other.Numerator * Denominator); => (int)(Numerator * other.Denominator) - (int)(other.Numerator * Denominator);
#endregion #endregion
@ -115,22 +115,22 @@ namespace Greenshot.Base.Core
#region Scale operators #region Scale operators
public static Fraction operator *(Fraction left, Fraction right) 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) 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) 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) 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) 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) public static Fraction operator /(uint left, Fraction right)
=> new Fraction(left * right.Denominator, right.Numerator); => new(left * right.Denominator, right.Numerator);
#endregion #endregion
@ -143,10 +143,10 @@ namespace Greenshot.Base.Core
=> 1.0f * fraction.Numerator / fraction.Denominator; => 1.0f * fraction.Numerator / fraction.Denominator;
public static implicit operator Fraction(uint number) public static implicit operator Fraction(uint number)
=> new Fraction(number, 1u); => new(number, 1u);
public static implicit operator Fraction((uint numerator, uint demoninator) tuple) public static implicit operator Fraction((uint numerator, uint demoninator) tuple)
=> new Fraction(tuple.numerator, tuple.demoninator); => new(tuple.numerator, tuple.demoninator);
#endregion #endregion

View file

@ -29,21 +29,12 @@ namespace Greenshot.Base.Core
/// </summary> /// </summary>
public static class GreenshotResources 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) public static Image GetImage(string imageName) => (Image)GreenshotResourceManager.GetObject(imageName);
{
return (Image) GreenshotResourceManager.GetObject(imageName);
}
public static Icon GetIcon(string imageName) public static Icon GetIcon(string imageName) => (Icon)GreenshotResourceManager.GetObject(imageName);
{
return (Icon) GreenshotResourceManager.GetObject(imageName);
}
public static Icon GetGreenshotIcon() public static Icon GetGreenshotIcon() => GetIcon("Greenshot.Icon");
{
return GetIcon("Greenshot.Icon");
}
} }
} }

View file

@ -85,15 +85,10 @@ namespace Greenshot.Base.Core
if (ieVersion > 9) if (ieVersion > 9)
{ {
return ieVersion * 1000 + (ignoreDoctype ? 1 : 0); return (ieVersion * 1000) + (ignoreDoctype ? 1 : 0);
} }
if (ieVersion > 7) return ieVersion > 7 ? ieVersion * 1111 : 7000;
{
return ieVersion * 1111;
}
return 7000;
} }
/// <summary> /// <summary>
@ -111,10 +106,7 @@ namespace Greenshot.Base.Core
/// </summary> /// </summary>
/// <param name="applicationName">Name of the process</param> /// <param name="applicationName">Name of the process</param>
/// <param name="ignoreDoctype">true to ignore the doctype when loading a page</param> /// <param name="ignoreDoctype">true to ignore the doctype when loading a page</param>
public static void FixBrowserVersion(string applicationName, bool ignoreDoctype = true) public static void FixBrowserVersion(string applicationName, bool ignoreDoctype = true) => FixBrowserVersion(applicationName, GetEmbVersion(ignoreDoctype));
{
FixBrowserVersion(applicationName, GetEmbVersion(ignoreDoctype));
}
/// <summary> /// <summary>
/// Fix the browser version for the specified application /// Fix the browser version for the specified application
@ -191,7 +183,7 @@ namespace Greenshot.Base.Core
WindowDetails directUIWD = GetDirectUI(ieWindow); WindowDetails directUIWD = GetDirectUI(ieWindow);
if (directUIWD != null) if (directUIWD != null)
{ {
Accessible ieAccessible = new Accessible(directUIWD.Handle); Accessible ieAccessible = new(directUIWD.Handle);
foreach (string url in ieAccessible.IETabUrls) foreach (string url in ieAccessible.IETabUrls)
{ {
yield return url; yield return url;

View file

@ -51,7 +51,6 @@ namespace Greenshot.Base.Core
private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>();
private const int ExifOrientationId = 0x0112; private const int ExifOrientationId = 0x0112;
/// <summary> /// <summary>
/// Make sure the image is orientated correctly /// Make sure the image is orientated correctly
/// </summary> /// </summary>
@ -75,7 +74,7 @@ namespace Greenshot.Base.Core
PropertyItem item = image.GetPropertyItem(ExifOrientationId); PropertyItem item = image.GetPropertyItem(ExifOrientationId);
ExifOrientations orientation = (ExifOrientations) item.Value[0]; ExifOrientations orientation = (ExifOrientations)item.Value[0];
// Orient the image. // Orient the image.
switch (orientation) switch (orientation)
{ {
@ -106,7 +105,7 @@ namespace Greenshot.Base.Core
} }
// Set the orientation to be normal, as we rotated the image. // 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); image.SetPropertyItem(item);
} }
catch (Exception orientEx) catch (Exception orientEx)
@ -130,34 +129,34 @@ namespace Greenshot.Base.Core
int srcHeight = image.Height; int srcHeight = image.Height;
if (thumbHeight < 0) if (thumbHeight < 0)
{ {
thumbHeight = (int) (thumbWidth * (srcHeight / (float) srcWidth)); thumbHeight = (int)(thumbWidth * (srcHeight / (float)srcWidth));
} }
if (thumbWidth < 0) if (thumbWidth < 0)
{ {
thumbWidth = (int) (thumbHeight * (srcWidth / (float) srcHeight)); thumbWidth = (int)(thumbHeight * (srcWidth / (float)srcHeight));
} }
if (maxWidth > 0 && thumbWidth > maxWidth) if (maxWidth > 0 && thumbWidth > maxWidth)
{ {
thumbWidth = Math.Min(thumbWidth, maxWidth); thumbWidth = Math.Min(thumbWidth, maxWidth);
thumbHeight = (int) (thumbWidth * (srcHeight / (float) srcWidth)); thumbHeight = (int)(thumbWidth * (srcHeight / (float)srcWidth));
} }
if (maxHeight > 0 && thumbHeight > maxHeight) if (maxHeight > 0 && thumbHeight > maxHeight)
{ {
thumbHeight = Math.Min(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)) using (Graphics graphics = Graphics.FromImage(bmp))
{ {
graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; 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); 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); area ??= new NativeRect(0, 0, fastBitmap.Width, fastBitmap.Height);
NativeRect cropNativeRect = NativeRect.Empty; NativeRect cropNativeRect = NativeRect.Empty;
Color referenceColor = fastBitmap.GetColorAt(colorPoint.X, colorPoint.Y); Color referenceColor = fastBitmap.GetColorAt(colorPoint.X, colorPoint.Y);
NativePoint min = new NativePoint(int.MaxValue, int.MaxValue); NativePoint min = new(int.MaxValue, int.MaxValue);
NativePoint max = new NativePoint(int.MinValue, int.MinValue); NativePoint max = new(int.MinValue, int.MinValue);
if (cropDifference > 0) 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 (!(NativePoint.Empty.Equals(min) && max.Equals(new NativePoint(area.Value.Width - 1, area.Value.Height - 1))) && !(min.X == int.MaxValue || min.Y == int.MaxValue || max.X == int.MinValue || min.X == int.MinValue))
{
if (!(min.X == int.MaxValue || min.Y == int.MaxValue || max.X == int.MinValue || min.X == int.MinValue))
{ {
cropNativeRect = new NativeRect(min.X, min.Y, max.X - min.X + 1, max.Y - min.Y + 1); cropNativeRect = new NativeRect(min.X, min.Y, max.X - min.X + 1, max.Y - min.Y + 1);
} }
}
return cropNativeRect; return cropNativeRect;
} }
@ -279,7 +275,7 @@ namespace Greenshot.Base.Core
// Bottom Left // Bottom Left
// Top Right // Top Right
// Bottom Right // Bottom Right
using (IFastBitmap fastBitmap = FastBitmap.Create((Bitmap) image)) using (IFastBitmap fastBitmap = FastBitmap.Create((Bitmap)image))
{ {
// find biggest area // find biggest area
foreach (var checkPoint in checkPoints) 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); Image returnImage = CreateEmpty(sourceImage.Width, sourceImage.Height, PixelFormat.Format32bppArgb, Color.Empty, sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
using (var path = new GraphicsPath()) using (var path = new GraphicsPath())
{ {
Random random = new Random(); Random random = new();
int horizontalRegions = (int) Math.Round((float) sourceImage.Width / horizontalToothRange); int horizontalRegions = (int)Math.Round((float)sourceImage.Width / horizontalToothRange);
int verticalRegions = (int) Math.Round((float) sourceImage.Height / verticalToothRange); int verticalRegions = (int)Math.Round((float)sourceImage.Height / verticalToothRange);
var topLeft = new NativePoint(0, 0); var topLeft = new NativePoint(0, 0);
var topRight = new NativePoint(sourceImage.Width, 0); var topRight = new NativePoint(sourceImage.Width, 0);
@ -429,7 +425,7 @@ namespace Greenshot.Base.Core
{ {
for (int i = 1; i < horizontalRegions - 1; i++) 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))); 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) 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) 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) 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) 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> /// <returns>NativeRect</returns>
public static NativeRect CreateIntersectRectangle(NativeSize applySize, NativeRect rect, bool invert) public static NativeRect CreateIntersectRectangle(NativeSize applySize, NativeRect rect, bool invert)
{ {
NativeRect myRect;
if (invert) if (invert)
{ {
myRect = new NativeRect(0, 0, applySize.Width, applySize.Height); return new NativeRect(0, 0, applySize.Width, applySize.Height);
} }
else else
{ {
NativeRect applyRect = new NativeRect(0, 0, applySize.Width, applySize.Height); NativeRect applyRect = new(0, 0, applySize.Width, applySize.Height);
myRect = new NativeRect(rect.X, rect.Y, rect.Width, rect.Height).Intersect(applyRect); return new NativeRect(rect.X, rect.Y, rect.Width, rect.Height).Intersect(applyRect);
} }
return myRect;
} }
/// <summary> /// <summary>
@ -801,7 +794,7 @@ namespace Greenshot.Base.Core
NativePoint offset = shadowOffset.Offset(shadowSize - 1, shadowSize - 1); NativePoint offset = shadowOffset.Offset(shadowSize - 1, shadowSize - 1);
matrix.Translate(offset.X, offset.Y, MatrixOrder.Append); matrix.Translate(offset.X, offset.Y, MatrixOrder.Append);
// Create a new "clean" image // 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); sourceBitmap.HorizontalResolution, sourceBitmap.VerticalResolution);
// Make sure the shadow is odd, there is no reason for an even blur! // Make sure the shadow is odd, there is no reason for an even blur!
if ((shadowSize & 1) == 0) if ((shadowSize & 1) == 0)
@ -811,29 +804,22 @@ namespace Greenshot.Base.Core
bool useGdiBlur = GdiPlusApi.IsBlurPossible(shadowSize); bool useGdiBlur = GdiPlusApi.IsBlurPossible(shadowSize);
// Create "mask" for the shadow // Create "mask" for the shadow
ColorMatrix maskMatrix = new ColorMatrix ColorMatrix maskMatrix = new()
{ {
Matrix00 = 0, Matrix00 = 0,
Matrix11 = 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); NativeRect shadowNativeRect = new(new NativePoint(shadowSize, shadowSize), sourceBitmap.Size);
ApplyColorMatrix((Bitmap) sourceBitmap, NativeRect.Empty, returnImage, shadowNativeRect, maskMatrix); ApplyColorMatrix((Bitmap)sourceBitmap, NativeRect.Empty, returnImage, shadowNativeRect, maskMatrix);
// blur "shadow", apply to whole new image // blur "shadow", apply to whole new image
if (useGdiBlur) if (useGdiBlur)
{ {
// Use GDI Blur // 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); GdiPlusApi.ApplyBlur(returnImage, newImageNativeRect, shadowSize + 1, false);
} }
else else
@ -868,8 +854,8 @@ namespace Greenshot.Base.Core
/// <returns>Negative bitmap</returns> /// <returns>Negative bitmap</returns>
public static Bitmap CreateNegative(Image sourceImage) public static Bitmap CreateNegative(Image sourceImage)
{ {
Bitmap clone = (Bitmap) Clone(sourceImage); Bitmap clone = (Bitmap)Clone(sourceImage);
ColorMatrix invertMatrix = new ColorMatrix(new[] ColorMatrix invertMatrix = new(new[]
{ {
new float[] new float[]
{ {
@ -901,10 +887,7 @@ namespace Greenshot.Base.Core
/// </summary> /// </summary>
/// <param name="source">Image to apply matrix to</param> /// <param name="source">Image to apply matrix to</param>
/// <param name="colorMatrix">ColorMatrix to apply</param> /// <param name="colorMatrix">ColorMatrix to apply</param>
public static void ApplyColorMatrix(Bitmap source, ColorMatrix colorMatrix) public static void ApplyColorMatrix(Bitmap source, ColorMatrix colorMatrix) => ApplyColorMatrix(source, NativeRect.Empty, source, NativeRect.Empty, colorMatrix);
{
ApplyColorMatrix(source, NativeRect.Empty, source, NativeRect.Empty, colorMatrix);
}
/// <summary> /// <summary>
/// Apply a color matrix by copying from the source to the destination /// 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> /// <param name="colorMatrix">ColorMatrix to apply</param>
public static void ApplyColorMatrix(Bitmap source, NativeRect sourceRect, Bitmap dest, NativeRect destRect, ColorMatrix colorMatrix) 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.ClearColorMatrix();
imageAttributes.SetColorMatrix(colorMatrix); imageAttributes.SetColorMatrix(colorMatrix);
ApplyImageAttributes(source, sourceRect, dest, destRect, imageAttributes); 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) 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 // "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); matrix.Translate(offset.X, offset.Y, MatrixOrder.Append);
// Create a new "clean" image // 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); sourceImage.VerticalResolution);
using (Graphics graphics = Graphics.FromImage(newImage)) using (Graphics graphics = Graphics.FromImage(newImage))
{ {
@ -1006,10 +989,10 @@ namespace Greenshot.Base.Core
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; 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)); 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, LineJoin = LineJoin.Round,
StartCap = LineCap.Round, StartCap = LineCap.Round,
@ -1038,7 +1021,7 @@ namespace Greenshot.Base.Core
public static ImageAttributes CreateAdjustAttributes(float brightness, float contrast, float gamma) public static ImageAttributes CreateAdjustAttributes(float brightness, float contrast, float gamma)
{ {
float adjustedBrightness = brightness - 1.0f; float adjustedBrightness = brightness - 1.0f;
ColorMatrix applyColorMatrix = new ColorMatrix( ColorMatrix applyColorMatrix = new(
new[] new[]
{ {
new[] new[]
@ -1064,7 +1047,7 @@ namespace Greenshot.Base.Core
}); });
//create some image attributes //create some image attributes
ImageAttributes attributes = new ImageAttributes(); ImageAttributes attributes = new();
attributes.ClearColorMatrix(); attributes.ClearColorMatrix();
attributes.SetColorMatrix(applyColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); attributes.SetColorMatrix(applyColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
attributes.SetGamma(gamma, ColorAdjustType.Bitmap); attributes.SetGamma(gamma, ColorAdjustType.Bitmap);
@ -1088,7 +1071,7 @@ namespace Greenshot.Base.Core
sourceImage.VerticalResolution); sourceImage.VerticalResolution);
using (ImageAttributes adjustAttributes = CreateAdjustAttributes(brightness, contrast, gamma)) 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; return newBitmap;
@ -1101,8 +1084,8 @@ namespace Greenshot.Base.Core
/// <returns>Bitmap with grayscale</returns> /// <returns>Bitmap with grayscale</returns>
public static Image CreateGrayscale(Image sourceImage) public static Image CreateGrayscale(Image sourceImage)
{ {
Bitmap clone = (Bitmap) Clone(sourceImage); Bitmap clone = (Bitmap)Clone(sourceImage);
ColorMatrix grayscaleMatrix = new ColorMatrix(new[] ColorMatrix grayscaleMatrix = new(new[]
{ {
new[] new[]
{ {
@ -1134,28 +1117,17 @@ namespace Greenshot.Base.Core
/// </summary> /// </summary>
/// <param name="pixelformat">PixelFormat to check</param> /// <param name="pixelformat">PixelFormat to check</param>
/// <returns>bool if we support it</returns> /// <returns>bool if we support it</returns>
public static bool SupportsPixelFormat(PixelFormat pixelformat) public static bool SupportsPixelFormat(PixelFormat pixelformat) => pixelformat.Equals(PixelFormat.Format32bppArgb) ||
{
return pixelformat.Equals(PixelFormat.Format32bppArgb) ||
pixelformat.Equals(PixelFormat.Format32bppPArgb) || pixelformat.Equals(PixelFormat.Format32bppPArgb) ||
pixelformat.Equals(PixelFormat.Format32bppRgb) || pixelformat.Equals(PixelFormat.Format32bppRgb) ||
pixelformat.Equals(PixelFormat.Format24bppRgb); pixelformat.Equals(PixelFormat.Format24bppRgb);
}
/// <summary> /// <summary>
/// Wrapper for just cloning which calls the CloneArea /// Wrapper for just cloning which calls the CloneArea
/// </summary> /// </summary>
/// <param name="sourceImage">Image to clone</param> /// <param name="sourceImage">Image to clone</param>
/// <returns>Bitmap with clone image data</returns> /// <returns>Bitmap with clone image data</returns>
public static Image Clone(Image sourceImage) public static Image Clone(Image sourceImage) => sourceImage is Metafile ? (Image)sourceImage.Clone() : CloneArea(sourceImage, NativeRect.Empty, PixelFormat.DontCare);
{
if (sourceImage is Metafile)
{
return (Image) sourceImage.Clone();
}
return CloneArea(sourceImage, NativeRect.Empty, PixelFormat.DontCare);
}
/// <summary> /// <summary>
/// Wrapper for just cloning & TargetFormat which calls the CloneArea /// 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="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> /// <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> /// <returns>Bitmap with clone image data</returns>
public static Bitmap Clone(Image sourceBitmap, PixelFormat targetFormat) public static Bitmap Clone(Image sourceBitmap, PixelFormat targetFormat) => CloneArea(sourceBitmap, NativeRect.Empty, targetFormat);
{
return CloneArea(sourceBitmap, NativeRect.Empty, targetFormat);
}
/// <summary> /// <summary>
/// Clone an image, taking some rules into account: /// 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) public static Bitmap CloneArea(Image sourceImage, NativeRect sourceRect, PixelFormat targetFormat)
{ {
Bitmap newImage; 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 // Make sure the source is not NativeRect.Empty
if (NativeRect.Empty.Equals(sourceRect)) sourceRect = NativeRect.Empty.Equals(sourceRect)
{ ? new NativeRect(0, 0, sourceImage.Width, sourceImage.Height)
sourceRect = new NativeRect(0, 0, sourceImage.Width, sourceImage.Height); : sourceRect.Intersect(bitmapRect);
}
else
{
sourceRect = sourceRect.Intersect(bitmapRect);
}
// If no pixelformat is supplied // If no pixelformat is supplied
if (targetFormat is PixelFormat.DontCare or PixelFormat.Undefined) if (targetFormat is PixelFormat.DontCare or PixelFormat.Undefined)
@ -1201,13 +1165,9 @@ namespace Greenshot.Base.Core
{ {
targetFormat = sourceImage.PixelFormat; targetFormat = sourceImage.PixelFormat;
} }
else if (Image.IsAlphaPixelFormat(sourceImage.PixelFormat))
{
targetFormat = PixelFormat.Format32bppArgb;
}
else 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) public static Bitmap CreateEmpty(int width, int height, PixelFormat format, Color backgroundColor, float horizontalResolution = 96f, float verticalResolution = 96f)
{ {
// Create a new "clean" image // Create a new "clean" image
Bitmap newImage = new Bitmap(width, height, format); Bitmap newImage = new(width, height, format);
newImage.SetResolution(horizontalResolution, verticalResolution); newImage.SetResolution(horizontalResolution, verticalResolution);
if (format != PixelFormat.Format8bppIndexed) if (format != PixelFormat.Format8bppIndexed)
{ {
@ -1378,10 +1338,7 @@ namespace Greenshot.Base.Core
/// <param name="newHeight"></param> /// <param name="newHeight"></param>
/// <param name="matrix"></param> /// <param name="matrix"></param>
/// <returns></returns> /// <returns></returns>
public static Image ResizeImage(Image sourceImage, bool maintainAspectRatio, int newWidth, int newHeight, Matrix matrix) public static Image ResizeImage(Image sourceImage, bool maintainAspectRatio, int newWidth, int newHeight, Matrix matrix) => ResizeImage(sourceImage, maintainAspectRatio, false, Color.Empty, newWidth, newHeight, matrix);
{
return ResizeImage(sourceImage, maintainAspectRatio, false, Color.Empty, newWidth, newHeight, matrix);
}
/// <summary> /// <summary>
/// Count how many times the supplied color exists /// Count how many times the supplied color exists
@ -1399,7 +1356,7 @@ namespace Greenshot.Base.Core
toCount &= 0xffffff; 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 y = 0; y < bb.Height; y++)
{ {
for (int x = 0; x < bb.Width; x++) for (int x = 0; x < bb.Width; x++)
@ -1436,32 +1393,32 @@ namespace Greenshot.Base.Core
int destX = 0; int destX = 0;
int destY = 0; int destY = 0;
var nPercentW = newWidth / (float) sourceImage.Width; var nPercentW = newWidth / (float)sourceImage.Width;
var nPercentH = newHeight / (float) sourceImage.Height; var nPercentH = newHeight / (float)sourceImage.Height;
if (maintainAspectRatio) if (maintainAspectRatio)
{ {
if ((int) nPercentW == 1) if ((int)nPercentW == 1)
{ {
nPercentW = nPercentH; nPercentW = nPercentH;
if (canvasUseNewSize) 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; nPercentH = nPercentW;
if (canvasUseNewSize) 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; nPercentW = nPercentH;
if (canvasUseNewSize) 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 else
@ -1469,13 +1426,13 @@ namespace Greenshot.Base.Core
nPercentH = nPercentW; nPercentH = nPercentW;
if (canvasUseNewSize) 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 destWidth = (int)(sourceImage.Width * nPercentW);
int destHeight = (int) (sourceImage.Height * nPercentH); int destHeight = (int)(sourceImage.Height * nPercentH);
if (newWidth == 0) if (newWidth == 0)
{ {
newWidth = destWidth; newWidth = destWidth;
@ -1490,18 +1447,18 @@ namespace Greenshot.Base.Core
if (maintainAspectRatio && canvasUseNewSize) if (maintainAspectRatio && canvasUseNewSize)
{ {
newImage = CreateEmpty(newWidth, newHeight, sourceImage.PixelFormat, backgroundColor, sourceImage.HorizontalResolution, sourceImage.VerticalResolution); 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 else
{ {
newImage = CreateEmpty(destWidth, destHeight, sourceImage.PixelFormat, backgroundColor, sourceImage.HorizontalResolution, sourceImage.VerticalResolution); 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)) using (Graphics graphics = Graphics.FromImage(newImage))
{ {
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
using ImageAttributes wrapMode = new ImageAttributes(); using ImageAttributes wrapMode = new();
wrapMode.SetWrapMode(WrapMode.TileFlipXY); wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(sourceImage, new NativeRect(destX, destY, destWidth, destHeight), 0, 0, sourceImage.Width, sourceImage.Height, GraphicsUnit.Pixel, wrapMode); 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; return PixelFormat.Format24bppRgb;
} }
if (pixelFormat == PixelFormats.Bgr32) return pixelFormat == PixelFormats.Bgr32 ? PixelFormat.Format32bppRgb : throw new NotSupportedException($"Can't map {pixelFormat}.");
{
return PixelFormat.Format32bppRgb;
}
throw new NotSupportedException($"Can't map {pixelFormat}.");
} }
/// <summary> /// <summary>
@ -1605,7 +1557,7 @@ namespace Greenshot.Base.Core
{ {
var pixelFormat = bitmapSource.Format.Map(); 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); 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); bitmapSource.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
bitmap.UnlockBits(data); 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 ILog Log = LogManager.GetLogger(typeof(ImageIO));
private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>(); private static readonly CoreConfiguration CoreConfig = IniConfig.GetIniSection<CoreConfiguration>();
private static readonly int PROPERTY_TAG_SOFTWARE_USED = 0x0131; 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> /// <summary>
/// Creates a PropertyItem (Metadata) to store with the image. /// 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[] ConstructorInfo ci = typeof(PropertyItem).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, new Type[]
{ {
}, null); }, null);
propertyItem = (PropertyItem) ci.Invoke(null); propertyItem = (PropertyItem)ci.Invoke(null);
// Make sure it's of type string // Make sure it's of type string
propertyItem.Type = 2; propertyItem.Type = 2;
// Set the ID // Set the ID
@ -182,10 +182,10 @@ namespace Greenshot.Base.Core
} }
Image tmpImage; Image tmpImage;
if (outputSettings.Effects != null && outputSettings.Effects.Count > 0) if (outputSettings.Effects?.Count > 0)
{ {
// apply effects, if there are any // apply effects, if there are any
using (Matrix matrix = new Matrix()) using (Matrix matrix = new())
{ {
tmpImage = ImageHelper.ApplyEffects(imageToSave, outputSettings.Effects, matrix); tmpImage = ImageHelper.ApplyEffects(imageToSave, outputSettings.Effects, matrix);
} }
@ -211,7 +211,7 @@ namespace Greenshot.Base.Core
bool isAlpha = Image.IsAlphaPixelFormat(imageToSave.PixelFormat); bool isAlpha = Image.IsAlphaPixelFormat(imageToSave.PixelFormat);
if (outputSettings.ReduceColors || (!isAlpha && CoreConfig.OutputFileAutoReduceColors)) if (outputSettings.ReduceColors || (!isAlpha && CoreConfig.OutputFileAutoReduceColors))
{ {
using var quantizer = new WuQuantizer((Bitmap) imageToSave); using var quantizer = new WuQuantizer((Bitmap)imageToSave);
int colorCount = quantizer.GetColorCount(); int colorCount = quantizer.GetColorCount();
Log.InfoFormat("Image with format {0} has {1} colors", imageToSave.PixelFormat, colorCount); Log.InfoFormat("Image with format {0} has {1} colors", imageToSave.PixelFormat, colorCount);
if (!outputSettings.ReduceColors && colorCount >= 256) if (!outputSettings.ReduceColors && colorCount >= 256)
@ -304,7 +304,7 @@ namespace Greenshot.Base.Core
// check whether path exists - if not create it // check whether path exists - if not create it
if (path != null) if (path != null)
{ {
DirectoryInfo di = new DirectoryInfo(path); DirectoryInfo di = new(path);
if (!di.Exists) if (!di.Exists)
{ {
Directory.CreateDirectory(di.FullName); Directory.CreateDirectory(di.FullName);
@ -313,14 +313,14 @@ namespace Greenshot.Base.Core
if (!allowOverwrite && File.Exists(fullPath)) 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); throwingException.Data.Add("fullPath", fullPath);
throw throwingException; throw throwingException;
} }
Log.DebugFormat("Saving surface to {0}", fullPath); Log.DebugFormat("Saving surface to {0}", fullPath);
// Create the stream and call SaveToStream // 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); SaveToStream(surface, stream, outputSettings);
} }
@ -343,7 +343,7 @@ namespace Greenshot.Base.Core
OutputFormat format = OutputFormat.png; OutputFormat format = OutputFormat.png;
try try
{ {
format = (OutputFormat) Enum.Parse(typeof(OutputFormat), extension.ToLower()); format = (OutputFormat)Enum.Parse(typeof(OutputFormat), extension.ToLower());
} }
catch (ArgumentException ae) catch (ArgumentException ae)
{ {
@ -362,17 +362,17 @@ namespace Greenshot.Base.Core
public static string SaveWithDialog(ISurface surface, ICaptureDetails captureDetails) public static string SaveWithDialog(ISurface surface, ICaptureDetails captureDetails)
{ {
string returnValue = null; string returnValue = null;
using (SaveImageFileDialog saveImageFileDialog = new SaveImageFileDialog(captureDetails)) using (SaveImageFileDialog saveImageFileDialog = new(captureDetails))
{ {
DialogResult dialogResult = saveImageFileDialog.ShowDialog(); DialogResult dialogResult = saveImageFileDialog.ShowDialog();
if (!dialogResult.Equals(DialogResult.OK)) return returnValue; if (!dialogResult.Equals(DialogResult.OK)) return returnValue;
try try
{ {
string fileNameWithExtension = saveImageFileDialog.FileNameWithExtension; string fileNameWithExtension = saveImageFileDialog.FileNameWithExtension;
SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(FormatForFilename(fileNameWithExtension)); SurfaceOutputSettings outputSettings = new(FormatForFilename(fileNameWithExtension));
if (CoreConfig.OutputFilePromptQuality) if (CoreConfig.OutputFilePromptQuality)
{ {
QualityDialog qualityDialog = new QualityDialog(outputSettings); QualityDialog qualityDialog = new(outputSettings);
qualityDialog.ShowDialog(); 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 // Prevent problems with "other characters", which causes a problem in e.g. Outlook 2007 or break our HTML
filename = Regex.Replace(filename, @"[^\d\w\.]", "_"); filename = Regex.Replace(filename, @"[^\d\w\.]", "_");
// Remove multiple "_" // Remove multiple "_"
filename = Regex.Replace(filename, @"_+", "_"); filename = Regex.Replace(filename, "_+", "_");
string tmpFile = Path.Combine(Path.GetTempPath(), filename); string tmpFile = Path.Combine(Path.GetTempPath(), filename);
Log.Debug("Creating TMP File: " + tmpFile); Log.Debug("Creating TMP File: " + tmpFile);
@ -625,7 +625,7 @@ namespace Greenshot.Base.Core
// Start at -14 read "GreenshotXX.YY" (XX=Major, YY=Minor) // Start at -14 read "GreenshotXX.YY" (XX=Major, YY=Minor)
const int markerSize = 14; const int markerSize = 14;
surfaceFileStream.Seek(-markerSize, SeekOrigin.End); surfaceFileStream.Seek(-markerSize, SeekOrigin.End);
using (StreamReader streamReader = new StreamReader(surfaceFileStream)) using (StreamReader streamReader = new(surfaceFileStream))
{ {
var greenshotMarker = streamReader.ReadToEnd(); var greenshotMarker = streamReader.ReadToEnd();
if (!greenshotMarker.StartsWith("Greenshot")) if (!greenshotMarker.StartsWith("Greenshot"))
@ -636,7 +636,7 @@ namespace Greenshot.Base.Core
Log.InfoFormat("Greenshot file format: {0}", greenshotMarker); Log.InfoFormat("Greenshot file format: {0}", greenshotMarker);
const int filesizeLocation = 8 + markerSize; const int filesizeLocation = 8 + markerSize;
surfaceFileStream.Seek(-filesizeLocation, SeekOrigin.End); surfaceFileStream.Seek(-filesizeLocation, SeekOrigin.End);
using BinaryReader reader = new BinaryReader(surfaceFileStream); using BinaryReader reader = new(surfaceFileStream);
long bytesWritten = reader.ReadInt64(); long bytesWritten = reader.ReadInt64();
surfaceFileStream.Seek(-(bytesWritten + filesizeLocation), SeekOrigin.End); surfaceFileStream.Seek(-(bytesWritten + filesizeLocation), SeekOrigin.End);
returnSurface.LoadElementsFromStream(surfaceFileStream); returnSurface.LoadElementsFromStream(surfaceFileStream);

View file

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

View file

@ -36,17 +36,17 @@ namespace Greenshot.Base.Core
/// This class supplies the GUI with translations, based upon keys. /// 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 /// The language resources are loaded from the language files found on fixed or supplied paths
/// </summary> /// </summary>
public class Language public static class Language
{ {
private static readonly ILog Log = LogManager.GetLogger(typeof(Language)); private static readonly ILog Log = LogManager.GetLogger(typeof(Language));
private static readonly List<string> LanguagePaths = new(); private static readonly List<string> LanguagePaths = new();
private static readonly Dictionary<string, List<LanguageFile>> LanguageFiles = new(); private static readonly Dictionary<string, List<LanguageFile>> LanguageFiles = new();
private static readonly Dictionary<string, string> HelpFiles = new(); private static readonly Dictionary<string, string> HelpFiles = new();
private const string DefaultLanguage = "en-US"; private const string DefaultLanguage = "en-US";
private const string HelpFilenamePattern = @"help-*.html"; private const string HelpFilenamePattern = "help-*.html";
private const string LanguageFilenamePattern = @"language*.xml"; private const string LanguageFilenamePattern = "language*.xml";
private static readonly Regex PrefixRegexp = new(@"language_([a-zA-Z0-9]+).*"); 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 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 const string LanguageGroupsKey = @"SYSTEM\CurrentControlSet\Control\Nls\Language Groups";
private static readonly List<string> UnsupportedLanguageGroups = new(); private static readonly List<string> UnsupportedLanguageGroups = new();
private static readonly Dictionary<string, string> Resources = new(); private static readonly Dictionary<string, string> Resources = new();
@ -88,7 +88,7 @@ namespace Greenshot.Base.Core
// Startup path // Startup path
if (applicationFolder != null) if (applicationFolder != null)
{ {
AddPath(Path.Combine(applicationFolder, @"Languages")); AddPath(Path.Combine(applicationFolder, "Languages"));
} }
} }
catch (Exception pathException) catch (Exception pathException)
@ -104,7 +104,7 @@ namespace Greenshot.Base.Core
string[] groups = languageGroupsKey.GetValueNames(); string[] groups = languageGroupsKey.GetValueNames();
foreach (string group in groups) foreach (string group in groups)
{ {
string groupValue = (string) languageGroupsKey.GetValue(group); string groupValue = (string)languageGroupsKey.GetValue(group);
bool isGroupNotInstalled = "0".Equals(groupValue); bool isGroupNotInstalled = "0".Equals(groupValue);
if (isGroupNotInstalled) if (isGroupNotInstalled)
{ {
@ -218,7 +218,7 @@ namespace Greenshot.Base.Core
{ {
Resources.Clear(); Resources.Clear();
LoadFiles(DefaultLanguage); LoadFiles(DefaultLanguage);
if (_currentLanguage != null && !_currentLanguage.Equals(DefaultLanguage)) if (_currentLanguage?.Equals(DefaultLanguage) == false)
{ {
LoadFiles(_currentLanguage); LoadFiles(_currentLanguage);
} }
@ -239,7 +239,7 @@ namespace Greenshot.Base.Core
} }
else else
{ {
if (_currentLanguage == null || !_currentLanguage.Equals(ietf)) if (_currentLanguage?.Equals(ietf) != true)
{ {
_currentLanguage = ietf; _currentLanguage = ietf;
Reload(); Reload();
@ -328,18 +328,7 @@ namespace Greenshot.Base.Core
/// <summary> /// <summary>
/// Return the path to the help-file /// Return the path to the help-file
/// </summary> /// </summary>
public static string HelpFilePath public static string HelpFilePath => HelpFiles.ContainsKey(_currentLanguage) ? HelpFiles[_currentLanguage] : HelpFiles[DefaultLanguage];
{
get
{
if (HelpFiles.ContainsKey(_currentLanguage))
{
return HelpFiles[_currentLanguage];
}
return HelpFiles[DefaultLanguage];
}
}
/// <summary> /// <summary>
/// Load the resources from the language file /// Load the resources from the language file
@ -350,7 +339,7 @@ namespace Greenshot.Base.Core
Log.InfoFormat("Loading language file {0}", languageFile.Filepath); Log.InfoFormat("Loading language file {0}", languageFile.Filepath);
try try
{ {
XmlDocument xmlDocument = new XmlDocument(); XmlDocument xmlDocument = new();
xmlDocument.Load(languageFile.Filepath); xmlDocument.Load(languageFile.Filepath);
XmlNodeList resourceNodes = xmlDocument.GetElementsByTagName("resource"); XmlNodeList resourceNodes = xmlDocument.GetElementsByTagName("resource");
foreach (XmlNode resourceNode in resourceNodes) foreach (XmlNode resourceNode in resourceNodes)
@ -578,25 +567,14 @@ namespace Greenshot.Base.Core
/// <param name="prefix"></param> /// <param name="prefix"></param>
/// <param name="key"></param> /// <param name="key"></param>
/// <returns>true if available</returns> /// <returns>true if available</returns>
public static bool HasKey(string prefix, string key) public static bool HasKey(string prefix, string key) => HasKey(prefix + "." + key);
{
return HasKey(prefix + "." + key);
}
/// <summary> /// <summary>
/// Check if a resource with key exists /// Check if a resource with key exists
/// </summary> /// </summary>
/// <param name="key"></param> /// <param name="key"></param>
/// <returns>true if available</returns> /// <returns>true if available</returns>
public static bool HasKey(string key) public static bool HasKey(string key) => key != null && Resources.ContainsKey(key);
{
if (key == null)
{
return false;
}
return Resources.ContainsKey(key);
}
/// <summary> /// <summary>
/// TryGet method which combines HasKey & GetString /// TryGet method which combines HasKey & GetString
@ -604,10 +582,7 @@ namespace Greenshot.Base.Core
/// <param name="key"></param> /// <param name="key"></param>
/// <param name="languageString">out string</param> /// <param name="languageString">out string</param>
/// <returns></returns> /// <returns></returns>
public static bool TryGetString(string key, out string languageString) public static bool TryGetString(string key, out string languageString) => Resources.TryGetValue(key, out languageString);
{
return Resources.TryGetValue(key, out languageString);
}
/// <summary> /// <summary>
/// TryGet method which combines HasKey & GetString /// TryGet method which combines HasKey & GetString
@ -616,10 +591,7 @@ namespace Greenshot.Base.Core
/// <param name="key">string with key</param> /// <param name="key">string with key</param>
/// <param name="languageString">out string</param> /// <param name="languageString">out string</param>
/// <returns></returns> /// <returns></returns>
public static bool TryGetString(string prefix, string key, out string languageString) public static bool TryGetString(string prefix, string key, out string languageString) => Resources.TryGetValue(prefix + "." + key, out languageString);
{
return Resources.TryGetValue(prefix + "." + key, out languageString);
}
/// <summary> /// <summary>
/// TryGet method which combines HasKey & GetString /// TryGet method which combines HasKey & GetString
@ -628,10 +600,7 @@ namespace Greenshot.Base.Core
/// <param name="key">Enum with key</param> /// <param name="key">Enum with key</param>
/// <param name="languageString">out string</param> /// <param name="languageString">out string</param>
/// <returns></returns> /// <returns></returns>
public static bool TryGetString(string prefix, Enum key, out string languageString) public static bool TryGetString(string prefix, Enum key, out string languageString) => Resources.TryGetValue(prefix + "." + key, out languageString);
{
return Resources.TryGetValue(prefix + "." + key, out languageString);
}
/// <summary> /// <summary>
/// Translate /// Translate
@ -642,12 +611,7 @@ namespace Greenshot.Base.Core
{ {
string typename = key.GetType().Name; string typename = key.GetType().Name;
string enumKey = typename + "." + key; string enumKey = typename + "." + key;
if (HasKey(enumKey)) return HasKey(enumKey) ? GetString(enumKey) : key.ToString();
{
return GetString(enumKey);
}
return key.ToString();
} }
/// <summary> /// <summary>
@ -655,15 +619,7 @@ namespace Greenshot.Base.Core
/// </summary> /// </summary>
/// <param name="key">Enum</param> /// <param name="key">Enum</param>
/// <returns>resource or a "string ###key### not found"</returns> /// <returns>resource or a "string ###key### not found"</returns>
public static string GetString(Enum key) public static string GetString(Enum key) => key == null ? null : GetString(key.ToString());
{
if (key == null)
{
return null;
}
return GetString(key.ToString());
}
/// <summary> /// <summary>
/// Get the resource for prefix.key /// Get the resource for prefix.key
@ -671,15 +627,7 @@ namespace Greenshot.Base.Core
/// <param name="prefix">string</param> /// <param name="prefix">string</param>
/// <param name="key">Enum</param> /// <param name="key">Enum</param>
/// <returns>resource or a "string ###prefix.key### not found"</returns> /// <returns>resource or a "string ###prefix.key### not found"</returns>
public static string GetString(string prefix, Enum key) public static string GetString(string prefix, Enum key) => key == null ? null : GetString(prefix + "." + key);
{
if (key == null)
{
return null;
}
return GetString(prefix + "." + key);
}
/// <summary> /// <summary>
/// Get the resource for prefix.key /// Get the resource for prefix.key
@ -687,10 +635,7 @@ namespace Greenshot.Base.Core
/// <param name="prefix">string</param> /// <param name="prefix">string</param>
/// <param name="key">string</param> /// <param name="key">string</param>
/// <returns>resource or a "string ###prefix.key### not found"</returns> /// <returns>resource or a "string ###prefix.key### not found"</returns>
public static string GetString(string prefix, string key) public static string GetString(string prefix, string key) => GetString(prefix + "." + key);
{
return GetString(prefix + "." + key);
}
/// <summary> /// <summary>
/// Get the resource for key /// Get the resource for key
@ -704,63 +649,41 @@ namespace Greenshot.Base.Core
return null; return null;
} }
if (!Resources.TryGetValue(key, out var returnValue)) return !Resources.TryGetValue(key, out var returnValue) ? "string ###" + key + "### not found" : returnValue;
{
return "string ###" + key + "### not found";
}
return returnValue;
} }
/// <summary> /// <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> /// </summary>
/// <param name="key">Enum</param> /// <param name="key">Enum</param>
/// <param name="param">object</param> /// <param name="param">object</param>
/// <returns>formatted resource or a "string ###key### not found"</returns> /// <returns>formatted resource or a "string ###key### not found"</returns>
public static string GetFormattedString(Enum key, object param) public static string GetFormattedString(Enum key, object param) => GetFormattedString(key.ToString(), param);
{
return GetFormattedString(key.ToString(), param);
}
/// <summary> /// <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> /// </summary>
/// <param name="prefix">string</param> /// <param name="prefix">string</param>
/// <param name="key">Enum</param> /// <param name="key">Enum</param>
/// <param name="param">object</param> /// <param name="param">object</param>
/// <returns>formatted resource or a "string ###prefix.key### not found"</returns> /// <returns>formatted resource or a "string ###prefix.key### not found"</returns>
public static string GetFormattedString(string prefix, Enum key, object param) public static string GetFormattedString(string prefix, Enum key, object param) => GetFormattedString(prefix, key.ToString(), param);
{
return GetFormattedString(prefix, key.ToString(), param);
}
/// <summary> /// <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> /// </summary>
/// <param name="prefix">string</param> /// <param name="prefix">string</param>
/// <param name="key">string</param> /// <param name="key">string</param>
/// <param name="param">object</param> /// <param name="param">object</param>
/// <returns>formatted resource or a "string ###prefix.key### not found"</returns> /// <returns>formatted resource or a "string ###prefix.key### not found"</returns>
public static string GetFormattedString(string prefix, string key, object param) public static string GetFormattedString(string prefix, string key, object param) => GetFormattedString(prefix + "." + key, param);
{
return GetFormattedString(prefix + "." + key, param);
}
/// <summary> /// <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> /// </summary>
/// <param name="key">string</param> /// <param name="key">string</param>
/// <param name="param">object</param> /// <param name="param">object</param>
/// <returns>formatted resource or a "string ###key### not found"</returns> /// <returns>formatted resource or a "string ###key### not found"</returns>
public static string GetFormattedString(string key, object param) public static string GetFormattedString(string key, object param) => !Resources.TryGetValue(key, out var returnValue) ? "string ###" + key + "### not found" : string.Format(returnValue, param);
{
if (!Resources.TryGetValue(key, out var returnValue))
{
return "string ###" + key + "### not found";
}
return string.Format(returnValue, param);
}
} }
} }

View file

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

View file

@ -88,12 +88,11 @@ namespace Greenshot.Base.Core
// Get the logfile name // Get the logfile name
try 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 (appender is FileAppender fileAppender)
if (fileAppender != null)
{ {
return fileAppender.File; return fileAppender.File;
} }
@ -117,7 +116,7 @@ namespace Greenshot.Base.Core
{ {
protected override void Convert(TextWriter writer, object state) 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)); writer.Write(Environment.GetFolderPath(specialFolder));
} }
} }

View file

@ -77,7 +77,7 @@ namespace Greenshot.Base.Core
public static MemoryStream GetAsMemoryStream(string url) public static MemoryStream GetAsMemoryStream(string url)
{ {
var request = CreateWebRequest(url); var request = CreateWebRequest(url);
using var response = (HttpWebResponse) request.GetResponse(); using var response = (HttpWebResponse)request.GetResponse();
var memoryStream = new MemoryStream(); var memoryStream = new MemoryStream();
using (var responseStream = response.GetResponseStream()) using (var responseStream = response.GetResponseStream())
{ {
@ -99,7 +99,7 @@ namespace Greenshot.Base.Core
var fileFormatHandlers = SimpleServiceProvider.Current.GetAllInstances<IFileFormatHandler>(); var fileFormatHandlers = SimpleServiceProvider.Current.GetAllInstances<IFileFormatHandler>();
var extensions = string.Join("|", fileFormatHandlers.ExtensionsFor(FileFormatHandlerActions.LoadFromStream)); 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); var match = imageUrlRegex.Match(url);
try try
{ {
@ -162,7 +162,7 @@ namespace Greenshot.Base.Core
var extensions = string.Join("|", fileFormatHandlers.ExtensionsFor(FileFormatHandlerActions.LoadFromStream)); 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); var match = imageUrlRegex.Match(url);
try try
{ {
@ -214,10 +214,7 @@ namespace Greenshot.Base.Core
/// </summary> /// </summary>
/// <param name="uri">string with uri to connect to</param> /// <param name="uri">string with uri to connect to</param>
/// <returns>WebRequest</returns> /// <returns>WebRequest</returns>
public static HttpWebRequest CreateWebRequest(string uri) public static HttpWebRequest CreateWebRequest(string uri) => CreateWebRequest(new Uri(uri));
{
return CreateWebRequest(new Uri(uri));
}
/// <summary> /// <summary>
/// Helper method to create a web request with a lot of default settings /// 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="uri">string with uri to connect to</param>
/// /// <param name="method">Method to use</param> /// /// <param name="method">Method to use</param>
/// <returns>WebRequest</returns> /// <returns>WebRequest</returns>
public static HttpWebRequest CreateWebRequest(string uri, HTTPMethod method) public static HttpWebRequest CreateWebRequest(string uri, HTTPMethod method) => CreateWebRequest(new Uri(uri), method);
{
return CreateWebRequest(new Uri(uri), method);
}
/// <summary> /// <summary>
/// Helper method to create a web request with a lot of default settings /// Helper method to create a web request with a lot of default settings
@ -250,7 +244,7 @@ namespace Greenshot.Base.Core
/// <returns>WebRequest</returns> /// <returns>WebRequest</returns>
public static HttpWebRequest CreateWebRequest(Uri uri) 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; webRequest.Proxy = Config.UseProxy ? CreateProxy(uri) : null;
// Make sure the default credentials are available // Make sure the default credentials are available
webRequest.Credentials = CredentialCache.DefaultCredentials; webRequest.Credentials = CredentialCache.DefaultCredentials;
@ -352,7 +346,6 @@ namespace Greenshot.Base.Core
} }
return result.ToString(); return result.ToString();
} }
/// <summary> /// <summary>
@ -594,10 +587,7 @@ namespace Greenshot.Base.Core
/// <param name="webRequest">The request object.</param> /// <param name="webRequest">The request object.</param>
/// <returns>The response data.</returns> /// <returns>The response data.</returns>
/// TODO: This method should handle the StatusCode better! /// TODO: This method should handle the StatusCode better!
public static string GetResponseAsString(HttpWebRequest webRequest) public static string GetResponseAsString(HttpWebRequest webRequest) => GetResponseAsString(webRequest, false);
{
return GetResponseAsString(webRequest, false);
}
/// <summary> /// <summary>
/// Read the response as string /// Read the response as string
@ -617,7 +607,7 @@ namespace Greenshot.Base.Core
Stream responseStream = response.GetResponseStream(); Stream responseStream = response.GetResponseStream();
if (responseStream != null) if (responseStream != null)
{ {
using StreamReader reader = new StreamReader(responseStream, true); using StreamReader reader = new(responseStream, true);
responseData = reader.ReadToEnd(); responseData = reader.ReadToEnd();
} }
} }
@ -638,9 +628,9 @@ namespace Greenshot.Base.Core
bool isHttpError = false; bool isHttpError = false;
try try
{ {
response = (HttpWebResponse) webRequest.GetResponse(); response = (HttpWebResponse)webRequest.GetResponse();
Log.InfoFormat("Response status: {0}", response.StatusCode); Log.InfoFormat("Response status: {0}", response.StatusCode);
isHttpError = (int) response.StatusCode >= 300; isHttpError = (int)response.StatusCode >= 300;
if (isHttpError) if (isHttpError)
{ {
Log.ErrorFormat("HTTP error {0}", response.StatusCode); Log.ErrorFormat("HTTP error {0}", response.StatusCode);
@ -655,7 +645,7 @@ namespace Greenshot.Base.Core
} }
catch (WebException e) catch (WebException e)
{ {
response = (HttpWebResponse) e.Response; response = (HttpWebResponse)e.Response;
HttpStatusCode statusCode = HttpStatusCode.Unused; HttpStatusCode statusCode = HttpStatusCode.Unused;
if (response != null) if (response != null)
{ {
@ -731,9 +721,9 @@ namespace Greenshot.Base.Core
/// <returns>string</returns> /// <returns>string</returns>
public string ToBase64String(Base64FormattingOptions formattingOptions) public string ToBase64String(Base64FormattingOptions formattingOptions)
{ {
using MemoryStream stream = new MemoryStream(); using MemoryStream stream = new();
ImageIO.SaveToStream(_surface, stream, _outputSettings); 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> /// <summary>
@ -743,7 +733,7 @@ namespace Greenshot.Base.Core
/// <returns>byte[]</returns> /// <returns>byte[]</returns>
public byte[] ToByteArray() public byte[] ToByteArray()
{ {
using MemoryStream stream = new MemoryStream(); using MemoryStream stream = new();
ImageIO.SaveToStream(_surface, stream, _outputSettings); ImageIO.SaveToStream(_surface, stream, _outputSettings);
return stream.ToArray(); return stream.ToArray();
} }
@ -767,11 +757,9 @@ namespace Greenshot.Base.Core
/// A plain "write data to stream" /// A plain "write data to stream"
/// </summary> /// </summary>
/// <param name="dataStream"></param> /// <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. // Write the file data directly to the Stream, rather than serializing it to a string.
ImageIO.SaveToStream(_surface, dataStream, _outputSettings); ImageIO.SaveToStream(_surface, dataStream, _outputSettings);
}
/// <summary> /// <summary>
/// Upload the Surface as image to the webrequest /// Upload the Surface as image to the webrequest

View file

@ -39,7 +39,7 @@ namespace Greenshot.Base.Core.OAuth
public class LocalJsonReceiver public class LocalJsonReceiver
{ {
private static readonly ILog Log = LogManager.GetLogger(typeof(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; private IDictionary<string, string> _returnValues;
/// <summary> /// <summary>
@ -121,7 +121,7 @@ namespace Greenshot.Base.Core.OAuth
/// <param name="result">IAsyncResult</param> /// <param name="result">IAsyncResult</param>
private void ListenerCallback(IAsyncResult result) 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 not listening return immediately as this method is called one last time after Close()
if (!listener.IsListening) if (!listener.IsListening)
@ -192,7 +192,7 @@ namespace Greenshot.Base.Core.OAuth
try try
{ {
listener.Start(); listener.Start();
return ((IPEndPoint) listener.LocalEndpoint).Port; return ((IPEndPoint)listener.LocalEndpoint).Port;
} }
finally finally
{ {

View file

@ -38,7 +38,7 @@ namespace Greenshot.Base.Core.OAuth
public class LocalServerCodeReceiver public class LocalServerCodeReceiver
{ {
private static readonly ILog Log = LogManager.GetLogger(typeof(LocalServerCodeReceiver)); private static readonly ILog Log = LogManager.GetLogger(typeof(LocalServerCodeReceiver));
private readonly ManualResetEvent _ready = new ManualResetEvent(true); private readonly ManualResetEvent _ready = new(true);
/// <summary> /// <summary>
/// The call back format. Expects one port parameter. /// 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/"; public string LoopbackCallbackUrl { get; set; } = "http://localhost:{0}/authorize/";
/// <summary> /// <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 /// You can use CloudServiceName where you want to show the CloudServiceName from your OAuth2 settings
/// </summary> /// </summary>
public string ClosePageResponse { get; set; } = @"<html> public string ClosePageResponse { get; set; } = @"<html>
@ -71,24 +71,12 @@ Greenshot received information from CloudServiceName. You can close this browser
/// <summary> /// <summary>
/// The URL to redirect to /// The URL to redirect to
/// </summary> /// </summary>
protected string RedirectUri protected string RedirectUri => !string.IsNullOrEmpty(_redirectUri) ? _redirectUri : (_redirectUri = string.Format(LoopbackCallbackUrl, GetRandomUnusedPort()));
{
get
{
if (!string.IsNullOrEmpty(_redirectUri))
{
return _redirectUri;
}
return _redirectUri = string.Format(LoopbackCallbackUrl, GetRandomUnusedPort());
}
}
private string _cloudServiceName; private string _cloudServiceName;
private readonly IDictionary<string, string> _returnValues = new Dictionary<string, string>(); private readonly IDictionary<string, string> _returnValues = new Dictionary<string, string>();
/// <summary> /// <summary>
/// The OAuth code receiver /// The OAuth code receiver
/// </summary> /// </summary>
@ -142,7 +130,7 @@ Greenshot received information from CloudServiceName. You can close this browser
/// <param name="result">IAsyncResult</param> /// <param name="result">IAsyncResult</param>
private void ListenerCallback(IAsyncResult result) 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 not listening return immediately as this method is called one last time after Close()
if (!listener.IsListening) if (!listener.IsListening)
@ -153,7 +141,6 @@ Greenshot received information from CloudServiceName. You can close this browser
// Use EndGetContext to complete the asynchronous operation. // Use EndGetContext to complete the asynchronous operation.
HttpListenerContext context = listener.EndGetContext(result); HttpListenerContext context = listener.EndGetContext(result);
// Handle request // Handle request
HttpListenerRequest request = context.Request; HttpListenerRequest request = context.Request;
try try
@ -199,7 +186,7 @@ Greenshot received information from CloudServiceName. You can close this browser
try try
{ {
listener.Start(); listener.Start();
return ((IPEndPoint) listener.LocalEndpoint).Port; return ((IPEndPoint)listener.LocalEndpoint).Port;
} }
finally finally
{ {

View file

@ -82,7 +82,7 @@ namespace Greenshot.Base.Core.OAuth
throw new Exception($"{refreshTokenResult["error"]} - {refreshTokenResult["error_description"]}"); 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 // 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" // "refresh_token":"1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
if (refreshTokenResult.ContainsKey(AccessToken)) if (refreshTokenResult.ContainsKey(AccessToken))
{ {
settings.AccessToken = (string) refreshTokenResult[AccessToken]; settings.AccessToken = (string)refreshTokenResult[AccessToken];
} }
if (refreshTokenResult.ContainsKey(RefreshToken)) if (refreshTokenResult.ContainsKey(RefreshToken))
{ {
settings.RefreshToken = (string) refreshTokenResult[RefreshToken]; settings.RefreshToken = (string)refreshTokenResult[RefreshToken];
} }
if (refreshTokenResult.ContainsKey(ExpiresIn)) if (refreshTokenResult.ContainsKey(ExpiresIn))
@ -105,7 +105,7 @@ namespace Greenshot.Base.Core.OAuth
object seconds = refreshTokenResult[ExpiresIn]; object seconds = refreshTokenResult[ExpiresIn];
if (seconds != null) 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]; var expiresIn = callbackParameters[ExpiresIn];
settings.AccessTokenExpires = DateTimeOffset.MaxValue; settings.AccessTokenExpires = DateTimeOffset.MaxValue;
if (expiresIn != null) if (expiresIn != null && double.TryParse(expiresIn, out var seconds))
{
if (double.TryParse(expiresIn, out var seconds))
{ {
settings.AccessTokenExpires = DateTimeOffset.Now.AddSeconds(seconds); settings.AccessTokenExpires = DateTimeOffset.Now.AddSeconds(seconds);
} }
} }
}
settings.AccessToken = callbackParameters[AccessToken]; settings.AccessToken = callbackParameters[AccessToken];
return true; return true;
@ -187,7 +184,7 @@ namespace Greenshot.Base.Core.OAuth
IDictionary<string, object> accessTokenResult = JSONHelper.JsonDecode(accessTokenJsonResult); IDictionary<string, object> accessTokenResult = JSONHelper.JsonDecode(accessTokenJsonResult);
if (accessTokenResult.ContainsKey("error")) 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! // Refresh token has also expired, we need a new one!
settings.RefreshToken = null; settings.RefreshToken = null;
@ -202,19 +199,19 @@ namespace Greenshot.Base.Core.OAuth
throw new Exception($"{accessTokenResult["error"]} - {accessTokenResult["error_description"]}"); throw new Exception($"{accessTokenResult["error"]} - {accessTokenResult["error_description"]}");
} }
throw new Exception((string) accessTokenResult["error"]); throw new Exception((string)accessTokenResult["error"]);
} }
if (accessTokenResult.ContainsKey(AccessToken)) if (accessTokenResult.ContainsKey(AccessToken))
{ {
settings.AccessToken = (string) accessTokenResult[AccessToken]; settings.AccessToken = (string)accessTokenResult[AccessToken];
settings.AccessTokenExpires = DateTimeOffset.MaxValue; settings.AccessTokenExpires = DateTimeOffset.MaxValue;
} }
if (accessTokenResult.ContainsKey(RefreshToken)) if (accessTokenResult.ContainsKey(RefreshToken))
{ {
// Refresh the refresh token :) // Refresh the refresh token :)
settings.RefreshToken = (string) accessTokenResult[RefreshToken]; settings.RefreshToken = (string)accessTokenResult[RefreshToken];
} }
if (accessTokenResult.ContainsKey(ExpiresIn)) if (accessTokenResult.ContainsKey(ExpiresIn))
@ -222,7 +219,7 @@ namespace Greenshot.Base.Core.OAuth
object seconds = accessTokenResult[ExpiresIn]; object seconds = accessTokenResult[ExpiresIn];
if (seconds != null) 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); throw new Exception(errorDescription);
} }
if ("access_denied" == error) if (error == "access_denied")
{ {
throw new UnauthorizedAccessException("Access denied"); throw new UnauthorizedAccessException("Access denied");
} }
@ -324,7 +321,7 @@ namespace Greenshot.Base.Core.OAuth
throw new ArgumentNullException(nameof(settings.BrowserSize)); 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(); loginForm.ShowDialog();
if (!loginForm.IsOk) return false; if (!loginForm.IsOk) return false;
if (loginForm.CallbackParameters.TryGetValue(Code, out var code) && !string.IsNullOrEmpty(code)) if (loginForm.CallbackParameters.TryGetValue(Code, out var code) && !string.IsNullOrEmpty(code))
@ -362,7 +359,7 @@ namespace Greenshot.Base.Core.OAuth
throw new Exception(errorDescription); throw new Exception(errorDescription);
} }
if ("access_denied" == error) if (error == "access_denied")
{ {
throw new UnauthorizedAccessException("Access denied"); throw new UnauthorizedAccessException("Access denied");
} }
@ -393,13 +390,10 @@ namespace Greenshot.Base.Core.OAuth
public static void CheckAndAuthenticateOrRefresh(OAuth2Settings settings) public static void CheckAndAuthenticateOrRefresh(OAuth2Settings settings)
{ {
// Get Refresh / Access token // Get Refresh / Access token
if (string.IsNullOrEmpty(settings.RefreshToken)) if (string.IsNullOrEmpty(settings.RefreshToken) && !Authorize(settings))
{
if (!Authorize(settings))
{ {
throw new Exception("Authentication cancelled"); throw new Exception("Authentication cancelled");
} }
}
if (settings.IsAccessTokenExpired) if (settings.IsAccessTokenExpired)
{ {

View file

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

View file

@ -29,6 +29,7 @@ using System.Text;
using System.Threading; using System.Threading;
using Greenshot.Base.Controls; using Greenshot.Base.Controls;
using log4net; using log4net;
using System.Linq;
namespace Greenshot.Base.Core.OAuth namespace Greenshot.Base.Core.OAuth
{ {
@ -58,11 +59,9 @@ namespace Greenshot.Base.Core.OAuth
protected const string HMACSHA1SignatureType = "HMAC-SHA1"; protected const string HMACSHA1SignatureType = "HMAC-SHA1";
protected const string PlainTextSignatureType = "PLAINTEXT"; protected const string PlainTextSignatureType = "PLAINTEXT";
protected static Random random = new Random(); protected static Random random = new();
protected const string UnreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"; protected const string UnreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
private string _userAgent = "Greenshot";
private IDictionary<string, string> _requestTokenResponseParameters; private IDictionary<string, string> _requestTokenResponseParameters;
public IDictionary<string, object> RequestTokenParameters { get; } = new Dictionary<string, object>(); 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 bool UseMultipartFormData { get; set; }
public string UserAgent public string UserAgent { get; set; } = "Greenshot";
{
get { return _userAgent; }
set { _userAgent = value; }
}
public string CallbackUrl { get; set; } = "https://getgreenshot.org"; public string CallbackUrl { get; set; } = "https://getgreenshot.org";
@ -166,7 +161,7 @@ namespace Greenshot.Base.Core.OAuth
queryParameters = new SortedDictionary<string, object>(queryParameters); queryParameters = new SortedDictionary<string, object>(queryParameters);
StringBuilder sb = new StringBuilder(); StringBuilder sb = new();
foreach (string key in queryParameters.Keys) foreach (string key in queryParameters.Keys)
{ {
if (queryParameters[key] is string) 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> /// <returns>Returns a Url encoded string (unicode) with UTF-8 encoded % values</returns>
public static string UrlEncode3986(string value) public static string UrlEncode3986(string value)
{ {
StringBuilder result = new StringBuilder(); StringBuilder result = new();
foreach (char symbol in value) foreach (char symbol in value)
{ {
@ -225,11 +220,9 @@ namespace Greenshot.Base.Core.OAuth
/// Generate a nonce /// Generate a nonce
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public static string GenerateNonce() public static string GenerateNonce() =>
{
// Just a simple implementation of a random number between 123400 and 9999999 // Just a simple implementation of a random number between 123400 and 9999999
return random.Next(123400, 9999999).ToString(); random.Next(123400, 9999999).ToString();
}
/// <summary> /// <summary>
/// Get the request token using the consumer key and secret. Also initializes tokensecret /// 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)) 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; throw e;
} }
Log.DebugFormat("Opening AuthorizationLink: {0}", AuthorizationLink); Log.DebugFormat("Opening AuthorizationLink: {0}", AuthorizationLink);
OAuthLoginForm oAuthLoginForm = new OAuthLoginForm(LoginTitle, BrowserSize, AuthorizationLink, CallbackUrl); OAuthLoginForm oAuthLoginForm = new(LoginTitle, BrowserSize, AuthorizationLink, CallbackUrl);
oAuthLoginForm.ShowDialog(); oAuthLoginForm.ShowDialog();
if (oAuthLoginForm.IsOk) if (oAuthLoginForm.IsOk && oAuthLoginForm.CallbackParameters != null)
{
if (oAuthLoginForm.CallbackParameters != null)
{ {
if (oAuthLoginForm.CallbackParameters.TryGetValue(OAUTH_TOKEN_KEY, out var tokenValue)) if (oAuthLoginForm.CallbackParameters.TryGetValue(OAUTH_TOKEN_KEY, out var tokenValue))
{ {
@ -290,16 +281,10 @@ namespace Greenshot.Base.Core.OAuth
Verifier = verifierValue; Verifier = verifierValue;
} }
} }
}
if (CheckVerifier) if (CheckVerifier)
{ {
if (!string.IsNullOrEmpty(Verifier)) return !string.IsNullOrEmpty(Verifier) ? Token : null;
{
return Token;
}
return null;
} }
return Token; return Token;
@ -313,7 +298,7 @@ namespace Greenshot.Base.Core.OAuth
{ {
if (string.IsNullOrEmpty(Token) || (CheckVerifier && string.IsNullOrEmpty(Verifier))) 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; throw e;
} }
@ -394,10 +379,7 @@ namespace Greenshot.Base.Core.OAuth
/// <param name="postData">Data to post (MemoryStream)</param> /// <param name="postData">Data to post (MemoryStream)</param>
/// <returns>The web server response.</returns> /// <returns>The web server response.</returns>
public string MakeOAuthRequest(HTTPMethod method, string requestUrl, IDictionary<string, object> parametersToSign, IDictionary<string, object> additionalParameters, public string MakeOAuthRequest(HTTPMethod method, string requestUrl, IDictionary<string, object> parametersToSign, IDictionary<string, object> additionalParameters,
IBinaryContainer postData) IBinaryContainer postData) => MakeOAuthRequest(method, requestUrl, requestUrl, null, parametersToSign, additionalParameters, postData);
{
return MakeOAuthRequest(method, requestUrl, requestUrl, null, parametersToSign, additionalParameters, postData);
}
/// <summary> /// <summary>
/// Submit a web request using oAuth. /// Submit a web request using oAuth.
@ -410,10 +392,7 @@ namespace Greenshot.Base.Core.OAuth
/// <param name="postData">Data to post (MemoryStream)</param> /// <param name="postData">Data to post (MemoryStream)</param>
/// <returns>The web server response.</returns> /// <returns>The web server response.</returns>
public string MakeOAuthRequest(HTTPMethod method, string requestUrl, IDictionary<string, string> headers, IDictionary<string, object> parametersToSign, public string MakeOAuthRequest(HTTPMethod method, string requestUrl, IDictionary<string, string> headers, IDictionary<string, object> parametersToSign,
IDictionary<string, object> additionalParameters, IBinaryContainer postData) IDictionary<string, object> additionalParameters, IBinaryContainer postData) => MakeOAuthRequest(method, requestUrl, requestUrl, headers, parametersToSign, additionalParameters, postData);
{
return MakeOAuthRequest(method, requestUrl, requestUrl, headers, parametersToSign, additionalParameters, postData);
}
/// <summary> /// <summary>
/// Submit a web request using oAuth. /// Submit a web request using oAuth.
@ -426,10 +405,7 @@ namespace Greenshot.Base.Core.OAuth
/// <param name="postData">Data to post (MemoryStream)</param> /// <param name="postData">Data to post (MemoryStream)</param>
/// <returns>The web server response.</returns> /// <returns>The web server response.</returns>
public string MakeOAuthRequest(HTTPMethod method, string signUrl, string requestUrl, IDictionary<string, object> parametersToSign, public string MakeOAuthRequest(HTTPMethod method, string signUrl, string requestUrl, IDictionary<string, object> parametersToSign,
IDictionary<string, object> additionalParameters, IBinaryContainer postData) IDictionary<string, object> additionalParameters, IBinaryContainer postData) => MakeOAuthRequest(method, signUrl, requestUrl, null, parametersToSign, additionalParameters, postData);
{
return MakeOAuthRequest(method, signUrl, requestUrl, null, parametersToSign, additionalParameters, postData);
}
/// <summary> /// <summary>
/// Submit a web request using oAuth. /// Submit a web request using oAuth.
@ -455,13 +431,10 @@ namespace Greenshot.Base.Core.OAuth
while (retries-- > 0) while (retries-- > 0)
{ {
// If we are not trying to get a Authorization or Accestoken, and we don't have a token, create one // If we are not trying to get a Authorization or Accestoken, and we don't have a token, create one
if (string.IsNullOrEmpty(Token)) if (string.IsNullOrEmpty(Token) && (!AutoLogin || !Authorize()))
{
if (!AutoLogin || !Authorize())
{ {
throw new Exception("Not authorized"); throw new Exception("Not authorized");
} }
}
try try
{ {
@ -490,15 +463,10 @@ namespace Greenshot.Base.Core.OAuth
Token = null; Token = null;
TokenSecret = null; TokenSecret = null;
// Remove oauth keys, so they aren't added double // Remove oauth keys, so they aren't added double
List<string> keysToDelete = new List<string>(); List<string> keysToDelete = new();
foreach (string parameterKey in parametersToSign.Keys) keysToDelete.AddRange(from string parameterKey in parametersToSign.Keys
{ where parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX)
if (parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX)) select parameterKey);
{
keysToDelete.Add(parameterKey);
}
}
foreach (string keyToDelete in keysToDelete) foreach (string keyToDelete in keysToDelete)
{ {
parametersToSign.Remove(keyToDelete); parametersToSign.Remove(keyToDelete);
@ -529,13 +497,13 @@ namespace Greenshot.Base.Core.OAuth
} }
// Build the signature base // Build the signature base
StringBuilder signatureBase = new StringBuilder(); StringBuilder signatureBase = new();
// Add Method to signature base // Add Method to signature base
signatureBase.Append(method).Append("&"); signatureBase.Append(method).Append("&");
// Add normalized URL // Add normalized URL
Uri url = new Uri(requestUrl); Uri url = new(requestUrl);
string normalizedUrl = string.Format(CultureInfo.InvariantCulture, "{0}://{1}", url.Scheme, url.Host); 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))) if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443)))
{ {
@ -586,7 +554,7 @@ namespace Greenshot.Base.Core.OAuth
break; break;
default: default:
// Generate Signature and add it to the parameters // Generate Signature and add it to the parameters
HMACSHA1 hmacsha1 = new HMACSHA1 HMACSHA1 hmacsha1 = new()
{ {
Key = Encoding.UTF8.GetBytes(key) Key = Encoding.UTF8.GetBytes(key)
}; };
@ -643,19 +611,16 @@ namespace Greenshot.Base.Core.OAuth
requestParameters = parameters; requestParameters = parameters;
} }
if (HTTPMethod.GET == method || postData != null) if ((HTTPMethod.GET == method || postData != null) && requestParameters.Count > 0)
{
if (requestParameters.Count > 0)
{ {
// Add the parameters to the request // Add the parameters to the request
requestUrl += "?" + NetworkHelper.GenerateQueryParameters(requestParameters); requestUrl += "?" + NetworkHelper.GenerateQueryParameters(requestParameters);
} }
}
// Create webrequest // Create webrequest
HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(requestUrl, method); HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(requestUrl, method);
webRequest.ServicePoint.Expect100Continue = false; webRequest.ServicePoint.Expect100Continue = false;
webRequest.UserAgent = _userAgent; webRequest.UserAgent = UserAgent;
if (UseHttpHeadersForAuthorization && authHeader != null) if (UseHttpHeadersForAuthorization && authHeader != null)
{ {
@ -679,12 +644,11 @@ namespace Greenshot.Base.Core.OAuth
} }
else else
{ {
StringBuilder form = new StringBuilder(); StringBuilder form = new();
foreach (string parameterKey in requestParameters.Keys) foreach (string parameterKey in requestParameters.Keys)
{ {
var binaryParameter = parameters[parameterKey] as IBinaryContainer;
form.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey), 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 & // Remove trailing &

View file

@ -57,7 +57,7 @@ namespace Greenshot.Base.Core
using var stream = new MemoryStream(); using var stream = new MemoryStream();
formatter.Serialize(stream, source); formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin); stream.Seek(0, SeekOrigin.Begin);
return (T) formatter.Deserialize(stream); return (T)formatter.Deserialize(stream);
} }
/// <summary> /// <summary>

View file

@ -42,10 +42,7 @@ namespace Greenshot.Base.Core
private const string PathKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\"; private const string PathKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\";
private static readonly IDictionary<string, Image> ExeIconCache = new Dictionary<string, Image>(); private static readonly IDictionary<string, Image> ExeIconCache = new Dictionary<string, Image>();
static PluginUtils() static PluginUtils() => CoreConfig.PropertyChanged += OnIconSizeChanged;
{
CoreConfig.PropertyChanged += OnIconSizeChanged;
}
/// <summary> /// <summary>
/// Clear icon cache /// Clear icon cache
@ -84,7 +81,7 @@ namespace Greenshot.Base.Core
if (key != null) if (key != null)
{ {
// "" is the default key, which should point to the requested location // "" 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) protected virtual void Dispose(bool disposing)
{ {
if (disposing) if (disposing && resultBitmap != null)
{
if (resultBitmap != null)
{ {
resultBitmap.Dispose(); resultBitmap.Dispose();
resultBitmap = null; resultBitmap = null;
} }
} }
}
/// <summary> /// <summary>
/// See <see cref="IColorQuantizer.Prepare"/> for more details. /// See <see cref="IColorQuantizer.Prepare"/> for more details.
@ -130,7 +127,7 @@ namespace Greenshot.Base.Core
{ {
this.sourceBitmap = sourceBitmap; this.sourceBitmap = sourceBitmap;
// Make sure the color count variables are reset // 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; colorCount = 0;
// creates all the cubes // 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 // 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); using IFastBitmap sourceFastBitmap = FastBitmap.Create(sourceBitmap);
IFastBitmapWithBlend sourceFastBitmapWithBlend = sourceFastBitmap as IFastBitmapWithBlend;
sourceFastBitmap.Lock(); sourceFastBitmap.Lock();
using FastChunkyBitmap destinationFastBitmap = FastBitmap.CreateEmpty(sourceBitmap.Size, PixelFormat.Format8bppIndexed, Color.White) as FastChunkyBitmap; using FastChunkyBitmap destinationFastBitmap = FastBitmap.CreateEmpty(sourceBitmap.Size, PixelFormat.Format8bppIndexed, Color.White) as FastChunkyBitmap;
destinationFastBitmap.Lock(); destinationFastBitmap.Lock();
@ -175,15 +171,9 @@ namespace Greenshot.Base.Core
{ {
for (int x = 0; x < sourceFastBitmap.Width; x++) for (int x = 0; x < sourceFastBitmap.Width; x++)
{ {
Color color; Color color = sourceFastBitmap is not IFastBitmapWithBlend sourceFastBitmapWithBlend
if (sourceFastBitmapWithBlend == null) ? sourceFastBitmap.GetColorAt(x, y)
{ : sourceFastBitmapWithBlend.GetBlendedColorAt(x, y);
color = sourceFastBitmap.GetColorAt(x, y);
}
else
{
color = sourceFastBitmapWithBlend.GetBlendedColorAt(x, y);
}
// To count the colors // To count the colors
int index = color.ToArgb() & 0x00ffffff; int index = color.ToArgb() & 0x00ffffff;
@ -207,7 +197,7 @@ namespace Greenshot.Base.Core
// Store the initial "match" // Store the initial "match"
int paletteIndex = (indexRed << 10) + (indexRed << 6) + indexRed + (indexGreen << 5) + indexGreen + indexBlue; 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> /// <summary>
/// See <see cref="IColorQuantizer.Prepare"/> for more details. /// See <see cref="IColorQuantizer.Prepare"/> for more details.
/// </summary> /// </summary>
public int GetColorCount() public int GetColorCount() => colorCount;
{
return colorCount;
}
/// <summary> /// <summary>
/// Reindex the 24/32 BPP (A)RGB image to a 8BPP /// Reindex the 24/32 BPP (A)RGB image to a 8BPP
@ -228,13 +215,12 @@ namespace Greenshot.Base.Core
/// <returns>Bitmap</returns> /// <returns>Bitmap</returns>
public Bitmap SimpleReindex() public Bitmap SimpleReindex()
{ {
List<Color> colors = new List<Color>(); List<Color> colors = new();
Dictionary<Color, byte> lookup = new Dictionary<Color, byte>(); Dictionary<Color, byte> lookup = new();
using (FastChunkyBitmap bbbDest = FastBitmap.Create(resultBitmap) as FastChunkyBitmap) using (FastChunkyBitmap bbbDest = FastBitmap.Create(resultBitmap) as FastChunkyBitmap)
{ {
bbbDest.Lock(); bbbDest.Lock();
using IFastBitmap bbbSrc = FastBitmap.Create(sourceBitmap); using IFastBitmap bbbSrc = FastBitmap.Create(sourceBitmap);
IFastBitmapWithBlend bbbSrcBlend = bbbSrc as IFastBitmapWithBlend;
bbbSrc.Lock(); bbbSrc.Lock();
byte index; byte index;
@ -242,16 +228,7 @@ namespace Greenshot.Base.Core
{ {
for (int x = 0; x < bbbSrc.Width; x++) for (int x = 0; x < bbbSrc.Width; x++)
{ {
Color color; Color color = bbbSrc is IFastBitmapWithBlend bbbSrcBlend ? bbbSrcBlend.GetBlendedColorAt(x, y) : bbbSrc.GetColorAt(x, y);
if (bbbSrcBlend != null)
{
color = bbbSrcBlend.GetBlendedColorAt(x, y);
}
else
{
color = bbbSrc.GetColorAt(x, y);
}
if (lookup.ContainsKey(color)) if (lookup.ContainsKey(color))
{ {
index = lookup[color]; index = lookup[color];
@ -259,7 +236,7 @@ namespace Greenshot.Base.Core
else else
{ {
colors.Add(color); colors.Add(color);
index = (byte) (colors.Count - 1); index = (byte)(colors.Count - 1);
lookup.Add(color, index); lookup.Add(color, index);
} }
@ -273,14 +250,7 @@ namespace Greenshot.Base.Core
Color[] entries = imagePalette.Entries; Color[] entries = imagePalette.Entries;
for (int paletteIndex = 0; paletteIndex < 256; paletteIndex++) for (int paletteIndex = 0; paletteIndex < 256; paletteIndex++)
{ {
if (paletteIndex < colorCount) entries[paletteIndex] = paletteIndex < colorCount ? colors[paletteIndex] : Color.Black;
{
entries[paletteIndex] = colors[paletteIndex];
}
else
{
entries[paletteIndex] = Color.Black;
}
} }
resultBitmap.Palette = imagePalette; resultBitmap.Palette = imagePalette;
@ -364,9 +334,9 @@ namespace Greenshot.Base.Core
if (weight > 0) if (weight > 0)
{ {
lookupRed[k] = (int) (Volume(cubes[k], momentsRed) / weight); lookupRed[k] = (int)(Volume(cubes[k], momentsRed) / weight);
lookupGreen[k] = (int) (Volume(cubes[k], momentsGreen) / weight); lookupGreen[k] = (int)(Volume(cubes[k], momentsGreen) / weight);
lookupBlue[k] = (int) (Volume(cubes[k], momentsBlue) / weight); lookupBlue[k] = (int)(Volume(cubes[k], momentsBlue) / weight);
} }
else else
{ {
@ -386,14 +356,13 @@ namespace Greenshot.Base.Core
using (FastChunkyBitmap dest = FastBitmap.Create(resultBitmap) as FastChunkyBitmap) using (FastChunkyBitmap dest = FastBitmap.Create(resultBitmap) as FastChunkyBitmap)
{ {
using IFastBitmap src = FastBitmap.Create(sourceBitmap); using IFastBitmap src = FastBitmap.Create(sourceBitmap);
IFastBitmapWithBlend srcBlend = src as IFastBitmapWithBlend; Dictionary<Color, byte> lookup = new();
Dictionary<Color, byte> lookup = new Dictionary<Color, byte>();
for (int y = 0; y < src.Height; y++) for (int y = 0; y < src.Height; y++)
{ {
for (int x = 0; x < src.Width; x++) for (int x = 0; x < src.Width; x++)
{ {
Color color; Color color;
if (srcBlend != null) if (src is IFastBitmapWithBlend srcBlend)
{ {
// WithoutAlpha, this makes it possible to ignore the alpha // WithoutAlpha, this makes it possible to ignore the alpha
color = srcBlend.GetBlendedColorAt(x, y); color = srcBlend.GetBlendedColorAt(x, y);
@ -423,12 +392,12 @@ namespace Greenshot.Base.Core
int deltaGreen = color.G - foundGreen; int deltaGreen = color.G - foundGreen;
int deltaBlue = color.B - foundBlue; int deltaBlue = color.B - foundBlue;
int distance = deltaRed * deltaRed + deltaGreen * deltaGreen + deltaBlue * deltaBlue; int distance = (deltaRed * deltaRed) + (deltaGreen * deltaGreen) + (deltaBlue * deltaBlue);
if (distance < bestDistance) if (distance < bestDistance)
{ {
bestDistance = distance; bestDistance = distance;
bestMatch = (byte) lookupIndex; bestMatch = (byte)lookupIndex;
} }
} }
@ -450,7 +419,6 @@ namespace Greenshot.Base.Core
} }
} }
// generates palette // generates palette
ColorPalette imagePalette = resultBitmap.Palette; ColorPalette imagePalette = resultBitmap.Palette;
Color[] entries = imagePalette.Entries; Color[] entries = imagePalette.Entries;
@ -531,9 +499,7 @@ namespace Greenshot.Base.Core
/// <summary> /// <summary>
/// Computes the volume of the cube in a specific moment. /// Computes the volume of the cube in a specific moment.
/// </summary> /// </summary>
private static long Volume(WuColorCube cube, long[,,] moment) private static long Volume(WuColorCube cube, long[,,] moment) => moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] -
{
return moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] -
moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] - moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] -
moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] + moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] +
moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] - 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.GreenMaximum, cube.BlueMinimum] +
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] - moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] -
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum]; moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum];
}
/// <summary> /// <summary>
/// Computes the volume of the cube in a specific moment. For the floating-point values. /// Computes the volume of the cube in a specific moment. For the floating-point values.
/// </summary> /// </summary>
private static float VolumeFloat(WuColorCube cube, float[,,] moment) private static float VolumeFloat(WuColorCube cube, float[,,] moment) => moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] -
{
return moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] -
moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] - moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] -
moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] + moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] +
moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] - 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.GreenMaximum, cube.BlueMinimum] +
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] - moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] -
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum]; moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum];
}
/// <summary> /// <summary>
/// Splits the cube in given position, and color direction. /// Splits the cube in given position, and color direction.
/// </summary> /// </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.GreenMaximum, cube.BlueMinimum] -
moment[position, cube.GreenMinimum, cube.BlueMaximum] + moment[position, cube.GreenMinimum, cube.BlueMaximum] +
moment[position, cube.GreenMinimum, cube.BlueMinimum]), moment[position, cube.GreenMinimum, cube.BlueMinimum],
GREEN => (moment[cube.RedMaximum, position, cube.BlueMaximum] - GREEN => moment[cube.RedMaximum, position, cube.BlueMaximum] -
moment[cube.RedMaximum, position, cube.BlueMinimum] - moment[cube.RedMaximum, position, cube.BlueMinimum] -
moment[cube.RedMinimum, position, cube.BlueMaximum] + moment[cube.RedMinimum, position, cube.BlueMaximum] +
moment[cube.RedMinimum, position, cube.BlueMinimum]), moment[cube.RedMinimum, position, cube.BlueMinimum],
BLUE => (moment[cube.RedMaximum, cube.GreenMaximum, position] - BLUE => moment[cube.RedMaximum, cube.GreenMaximum, position] -
moment[cube.RedMaximum, cube.GreenMinimum, position] - moment[cube.RedMaximum, cube.GreenMinimum, position] -
moment[cube.RedMinimum, cube.GreenMaximum, position] + moment[cube.RedMinimum, cube.GreenMaximum, position] +
moment[cube.RedMinimum, cube.GreenMinimum, position]), moment[cube.RedMinimum, cube.GreenMinimum, position],
_ => 0, _ => 0,
}; };
}
/// <summary> /// <summary>
/// Splits the cube in a given color direction at its minimum. /// Splits the cube in a given color direction at its minimum.
/// </summary> /// </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.GreenMaximum, cube.BlueMinimum] +
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] - moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] -
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum]), moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum],
GREEN => (-moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] + GREEN => -moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] +
moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] + moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] +
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] - moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] -
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum]), moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum],
BLUE => (-moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] + BLUE => -moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] +
moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] + moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] +
moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] - moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] -
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum]), moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum],
_ => 0 _ => 0
}; };
}
/// <summary> /// <summary>
/// Calculates statistical variance for a given cube. /// Calculates statistical variance for a given cube.
@ -615,7 +571,7 @@ namespace Greenshot.Base.Core
float volumeMoment = VolumeFloat(cube, moments); float volumeMoment = VolumeFloat(cube, moments);
float volumeWeight = Volume(cube, weights); 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); 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) // the cube cannot be cut at bottom (this would lead to empty cube)
if (halfWeight != 0) 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; float temp = halfDistance / halfWeight;
halfRed = wholeRed - halfRed; halfRed = wholeRed - halfRed;
@ -654,7 +610,7 @@ namespace Greenshot.Base.Core
if (halfWeight != 0) 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; temp += halfDistance / halfWeight;
if (temp > result) if (temp > result)
@ -707,14 +663,7 @@ namespace Greenshot.Base.Core
} }
else else
{ {
if ((maxGreen >= maxRed) && (maxGreen >= maxBlue)) direction = (maxGreen >= maxRed) && (maxGreen >= maxBlue) ? GREEN : BLUE;
{
direction = GREEN;
}
else
{
direction = BLUE;
}
} }
second.RedMaximum = first.RedMaximum; second.RedMaximum = first.RedMaximum;
@ -762,7 +711,7 @@ namespace Greenshot.Base.Core
{ {
for (int blueIndex = cube.BlueMinimum + 1; blueIndex <= cube.BlueMaximum; ++blueIndex) 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) if (key != null)
{ {
result = (string) key.GetValue(value); result = (string)key.GetValue(value);
} }
if (string.IsNullOrEmpty(result)) if (string.IsNullOrEmpty(result))
@ -67,7 +67,7 @@ namespace Greenshot.Base.Core
{ {
if (key != null) if (key != null)
{ {
result = (string) key.GetValue(value); result = (string)key.GetValue(value);
} }
if (!string.IsNullOrEmpty(result)) return result; if (!string.IsNullOrEmpty(result)) return result;
@ -78,7 +78,7 @@ namespace Greenshot.Base.Core
{ {
if (key != null) 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>() public IReadOnlyList<TService> GetAllInstances<TService>()
{ {
var typeOfService = typeof(TService); var typeOfService = typeof(TService);
if (!_services.TryGetValue(typeOfService, out var results)) return !_services.TryGetValue(typeOfService, out var results) ? Array.Empty<TService>() : (IReadOnlyList<TService>)results.Cast<TService>().ToArray();
{
return Array.Empty<TService>();
} }
return results.Cast<TService>().ToArray(); public TService GetInstance<TService>() => GetAllInstances<TService>().SingleOrDefault();
}
public TService GetInstance<TService>()
{
return GetAllInstances<TService>().SingleOrDefault();
}
public void AddService<TService>(IEnumerable<TService> services) public void AddService<TService>(IEnumerable<TService> services)
{ {
@ -50,9 +42,6 @@ namespace Greenshot.Base.Core
} }
} }
public void AddService<TService>(params TService[] services) public void AddService<TService>(params TService[] services) => AddService(services.AsEnumerable());
{
AddService(services.AsEnumerable());
}
} }
} }

View file

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

View file

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

View file

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

View file

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

View file

@ -38,10 +38,7 @@ namespace Greenshot.Base.Core
/// </summary> /// </summary>
/// <param name="m">Message</param> /// <param name="m">Message</param>
/// <returns>true if the message should be filtered</returns> /// <returns>true if the message should be filtered</returns>
public bool PreFilterMessage(ref Message m) public bool PreFilterMessage(ref Message m) => PreFilterMessageExternal(ref m);
{
return PreFilterMessageExternal(ref m);
}
/// <summary> /// <summary>
/// Also used in the MainForm WndProc /// Also used in the MainForm WndProc
@ -50,7 +47,7 @@ namespace Greenshot.Base.Core
/// <returns>true if the message should be filtered</returns> /// <returns>true if the message should be filtered</returns>
public static bool PreFilterMessageExternal(ref Message m) 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; 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()); 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> /// </summary>
public class AdjustEffect : IEffect public class AdjustEffect : IEffect
{ {
public AdjustEffect() public AdjustEffect() => Reset();
{
Reset();
}
public float Contrast { get; set; } public float Contrast { get; set; }
public float Brightness { get; set; } public float Brightness { get; set; }
@ -46,9 +43,6 @@ namespace Greenshot.Base.Effects
Gamma = 1f; Gamma = 1f;
} }
public Image Apply(Image sourceImage, Matrix matrix) public Image Apply(Image sourceImage, Matrix matrix) => ImageHelper.Adjust(sourceImage, Brightness, Contrast, Gamma);
{
return ImageHelper.Adjust(sourceImage, Brightness, Contrast, Gamma);
}
} }
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -33,7 +33,7 @@ namespace Greenshot.Base.Help
{ {
private static readonly ILog Log = LogManager.GetLogger(typeof(HelpFileLoader)); 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() public static void LoadHelp()
{ {
@ -89,12 +89,12 @@ namespace Greenshot.Base.Help
try try
{ {
HttpWebRequest req = NetworkHelper.CreateWebRequest(url); HttpWebRequest req = NetworkHelper.CreateWebRequest(url);
using HttpWebResponse res = (HttpWebResponse) req.GetResponse(); using HttpWebResponse res = (HttpWebResponse)req.GetResponse();
return res.StatusCode; return res.StatusCode;
} }
catch (WebException e) 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)] [DispId(1014)]
[return: MarshalAs(UnmanagedType.BStr)] [return: MarshalAs(UnmanagedType.BStr)]
get; get;
[DispId(1014)] set; [DispId(1014)]
set;
} }
} }
} }

View file

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

View file

@ -71,7 +71,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT background (BSTR value); // IDL: HRESULT background (BSTR value);
// VB6: Sub background (ByVal value As String) // 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> /// <summary><para><c>backgroundAttachment</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -87,7 +88,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT backgroundAttachment (BSTR value); // IDL: HRESULT backgroundAttachment (BSTR value);
// VB6: Sub backgroundAttachment (ByVal value As String) // 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> /// <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); // IDL: HRESULT backgroundColor ([out, retval] VARIANT* ReturnValue);
// VB6: Function backgroundColor As Any // VB6: Function backgroundColor As Any
[DispId(-501)] get; [DispId(-501)]
get;
// IDL: HRESULT backgroundColor (VARIANT value); // IDL: HRESULT backgroundColor (VARIANT value);
// VB6: Sub backgroundColor (ByVal value As Any) // 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> /// <summary><para><c>backgroundImage</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -117,7 +121,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT backgroundImage (BSTR value); // IDL: HRESULT backgroundImage (BSTR value);
// VB6: Sub backgroundImage (ByVal value As String) // 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> /// <summary><para><c>backgroundPosition</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -133,7 +138,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT backgroundPosition (BSTR value); // IDL: HRESULT backgroundPosition (BSTR value);
// VB6: Sub backgroundPosition (ByVal value As String) // 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> /// <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); // IDL: HRESULT backgroundPositionX ([out, retval] VARIANT* ReturnValue);
// VB6: Function backgroundPositionX As Any // VB6: Function backgroundPositionX As Any
[DispId(-2147413079)] get; [DispId(-2147413079)]
get;
// IDL: HRESULT backgroundPositionX (VARIANT value); // IDL: HRESULT backgroundPositionX (VARIANT value);
// VB6: Sub backgroundPositionX (ByVal value As Any) // 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> /// <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); // IDL: HRESULT backgroundPositionY ([out, retval] VARIANT* ReturnValue);
// VB6: Function backgroundPositionY As Any // VB6: Function backgroundPositionY As Any
[DispId(-2147413078)] get; [DispId(-2147413078)]
get;
// IDL: HRESULT backgroundPositionY (VARIANT value); // IDL: HRESULT backgroundPositionY (VARIANT value);
// VB6: Sub backgroundPositionY (ByVal value As Any) // 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> /// <summary><para><c>backgroundRepeat</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -177,7 +187,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT backgroundRepeat (BSTR value); // IDL: HRESULT backgroundRepeat (BSTR value);
// VB6: Sub backgroundRepeat (ByVal value As String) // 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> /// <summary><para><c>border</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -193,7 +204,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT border (BSTR value); // IDL: HRESULT border (BSTR value);
// VB6: Sub border (ByVal value As String) // 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> /// <summary><para><c>borderBottom</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -209,7 +221,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT borderBottom (BSTR value); // IDL: HRESULT borderBottom (BSTR value);
// VB6: Sub borderBottom (ByVal value As String) // 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> /// <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); // IDL: HRESULT borderBottomColor ([out, retval] VARIANT* ReturnValue);
// VB6: Function borderBottomColor As Any // VB6: Function borderBottomColor As Any
[DispId(-2147413055)] get; [DispId(-2147413055)]
get;
// IDL: HRESULT borderBottomColor (VARIANT value); // IDL: HRESULT borderBottomColor (VARIANT value);
// VB6: Sub borderBottomColor (ByVal value As Any) // 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> /// <summary><para><c>borderBottomStyle</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -239,7 +254,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT borderBottomStyle (BSTR value); // IDL: HRESULT borderBottomStyle (BSTR value);
// VB6: Sub borderBottomStyle (ByVal value As String) // 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> /// <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); // IDL: HRESULT borderBottomWidth ([out, retval] VARIANT* ReturnValue);
// VB6: Function borderBottomWidth As Any // VB6: Function borderBottomWidth As Any
[DispId(-2147413050)] get; [DispId(-2147413050)]
get;
// IDL: HRESULT borderBottomWidth (VARIANT value); // IDL: HRESULT borderBottomWidth (VARIANT value);
// VB6: Sub borderBottomWidth (ByVal value As Any) // 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> /// <summary><para><c>borderColor</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -269,7 +287,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT borderColor (BSTR value); // IDL: HRESULT borderColor (BSTR value);
// VB6: Sub borderColor (ByVal value As String) // 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> /// <summary><para><c>borderLeft</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -285,7 +304,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT borderLeft (BSTR value); // IDL: HRESULT borderLeft (BSTR value);
// VB6: Sub borderLeft (ByVal value As String) // 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> /// <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); // IDL: HRESULT borderLeftColor ([out, retval] VARIANT* ReturnValue);
// VB6: Function borderLeftColor As Any // VB6: Function borderLeftColor As Any
[DispId(-2147413054)] get; [DispId(-2147413054)]
get;
// IDL: HRESULT borderLeftColor (VARIANT value); // IDL: HRESULT borderLeftColor (VARIANT value);
// VB6: Sub borderLeftColor (ByVal value As Any) // 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> /// <summary><para><c>borderLeftStyle</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -315,7 +337,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT borderLeftStyle (BSTR value); // IDL: HRESULT borderLeftStyle (BSTR value);
// VB6: Sub borderLeftStyle (ByVal value As String) // 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> /// <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); // IDL: HRESULT borderLeftWidth ([out, retval] VARIANT* ReturnValue);
// VB6: Function borderLeftWidth As Any // VB6: Function borderLeftWidth As Any
[DispId(-2147413049)] get; [DispId(-2147413049)]
get;
// IDL: HRESULT borderLeftWidth (VARIANT value); // IDL: HRESULT borderLeftWidth (VARIANT value);
// VB6: Sub borderLeftWidth (ByVal value As Any) // 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> /// <summary><para><c>borderRight</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -345,7 +370,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT borderRight (BSTR value); // IDL: HRESULT borderRight (BSTR value);
// VB6: Sub borderRight (ByVal value As String) // 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> /// <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); // IDL: HRESULT borderRightColor ([out, retval] VARIANT* ReturnValue);
// VB6: Function borderRightColor As Any // VB6: Function borderRightColor As Any
[DispId(-2147413056)] get; [DispId(-2147413056)]
get;
// IDL: HRESULT borderRightColor (VARIANT value); // IDL: HRESULT borderRightColor (VARIANT value);
// VB6: Sub borderRightColor (ByVal value As Any) // 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> /// <summary><para><c>borderRightStyle</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -375,7 +403,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT borderRightStyle (BSTR value); // IDL: HRESULT borderRightStyle (BSTR value);
// VB6: Sub borderRightStyle (ByVal value As String) // 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> /// <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); // IDL: HRESULT borderRightWidth ([out, retval] VARIANT* ReturnValue);
// VB6: Function borderRightWidth As Any // VB6: Function borderRightWidth As Any
[DispId(-2147413051)] get; [DispId(-2147413051)]
get;
// IDL: HRESULT borderRightWidth (VARIANT value); // IDL: HRESULT borderRightWidth (VARIANT value);
// VB6: Sub borderRightWidth (ByVal value As Any) // 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> /// <summary><para><c>borderStyle</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -405,7 +436,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT borderStyle (BSTR value); // IDL: HRESULT borderStyle (BSTR value);
// VB6: Sub borderStyle (ByVal value As String) // 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> /// <summary><para><c>borderTop</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -421,7 +453,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT borderTop (BSTR value); // IDL: HRESULT borderTop (BSTR value);
// VB6: Sub borderTop (ByVal value As String) // 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> /// <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); // IDL: HRESULT borderTopColor ([out, retval] VARIANT* ReturnValue);
// VB6: Function borderTopColor As Any // VB6: Function borderTopColor As Any
[DispId(-2147413057)] get; [DispId(-2147413057)]
get;
// IDL: HRESULT borderTopColor (VARIANT value); // IDL: HRESULT borderTopColor (VARIANT value);
// VB6: Sub borderTopColor (ByVal value As Any) // 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> /// <summary><para><c>borderTopStyle</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -451,7 +486,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT borderTopStyle (BSTR value); // IDL: HRESULT borderTopStyle (BSTR value);
// VB6: Sub borderTopStyle (ByVal value As String) // 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> /// <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); // IDL: HRESULT borderTopWidth ([out, retval] VARIANT* ReturnValue);
// VB6: Function borderTopWidth As Any // VB6: Function borderTopWidth As Any
[DispId(-2147413052)] get; [DispId(-2147413052)]
get;
// IDL: HRESULT borderTopWidth (VARIANT value); // IDL: HRESULT borderTopWidth (VARIANT value);
// VB6: Sub borderTopWidth (ByVal value As Any) // 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> /// <summary><para><c>borderWidth</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -481,7 +519,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT borderWidth (BSTR value); // IDL: HRESULT borderWidth (BSTR value);
// VB6: Sub borderWidth (ByVal value As String) // 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> /// <summary><para><c>clear</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -497,7 +536,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT clear (BSTR value); // IDL: HRESULT clear (BSTR value);
// VB6: Sub clear (ByVal value As String) // 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> /// <summary><para><c>clip</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -513,7 +553,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT clip (BSTR value); // IDL: HRESULT clip (BSTR value);
// VB6: Sub clip (ByVal value As String) // 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> /// <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); // IDL: HRESULT color ([out, retval] VARIANT* ReturnValue);
// VB6: Function color As Any // VB6: Function color As Any
[DispId(-2147413110)] get; [DispId(-2147413110)]
get;
// IDL: HRESULT color (VARIANT value); // IDL: HRESULT color (VARIANT value);
// VB6: Sub color (ByVal value As Any) // 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> /// <summary><para><c>cssText</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -543,7 +586,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT cssText (BSTR value); // IDL: HRESULT cssText (BSTR value);
// VB6: Sub cssText (ByVal value As String) // 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> /// <summary><para><c>cursor</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -559,7 +603,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT cursor (BSTR value); // IDL: HRESULT cursor (BSTR value);
// VB6: Sub cursor (ByVal value As String) // 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> /// <summary><para><c>display</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -575,7 +620,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT display (BSTR value); // IDL: HRESULT display (BSTR value);
// VB6: Sub display (ByVal value As String) // 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> /// <summary><para><c>filter</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -591,7 +637,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT filter (BSTR value); // IDL: HRESULT filter (BSTR value);
// VB6: Sub filter (ByVal value As String) // 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> /// <summary><para><c>font</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -607,7 +654,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT font (BSTR value); // IDL: HRESULT font (BSTR value);
// VB6: Sub font (ByVal value As String) // 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> /// <summary><para><c>fontFamily</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -623,7 +671,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT fontFamily (BSTR value); // IDL: HRESULT fontFamily (BSTR value);
// VB6: Sub fontFamily (ByVal value As String) // 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> /// <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); // IDL: HRESULT fontSize ([out, retval] VARIANT* ReturnValue);
// VB6: Function fontSize As Any // VB6: Function fontSize As Any
[DispId(-2147413093)] get; [DispId(-2147413093)]
get;
// IDL: HRESULT fontSize (VARIANT value); // IDL: HRESULT fontSize (VARIANT value);
// VB6: Sub fontSize (ByVal value As Any) // 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> /// <summary><para><c>fontStyle</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -653,7 +704,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT fontStyle (BSTR value); // IDL: HRESULT fontStyle (BSTR value);
// VB6: Sub fontStyle (ByVal value As String) // 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> /// <summary><para><c>fontVariant</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -669,7 +721,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT fontVariant (BSTR value); // IDL: HRESULT fontVariant (BSTR value);
// VB6: Sub fontVariant (ByVal value As String) // 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> /// <summary><para><c>fontWeight</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -685,7 +738,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT fontWeight (BSTR value); // IDL: HRESULT fontWeight (BSTR value);
// VB6: Sub fontWeight (ByVal value As String) // 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> /// <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); // IDL: HRESULT height ([out, retval] VARIANT* ReturnValue);
// VB6: Function height As Any // VB6: Function height As Any
[DispId(-2147418106)] get; [DispId(-2147418106)]
get;
// IDL: HRESULT height (VARIANT value); // IDL: HRESULT height (VARIANT value);
// VB6: Sub height (ByVal value As Any) // 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> /// <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); // IDL: HRESULT left ([out, retval] VARIANT* ReturnValue);
// VB6: Function left As Any // VB6: Function left As Any
[DispId(-2147418109)] get; [DispId(-2147418109)]
get;
// IDL: HRESULT left (VARIANT value); // IDL: HRESULT left (VARIANT value);
// VB6: Sub left (ByVal value As Any) // 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> /// <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); // IDL: HRESULT letterSpacing ([out, retval] VARIANT* ReturnValue);
// VB6: Function letterSpacing As Any // VB6: Function letterSpacing As Any
[DispId(-2147413104)] get; [DispId(-2147413104)]
get;
// IDL: HRESULT letterSpacing (VARIANT value); // IDL: HRESULT letterSpacing (VARIANT value);
// VB6: Sub letterSpacing (ByVal value As Any) // 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> /// <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); // IDL: HRESULT lineHeight ([out, retval] VARIANT* ReturnValue);
// VB6: Function lineHeight As Any // VB6: Function lineHeight As Any
[DispId(-2147413106)] get; [DispId(-2147413106)]
get;
// IDL: HRESULT lineHeight (VARIANT value); // IDL: HRESULT lineHeight (VARIANT value);
// VB6: Sub lineHeight (ByVal value As Any) // 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> /// <summary><para><c>listStyle</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -757,7 +819,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT listStyle (BSTR value); // IDL: HRESULT listStyle (BSTR value);
// VB6: Sub listStyle (ByVal value As String) // 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> /// <summary><para><c>listStyleImage</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -773,7 +836,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT listStyleImage (BSTR value); // IDL: HRESULT listStyleImage (BSTR value);
// VB6: Sub listStyleImage (ByVal value As String) // 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> /// <summary><para><c>listStylePosition</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -789,7 +853,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT listStylePosition (BSTR value); // IDL: HRESULT listStylePosition (BSTR value);
// VB6: Sub listStylePosition (ByVal value As String) // 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> /// <summary><para><c>listStyleType</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -805,7 +870,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT listStyleType (BSTR value); // IDL: HRESULT listStyleType (BSTR value);
// VB6: Sub listStyleType (ByVal value As String) // 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> /// <summary><para><c>margin</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -821,7 +887,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT margin (BSTR value); // IDL: HRESULT margin (BSTR value);
// VB6: Sub margin (ByVal value As String) // 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> /// <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); // IDL: HRESULT marginBottom ([out, retval] VARIANT* ReturnValue);
// VB6: Function marginBottom As Any // VB6: Function marginBottom As Any
[DispId(-2147413073)] get; [DispId(-2147413073)]
get;
// IDL: HRESULT marginBottom (VARIANT value); // IDL: HRESULT marginBottom (VARIANT value);
// VB6: Sub marginBottom (ByVal value As Any) // 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> /// <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); // IDL: HRESULT marginLeft ([out, retval] VARIANT* ReturnValue);
// VB6: Function marginLeft As Any // VB6: Function marginLeft As Any
[DispId(-2147413072)] get; [DispId(-2147413072)]
get;
// IDL: HRESULT marginLeft (VARIANT value); // IDL: HRESULT marginLeft (VARIANT value);
// VB6: Sub marginLeft (ByVal value As Any) // 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> /// <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); // IDL: HRESULT marginRight ([out, retval] VARIANT* ReturnValue);
// VB6: Function marginRight As Any // VB6: Function marginRight As Any
[DispId(-2147413074)] get; [DispId(-2147413074)]
get;
// IDL: HRESULT marginRight (VARIANT value); // IDL: HRESULT marginRight (VARIANT value);
// VB6: Sub marginRight (ByVal value As Any) // 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> /// <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); // IDL: HRESULT marginTop ([out, retval] VARIANT* ReturnValue);
// VB6: Function marginTop As Any // VB6: Function marginTop As Any
[DispId(-2147413075)] get; [DispId(-2147413075)]
get;
// IDL: HRESULT marginTop (VARIANT value); // IDL: HRESULT marginTop (VARIANT value);
// VB6: Sub marginTop (ByVal value As Any) // 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> /// <summary><para><c>overflow</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -893,7 +968,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT overflow (BSTR value); // IDL: HRESULT overflow (BSTR value);
// VB6: Sub overflow (ByVal value As String) // 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> /// <summary><para><c>padding</c> property of <c>IHTMLStyle</c> interface.</para></summary>
@ -909,7 +985,8 @@ namespace Greenshot.Base.IEInterop
get; get;
// IDL: HRESULT padding (BSTR value); // IDL: HRESULT padding (BSTR value);
// VB6: Sub padding (ByVal value As String) // 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> /// <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); // IDL: HRESULT paddingBottom ([out, retval] VARIANT* ReturnValue);
// VB6: Function paddingBottom As Any // VB6: Function paddingBottom As Any
[DispId(-2147413098)] get; [DispId(-2147413098)]
get;
// IDL: HRESULT paddingBottom (VARIANT value); // IDL: HRESULT paddingBottom (VARIANT value);
// VB6: Sub paddingBottom (ByVal value As Any) // 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> /// <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); // IDL: HRESULT paddingLeft ([out, retval] VARIANT* ReturnValue);
// VB6: Function paddingLeft As Any // VB6: Function paddingLeft As Any
[DispId(-2147413097)] get; [DispId(-2147413097)]
get;
// IDL: HRESULT paddingLeft (VARIANT value); // IDL: HRESULT paddingLeft (VARIANT value);
// VB6: Sub paddingLeft (ByVal value As Any) // 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> /// <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)] [DispId(1004)]
[return: MarshalAs(UnmanagedType.BStr)] [return: MarshalAs(UnmanagedType.BStr)]
get; get;
[DispId(1004)] set; [DispId(1004)]
set;
} }
} }
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -43,7 +43,7 @@ namespace Greenshot.Base.Interop
/// </exception> /// </exception>
public static ComProgIdAttribute GetAttribute(Type interfaceType) public static ComProgIdAttribute GetAttribute(Type interfaceType)
{ {
if (null == interfaceType) if (interfaceType == null)
{ {
throw new ArgumentNullException(nameof(interfaceType)); throw new ArgumentNullException(nameof(interfaceType));
} }
@ -51,34 +51,26 @@ namespace Greenshot.Base.Interop
Type attributeType = typeof(ComProgIdAttribute); Type attributeType = typeof(ComProgIdAttribute);
object[] attributes = interfaceType.GetCustomAttributes(attributeType, false); object[] attributes = interfaceType.GetCustomAttributes(attributeType, false);
if (0 == attributes.Length) if (attributes.Length == 0)
{ {
Type[] interfaces = interfaceType.GetInterfaces(); Type[] interfaces = interfaceType.GetInterfaces();
foreach (Type t in interfaces) foreach (Type t in interfaces)
{ {
interfaceType = t; interfaceType = t;
attributes = interfaceType.GetCustomAttributes(attributeType, false); attributes = interfaceType.GetCustomAttributes(attributeType, false);
if (0 != attributes.Length) if (attributes.Length != 0)
{ {
break; break;
} }
} }
} }
if (0 == attributes.Length) return attributes.Length == 0 ? null : (ComProgIdAttribute)attributes[0];
{
return null;
}
return (ComProgIdAttribute) attributes[0];
} }
/// <summary>Constructor</summary> /// <summary>Constructor</summary>
/// <param name="value">The COM ProgID.</param> /// <param name="value">The COM ProgID.</param>
public ComProgIdAttribute(string value) public ComProgIdAttribute(string value) => Value = value;
{
Value = value;
}
/// <summary> /// <summary>
/// Returns the COM ProgID /// 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")] [IniProperty("DefaultEditorSize", Description = "The size for the editor when it's opened without a capture", DefaultValue = "500,500")]
public NativeSize DefaultEditorSize { get; set; } public NativeSize DefaultEditorSize { get; set; }
public override void AfterLoad() public override void AfterLoad()
{ {
base.AfterLoad(); base.AfterLoad();
@ -140,15 +139,8 @@ namespace Greenshot.Editor.Configuration
LastUsedFieldValues ??= new Dictionary<string, object>(); LastUsedFieldValues ??= new Dictionary<string, object>();
// check if settings for the requesting type exist, if not create! // check if settings for the requesting type exist, if not create!
if (LastUsedFieldValues.ContainsKey(requestedField))
{
LastUsedFieldValues[requestedField] = field.Value; LastUsedFieldValues[requestedField] = field.Value;
} }
else
{
LastUsedFieldValues.Add(requestedField, field.Value);
}
}
public void ResetEditorPlacement() 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.")] [Category("Greenshot"), DefaultValue(null), Description("Specifies key of the language file to use when displaying the text.")]
public string LanguageKey { get; set; } public string LanguageKey { get; set; }
public BindableToolStripButton() public BindableToolStripButton() => CheckedChanged += BindableToolStripButton_CheckedChanged;
{
CheckedChanged += BindableToolStripButton_CheckedChanged;
}
private void BindableToolStripButton_CheckedChanged(object sender, EventArgs e) private void BindableToolStripButton_CheckedChanged(object sender, EventArgs e) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Checked"));
{
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.")] [Category("Greenshot"), DefaultValue(null), Description("Specifies key of the language file to use when displaying the text.")]
public string LanguageKey { get; set; } public string LanguageKey { get; set; }
public BindableToolStripComboBox() public BindableToolStripComboBox() => SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged;
{
SelectedIndexChanged += BindableToolStripComboBox_SelectedIndexChanged;
}
private void BindableToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e) private void BindableToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedItem"));
{
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; if (Tag == null && DropDownItems.Count > 0) Tag = DropDownItems[0].Tag;
return Tag; return Tag;
} }
set { AdoptFromTag(value); } set => AdoptFromTag(value);
} }
protected override void OnDropDownItemClicked(ToolStripItemClickedEventArgs e) protected override void OnDropDownItemClicked(ToolStripItemClickedEventArgs e)
{ {
ToolStripItem clickedItem = e.ClickedItem; ToolStripItem clickedItem = e.ClickedItem;
if (Tag == null || !Tag.Equals(clickedItem.Tag)) if (Tag?.Equals(clickedItem.Tag) != true)
{ {
Tag = clickedItem.Tag; Tag = clickedItem.Tag;
Image = clickedItem.Image; Image = clickedItem.Image;
@ -62,12 +62,12 @@ namespace Greenshot.Editor.Controls
private void AdoptFromTag(object tag) private void AdoptFromTag(object tag)
{ {
if (Tag == null || !Tag.Equals(tag)) if (Tag?.Equals(tag) != true)
{ {
Tag = tag; Tag = tag;
foreach (ToolStripItem item in DropDownItems) foreach (ToolStripItem item in DropDownItems)
{ {
if (item.Tag != null && item.Tag.Equals(tag)) if (item.Tag?.Equals(tag) == true)
{ {
Image = item.Image; Image = item.Image;
break; 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.")] [Category("Greenshot"), DefaultValue(null), Description("Specifies key of the language file to use when displaying the text.")]
public string LanguageKey { get; set; } public string LanguageKey { get; set; }
public ColorButton() public ColorButton() => Click += ColorButtonClick;
{
Click += ColorButtonClick;
}
public Color SelectedColor public Color SelectedColor
{ {
get { return _selectedColor; } get => _selectedColor;
set set
{ {
_selectedColor = value; _selectedColor = value;
Brush brush; Brush brush = value != Color.Transparent ? new SolidBrush(value) : new HatchBrush(HatchStyle.Percent50, Color.White, Color.Gray);
if (value != Color.Transparent)
{
brush = new SolidBrush(value);
}
else
{
brush = new HatchBrush(HatchStyle.Percent50, Color.White, Color.Gray);
}
if (Image != null) if (Image != null)
{ {
using Graphics graphics = Graphics.FromImage(Image); using Graphics graphics = Graphics.FromImage(Image);

View file

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

View file

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

View file

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