Deal with warnings

This commit is contained in:
Michael Adams 2022-07-14 14:31:31 -07:00
commit de6644b543
223 changed files with 1431 additions and 3817 deletions

View file

@ -94,6 +94,14 @@ dotnet_diagnostic.S4136.severity = silent
# IDE1006: Naming Styles # IDE1006: Naming Styles
dotnet_diagnostic.IDE1006.severity = none 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}] [*.{cs,vb}]
#### Naming styles #### #### Naming styles ####

View file

@ -54,17 +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
return IsTerminalServerSession ? 1 : milliseconds / VRefresh; IsTerminalServerSession ? 1 : 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
@ -114,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,15 +53,14 @@ 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)
{ {
@ -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

@ -40,29 +40,20 @@ namespace Greenshot.Base.Controls
{ {
} }
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

@ -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)
{ {
@ -108,9 +105,6 @@ namespace Greenshot.Base.Controls
/// 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

@ -72,15 +72,9 @@ 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) ||
{
get
{
return (Application.ExecutablePath.IndexOf("devenv.exe", StringComparison.OrdinalIgnoreCase) > -1) ||
Application.ExecutablePath.IndexOf("sharpdevelop.exe", StringComparison.OrdinalIgnoreCase) > -1 || Application.ExecutablePath.IndexOf("sharpdevelop.exe", StringComparison.OrdinalIgnoreCase) > -1 ||
(Application.ExecutablePath.IndexOf("wdexpress.exe", StringComparison.OrdinalIgnoreCase) > -1); (Application.ExecutablePath.IndexOf("wdexpress.exe", StringComparison.OrdinalIgnoreCase) > -1);
}
}
#endif #endif
protected bool ManualLanguageApply { get; set; } protected bool ManualLanguageApply { get; set; }
@ -92,10 +86,7 @@ namespace Greenshot.Base.Controls
/// </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
@ -148,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
@ -162,7 +151,6 @@ namespace Greenshot.Base.Controls
// ignored // ignored
} }
} }
}
base.OnPaint(e); base.OnPaint(e);
} }
@ -215,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 && !ManualStoreFields) 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);
} }

View file

@ -243,10 +243,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
@ -336,7 +333,7 @@ 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))
@ -344,7 +341,7 @@ namespace Greenshot.Base.Controls
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;
} }
@ -384,10 +381,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,10 +390,7 @@ 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)
{ {
@ -427,10 +418,7 @@ namespace Greenshot.Base.Controls
return hotkeyString.ToString(); return hotkeyString.ToString();
} }
public static string HotkeyToLocalizedString(Keys modifierKeyCode, Keys virtualKeyCode) public static string HotkeyToLocalizedString(Keys modifierKeyCode, Keys virtualKeyCode) => HotkeyModifiersToLocalizedString(modifierKeyCode) + GetKeyName(virtualKeyCode);
{
return HotkeyModifiersToLocalizedString(modifierKeyCode) + GetKeyName(virtualKeyCode);
}
public static string HotkeyModifiersToLocalizedString(Keys modifierKeyCode) public static string HotkeyModifiersToLocalizedString(Keys modifierKeyCode)
{ {
@ -463,22 +451,22 @@ namespace Greenshot.Base.Controls
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;
} }
@ -503,10 +491,7 @@ namespace Greenshot.Base.Controls
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

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)
{ {
@ -126,7 +123,7 @@ namespace Greenshot.Base.Controls
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 fo = new()
{ {
Label = ifo.ToUpper(), Label = ifo.ToUpper(),
@ -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
{ {

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

@ -86,13 +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
{
return (CoreConfig.ExcludeDestinations?.Contains(Designation)) != true;
}
}
public abstract ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails); public abstract ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails);
@ -129,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.
@ -188,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)
@ -235,7 +226,7 @@ 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;
@ -311,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);

View file

@ -86,15 +86,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)
{ {
@ -194,9 +188,7 @@ namespace Greenshot.Base.Core
{ {
_ = tab.accessible.get_accState(CHILDID_SELF); _ = 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;
@ -206,17 +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

@ -110,22 +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
{
return _queue.Count == 0 ? Last : _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
@ -146,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
@ -167,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
@ -204,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 switch
{ {
EasingMode.EaseOut => Easing.EaseOut(CurrentFrameNr / (double)Frames, EasingType), EasingMode.EaseOut => Easing.EaseOut(CurrentFrameNr / (double)Frames, EasingType),
EasingMode.EaseInOut => Easing.EaseInOut(CurrentFrameNr / (double)Frames, EasingType), EasingMode.EaseInOut => Easing.EaseInOut(CurrentFrameNr / (double)Frames, EasingType),
EasingMode.EaseIn => Easing.EaseIn(CurrentFrameNr / (double)Frames, EasingType), EasingMode.EaseIn => Easing.EaseIn(CurrentFrameNr / (double)Frames, EasingType),
_ => 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
@ -252,13 +230,7 @@ namespace Greenshot.Base.Core
/// <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
{
return CurrentFrameNr < Frames || _queue.Count > 0;
}
}
/// <summary> /// <summary>
/// Get the next animation frame value object /// Get the next animation frame value object
@ -515,10 +487,7 @@ 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
@ -535,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)
{ {

View file

@ -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
@ -87,10 +78,7 @@ namespace Greenshot.Base.Core
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;
@ -162,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
@ -234,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,10 +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;
{
MetaData[key] = value;
}
/// <inheritdoc /> /// <inheritdoc />
public CaptureMode CaptureMode { get; set; } public CaptureMode CaptureMode { get; set; }
@ -66,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)
@ -92,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

@ -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;
} }
@ -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
@ -885,10 +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;
{
return ContainsText(dataObject) ? (string)dataObject.GetData(DataFormats.Text) : null;
}
/// <summary> /// <summary>
/// Set text to the clipboard /// Set text to the clipboard
@ -1177,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
@ -1210,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;
} }
@ -1228,10 +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;
{
return type != null ? GetFromDataObject(dataObj, type.FullName) : null;
}
/// <summary> /// <summary>
/// Get ImageFilenames from the IDataObject /// Get ImageFilenames from the IDataObject

View file

@ -365,7 +365,7 @@ namespace Greenshot.Base.Core
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?.Contains(experimentalFeature) == true;
}
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?.Contains("OneNote") == true) if (ExcludeDestinations?.Contains("OneNote") == true && LastSaveWithVersion?.StartsWith("1.1") == true)
{
if (LastSaveWithVersion?.StartsWith("1.1") == true)
{ {
ExcludeDestinations.Remove("OneNote"); ExcludeDestinations.Remove("OneNote");
} }
}
if (OutputDestinations == null) 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

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

View file

@ -37,12 +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?.Contains(destination.Designation) != true).OrderBy(p => p.Priority).ThenBy(p => p.Description);
}
/// <summary> /// <summary>
/// Get a destination by a designation /// Get a destination by a designation
@ -56,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;
} }
@ -74,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

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

@ -20,10 +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);
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{ {
@ -53,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);
@ -108,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":
@ -206,17 +200,12 @@ namespace Greenshot.Base.Core
} }
} }
private void RetrieveDropShadowEffectValues(DropShadowEffect effect, StringBuilder sb) private void RetrieveDropShadowEffectValues(DropShadowEffect effect, StringBuilder sb) =>
{
// Fix to prevent BUG-1753 is to use the numberFormatInfo // 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)
{ {
@ -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,9 +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;
else if (majorVersion == 5) case 5:
{
if (productType == WindowsProductTypes.VER_NT_WORKSTATION) if (productType == WindowsProductTypes.VER_NT_WORKSTATION)
{ {
if ((suiteMask & WindowsSuites.Personal) != 0) if ((suiteMask & WindowsSuites.Personal) != 0)
@ -333,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
@ -350,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
@ -373,15 +371,13 @@ namespace Greenshot.Base.Core
// Windows Server 2003 Standard Edition // Windows Server 2003 Standard Edition
edition = "Standard"; edition = "Standard";
} }
break;
} }
} }
} break;
else if (majorVersion == 6) case 6 when Kernel32Api.GetProductInfo(majorVersion, minorVersion, osVersionInfo.ServicePackMajor, osVersionInfo.ServicePackMinor, out var windowsProduct):
{
if (Kernel32Api.GetProductInfo(majorVersion, minorVersion, osVersionInfo.ServicePackMajor, osVersionInfo.ServicePackMinor, out var windowsProduct))
{
edition = windowsProduct.GetEnumDescription(); edition = windowsProduct.GetEnumDescription();
} break;
} }
} }
@ -423,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:

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,35 +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
{
return Area == NativeRect.Empty ? (NativeSize)Bitmap.Size : 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
{
return Area == NativeRect.Empty ? Bitmap.Width : 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
{
return Area == NativeRect.Empty ? Bitmap.Height : Area.Height;
}
}
private int _left; private int _left;
@ -532,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;
@ -580,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
@ -609,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);
@ -653,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)
{ {
@ -696,10 +654,7 @@ namespace Greenshot.Base.Core
private readonly Color[] _colorEntries; private readonly Color[] _colorEntries;
private readonly Dictionary<Color, byte> _colorCache = new(); 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
@ -720,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
@ -731,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
@ -934,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

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
@ -98,13 +95,12 @@ namespace Greenshot.Base.Core.FileFormatHandlers
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;
} }

View file

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

View file

@ -31,19 +31,10 @@ namespace Greenshot.Base.Core
{ {
private static readonly ComponentResourceManager GreenshotResourceManager = new(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

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

View file

@ -244,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;
} }
@ -811,16 +808,9 @@ namespace Greenshot.Base.Core
{ {
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(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);
@ -897,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
@ -1130,23 +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);
{
return sourceImage is Metafile ? (Image)sourceImage.Clone() : 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
@ -1154,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:
@ -1176,14 +1154,9 @@ namespace Greenshot.Base.Core
NativeRect bitmapRect = new(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)
@ -1192,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;
} }
} }
@ -1369,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

View file

@ -84,21 +84,18 @@ namespace Greenshot.Base.Core
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)
@ -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

@ -328,13 +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
{
return HelpFiles.ContainsKey(_currentLanguage) ? HelpFiles[_currentLanguage] : HelpFiles[DefaultLanguage];
}
}
/// <summary> /// <summary>
/// Load the resources from the language file /// Load the resources from the language file
@ -573,20 +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);
{
return key != null && Resources.ContainsKey(key);
}
/// <summary> /// <summary>
/// TryGet method which combines HasKey & GetString /// TryGet method which combines HasKey & GetString
@ -594,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
@ -606,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
@ -618,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
@ -640,10 +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());
{
return key == null ? null : GetString(key.ToString());
}
/// <summary> /// <summary>
/// Get the resource for prefix.key /// Get the resource for prefix.key
@ -651,10 +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);
{
return key == null ? null : GetString(prefix + "." + key);
}
/// <summary> /// <summary>
/// Get the resource for prefix.key /// Get the resource for prefix.key
@ -662,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
@ -688,10 +658,7 @@ namespace Greenshot.Base.Core
/// <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 with string.format an supply the parameters
@ -700,10 +667,7 @@ namespace Greenshot.Base.Core
/// <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 with string.format an supply the parameters
@ -712,10 +676,7 @@ namespace Greenshot.Base.Core
/// <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 with string.format an supply the parameters
@ -723,9 +684,6 @@ namespace Greenshot.Base.Core
/// <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);
{
return !Resources.TryGetValue(key, out var returnValue) ? "string ###" + key + "### not found" : string.Format(returnValue, param);
}
} }
} }

View file

@ -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
@ -593,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
@ -766,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

@ -71,13 +71,7 @@ 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
{
return !string.IsNullOrEmpty(_redirectUri) ? _redirectUri : (_redirectUri = string.Format(LoopbackCallbackUrl, GetRandomUnusedPort()));
}
}
private string _cloudServiceName; private string _cloudServiceName;

View file

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

@ -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
{ {
@ -219,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
@ -270,9 +269,7 @@ namespace Greenshot.Base.Core.OAuth
Log.DebugFormat("Opening AuthorizationLink: {0}", AuthorizationLink); Log.DebugFormat("Opening AuthorizationLink: {0}", AuthorizationLink);
OAuthLoginForm oAuthLoginForm = new(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))
{ {
@ -284,7 +281,6 @@ namespace Greenshot.Base.Core.OAuth
Verifier = verifierValue; Verifier = verifierValue;
} }
} }
}
if (CheckVerifier) if (CheckVerifier)
{ {
@ -383,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.
@ -399,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.
@ -415,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.
@ -444,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
{ {
@ -480,14 +464,9 @@ namespace Greenshot.Base.Core.OAuth
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> 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);
@ -632,14 +611,11 @@ 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);

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

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.
@ -174,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 (sourceFastBitmap is not IFastBitmapWithBlend sourceFastBitmapWithBlend) ? 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;
@ -216,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
@ -240,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 (bbbSrc is IFastBitmapWithBlend bbbSrcBlend)
{
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];
@ -271,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;
@ -527,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] -
@ -537,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] -
@ -552,14 +519,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>
/// 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] -
@ -575,14 +539,11 @@ namespace Greenshot.Base.Core
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] +
@ -598,7 +559,6 @@ namespace Greenshot.Base.Core
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.
@ -703,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;

View file

@ -20,10 +20,7 @@ namespace Greenshot.Base.Core
return !_services.TryGetValue(typeOfService, out var results) ? Array.Empty<TService>() : (IReadOnlyList<TService>)results.Cast<TService>().ToArray(); return !_services.TryGetValue(typeOfService, out var results) ? Array.Empty<TService>() : (IReadOnlyList<TService>)results.Cast<TService>().ToArray();
} }
public TService GetInstance<TService>() public TService GetInstance<TService>() => GetAllInstances<TService>().SingleOrDefault();
{
return GetAllInstances<TService>().SingleOrDefault();
}
public void AddService<TService>(IEnumerable<TService> services) public void AddService<TService>(IEnumerable<TService> services)
{ {
@ -45,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
@ -85,7 +82,7 @@ namespace Greenshot.Base.Core
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
List<object> values = new(); 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"];

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
@ -338,13 +336,9 @@ namespace Greenshot.Base.Core
{ {
// Collect all screens inside this capture // Collect all screens inside this capture
List<Screen> screensInsideCapture = new(); 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;

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;
@ -106,15 +103,9 @@ namespace Greenshot.Base.Core
/// 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
@ -144,18 +135,12 @@ namespace Greenshot.Base.Core
/// <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
@ -270,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
{ {
@ -302,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;
} }
@ -361,10 +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);
{
return _childWindows ?? GetChildren(0);
}
/// <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
@ -467,22 +442,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
return !IsCloaked && User32Api.IsWindowVisible(Handle); !IsCloaked && User32Api.IsWindowVisible(Handle);
}
}
public bool HasParent public bool HasParent
{ {
@ -543,15 +510,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)
{ {
@ -564,14 +528,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
@ -588,18 +549,12 @@ namespace Greenshot.Base.Core
/// <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)
@ -623,10 +578,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,
@ -796,10 +748,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;
@ -810,7 +760,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()
@ -894,13 +843,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))
@ -914,8 +859,6 @@ namespace Greenshot.Base.Core
RemoveCorners(capturedBitmap); RemoveCorners(capturedBitmap);
} }
} }
}
}
finally finally
{ {
// Make sure to ALWAYS unfreeze!! // Make sure to ALWAYS unfreeze!!
@ -1076,14 +1019,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;
} }
@ -1146,10 +1082,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
@ -1178,7 +1111,7 @@ namespace Greenshot.Base.Core
return false; return false;
} }
if (titleOrProcessname.ToLower().Contains("greenshot")) if (titleOrProcessname.IndexOf("greenshot", StringComparison.CurrentCultureIgnoreCase) >= 0)
{ {
return false; return false;
} }
@ -1339,10 +1272,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
@ -1370,28 +1300,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"
@ -1618,13 +1539,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
{
return AppVisibility != null && AppVisibility.IsLauncherVisible;
}
}
/// <summary> /// <summary>
/// Make a string representation of the window details /// Make a string representation of the window details

View file

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

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,17 +34,11 @@ 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)
{ {

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

@ -29,10 +29,7 @@ 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 Description;
public string Name { get; set; } public string Name { get; set; }
@ -44,15 +41,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
{ {
@ -152,15 +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
{
get
{
return IsInitialized
? CreateIniLocation(_configName + IniExtension, false) ? CreateIniLocation(_configName + IniExtension, false)
: throw new InvalidOperationException("Ini configuration was not initialized!"); : throw new InvalidOperationException("Ini configuration was not initialized!");
}
}
/// <summary> /// <summary>
/// Create the location of the configuration file /// Create the location of the configuration file
@ -325,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
@ -409,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>
/// ///

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,21 +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
{
return iniSectionAttribute ??= GetIniSectionAttribute(GetType());
}
}
/// <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
@ -65,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
@ -77,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
@ -129,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)
{ {
@ -161,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);
@ -202,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

@ -59,7 +59,7 @@ namespace Greenshot.Base.IniFile
{ {
get get
{ {
return Attributes != null && Attributes.FixedValue; return Attributes?.FixedValue == true;
} }
set set
{ {
@ -77,7 +77,7 @@ namespace Greenshot.Base.IniFile
{ {
get get
{ {
return Attributes != null && Attributes.Expert; return Attributes?.Expert == true;
} }
set set
{ {
@ -98,13 +98,7 @@ 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
{
return _propertyInfo == null ? _fieldInfo : _propertyInfo;
}
}
/// <summary> /// <summary>
/// Returns the IniSection this value is contained in /// Returns the IniSection this value is contained in
@ -193,13 +187,10 @@ namespace Greenshot.Base.IniFile
} }
} }
if (myValue == null) if (myValue == null && Attributes.ExcludeIfNull)
{
if (Attributes.ExcludeIfNull)
{ {
return; return;
} }
}
if (!onlyProperties) if (!onlyProperties)
{ {
@ -520,10 +511,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

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

@ -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.
@ -84,7 +75,7 @@ namespace Greenshot.Base.Interfaces.Plugin
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!
return OutputFormat.gif.Equals(Format) || _reduceColors; return !(!OutputFormat.gif.Equals(Format) && !_reduceColors);
} }
set { _reduceColors = value; } set { _reduceColors = value; }
} }

View file

@ -232,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.
@ -243,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.
@ -259,13 +253,10 @@ namespace Greenshot.Base.Interop
/// </returns> /// </returns>
public override bool Equals(object value) public override bool Equals(object value)
{ {
if (value != null && RemotingServices.IsTransparentProxy(value)) if (value != null && RemotingServices.IsTransparentProxy(value) && RemotingServices.GetRealProxy(value) is COMWrapper wrapper)
{
if (RemotingServices.GetRealProxy(value) is COMWrapper wrapper)
{ {
return _comObject == wrapper._comObject; return _comObject == wrapper._comObject;
} }
}
return base.Equals(value); return base.Equals(value);
} }
@ -559,9 +550,7 @@ namespace Greenshot.Base.Interop
{ {
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 (wrapper != null && wrapper._comObject != arg) if (wrapper != null && wrapper._comObject != arg)
@ -577,7 +566,6 @@ namespace Greenshot.Base.Interop
arg = wrapper.GetTransparentProxy(); arg = wrapper.GetTransparentProxy();
} }
}
outArgs[i] = arg; outArgs[i] = arg;
} }

View file

@ -70,10 +70,7 @@ namespace Greenshot.Base.Interop
/// <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

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

@ -41,10 +41,7 @@ namespace Greenshot.Editor.Controls
[Category("Greenshot"), DefaultValue(null), Description("Specifies key of the language file to use when displaying the text.")] [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
{ {
@ -53,16 +50,7 @@ namespace Greenshot.Editor.Controls
{ {
_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

@ -29,12 +29,10 @@ namespace Greenshot.Editor.Controls
/// </summary> /// </summary>
public class NonJumpingPanel : Panel public class NonJumpingPanel : Panel
{ {
protected override Point ScrollToControl(Control activeControl) protected override Point ScrollToControl(Control activeControl) =>
{
// Returning the current location prevents the panel from // Returning the current location prevents the panel from
// scrolling to the active control when the panel loses and regains focus // scrolling to the active control when the panel loses and regains focus
return DisplayRectangle.Location; DisplayRectangle.Location;
}
/// <summary> /// <summary>
/// Add horizontal scrolling to the panel, when using the wheel and the shift key is pressed /// Add horizontal scrolling to the panel, when using the wheel and the shift key is pressed

View file

@ -78,10 +78,7 @@ namespace Greenshot.Editor.Controls
/// <summary> /// <summary>
/// The bulk of the clean-up code is implemented in Dispose(bool) /// The bulk of the clean-up code is implemented in Dispose(bool)
/// </summary> /// </summary>
public new void Dispose() public new void Dispose() => Dispose(true);
{
Dispose(true);
}
/// <summary> /// <summary>
/// This Dispose is called from the Dispose and the Destructor. /// This Dispose is called from the Dispose and the Destructor.
@ -176,16 +173,10 @@ namespace Greenshot.Editor.Controls
public bool PreFilterMessage(ref Message m) public bool PreFilterMessage(ref Message m)
{ {
if (_dragging) if (_dragging && m.Msg == (int)WindowsMessages.WM_CHAR && (int)m.WParam == VkEsc)
{
if (m.Msg == (int)WindowsMessages.WM_CHAR)
{
if ((int)m.WParam == VkEsc)
{ {
User32Api.ReleaseCapture(); User32Api.ReleaseCapture();
} }
}
}
return false; return false;
} }
@ -195,9 +186,6 @@ namespace Greenshot.Editor.Controls
{ {
public Color Color; public Color Color;
public PipetteUsedArgs(Color c) public PipetteUsedArgs(Color c) => Color = c;
{
Color = c;
}
} }
} }

View file

@ -39,10 +39,7 @@ namespace Greenshot.Editor.Controls
private Color _selectedColor = Color.Transparent; private Color _selectedColor = Color.Transparent;
public ToolStripColorButton() public ToolStripColorButton() => Click += ColorButtonClick;
{
Click += ColorButtonClick;
}
public Color SelectedColor public Color SelectedColor
{ {
@ -51,16 +48,7 @@ namespace Greenshot.Editor.Controls
{ {
_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

@ -79,9 +79,6 @@ namespace Greenshot.Editor.Controls
NumericUpDown.ValueChanged -= _valueChanged; NumericUpDown.ValueChanged -= _valueChanged;
} }
private void _valueChanged(object sender, EventArgs e) private void _valueChanged(object sender, EventArgs e) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value"));
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value"));
}
} }
} }

View file

@ -48,22 +48,13 @@ namespace Greenshot.Editor.Destinations
// Do not remove, is needed for the framework // Do not remove, is needed for the framework
} }
public EditorDestination(IImageEditor editor) public EditorDestination(IImageEditor editor) => this.editor = editor;
{
this.editor = editor;
}
public override string Designation => DESIGNATION; public override string Designation => DESIGNATION;
public override string Description public override string Description => editor == null
{
get
{
return editor == null
? Language.GetString(LangKey.settings_destination_editor) ? Language.GetString(LangKey.settings_destination_editor)
: Language.GetString(LangKey.settings_destination_editor) + " - " + editor.CaptureDetails.Title?.Substring(0, Math.Min(20, editor.CaptureDetails.Title.Length)); : Language.GetString(LangKey.settings_destination_editor) + " - " + editor.CaptureDetails.Title?.Substring(0, Math.Min(20, editor.CaptureDetails.Title.Length));
}
}
public override int Priority => 1; public override int Priority => 1;

View file

@ -51,10 +51,7 @@ namespace Greenshot.Editor.Drawing.Adorners
/// <summary> /// <summary>
/// Returns the cursor for when the mouse is over the adorner /// Returns the cursor for when the mouse is over the adorner
/// </summary> /// </summary>
public virtual Cursor Cursor public virtual Cursor Cursor => Cursors.SizeAll;
{
get { return Cursors.SizeAll; }
}
public IDrawableContainer Owner { get; set; } public IDrawableContainer Owner { get; set; }
@ -92,10 +89,7 @@ namespace Greenshot.Editor.Drawing.Adorners
/// </summary> /// </summary>
/// <param name="sender"></param> /// <param name="sender"></param>
/// <param name="mouseEventArgs"></param> /// <param name="mouseEventArgs"></param>
public virtual void MouseUp(object sender, MouseEventArgs mouseEventArgs) public virtual void MouseUp(object sender, MouseEventArgs mouseEventArgs) => EditStatus = EditStatus.IDLE;
{
EditStatus = EditStatus.IDLE;
}
/// <summary> /// <summary>
/// Return the location of the adorner /// Return the location of the adorner
@ -129,19 +123,13 @@ namespace Greenshot.Editor.Drawing.Adorners
/// <summary> /// <summary>
/// The adorner is active if the edit status is not idle or undrawn /// The adorner is active if the edit status is not idle or undrawn
/// </summary> /// </summary>
public virtual bool IsActive public virtual bool IsActive => EditStatus != EditStatus.IDLE && EditStatus != EditStatus.UNDRAWN;
{
get { return EditStatus != EditStatus.IDLE && EditStatus != EditStatus.UNDRAWN; }
}
/// <summary> /// <summary>
/// Adjust UI elements to the supplied DPI settings /// Adjust UI elements to the supplied DPI settings
/// </summary> /// </summary>
/// <param name="dpi">uint</param> /// <param name="dpi">uint</param>
public void AdjustToDpi(int dpi) public void AdjustToDpi(int dpi) => Size = DpiCalculator.ScaleWithDpi(DefaultSize, dpi);
{
Size = DpiCalculator.ScaleWithDpi(DefaultSize, dpi);
}
public Color OutlineColor { get; set; } = Color.White; public Color OutlineColor { get; set; } = Color.White;
public Color FillColor { get; set; } = Color.Black; public Color FillColor { get; set; } = Color.Black;

View file

@ -37,10 +37,7 @@ namespace Greenshot.Editor.Drawing.Adorners
public Positions Position { get; private set; } public Positions Position { get; private set; }
public MoveAdorner(IDrawableContainer owner, Positions position) : base(owner) public MoveAdorner(IDrawableContainer owner, Positions position) : base(owner) => Position = position;
{
Position = position;
}
/// <summary> /// <summary>
/// Returns the cursor for when the mouse is over the adorner /// Returns the cursor for when the mouse is over the adorner

View file

@ -37,10 +37,7 @@ namespace Greenshot.Editor.Drawing.Adorners
public Positions Position { get; private set; } public Positions Position { get; private set; }
public ResizeAdorner(IDrawableContainer owner, Positions position) : base(owner) public ResizeAdorner(IDrawableContainer owner, Positions position) : base(owner) => Position = position;
{
Position = position;
}
/// <summary> /// <summary>
/// Returns the cursor for when the mouse is over the adorner /// Returns the cursor for when the mouse is over the adorner

View file

@ -45,10 +45,7 @@ namespace Greenshot.Editor.Drawing.Adorners
/// </summary> /// </summary>
/// <param name="sender">object</param> /// <param name="sender">object</param>
/// <param name="mouseEventArgs">MouseEventArgs</param> /// <param name="mouseEventArgs">MouseEventArgs</param>
public override void MouseDown(object sender, MouseEventArgs mouseEventArgs) public override void MouseDown(object sender, MouseEventArgs mouseEventArgs) => EditStatus = EditStatus.MOVING;
{
EditStatus = EditStatus.MOVING;
}
/// <summary> /// <summary>
/// Handle the mouse move /// Handle the mouse move

View file

@ -59,10 +59,7 @@ namespace Greenshot.Editor.Drawing
Horizontal Horizontal
} }
public CropContainer(ISurface parent) : base(parent) public CropContainer(ISurface parent) : base(parent) => Init();
{
Init();
}
protected override void OnDeserialized(StreamingContext streamingContext) protected override void OnDeserialized(StreamingContext streamingContext)
{ {
@ -133,22 +130,13 @@ namespace Greenshot.Editor.Drawing
AddField(GetType(), FieldType.CROPMODE, CropModes.Default); AddField(GetType(), FieldType.CROPMODE, CropModes.Default);
} }
public override void Invalidate() public override void Invalidate() => _parent?.Invalidate();
{
_parent?.Invalidate();
}
/// <summary> /// <summary>
/// We need to override the DrawingBound, return a rectangle in the size of the image, to make sure this element is always draw /// We need to override the DrawingBound, return a rectangle in the size of the image, to make sure this element is always draw
/// (we create a transparent brown over the complete picture) /// (we create a transparent brown over the complete picture)
/// </summary> /// </summary>
public override NativeRect DrawingBounds public override NativeRect DrawingBounds => _parent?.Image is { } image ? new NativeRect(0, 0, image.Width, image.Height) : NativeRect.Empty;
{
get
{
return _parent?.Image is { } image ? new NativeRect(0, 0, image.Width, image.Height) : NativeRect.Empty;
}
}
public override void Draw(Graphics g, RenderMode rm) public override void Draw(Graphics g, RenderMode rm)
{ {
@ -195,9 +183,7 @@ namespace Greenshot.Editor.Drawing
/// </summary> /// </summary>
public override bool HasContextMenu => false; public override bool HasContextMenu => false;
public override bool HandleMouseDown(int x, int y) public override bool HandleMouseDown(int x, int y) => GetFieldValue(FieldType.CROPMODE) switch
{
return GetFieldValue(FieldType.CROPMODE) switch
{ {
//force horizontal crop to left edge //force horizontal crop to left edge
CropModes.Horizontal => base.HandleMouseDown(0, y), CropModes.Horizontal => base.HandleMouseDown(0, y),
@ -205,7 +191,6 @@ namespace Greenshot.Editor.Drawing
CropModes.Vertical => base.HandleMouseDown(x, 0), CropModes.Vertical => base.HandleMouseDown(x, 0),
_ => base.HandleMouseDown(x, y), _ => base.HandleMouseDown(x, y),
}; };
}
public override bool HandleMouseMove(int x, int y) public override bool HandleMouseMove(int x, int y)
{ {

View file

@ -42,10 +42,7 @@ namespace Greenshot.Editor.Drawing
protected Cursor cursor; protected Cursor cursor;
public CursorContainer(ISurface parent) : base(parent) public CursorContainer(ISurface parent) : base(parent) => Init();
{
Init();
}
protected override void OnDeserialized(StreamingContext streamingContext) protected override void OnDeserialized(StreamingContext streamingContext)
{ {
@ -53,15 +50,9 @@ namespace Greenshot.Editor.Drawing
Init(); Init();
} }
private void Init() private void Init() => CreateDefaultAdorners();
{
CreateDefaultAdorners();
}
public CursorContainer(ISurface parent, string filename) : this(parent) public CursorContainer(ISurface parent, string filename) : this(parent) => Load(filename);
{
Load(filename);
}
public Cursor Cursor public Cursor Cursor
{ {

View file

@ -74,10 +74,7 @@ namespace Greenshot.Editor.Drawing
protected EditStatus _defaultEditMode = EditStatus.DRAWING; protected EditStatus _defaultEditMode = EditStatus.DRAWING;
public EditStatus DefaultEditMode public EditStatus DefaultEditMode => _defaultEditMode;
{
get { return _defaultEditMode; }
}
/// <summary> /// <summary>
/// The public accessible Dispose /// The public accessible Dispose
@ -137,10 +134,7 @@ namespace Greenshot.Editor.Drawing
set => SwitchParent(value); set => SwitchParent(value);
} }
protected Surface InternalParent protected Surface InternalParent => (Surface)_parent;
{
get => (Surface)_parent;
}
[NonSerialized] private TargetAdorner _targetAdorner; [NonSerialized] private TargetAdorner _targetAdorner;
public TargetAdorner TargetAdorner => _targetAdorner; public TargetAdorner TargetAdorner => _targetAdorner;
@ -153,7 +147,7 @@ namespace Greenshot.Editor.Drawing
set set
{ {
_selected = value; _selected = value;
OnPropertyChanged("Selected"); OnPropertyChanged(nameof(Selected));
} }
} }
@ -290,15 +284,9 @@ namespace Greenshot.Editor.Drawing
_parent = parent; _parent = parent;
} }
public void Add(IFilter filter) public void Add(IFilter filter) => AddChild(filter);
{
AddChild(filter);
}
public void Remove(IFilter filter) public void Remove(IFilter filter) => RemoveChild(filter);
{
RemoveChild(filter);
}
private static int Round(float f) private static int Round(float f)
{ {
@ -352,10 +340,7 @@ namespace Greenshot.Editor.Drawing
} }
} }
public virtual bool InitContent() public virtual bool InitContent() => true;
{
return true;
}
public virtual void OnDoubleClick() public virtual void OnDoubleClick()
{ {
@ -454,10 +439,7 @@ namespace Greenshot.Editor.Drawing
// Empty as we do not want to add something to the context menu for every element // Empty as we do not want to add something to the context menu for every element
} }
public virtual bool Contains(int x, int y) public virtual bool Contains(int x, int y) => Bounds.Contains(x, y);
{
return Bounds.Contains(x, y);
}
public virtual bool ClickableAt(int x, int y) public virtual bool ClickableAt(int x, int y)
{ {
@ -608,20 +590,14 @@ namespace Greenshot.Editor.Drawing
/// </summary> /// </summary>
/// <param name="matrix"></param> /// <param name="matrix"></param>
/// <returns></returns> /// <returns></returns>
public static float CalculateScaleY(Matrix matrix) public static float CalculateScaleY(Matrix matrix) => matrix.Elements[M22];
{
return matrix.Elements[M22];
}
/// <summary> /// <summary>
/// Retrieve the X scale from the matrix /// Retrieve the X scale from the matrix
/// </summary> /// </summary>
/// <param name="matrix"></param> /// <param name="matrix"></param>
/// <returns></returns> /// <returns></returns>
public static float CalculateScaleX(Matrix matrix) public static float CalculateScaleX(Matrix matrix) => matrix.Elements[M11];
{
return matrix.Elements[M11];
}
/// <summary> /// <summary>
/// Retrieve the rotation angle from the matrix /// Retrieve the rotation angle from the matrix
@ -630,9 +606,8 @@ namespace Greenshot.Editor.Drawing
/// <returns></returns> /// <returns></returns>
public static int CalculateAngle(Matrix matrix) public static int CalculateAngle(Matrix matrix)
{ {
const int M11 = 0;
const int M21 = 2; const int M21 = 2;
var radians = Math.Atan2(matrix.Elements[M21], matrix.Elements[M11]); var radians = Math.Atan2(matrix.Elements[M21], matrix.Elements[0]);
return (int)-Math.Round(radians * 180 / Math.PI); return (int)-Math.Round(radians * 180 / Math.PI);
} }
@ -665,10 +640,7 @@ namespace Greenshot.Editor.Drawing
Height = points[1].Y - points[0].Y; Height = points[1].Y - points[0].Y;
} }
protected virtual IDoubleProcessor GetAngleRoundProcessor() protected virtual IDoubleProcessor GetAngleRoundProcessor() => ShapeAngleRoundBehavior.INSTANCE;
{
return ShapeAngleRoundBehavior.INSTANCE;
}
public virtual bool HasContextMenu => true; public virtual bool HasContextMenu => true;

View file

@ -53,15 +53,9 @@ namespace Greenshot.Editor.Drawing
{ {
} }
public DrawableContainerList(IEnumerable<IDrawableContainer> elements) public DrawableContainerList(IEnumerable<IDrawableContainer> elements) => AddRange(elements);
{
AddRange(elements);
}
public DrawableContainerList(Guid parentId) public DrawableContainerList(Guid parentId) => ParentID = parentId;
{
ParentID = parentId;
}
public EditStatus Status public EditStatus Status
{ {
@ -78,10 +72,7 @@ namespace Greenshot.Editor.Drawing
public List<IDrawableContainer> AsIDrawableContainerList() public List<IDrawableContainer> AsIDrawableContainerList()
{ {
List<IDrawableContainer> interfaceList = new(); List<IDrawableContainer> interfaceList = new();
foreach (IDrawableContainer container in this) interfaceList.AddRange(this);
{
interfaceList.Add(container);
}
return interfaceList; return interfaceList;
} }
@ -275,13 +266,12 @@ namespace Greenshot.Editor.Drawing
/// <returns></returns> /// <returns></returns>
public bool IntersectsWith(NativeRect clipRectangle) public bool IntersectsWith(NativeRect clipRectangle)
{ {
foreach (var dc in this) foreach (var _ in from dc in this
{ where dc.DrawingBounds.IntersectsWith(clipRectangle)
if (dc.DrawingBounds.IntersectsWith(clipRectangle)) select new { })
{ {
return true; return true;
} }
}
return false; return false;
} }
@ -758,11 +748,9 @@ namespace Greenshot.Editor.Drawing
} }
// This code added to correctly implement the disposable pattern. // This code added to correctly implement the disposable pattern.
public void Dispose() public void Dispose() =>
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true); Dispose(true);
}
/// <summary> /// <summary>
/// Adjust UI elements to the supplied DPI settings /// Adjust UI elements to the supplied DPI settings

View file

@ -38,10 +38,7 @@ namespace Greenshot.Editor.Drawing
[Serializable()] [Serializable()]
public class EllipseContainer : DrawableContainer public class EllipseContainer : DrawableContainer
{ {
public EllipseContainer(ISurface parent) : base(parent) public EllipseContainer(ISurface parent) : base(parent) => Init();
{
Init();
}
protected override void OnDeserialized(StreamingContext streamingContext) protected override void OnDeserialized(StreamingContext streamingContext)
{ {
@ -49,10 +46,7 @@ namespace Greenshot.Editor.Drawing
Init(); Init();
} }
private void Init() private void Init() => CreateDefaultAdorners();
{
CreateDefaultAdorners();
}
protected override void InitializeFields() protected override void InitializeFields()
{ {
@ -124,10 +118,7 @@ namespace Greenshot.Editor.Drawing
} }
} }
public override bool Contains(int x, int y) public override bool Contains(int x, int y) => EllipseContains(this, x, y);
{
return EllipseContains(this, x, y);
}
/// <summary> /// <summary>
/// Allow the code to be used externally /// Allow the code to be used externally
@ -141,7 +132,7 @@ namespace Greenshot.Editor.Drawing
double xDistanceFromCenter = x - (caller.Left + (caller.Width / 2)); double xDistanceFromCenter = x - (caller.Left + (caller.Width / 2));
double yDistanceFromCenter = y - (caller.Top + (caller.Height / 2)); double yDistanceFromCenter = y - (caller.Top + (caller.Height / 2));
// ellipse: x^2/a^2 + y^2/b^2 = 1 // ellipse: x^2/a^2 + y^2/b^2 = 1
return (Math.Pow(xDistanceFromCenter, 2) / Math.Pow(caller.Width / 2, 2)) + (Math.Pow(yDistanceFromCenter, 2) / Math.Pow(caller.Height / 2, 2)) < 1; return (Math.Pow(xDistanceFromCenter, 2) / Math.Pow(caller.Width / 2F, 2)) + (Math.Pow(yDistanceFromCenter, 2) / Math.Pow(caller.Height / 2, 2)) < 1;
} }
public override bool ClickableAt(int x, int y) public override bool ClickableAt(int x, int y)
@ -155,13 +146,10 @@ namespace Greenshot.Editor.Drawing
public static bool EllipseClickableAt(NativeRect rect, int lineThickness, Color fillColor, int x, int y) public static bool EllipseClickableAt(NativeRect rect, int lineThickness, Color fillColor, int x, int y)
{ {
// If we clicked inside the rectangle and it's visible we are clickable at. // If we clicked inside the rectangle and it's visible we are clickable at.
if (!Color.Transparent.Equals(fillColor)) if (!Color.Transparent.Equals(fillColor) && rect.Contains(x, y))
{
if (rect.Contains(x, y))
{ {
return true; return true;
} }
}
// check the rest of the lines // check the rest of the lines
if (lineThickness > 0) if (lineThickness > 0)

View file

@ -69,10 +69,7 @@ namespace Greenshot.Editor.Drawing.Fields
} }
} }
public void AddField(Type requestingType, IFieldType fieldType, object fieldValue) public void AddField(Type requestingType, IFieldType fieldType, object fieldValue) => AddField(EditorConfig.CreateField(requestingType, fieldType, fieldValue));
{
AddField(EditorConfig.CreateField(requestingType, fieldType, fieldValue));
}
public virtual void AddField(IField field) public virtual void AddField(IField field)
{ {
@ -82,13 +79,10 @@ namespace Greenshot.Editor.Drawing.Fields
return; return;
} }
if (_fieldsByType.ContainsKey(field.FieldType)) if (_fieldsByType.ContainsKey(field.FieldType) && LOG.IsDebugEnabled)
{
if (LOG.IsDebugEnabled)
{ {
LOG.DebugFormat("A field with of type '{0}' already exists in this {1}, will overwrite.", field.FieldType, GetType()); LOG.DebugFormat("A field with of type '{0}' already exists in this {1}, will overwrite.", field.FieldType, GetType());
} }
}
_fieldsByType[field.FieldType] = field; _fieldsByType[field.FieldType] = field;
@ -104,10 +98,7 @@ namespace Greenshot.Editor.Drawing.Fields
_handlers.Remove(field); _handlers.Remove(field);
} }
public IList<IField> GetFields() public IList<IField> GetFields() => fields;
{
return fields;
}
public IField GetField(IFieldType fieldType) public IField GetField(IFieldType fieldType)
{ {
@ -121,55 +112,25 @@ namespace Greenshot.Editor.Drawing.Fields
} }
} }
public object GetFieldValue(IFieldType fieldType) public object GetFieldValue(IFieldType fieldType) => GetField(fieldType)?.Value;
{
return GetField(fieldType)?.Value;
}
public string GetFieldValueAsString(IFieldType fieldType) public string GetFieldValueAsString(IFieldType fieldType) => Convert.ToString(GetFieldValue(fieldType));
{
return Convert.ToString(GetFieldValue(fieldType));
}
public int GetFieldValueAsInt(IFieldType fieldType) public int GetFieldValueAsInt(IFieldType fieldType) => Convert.ToInt32(GetFieldValue(fieldType));
{
return Convert.ToInt32(GetFieldValue(fieldType));
}
public decimal GetFieldValueAsDecimal(IFieldType fieldType) public decimal GetFieldValueAsDecimal(IFieldType fieldType) => Convert.ToDecimal(GetFieldValue(fieldType));
{
return Convert.ToDecimal(GetFieldValue(fieldType));
}
public double GetFieldValueAsDouble(IFieldType fieldType) public double GetFieldValueAsDouble(IFieldType fieldType) => Convert.ToDouble(GetFieldValue(fieldType));
{
return Convert.ToDouble(GetFieldValue(fieldType));
}
public float GetFieldValueAsFloat(IFieldType fieldType) public float GetFieldValueAsFloat(IFieldType fieldType) => Convert.ToSingle(GetFieldValue(fieldType));
{
return Convert.ToSingle(GetFieldValue(fieldType));
}
public bool GetFieldValueAsBool(IFieldType fieldType) public bool GetFieldValueAsBool(IFieldType fieldType) => Convert.ToBoolean(GetFieldValue(fieldType));
{
return Convert.ToBoolean(GetFieldValue(fieldType));
}
public Color GetFieldValueAsColor(IFieldType fieldType, Color defaultColor = default) public Color GetFieldValueAsColor(IFieldType fieldType, Color defaultColor = default) => (Color)(GetFieldValue(fieldType) ?? defaultColor);
{
return (Color)(GetFieldValue(fieldType) ?? defaultColor);
}
public bool HasField(IFieldType fieldType) public bool HasField(IFieldType fieldType) => _fieldsByType.ContainsKey(fieldType);
{
return _fieldsByType.ContainsKey(fieldType);
}
public bool HasFieldValue(IFieldType fieldType) public bool HasFieldValue(IFieldType fieldType) => HasField(fieldType) && _fieldsByType[fieldType].HasValue;
{
return HasField(fieldType) && _fieldsByType[fieldType].HasValue;
}
public void SetFieldValue(IFieldType fieldType, object value) public void SetFieldValue(IFieldType fieldType, object value)
{ {
@ -183,9 +144,6 @@ namespace Greenshot.Editor.Drawing.Fields
} }
} }
protected void OnFieldChanged(object sender, FieldChangedEventArgs e) protected void OnFieldChanged(object sender, FieldChangedEventArgs e) => _fieldChanged?.Invoke(sender, e);
{
_fieldChanged?.Invoke(sender, e);
}
} }
} }

View file

@ -23,6 +23,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Greenshot.Base.Interfaces.Drawing; using Greenshot.Base.Interfaces.Drawing;
using System.Linq;
namespace Greenshot.Editor.Drawing.Fields namespace Greenshot.Editor.Drawing.Fields
{ {
@ -46,10 +47,7 @@ namespace Greenshot.Editor.Drawing.Fields
public IList<IFieldHolder> Children = new List<IFieldHolder>(); public IList<IFieldHolder> Children = new List<IFieldHolder>();
protected AbstractFieldHolderWithChildren() protected AbstractFieldHolderWithChildren() => _fieldChangedEventHandler = OnFieldChanged;
{
_fieldChangedEventHandler = OnFieldChanged;
}
[OnDeserialized()] [OnDeserialized()]
private void OnDeserialized(StreamingContext context) private void OnDeserialized(StreamingContext context)
@ -98,15 +96,14 @@ namespace Greenshot.Editor.Drawing.Fields
} }
else else
{ {
foreach (IFieldHolder fh in Children) foreach (var fh in from IFieldHolder fh in Children
{ where fh.HasField(fieldType)
if (fh.HasField(fieldType)) select fh)
{ {
ret = fh.GetField(fieldType); ret = fh.GetField(fieldType);
break; break;
} }
} }
}
return ret ?? throw new ArgumentException("Field '" + fieldType + "' does not exist in " + GetType()); return ret ?? throw new ArgumentException("Field '" + fieldType + "' does not exist in " + GetType());
} }
@ -116,15 +113,14 @@ namespace Greenshot.Editor.Drawing.Fields
bool ret = base.HasField(fieldType); bool ret = base.HasField(fieldType);
if (!ret) if (!ret)
{ {
foreach (IFieldHolder fh in Children) foreach (var _ in from IFieldHolder fh in Children
{ where fh.HasField(fieldType)
if (fh.HasField(fieldType)) select new { })
{ {
ret = true; ret = true;
break; break;
} }
} }
}
return ret; return ret;
} }

View file

@ -28,15 +28,12 @@ namespace Greenshot.Editor.Drawing.Fields.Binding
/// </summary> /// </summary>
public abstract class AbstractBindingConverter<T1, T2> : IBindingConverter public abstract class AbstractBindingConverter<T1, T2> : IBindingConverter
{ {
public object convert(object o) public object convert(object o) => o switch
{
return o switch
{ {
null => null, null => null,
T1 => convert((T1)o), T1 => convert((T1)o),
_ => o is T2 t ? (object)convert(t) : throw new ArgumentException("Cannot handle argument of type " + o.GetType()) _ => o is T2 t ? (object)convert(t) : throw new ArgumentException("Cannot handle argument of type " + o.GetType())
}; };
}
protected abstract T2 convert(T1 o); protected abstract T2 convert(T1 o);
protected abstract T1 convert(T2 o); protected abstract T1 convert(T2 o);

View file

@ -72,10 +72,7 @@ namespace Greenshot.Editor.Drawing.Fields.Binding
/// <param name="fieldPropertyName">Property of 2nd object to bind</param> /// <param name="fieldPropertyName">Property of 2nd object to bind</param>
/// <param name="converter">taking care of converting the synchronized value to the correct target format and back</param> /// <param name="converter">taking care of converting the synchronized value to the correct target format and back</param>
public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName,
IBindingConverter converter) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) IBindingConverter converter) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) => Converter = converter;
{
Converter = converter;
}
/// <summary> /// <summary>
/// Bind properties of two objects bidirectionally, converting the values using a converter. /// Bind properties of two objects bidirectionally, converting the values using a converter.
@ -87,10 +84,7 @@ namespace Greenshot.Editor.Drawing.Fields.Binding
/// <param name="fieldPropertyName">Property of 2nd object to bind</param> /// <param name="fieldPropertyName">Property of 2nd object to bind</param>
/// <param name="validator">validator to intercept synchronization if the value does not match certain criteria</param> /// <param name="validator">validator to intercept synchronization if the value does not match certain criteria</param>
public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName,
IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) => _validator = validator;
{
_validator = validator;
}
/// <summary> /// <summary>
/// Bind properties of two objects bidirectionally, converting the values using a converter. /// Bind properties of two objects bidirectionally, converting the values using a converter.
@ -103,10 +97,7 @@ namespace Greenshot.Editor.Drawing.Fields.Binding
/// <param name="converter">taking care of converting the synchronized value to the correct target format and back</param> /// <param name="converter">taking care of converting the synchronized value to the correct target format and back</param>
/// <param name="validator">validator to intercept synchronization if the value does not match certain criteria</param> /// <param name="validator">validator to intercept synchronization if the value does not match certain criteria</param>
public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName, public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName,
IBindingConverter converter, IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName, converter) IBindingConverter converter, IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName, converter) => _validator = validator;
{
_validator = validator;
}
public void ControlPropertyChanged(object sender, PropertyChangedEventArgs e) public void ControlPropertyChanged(object sender, PropertyChangedEventArgs e)
{ {

View file

@ -34,19 +34,10 @@ namespace Greenshot.Editor.Drawing.Fields.Binding
{ {
} }
protected override decimal convert(double o) protected override decimal convert(double o) => Convert.ToDecimal(o) * 100;
{
return Convert.ToDecimal(o) * 100;
}
protected override double convert(decimal o) protected override double convert(decimal o) => Convert.ToDouble(o) / 100;
{
return Convert.ToDouble(o) / 100;
}
public static DecimalDoublePercentageConverter GetInstance() public static DecimalDoublePercentageConverter GetInstance() => _uniqueInstance ??= new DecimalDoublePercentageConverter();
{
return _uniqueInstance ??= new DecimalDoublePercentageConverter();
}
} }
} }

View file

@ -34,19 +34,10 @@ namespace Greenshot.Editor.Drawing.Fields.Binding
{ {
} }
protected override decimal convert(float o) protected override decimal convert(float o) => Convert.ToDecimal(o);
{
return Convert.ToDecimal(o);
}
protected override float convert(decimal o) protected override float convert(decimal o) => Convert.ToSingle(o);
{
return Convert.ToSingle(o);
}
public static DecimalFloatConverter GetInstance() public static DecimalFloatConverter GetInstance() => _uniqueInstance ??= new DecimalFloatConverter();
{
return _uniqueInstance ??= new DecimalFloatConverter();
}
} }
} }

View file

@ -34,19 +34,10 @@ namespace Greenshot.Editor.Drawing.Fields.Binding
{ {
} }
protected override decimal convert(int o) protected override decimal convert(int o) => Convert.ToDecimal(o);
{
return Convert.ToDecimal(o);
}
protected override int convert(decimal o) protected override int convert(decimal o) => Convert.ToInt32(o);
{
return Convert.ToInt32(o);
}
public static DecimalIntConverter GetInstance() public static DecimalIntConverter GetInstance() => _uniqueInstance ??= new DecimalIntConverter();
{
return _uniqueInstance ??= new DecimalIntConverter();
}
} }
} }

View file

@ -32,14 +32,8 @@ namespace Greenshot.Editor.Drawing.Fields.Binding
{ {
} }
public bool validate(object o) public bool validate(object o) => o != null;
{
return o != null;
}
public static NotNullValidator GetInstance() public static NotNullValidator GetInstance() => _uniqueInstance ??= new NotNullValidator();
{
return _uniqueInstance ??= new NotNullValidator();
}
} }
} }

View file

@ -44,7 +44,7 @@ namespace Greenshot.Editor.Drawing.Fields
if (!Equals(_myValue, value)) if (!Equals(_myValue, value))
{ {
_myValue = value; _myValue = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value")); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value)));
} }
} }
} }
@ -75,10 +75,7 @@ namespace Greenshot.Editor.Drawing.Fields
Scope = scope; Scope = scope;
} }
public Field(IFieldType fieldType) public Field(IFieldType fieldType) => FieldType = fieldType;
{
FieldType = fieldType;
}
/// <summary> /// <summary>
/// Returns true if this field holds a value other than null. /// Returns true if this field holds a value other than null.
@ -89,13 +86,10 @@ namespace Greenshot.Editor.Drawing.Fields
/// Creates a flat clone of this Field. The fields value itself is not cloned. /// Creates a flat clone of this Field. The fields value itself is not cloned.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public Field Clone() public Field Clone() => new(FieldType, Scope)
{
return new Field(FieldType, Scope)
{ {
Value = Value Value = Value
}; };
}
public override int GetHashCode() public override int GetHashCode()
{ {
@ -110,14 +104,8 @@ namespace Greenshot.Editor.Drawing.Fields
return hashCode; return hashCode;
} }
public override bool Equals(object obj) public override bool Equals(object obj) => obj is Field other && FieldType == other.FieldType && Equals(Scope, other.Scope);
{
return obj is Field other && FieldType == other.FieldType && Equals(Scope, other.Scope);
}
public override string ToString() public override string ToString() => string.Format("[Field FieldType={1} Value={0} Scope={2}]", _myValue, FieldType, Scope);
{
return string.Format("[Field FieldType={1} Value={0} Scope={2}]", _myValue, FieldType, Scope);
}
} }
} }

View file

@ -164,10 +164,8 @@ namespace Greenshot.Editor.Drawing.Fields
private IList<IField> FindCommonFields() private IList<IField> FindCommonFields()
{ {
IList<IField> returnFields = null; IList<IField> returnFields = null;
if (_boundContainers.Count > 0)
{
// take all fields from the least selected container... // take all fields from the least selected container...
if (_boundContainers[_boundContainers.Count - 1] is DrawableContainer leastSelectedContainer) if (_boundContainers.Count > 0 && _boundContainers[_boundContainers.Count - 1] is DrawableContainer leastSelectedContainer)
{ {
returnFields = leastSelectedContainer.GetFields(); returnFields = leastSelectedContainer.GetFields();
for (int i = 0; i < _boundContainers.Count - 1; i++) for (int i = 0; i < _boundContainers.Count - 1; i++)
@ -189,7 +187,6 @@ namespace Greenshot.Editor.Drawing.Fields
} }
} }
} }
}
return returnFields ?? new List<IField>(); return returnFields ?? new List<IField>();
} }

View file

@ -61,15 +61,9 @@ namespace Greenshot.Editor.Drawing.Fields
public string Name { get; set; } public string Name { get; set; }
private FieldType(string name) private FieldType(string name) => Name = name;
{
Name = name;
}
public override string ToString() public override string ToString() => Name;
{
return Name;
}
public override int GetHashCode() public override int GetHashCode()
{ {
@ -89,14 +83,8 @@ namespace Greenshot.Editor.Drawing.Fields
return other != null && Equals(Name, other.Name); return other != null && Equals(Name, other.Name);
} }
public static bool operator ==(FieldType a, FieldType b) public static bool operator ==(FieldType a, FieldType b) => Equals(a, b);
{
return Equals(a, b);
}
public static bool operator !=(FieldType a, FieldType b) public static bool operator !=(FieldType a, FieldType b) => !Equals(a, b);
{
return !Equals(a, b);
}
} }
} }

View file

@ -54,10 +54,7 @@ namespace Greenshot.Editor.Drawing
MAGNIFICATION MAGNIFICATION
}; };
protected FilterContainer(ISurface parent) : base(parent) protected FilterContainer(ISurface parent) : base(parent) => Init();
{
Init();
}
protected override void OnDeserialized(StreamingContext streamingContext) protected override void OnDeserialized(StreamingContext streamingContext)
{ {
@ -65,10 +62,7 @@ namespace Greenshot.Editor.Drawing
Init(); Init();
} }
private void Init() private void Init() => CreateDefaultAdorners();
{
CreateDefaultAdorners();
}
protected override void InitializeFields() protected override void InitializeFields()
{ {

View file

@ -52,7 +52,7 @@ namespace Greenshot.Editor.Drawing.Filters
set set
{ {
invert = value; invert = value;
OnPropertyChanged("Invert"); OnPropertyChanged(nameof(Invert));
} }
} }
@ -64,21 +64,12 @@ namespace Greenshot.Editor.Drawing.Filters
set { parent = value; } set { parent = value; }
} }
protected AbstractFilter(DrawableContainer parent) protected AbstractFilter(DrawableContainer parent) => this.parent = parent;
{
this.parent = parent;
}
public DrawableContainer GetParent() public DrawableContainer GetParent() => parent;
{
return parent;
}
public abstract void Apply(Graphics graphics, Bitmap applyBitmap, NativeRect rect, RenderMode renderMode); public abstract void Apply(Graphics graphics, Bitmap applyBitmap, NativeRect rect, RenderMode renderMode);
protected void OnPropertyChanged(string propertyName) protected void OnPropertyChanged(string propertyName) => propertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
{
propertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
} }
} }

View file

@ -41,7 +41,7 @@ namespace Greenshot.Editor.Drawing.Filters
set set
{ {
previewQuality = value; previewQuality = value;
OnPropertyChanged("PreviewQuality"); OnPropertyChanged(nameof(PreviewQuality));
} }
} }

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