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
dotnet_diagnostic.IDE1006.severity = none
dotnet_diagnostic.S927.severity = suggestion
# S1481: Unused local variables should be removed
dotnet_diagnostic.S1481.severity = silent
# IDE0076: Invalid global 'SuppressMessageAttribute'
dotnet_diagnostic.IDE0076.severity = none
dotnet_diagnostic.S101.severity = silent
[*.{cs,vb}]
#### Naming styles ####

View file

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

View file

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

View file

@ -40,29 +40,20 @@ namespace Greenshot.Base.Controls
{
}
public int QueryStatus(Guid pguidCmdGroup, int cCmds, IntPtr prgCmds, IntPtr pCmdText)
{
return OLECMDERR_E_NOTSUPPORTED;
}
public int QueryStatus(Guid pguidCmdGroup, int cCmds, IntPtr prgCmds, IntPtr pCmdText) => OLECMDERR_E_NOTSUPPORTED;
public int Exec(Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
if (pguidCmdGroup == CGID_DocHostCommandHandler)
if (pguidCmdGroup == CGID_DocHostCommandHandler && nCmdID == OLECMDID_SHOWSCRIPTERROR)
{
if (nCmdID == OLECMDID_SHOWSCRIPTERROR)
{
// do not need to alter pvaOut as the docs says, enough to return S_OK here
return S_OK;
}
// do not need to alter pvaOut as the docs says, enough to return S_OK here
return S_OK;
}
return OLECMDERR_E_NOTSUPPORTED;
}
}
protected override WebBrowserSiteBase CreateWebBrowserSiteBase()
{
return new ExtendedWebBrowserSite(this);
}
protected override WebBrowserSiteBase CreateWebBrowserSiteBase() => new ExtendedWebBrowserSite(this);
}
}

View file

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

View file

@ -37,10 +37,7 @@ namespace Greenshot.Base.Controls
[Category("Greenshot"), DefaultValue(null), Description("Specifies the property name to map the configuration.")]
public string PropertyName { get; set; }
public GreenshotComboBox()
{
SelectedIndexChanged += delegate { StoreSelectedEnum(); };
}
public GreenshotComboBox() => SelectedIndexChanged += delegate { StoreSelectedEnum(); };
public void SetValue(Enum currentValue)
{
@ -108,9 +105,6 @@ namespace Greenshot.Base.Controls
/// Get the selected enum value from the combobox, uses generics
/// </summary>
/// <returns>The enum value of the combobox</returns>
public Enum GetSelectedEnum()
{
return _selectedEnum;
}
public Enum GetSelectedEnum() => _selectedEnum;
}
}

View file

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

View file

@ -72,15 +72,9 @@ namespace Greenshot.Base.Controls
/// Used to check the designmode during a constructor
/// </summary>
/// <returns></returns>
protected static bool IsInDesignMode
{
get
{
return (Application.ExecutablePath.IndexOf("devenv.exe", StringComparison.OrdinalIgnoreCase) > -1) ||
protected static bool IsInDesignMode => (Application.ExecutablePath.IndexOf("devenv.exe", StringComparison.OrdinalIgnoreCase) > -1) ||
Application.ExecutablePath.IndexOf("sharpdevelop.exe", StringComparison.OrdinalIgnoreCase) > -1 ||
(Application.ExecutablePath.IndexOf("wdexpress.exe", StringComparison.OrdinalIgnoreCase) > -1);
}
}
#endif
protected bool ManualLanguageApply { get; set; }
@ -92,10 +86,7 @@ namespace Greenshot.Base.Controls
/// </summary>
protected bool ToFront { get; set; }
protected GreenshotForm()
{
DpiChanged += (sender, dpiChangedEventArgs) => DpiChangedHandler(dpiChangedEventArgs.DeviceDpiOld, dpiChangedEventArgs.DeviceDpiNew);
}
protected GreenshotForm() => DpiChanged += (sender, dpiChangedEventArgs) => DpiChangedHandler(dpiChangedEventArgs.DeviceDpiOld, dpiChangedEventArgs.DeviceDpiNew);
/// <summary>
/// This is the basic DpiChangedHandler responsible for all the DPI relative changes
@ -148,19 +139,16 @@ namespace Greenshot.Base.Controls
/// <param name="e"></param>
protected override void OnPaint(PaintEventArgs e)
{
if (DesignMode)
if (DesignMode && !_isDesignModeLanguageSet)
{
if (!_isDesignModeLanguageSet)
_isDesignModeLanguageSet = true;
try
{
_isDesignModeLanguageSet = true;
try
{
ApplyLanguage();
}
catch (Exception)
{
// ignored
}
ApplyLanguage();
}
catch (Exception)
{
// ignored
}
}
@ -215,13 +203,10 @@ namespace Greenshot.Base.Controls
/// <param name="e"></param>
protected override void OnClosed(EventArgs e)
{
if (!DesignMode && !ManualStoreFields)
if (!DesignMode && !ManualStoreFields && DialogResult == DialogResult.OK)
{
if (DialogResult == DialogResult.OK)
{
LOG.Info("Form was closed with OK: storing field values.");
StoreFields();
}
LOG.Info("Form was closed with OK: storing field values.");
StoreFields();
}
base.OnClosed(e);

View file

@ -243,10 +243,7 @@ namespace Greenshot.Base.Controls
/// Prevents the letter/whatever entered to show up in the TextBox
/// Without this, a "A" key press would appear as "aControl, Alt + A"
/// </summary>
private void HotkeyControl_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
private void HotkeyControl_KeyPress(object sender, KeyPressEventArgs e) => e.Handled = true;
/// <summary>
/// Handles some misc keys, such as Ctrl+Delete and Shift+Insert
@ -336,7 +333,7 @@ namespace Greenshot.Base.Controls
}
// Only validate input if it comes from the user
if (bCalledProgramatically == false)
if (!bCalledProgramatically)
{
// No modifier or shift only, AND a hotkey that needs another modifier
if ((_modifiers == Keys.Shift || _modifiers == Keys.None) && _needNonShiftModifier.Contains((int)_hotkey))
@ -344,7 +341,7 @@ namespace Greenshot.Base.Controls
if (_modifiers == Keys.None)
{
// Set Ctrl+Alt as the modifier unless Ctrl+Alt+<key> won't work...
if (_needNonAltGrModifier.Contains((int)_hotkey) == false)
if (!_needNonAltGrModifier.Contains((int)_hotkey))
{
_modifiers = Keys.Alt | Keys.Control;
}
@ -384,10 +381,7 @@ namespace Greenshot.Base.Controls
Text = HotkeyToLocalizedString(_modifiers, _hotkey);
}
public override string ToString()
{
return HotkeyToString(HotkeyModifiers, Hotkey);
}
public override string ToString() => HotkeyToString(HotkeyModifiers, Hotkey);
public static string GetLocalizedHotkeyStringFromString(string hotkeyString)
{
@ -396,10 +390,7 @@ namespace Greenshot.Base.Controls
return HotkeyToLocalizedString(modifiers, virtualKeyCode);
}
public static string HotkeyToString(Keys modifierKeyCode, Keys virtualKeyCode)
{
return HotkeyModifiersToString(modifierKeyCode) + virtualKeyCode;
}
public static string HotkeyToString(Keys modifierKeyCode, Keys virtualKeyCode) => HotkeyModifiersToString(modifierKeyCode) + virtualKeyCode;
public static string HotkeyModifiersToString(Keys modifierKeyCode)
{
@ -427,10 +418,7 @@ namespace Greenshot.Base.Controls
return hotkeyString.ToString();
}
public static string HotkeyToLocalizedString(Keys modifierKeyCode, Keys virtualKeyCode)
{
return HotkeyModifiersToLocalizedString(modifierKeyCode) + GetKeyName(virtualKeyCode);
}
public static string HotkeyToLocalizedString(Keys modifierKeyCode, Keys virtualKeyCode) => HotkeyModifiersToLocalizedString(modifierKeyCode) + GetKeyName(virtualKeyCode);
public static string HotkeyModifiersToLocalizedString(Keys modifierKeyCode)
{
@ -463,22 +451,22 @@ namespace Greenshot.Base.Controls
Keys modifiers = Keys.None;
if (!string.IsNullOrEmpty(modifiersString))
{
if (modifiersString.ToLower().Contains("alt"))
if (modifiersString.IndexOf("alt", StringComparison.CurrentCultureIgnoreCase) >= 0)
{
modifiers |= Keys.Alt;
}
if (modifiersString.ToLower().Contains("ctrl"))
if (modifiersString.IndexOf("ctrl", StringComparison.CurrentCultureIgnoreCase) >= 0)
{
modifiers |= Keys.Control;
}
if (modifiersString.ToLower().Contains("shift"))
if (modifiersString.IndexOf("shift", StringComparison.CurrentCultureIgnoreCase) >= 0)
{
modifiers |= Keys.Shift;
}
if (modifiersString.ToLower().Contains("win"))
if (modifiersString.IndexOf("win", StringComparison.CurrentCultureIgnoreCase) >= 0)
{
modifiers |= Keys.LWin;
}
@ -503,10 +491,7 @@ namespace Greenshot.Base.Controls
return key;
}
public static void RegisterHotkeyHwnd(IntPtr hWnd)
{
_hotkeyHwnd = hWnd;
}
public static void RegisterHotkeyHwnd(IntPtr hWnd) => _hotkeyHwnd = hWnd;
/// <summary>
/// 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
e.Handled = true;
}
}
}

View file

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

View file

@ -51,13 +51,10 @@ namespace Greenshot.Base.Controls
protected virtual void Dispose(bool disposing)
{
if (disposing)
if (disposing && SaveFileDialog != null)
{
if (SaveFileDialog != null)
{
SaveFileDialog.Dispose();
SaveFileDialog = null;
}
SaveFileDialog.Dispose();
SaveFileDialog = null;
}
}
@ -126,7 +123,7 @@ namespace Greenshot.Base.Controls
for (int i = 0; i < _filterOptions.Length; i++)
{
string ifo = supportedImageFormats[i].ToString();
if (ifo.ToLower().Equals("jpeg")) ifo = "Jpg"; // we dont want no jpeg files, so let the dialog check for jpg
if (ifo.Equals("jpeg", StringComparison.CurrentCultureIgnoreCase)) ifo = "Jpg"; // we dont want no jpeg files, so let the dialog check for jpg
FilterOption fo = new()
{
Label = ifo.ToUpper(),
@ -204,11 +201,9 @@ namespace Greenshot.Base.Controls
/// <summary>
/// sets InitialDirectory and FileName property of a SaveFileDialog smartly, considering default pattern and last used path
/// </summary>
private void ApplySuggestedValues()
{
private void ApplySuggestedValues() =>
// build the full path and set dialog properties
FileName = FilenameHelper.GetFilenameWithoutExtensionFromPattern(conf.OutputFileFilenamePattern, _captureDetails);
}
private class FilterOption
{

View file

@ -50,14 +50,9 @@ namespace Greenshot.Base.Controls
FormBorderStyle = FormBorderStyle.None;
TopMost = false;
Enabled = false;
if (conf.WindowCaptureMode == WindowCaptureMode.Auto || conf.WindowCaptureMode == WindowCaptureMode.Aero)
{
BackColor = Color.FromArgb(255, conf.DWMBackgroundColor.R, conf.DWMBackgroundColor.G, conf.DWMBackgroundColor.B);
}
else
{
BackColor = Color.White;
}
BackColor = conf.WindowCaptureMode == WindowCaptureMode.Auto || conf.WindowCaptureMode == WindowCaptureMode.Aero
? Color.FromArgb(255, conf.DWMBackgroundColor.R, conf.DWMBackgroundColor.G, conf.DWMBackgroundColor.B)
: Color.White;
// cleanup at close
FormClosing += delegate { UnregisterThumbnail(); };
@ -147,14 +142,9 @@ namespace Greenshot.Base.Controls
public void AlignToControl(Control alignTo)
{
var screenBounds = DisplayInfo.ScreenBounds;
if (screenBounds.Contains(alignTo.Left, alignTo.Top - Height))
{
Location = new Point(alignTo.Left + (alignTo.Width / 2) - (Width / 2), alignTo.Top - Height);
}
else
{
Location = new Point(alignTo.Left + (alignTo.Width / 2) - (Width / 2), alignTo.Bottom);
}
Location = screenBounds.Contains(alignTo.Left, alignTo.Top - Height)
? new Point(alignTo.Left + (alignTo.Width / 2) - (Width / 2), alignTo.Top - Height)
: new Point(alignTo.Left + (alignTo.Width / 2) - (Width / 2), alignTo.Bottom);
}
}
}

View file

@ -86,13 +86,7 @@ namespace Greenshot.Base.Core
public virtual bool IsLinkable => false;
public virtual bool IsActive
{
get
{
return (CoreConfig.ExcludeDestinations?.Contains(Designation)) != true;
}
}
public virtual bool IsActive => (CoreConfig.ExcludeDestinations?.Contains(Designation)) != true;
public abstract ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails);
@ -129,10 +123,7 @@ namespace Greenshot.Base.Core
}
}
public override string ToString()
{
return Description;
}
public override string ToString() => Description;
/// <summary>
/// Helper method to add events which set the tag, this way we can see why there might be a close.
@ -188,7 +179,7 @@ namespace Greenshot.Base.Core
menu.ResumeLayout();
};
menu.Closing += delegate (object source, ToolStripDropDownClosingEventArgs eventArgs)
menu.Closing += (object source, ToolStripDropDownClosingEventArgs eventArgs) =>
{
Log.DebugFormat("Close reason: {0}", eventArgs.CloseReason);
switch (eventArgs.CloseReason)
@ -235,7 +226,7 @@ namespace Greenshot.Base.Core
{
// Fix foreach loop variable for the delegate
ToolStripMenuItem item = destination.GetMenuItem(addDynamics, menu,
delegate (object sender, EventArgs e)
(object sender, EventArgs e) =>
{
ToolStripMenuItem toolStripMenuItem = sender as ToolStripMenuItem;
IDestination clickedDestination = (IDestination)toolStripMenuItem?.Tag;
@ -311,14 +302,7 @@ namespace Greenshot.Base.Core
var menuRectangle = new NativeRect(location, menu.Size);
menuRectangle = menuRectangle.Intersect(DisplayInfo.ScreenBounds);
if (menuRectangle.Height < menu.Height)
{
location = location.Offset(-40, -(menuRectangle.Height - menu.Height));
}
else
{
location = location.Offset(-40, -10);
}
location = menuRectangle.Height < menu.Height ? location.Offset(-40, -(menuRectangle.Height - menu.Height)) : location.Offset(-40, -10);
// This prevents the problem that the context menu shows in the task-bar
User32Api.SetForegroundWindow(SimpleServiceProvider.Current.GetInstance<NotifyIcon>().ContextMenuStrip.Handle);

View file

@ -86,15 +86,9 @@ namespace Greenshot.Base.Core
}
}
private string Name
{
get { return accessible.get_accName(CHILDID_SELF); }
}
private string Name => accessible.get_accName(CHILDID_SELF);
private int ChildCount
{
get { return accessible.accChildCount; }
}
private int ChildCount => accessible.accChildCount;
public Accessible(IntPtr hWnd)
{
@ -194,13 +188,10 @@ namespace Greenshot.Base.Core
{
_ = tab.accessible.get_accState(CHILDID_SELF);
var description = tab.accessible.get_accDescription(CHILDID_SELF);
if (!string.IsNullOrEmpty(description))
if (!string.IsNullOrEmpty(description) && description.Contains(Environment.NewLine))
{
if (description.Contains(Environment.NewLine))
{
var url = description.Substring(description.IndexOf(Environment.NewLine)).Trim();
yield return url;
}
var url = description.Substring(description.IndexOf(Environment.NewLine)).Trim();
yield return url;
}
}
}
@ -208,15 +199,9 @@ namespace Greenshot.Base.Core
}
}
private Accessible(IAccessible acc)
{
accessible = acc ?? throw new Exception();
}
private Accessible(IAccessible acc) => accessible = acc ?? throw new Exception();
private void Activate()
{
accessible.accDoDefaultAction(CHILDID_SELF);
}
private void Activate() => accessible.accDoDefaultAction(CHILDID_SELF);
private static object[] GetAccessibleChildren(IAccessible ao, out int childs)
{

View file

@ -110,22 +110,13 @@ namespace Greenshot.Base.Core
/// <summary>
/// Final animation value, this is including the legs
/// </summary>
public T Final
{
get
{
return _queue.Count == 0 ? Last : _queue.ToArray()[_queue.Count - 1].Destination;
}
}
public T Final => _queue.Count == 0 ? Last : _queue.ToArray()[_queue.Count - 1].Destination;
/// <summary>
/// This restarts the current animation and changes the last frame
/// </summary>
/// <param name="newDestination"></param>
public void ChangeDestination(T newDestination)
{
ChangeDestination(newDestination, Frames);
}
public void ChangeDestination(T newDestination) => ChangeDestination(newDestination, Frames);
/// <summary>
/// This restarts the current animation and changes the last frame
@ -146,20 +137,14 @@ namespace Greenshot.Base.Core
/// All values will stay the same
/// </summary>
/// <param name="queuedDestination"></param>
public void QueueDestinationLeg(T queuedDestination)
{
QueueDestinationLeg(queuedDestination, Frames, EasingType, EasingMode);
}
public void QueueDestinationLeg(T queuedDestination) => QueueDestinationLeg(queuedDestination, Frames, EasingType, EasingMode);
/// <summary>
/// Queue the destination, it will be used to continue at the last frame
/// </summary>
/// <param name="queuedDestination"></param>
/// <param name="frames"></param>
public void QueueDestinationLeg(T queuedDestination, int frames)
{
QueueDestinationLeg(queuedDestination, frames, EasingType, EasingMode);
}
public void QueueDestinationLeg(T queuedDestination, int frames) => QueueDestinationLeg(queuedDestination, frames, EasingType, EasingMode);
/// <summary>
/// Queue the destination, it will be used to continue at the last frame
@ -167,10 +152,7 @@ namespace Greenshot.Base.Core
/// <param name="queuedDestination"></param>
/// <param name="frames"></param>
/// <param name="easingType">EasingType</param>
public void QueueDestinationLeg(T queuedDestination, int frames, EasingType easingType)
{
QueueDestinationLeg(queuedDestination, frames, easingType, EasingMode);
}
public void QueueDestinationLeg(T queuedDestination, int frames, EasingType easingType) => QueueDestinationLeg(queuedDestination, frames, easingType, EasingMode);
/// <summary>
/// Queue the destination, it will be used to continue at the last frame
@ -204,17 +186,13 @@ namespace Greenshot.Base.Core
/// <summary>
/// Get the easing value, which is from 0-1 and depends on the frame
/// </summary>
protected double EasingValue
protected double EasingValue => EasingMode switch
{
get =>
EasingMode switch
{
EasingMode.EaseOut => Easing.EaseOut(CurrentFrameNr / (double)Frames, EasingType),
EasingMode.EaseInOut => Easing.EaseInOut(CurrentFrameNr / (double)Frames, EasingType),
EasingMode.EaseIn => Easing.EaseIn(CurrentFrameNr / (double)Frames, EasingType),
_ => Easing.EaseIn(CurrentFrameNr / (double)Frames, EasingType)
};
}
EasingMode.EaseOut => Easing.EaseOut(CurrentFrameNr / (double)Frames, EasingType),
EasingMode.EaseInOut => Easing.EaseInOut(CurrentFrameNr / (double)Frames, EasingType),
EasingMode.EaseIn => Easing.EaseIn(CurrentFrameNr / (double)Frames, EasingType),
_ => Easing.EaseIn(CurrentFrameNr / (double)Frames, EasingType)
};
/// <summary>
/// Get the current (previous) frame object
@ -252,13 +230,7 @@ namespace Greenshot.Base.Core
/// <summary>
/// Are there more frames to animate?
/// </summary>
public virtual bool HasNext
{
get
{
return CurrentFrameNr < Frames || _queue.Count > 0;
}
}
public virtual bool HasNext => CurrentFrameNr < Frames || _queue.Count > 0;
/// <summary>
/// Get the next animation frame value object
@ -515,10 +487,7 @@ namespace Greenshot.Base.Core
_ => throw new NotImplementedException()
};
public static double EaseInOut(double linearStep, EasingType easeInType, EasingType easeOutType)
{
return linearStep < 0.5 ? EaseInOut(linearStep, easeInType) : EaseInOut(linearStep, easeOutType);
}
public static double EaseInOut(double linearStep, EasingType easeInType, EasingType easeOutType) => linearStep < 0.5 ? EaseInOut(linearStep, easeInType) : EaseInOut(linearStep, easeOutType);
public static double EaseInOut(double linearStep, EasingType type) =>
type switch
@ -535,28 +504,16 @@ namespace Greenshot.Base.Core
private static class Sine
{
public static double EaseIn(double s)
{
return Math.Sin((s * (Math.PI / 2)) - (Math.PI / 2)) + 1;
}
public static double EaseIn(double s) => Math.Sin((s * (Math.PI / 2)) - (Math.PI / 2)) + 1;
public static double EaseOut(double s)
{
return Math.Sin(s * (Math.PI / 2));
}
public static double EaseOut(double s) => Math.Sin(s * (Math.PI / 2));
public static double EaseInOut(double s)
{
return Math.Sin((s * Math.PI) - (Math.PI / 2) + 1) / 2;
}
public static double EaseInOut(double s) => Math.Sin((s * Math.PI) - (Math.PI / 2) + 1) / 2;
}
private static class Power
{
public static double EaseIn(double s, int power)
{
return Math.Pow(s, power);
}
public static double EaseIn(double s, int power) => Math.Pow(s, power);
public static double EaseOut(double s, int power)
{

View file

@ -52,29 +52,20 @@ namespace Greenshot.Base.Core
/// Initialize the cache
/// </summary>
/// <param name="expiredCallback"></param>
public Cache(CacheObjectExpired expiredCallback) : this()
{
_expiredCallback = expiredCallback;
}
public Cache(CacheObjectExpired expiredCallback) : this() => _expiredCallback = expiredCallback;
/// <summary>
/// Initialize the cache with a expire setting
/// </summary>
/// <param name="secondsToExpire"></param>
public Cache(int secondsToExpire) : this()
{
_secondsToExpire = secondsToExpire;
}
public Cache(int secondsToExpire) : this() => _secondsToExpire = secondsToExpire;
/// <summary>
/// Initialize the cache with a expire setting
/// </summary>
/// <param name="secondsToExpire"></param>
/// <param name="expiredCallback"></param>
public Cache(int secondsToExpire, CacheObjectExpired expiredCallback) : this(expiredCallback)
{
_secondsToExpire = secondsToExpire;
}
public Cache(int secondsToExpire, CacheObjectExpired expiredCallback) : this(expiredCallback) => _secondsToExpire = secondsToExpire;
/// <summary>
/// Enumerable for the values in the cache
@ -87,10 +78,7 @@ namespace Greenshot.Base.Core
lock (_lockObject)
{
foreach (TV element in _internalCache.Values)
{
elements.Add(element);
}
elements.AddRange(_internalCache.Values);
}
foreach (TV element in elements)
@ -140,10 +128,7 @@ namespace Greenshot.Base.Core
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void Add(TK key, TV value)
{
Add(key, value, null);
}
public void Add(TK key, TV value) => Add(key, value, null);
/// <summary>
/// Add a value to the cache
@ -156,7 +141,7 @@ namespace Greenshot.Base.Core
lock (_lockObject)
{
var cachedItem = new CachedItem(key, value, secondsToExpire ?? _secondsToExpire);
cachedItem.Expired += delegate (TK cacheKey, TV cacheValue)
cachedItem.Expired += (TK cacheKey, TV cacheValue) =>
{
if (_internalCache.ContainsKey(cacheKey))
{
@ -242,10 +227,7 @@ namespace Greenshot.Base.Core
}
}
private void timerEvent_Elapsed(object sender, ElapsedEventArgs e)
{
ExpireNow();
}
private void timerEvent_Elapsed(object sender, ElapsedEventArgs e) => ExpireNow();
public TK Key { get; private set; }
public TV Item { get; private set; }

View file

@ -97,10 +97,7 @@ namespace Greenshot.Base.Core
}
}
public void NullImage()
{
_image = null;
}
public void NullImage() => _image = null;
private Icon _cursor;
@ -162,10 +159,7 @@ namespace Greenshot.Base.Core
/// Note: the supplied bitmap can be disposed immediately or when constructor is called.
/// </summary>
/// <param name="newImage">Image</param>
public Capture(Image newImage) : this()
{
Image = newImage;
}
public Capture(Image newImage) : this() => Image = newImage;
/// <summary>
/// Destructor
@ -234,10 +228,7 @@ namespace Greenshot.Base.Core
/// </summary>
/// <param name="x">x coordinates to move the mouse</param>
/// <param name="y">y coordinates to move the mouse</param>
public void MoveMouseLocation(int x, int y)
{
CursorLocation = CursorLocation.Offset(x, y);
}
public void MoveMouseLocation(int x, int y) => CursorLocation = CursorLocation.Offset(x, y);
// TODO: Enable when the elements are usable again.
///// <summary>

View file

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

View file

@ -187,14 +187,9 @@ EndSelection:<<<<<<<4
{
string messageText;
string clipboardOwner = GetClipboardOwner();
if (clipboardOwner != null)
{
messageText = Language.GetFormattedString("clipboard_inuse", clipboardOwner);
}
else
{
messageText = Language.GetString("clipboard_error");
}
messageText = clipboardOwner != null
? Language.GetFormattedString("clipboard_inuse", clipboardOwner)
: Language.GetString("clipboard_error");
Log.Error(messageText, clipboardSetException);
}
@ -221,14 +216,9 @@ EndSelection:<<<<<<<4
{
string messageText;
string clipboardOwner = GetClipboardOwner();
if (clipboardOwner != null)
{
messageText = Language.GetFormattedString("clipboard_inuse", clipboardOwner);
}
else
{
messageText = Language.GetString("clipboard_error");
}
messageText = clipboardOwner != null
? Language.GetFormattedString("clipboard_inuse", clipboardOwner)
: Language.GetString("clipboard_error");
Log.Error(messageText, ee);
}
@ -254,12 +244,9 @@ EndSelection:<<<<<<<4
/// <returns></returns>
public static bool ContainsText(IDataObject dataObject)
{
if (dataObject != null)
if (dataObject != null && (dataObject.GetDataPresent(DataFormats.Text) || dataObject.GetDataPresent(DataFormats.UnicodeText)))
{
if (dataObject.GetDataPresent(DataFormats.Text) || dataObject.GetDataPresent(DataFormats.UnicodeText))
{
return true;
}
return true;
}
return false;
@ -487,10 +474,7 @@ EndSelection:<<<<<<<4
/// </summary>
/// <param name="memoryStream"></param>
/// <returns>true if there is a valid stream</returns>
private static bool IsValidStream(MemoryStream memoryStream)
{
return memoryStream?.Length > 0;
}
private static bool IsValidStream(MemoryStream memoryStream) => memoryStream?.Length > 0;
/// <summary>
/// Wrapper for Clipboard.GetImage, Created for Bug #3432313
@ -885,10 +869,7 @@ EndSelection:<<<<<<<4
/// Get Text from the DataObject
/// </summary>
/// <returns>string if there is text on the clipboard</returns>
public static string GetText(IDataObject dataObject)
{
return ContainsText(dataObject) ? (string)dataObject.GetData(DataFormats.Text) : null;
}
public static string GetText(IDataObject dataObject) => ContainsText(dataObject) ? (string)dataObject.GetData(DataFormats.Text) : null;
/// <summary>
/// Set text to the clipboard
@ -1177,23 +1158,17 @@ EndSelection:<<<<<<<4
/// <param name="dataObject">IDataObject</param>
/// <param name="format">string with format</param>
/// <returns>true if one the format is found</returns>
public static bool ContainsFormat(IDataObject dataObject, string format)
{
return ContainsFormat(dataObject, new[]
public static bool ContainsFormat(IDataObject dataObject, string format) => ContainsFormat(dataObject, new[]
{
format
});
}
/// <summary>
/// Check if there is currently something on the clipboard which has one of the supplied formats
/// </summary>
/// <param name="formats">string[] with formats</param>
/// <returns>true if one of the formats was found</returns>
public static bool ContainsFormat(string[] formats)
{
return ContainsFormat(GetDataObject(), formats);
}
public static bool ContainsFormat(string[] formats) => ContainsFormat(GetDataObject(), formats);
/// <summary>
/// Check if there is currently something on the clipboard which has one of the supplied formats
@ -1210,13 +1185,12 @@ EndSelection:<<<<<<<4
return false;
}
foreach (string format in formats)
foreach (var _ in from string format in formats
where currentFormats.Contains(format)
select new { })
{
if (currentFormats.Contains(format))
{
formatFound = true;
break;
}
formatFound = true;
break;
}
return formatFound;
@ -1228,10 +1202,7 @@ EndSelection:<<<<<<<4
/// <param name="dataObj">IDataObject</param>
/// <param name="type">Type to get</param>
/// <returns>object from IDataObject</returns>
public static object GetFromDataObject(IDataObject dataObj, Type type)
{
return type != null ? GetFromDataObject(dataObj, type.FullName) : null;
}
public static object GetFromDataObject(IDataObject dataObj, Type type) => type != null ? GetFromDataObject(dataObj, type.FullName) : null;
/// <summary>
/// Get ImageFilenames from the IDataObject

View file

@ -365,7 +365,7 @@ namespace Greenshot.Base.Core
if (_iconSize != newSize)
{
_iconSize = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IconSize"));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IconSize)));
}
}
}
@ -383,10 +383,7 @@ namespace Greenshot.Base.Core
/// </summary>
/// <param name="experimentalFeature"></param>
/// <returns></returns>
public bool IsExperimentalFeatureEnabled(string experimentalFeature)
{
return ExperimentalFeatures?.Contains(experimentalFeature) == true;
}
public bool IsExperimentalFeatureEnabled(string experimentalFeature) => ExperimentalFeatures?.Contains(experimentalFeature) == true;
private string CreateOutputFilePath()
{
@ -456,20 +453,14 @@ namespace Greenshot.Base.Core
public override string PreCheckValue(string propertyName, string propertyValue)
{
// Changed the separator, now we need to correct this
if ("Destinations".Equals(propertyName))
if ("Destinations".Equals(propertyName) && propertyValue != null)
{
if (propertyValue != null)
{
return propertyValue.Replace('|', ',');
}
return propertyValue.Replace('|', ',');
}
if ("OutputFilePath".Equals(propertyName))
if ("OutputFilePath".Equals(propertyName) && string.IsNullOrEmpty(propertyValue))
{
if (string.IsNullOrEmpty(propertyValue))
{
return null;
}
return null;
}
return base.PreCheckValue(propertyName, propertyValue);
@ -528,12 +519,9 @@ namespace Greenshot.Base.Core
}
// Enable OneNote if upgrading from 1.1
if (ExcludeDestinations?.Contains("OneNote") == true)
if (ExcludeDestinations?.Contains("OneNote") == true && LastSaveWithVersion?.StartsWith("1.1") == true)
{
if (LastSaveWithVersion?.StartsWith("1.1") == true)
{
ExcludeDestinations.Remove("OneNote");
}
ExcludeDestinations.Remove("OneNote");
}
if (OutputDestinations == null)
@ -568,14 +556,11 @@ namespace Greenshot.Base.Core
if (NoGDICaptureForProduct != null)
{
// Fix error in configuration
if (NoGDICaptureForProduct.Count >= 2)
if (NoGDICaptureForProduct.Count >= 2 && "intellij".Equals(NoGDICaptureForProduct[0]) && "idea".Equals(NoGDICaptureForProduct[1]))
{
if ("intellij".Equals(NoGDICaptureForProduct[0]) && "idea".Equals(NoGDICaptureForProduct[1]))
{
NoGDICaptureForProduct.RemoveRange(0, 2);
NoGDICaptureForProduct.Add("Intellij Idea");
IsDirty = true;
}
NoGDICaptureForProduct.RemoveRange(0, 2);
NoGDICaptureForProduct.Add("Intellij Idea");
IsDirty = true;
}
for (int i = 0; i < NoGDICaptureForProduct.Count; i++)
@ -587,14 +572,11 @@ namespace Greenshot.Base.Core
if (NoDWMCaptureForProduct != null)
{
// Fix error in configuration
if (NoDWMCaptureForProduct.Count >= 3)
if (NoDWMCaptureForProduct.Count >= 3 && "citrix".Equals(NoDWMCaptureForProduct[0]) && "ica".Equals(NoDWMCaptureForProduct[1]) && "client".Equals(NoDWMCaptureForProduct[2]))
{
if ("citrix".Equals(NoDWMCaptureForProduct[0]) && "ica".Equals(NoDWMCaptureForProduct[1]) && "client".Equals(NoDWMCaptureForProduct[2]))
{
NoDWMCaptureForProduct.RemoveRange(0, 3);
NoDWMCaptureForProduct.Add("Citrix ICA Client");
IsDirty = true;
}
NoDWMCaptureForProduct.RemoveRange(0, 3);
NoDWMCaptureForProduct.Add("Citrix ICA Client");
IsDirty = true;
}
for (int i = 0; i < NoDWMCaptureForProduct.Count; i++)

View file

@ -275,10 +275,7 @@ namespace Greenshot.Base.Core
/// <summary>Shows the credentials dialog with the specified name.</summary>
/// <param name="name">The name for the credentials.</param>
/// <returns>Returns a DialogResult indicating the user action.</returns>
public DialogResult Show(string name)
{
return Show(null, name, Password, SaveChecked);
}
public DialogResult Show(string name) => Show(null, name, Password, SaveChecked);
/// <summary>Shows the credentials dialog with the specified owner, name, password and save checkbox status.</summary>
/// <param name="owner">The System.Windows.Forms.IWin32Window the dialog will display in front of.</param>

View file

@ -37,12 +37,8 @@ namespace Greenshot.Base.Core
/// Method to get all the destinations from the plugins
/// </summary>
/// <returns>List of IDestination</returns>
public static IEnumerable<IDestination> GetAllDestinations()
{
return SimpleServiceProvider.Current.GetAllInstances<IDestination>()
.Where(destination => destination.IsActive)
.Where(destination => CoreConfig.ExcludeDestinations?.Contains(destination.Designation) != true).OrderBy(p => p.Priority).ThenBy(p => p.Description);
}
public static IEnumerable<IDestination> GetAllDestinations() => SimpleServiceProvider.Current.GetAllInstances<IDestination>()
.Where(destination => destination.IsActive && CoreConfig.ExcludeDestinations?.Contains(destination.Designation) != true).OrderBy(p => p.Priority).ThenBy(p => p.Description);
/// <summary>
/// Get a destination by a designation
@ -56,12 +52,11 @@ namespace Greenshot.Base.Core
return null;
}
foreach (IDestination destination in GetAllDestinations())
foreach (var destination in from IDestination destination in GetAllDestinations()
where designation.Equals(destination.Designation)
select destination)
{
if (designation.Equals(destination.Designation))
{
return destination;
}
return destination;
}
return null;
@ -74,10 +69,7 @@ namespace Greenshot.Base.Core
/// <param name="designation">WellKnownDestinations</param>
/// <param name="surface">ISurface</param>
/// <param name="captureDetails">ICaptureDetails</param>
public static ExportInformation ExportCapture(bool manuallyInitiated, WellKnownDestinations designation, ISurface surface, ICaptureDetails captureDetails)
{
return ExportCapture(manuallyInitiated, designation.ToString(), surface, captureDetails);
}
public static ExportInformation ExportCapture(bool manuallyInitiated, WellKnownDestinations designation, ISurface surface, ICaptureDetails captureDetails) => ExportCapture(manuallyInitiated, designation.ToString(), surface, captureDetails);
/// <summary>
/// A simple helper method which will call ExportCapture for the destination with the specified designation

View file

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

View file

@ -20,10 +20,7 @@ namespace Greenshot.Base.Core
_numberFormatInfo.NumberGroupSeparator = ",";
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) => sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
@ -53,7 +50,7 @@ namespace Greenshot.Base.Core
return sb.ToString();
}
if (value.GetType() == typeof(TornEdgeEffect))
if (value is TornEdgeEffect)
{
TornEdgeEffect effect = value as TornEdgeEffect;
RetrieveDropShadowEffectValues(effect, sb);
@ -108,12 +105,9 @@ namespace Greenshot.Base.Core
{
case "Darkness":
// Fix to prevent BUG-1753
if (pair[1] != null && float.TryParse(pair[1], NumberStyles.Float, _numberFormatInfo, out var darkness))
if (pair[1] != null && float.TryParse(pair[1], NumberStyles.Float, _numberFormatInfo, out var darkness) && darkness <= 1.0)
{
if (darkness <= 1.0)
{
effect.Darkness = darkness;
}
effect.Darkness = darkness;
}
break;
@ -206,17 +200,12 @@ namespace Greenshot.Base.Core
}
}
private void RetrieveDropShadowEffectValues(DropShadowEffect effect, StringBuilder sb)
{
private void RetrieveDropShadowEffectValues(DropShadowEffect effect, StringBuilder sb) =>
// Fix to prevent BUG-1753 is to use the numberFormatInfo
sb.AppendFormat("Darkness:{0}|ShadowSize:{1}|ShadowOffset:{2},{3}", effect.Darkness.ToString("F2", _numberFormatInfo), effect.ShadowSize, effect.ShadowOffset.X,
effect.ShadowOffset.Y);
}
private void RetrieveTornEdgeEffectValues(TornEdgeEffect effect, StringBuilder sb)
{
sb.AppendFormat("GenerateShadow:{0}|ToothHeight:{1}|HorizontalToothRange:{2}|VerticalToothRange:{3}|Edges:{4},{5},{6},{7}", effect.GenerateShadow, effect.ToothHeight,
private void RetrieveTornEdgeEffectValues(TornEdgeEffect effect, StringBuilder sb) => sb.AppendFormat("GenerateShadow:{0}|ToothHeight:{1}|HorizontalToothRange:{2}|VerticalToothRange:{3}|Edges:{4},{5},{6},{7}", effect.GenerateShadow, effect.ToothHeight,
effect.HorizontalToothRange, effect.VerticalToothRange, effect.Edges[0], effect.Edges[1], effect.Edges[2], effect.Edges[3]);
}
}
}

View file

@ -54,11 +54,9 @@ namespace Greenshot.Base.Core
}
}
public static bool IsNet45OrNewer()
{
public static bool IsNet45OrNewer() =>
// Class "ReflectionContext" exists from .NET 4.5 onwards.
return Type.GetType("System.Reflection.ReflectionContext", false) != null;
}
Type.GetType("System.Reflection.ReflectionContext", false) != null;
public static string GetGreenshotVersion(bool shortVersion = false)
{
@ -304,84 +302,82 @@ namespace Greenshot.Base.Core
var productType = osVersionInfo.ProductType;
var suiteMask = osVersionInfo.SuiteMask;
if (majorVersion == 4)
switch (majorVersion)
{
if (productType == WindowsProductTypes.VER_NT_WORKSTATION)
{
// Windows NT 4.0 Workstation
edition = "Workstation";
}
else if (productType == WindowsProductTypes.VER_NT_SERVER)
{
edition = (suiteMask & WindowsSuites.Enterprise) != 0 ? "Enterprise Server" : "Standard Server";
}
}
else if (majorVersion == 5)
{
if (productType == WindowsProductTypes.VER_NT_WORKSTATION)
{
if ((suiteMask & WindowsSuites.Personal) != 0)
case 4:
if (productType == WindowsProductTypes.VER_NT_WORKSTATION)
{
// Windows XP Home Edition
edition = "Home";
// Windows NT 4.0 Workstation
edition = "Workstation";
}
else
else if (productType == WindowsProductTypes.VER_NT_SERVER)
{
// Windows XP / Windows 2000 Professional
edition = "Professional";
edition = (suiteMask & WindowsSuites.Enterprise) != 0 ? "Enterprise Server" : "Standard Server";
}
}
else if (productType == WindowsProductTypes.VER_NT_SERVER)
{
if (minorVersion == 0)
break;
case 5:
if (productType == WindowsProductTypes.VER_NT_WORKSTATION)
{
if ((suiteMask & WindowsSuites.DataCenter) != 0)
if ((suiteMask & WindowsSuites.Personal) != 0)
{
// Windows 2000 Datacenter Server
edition = "Datacenter Server";
}
else if ((suiteMask & WindowsSuites.Enterprise) != 0)
{
// Windows 2000 Advanced Server
edition = "Advanced Server";
// Windows XP Home Edition
edition = "Home";
}
else
{
// Windows 2000 Server
edition = "Server";
// Windows XP / Windows 2000 Professional
edition = "Professional";
}
}
else
else if (productType == WindowsProductTypes.VER_NT_SERVER)
{
if ((suiteMask & WindowsSuites.DataCenter) != 0)
switch (minorVersion)
{
// Windows Server 2003 Datacenter Edition
edition = "Datacenter";
}
else if ((suiteMask & WindowsSuites.Enterprise) != 0)
{
// Windows Server 2003 Enterprise Edition
edition = "Enterprise";
}
else if ((suiteMask & WindowsSuites.Blade) != 0)
{
// Windows Server 2003 Web Edition
edition = "Web Edition";
}
else
{
// Windows Server 2003 Standard Edition
edition = "Standard";
case 0:
if ((suiteMask & WindowsSuites.DataCenter) != 0)
{
// Windows 2000 Datacenter Server
edition = "Datacenter Server";
}
else if ((suiteMask & WindowsSuites.Enterprise) != 0)
{
// Windows 2000 Advanced Server
edition = "Advanced Server";
}
else
{
// Windows 2000 Server
edition = "Server";
}
break;
default:
if ((suiteMask & WindowsSuites.DataCenter) != 0)
{
// Windows Server 2003 Datacenter Edition
edition = "Datacenter";
}
else if ((suiteMask & WindowsSuites.Enterprise) != 0)
{
// Windows Server 2003 Enterprise Edition
edition = "Enterprise";
}
else if ((suiteMask & WindowsSuites.Blade) != 0)
{
// Windows Server 2003 Web Edition
edition = "Web Edition";
}
else
{
// Windows Server 2003 Standard Edition
edition = "Standard";
}
break;
}
}
}
}
else if (majorVersion == 6)
{
if (Kernel32Api.GetProductInfo(majorVersion, minorVersion, osVersionInfo.ServicePackMajor, osVersionInfo.ServicePackMinor, out var windowsProduct))
{
break;
case 6 when Kernel32Api.GetProductInfo(majorVersion, minorVersion, osVersionInfo.ServicePackMajor, osVersionInfo.ServicePackMinor, out var windowsProduct):
edition = windowsProduct.GetEnumDescription();
}
break;
}
}
@ -423,14 +419,7 @@ namespace Greenshot.Base.Core
switch (minorVersion)
{
case 0:
if (csdVersion == "B" || csdVersion == "C")
{
name = "Windows 95 OSR2";
}
else
{
name = "Windows 95";
}
name = csdVersion == "B" || csdVersion == "C" ? "Windows 95 OSR2" : "Windows 95";
break;
case 10:

View file

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

View file

@ -290,15 +290,9 @@ namespace Greenshot.Base.Core
protected bool BitsLocked;
protected byte* Pointer;
public static IFastBitmap Create(Bitmap source)
{
return Create(source, NativeRect.Empty);
}
public static IFastBitmap Create(Bitmap source) => Create(source, NativeRect.Empty);
public void SetResolution(float horizontal, float vertical)
{
Bitmap.SetResolution(horizontal, vertical);
}
public void SetResolution(float horizontal, float vertical) => Bitmap.SetResolution(horizontal, vertical);
/// <summary>
/// Factory for creating a FastBitmap depending on the pixelformat of the source
@ -324,10 +318,7 @@ namespace Greenshot.Base.Core
/// <param name="source">Bitmap to clone</param>
/// <param name="pixelFormat">new PixelFormat</param>
/// <returns>IFastBitmap</returns>
public static IFastBitmap CreateCloneOf(Image source, PixelFormat pixelFormat)
{
return CreateCloneOf(source, pixelFormat, NativeRect.Empty);
}
public static IFastBitmap CreateCloneOf(Image source, PixelFormat pixelFormat) => CreateCloneOf(source, pixelFormat, NativeRect.Empty);
/// <summary>
/// Factory for creating a FastBitmap as a destination for the source
@ -335,10 +326,7 @@ namespace Greenshot.Base.Core
/// <param name="source">Bitmap to clone</param>
/// <param name="area">Area of the bitmap to access, can be NativeRect.Empty for the whole</param>
/// <returns>IFastBitmap</returns>
public static IFastBitmap CreateCloneOf(Image source, NativeRect area)
{
return CreateCloneOf(source, PixelFormat.DontCare, area);
}
public static IFastBitmap CreateCloneOf(Image source, NativeRect area) => CreateCloneOf(source, PixelFormat.DontCare, area);
/// <summary>
/// Factory for creating a FastBitmap as a destination for the source
@ -408,35 +396,17 @@ namespace Greenshot.Base.Core
/// <summary>
/// Return the size of the image
/// </summary>
public NativeSize Size
{
get
{
return Area == NativeRect.Empty ? (NativeSize)Bitmap.Size : Area.Size;
}
}
public NativeSize Size => Area == NativeRect.Empty ? (NativeSize)Bitmap.Size : Area.Size;
/// <summary>
/// Return the width of the image
/// </summary>
public int Width
{
get
{
return Area == NativeRect.Empty ? Bitmap.Width : Area.Width;
}
}
public int Width => Area == NativeRect.Empty ? Bitmap.Width : Area.Width;
/// <summary>
/// Return the height of the image
/// </summary>
public int Height
{
get
{
return Area == NativeRect.Empty ? Bitmap.Height : Area.Height;
}
}
public int Height => Area == NativeRect.Empty ? Bitmap.Height : Area.Height;
private int _left;
@ -532,12 +502,9 @@ namespace Greenshot.Base.Core
protected virtual void Dispose(bool disposing)
{
Unlock();
if (disposing)
if (disposing && Bitmap != null && NeedsDispose)
{
if (Bitmap != null && NeedsDispose)
{
Bitmap.Dispose();
}
Bitmap.Dispose();
}
Bitmap = null;
@ -580,10 +547,7 @@ namespace Greenshot.Base.Core
/// </summary>
/// <param name="graphics"></param>
/// <param name="destination"></param>
public void DrawTo(Graphics graphics, NativePoint destination)
{
DrawTo(graphics, new NativeRect(destination, Area.Size));
}
public void DrawTo(Graphics graphics, NativePoint destination) => DrawTo(graphics, new NativeRect(destination, Area.Size));
/// <summary>
/// Draw the stored Bitmap on the Destination bitmap with the specified rectangle
@ -609,10 +573,7 @@ namespace Greenshot.Base.Core
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>true if x & y are inside the FastBitmap</returns>
public bool Contains(int x, int y)
{
return Area.Contains(x - Left, y - Top);
}
public bool Contains(int x, int y) => Area.Contains(x - Left, y - Top);
public abstract Color GetColorAt(int x, int y);
public abstract void SetColorAt(int x, int y, Color color);
@ -653,10 +614,7 @@ namespace Greenshot.Base.Core
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>true if x & y are inside the FastBitmap</returns>
bool IFastBitmapWithOffset.Contains(int x, int y)
{
return Area.Contains(x - Left, y - Top);
}
bool IFastBitmapWithOffset.Contains(int x, int y) => Area.Contains(x - Left, y - Top);
Color IFastBitmapWithOffset.GetColorAt(int x, int y)
{
@ -696,10 +654,7 @@ namespace Greenshot.Base.Core
private readonly Color[] _colorEntries;
private readonly Dictionary<Color, byte> _colorCache = new();
public FastChunkyBitmap(Bitmap source, NativeRect area) : base(source, area)
{
_colorEntries = Bitmap.Palette.Entries;
}
public FastChunkyBitmap(Bitmap source, NativeRect area) : base(source, area) => _colorEntries = Bitmap.Palette.Entries;
/// <summary>
/// Get the color from the specified location
@ -720,10 +675,7 @@ namespace Greenshot.Base.Core
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="color">byte[4] as reference</param>
public override void GetColorAt(int x, int y, byte[] color)
{
throw new NotImplementedException("No performance gain!");
}
public override void GetColorAt(int x, int y, byte[] color) => throw new NotImplementedException("No performance gain!");
/// <summary>
/// Set the color at the specified location from the specified array
@ -731,10 +683,7 @@ namespace Greenshot.Base.Core
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="color">byte[4] as reference</param>
public override void SetColorAt(int x, int y, byte[] color)
{
throw new NotImplementedException("No performance gain!");
}
public override void SetColorAt(int x, int y, byte[] color) => throw new NotImplementedException("No performance gain!");
/// <summary>
/// Get the color-index from the specified location
@ -934,10 +883,7 @@ namespace Greenshot.Base.Core
public Color BackgroundBlendColor { get; set; }
public Fast32ArgbBitmap(Bitmap source, NativeRect area) : base(source, area)
{
BackgroundBlendColor = Color.White;
}
public Fast32ArgbBitmap(Bitmap source, NativeRect area) : base(source, area) => BackgroundBlendColor = Color.White;
/// <summary>
/// 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="fileFormatHandlerAction"></param>
/// <returns></returns>
public static IEnumerable<string> ExtensionsFor(this IEnumerable<IFileFormatHandler> fileFormatHandlers, FileFormatHandlerActions fileFormatHandlerAction)
{
return fileFormatHandlers.Where(ffh => ffh.SupportedExtensions.ContainsKey(fileFormatHandlerAction)).SelectMany(ffh => ffh.SupportedExtensions[fileFormatHandlerAction]).Distinct().OrderBy(e => e);
}
public static IEnumerable<string> ExtensionsFor(this IEnumerable<IFileFormatHandler> fileFormatHandlers, FileFormatHandlerActions fileFormatHandlerAction) => fileFormatHandlers.Where(ffh => ffh.SupportedExtensions.ContainsKey(fileFormatHandlerAction)).SelectMany(ffh => ffh.SupportedExtensions[fileFormatHandlerAction]).Distinct().OrderBy(e => e);
/// <summary>
/// Extension method to check if a certain IFileFormatHandler supports a certain action with a specific extension
@ -98,12 +95,11 @@ namespace Greenshot.Base.Core.FileFormatHandlers
return false;
}
foreach (var fileFormatHandler in saveFileFormatHandlers)
foreach (var _ in from fileFormatHandler in saveFileFormatHandlers
where fileFormatHandler.TrySaveToStream(bitmap, destination, extension, surface)
select new { })
{
if (fileFormatHandler.TrySaveToStream(bitmap, destination, extension, surface))
{
return true;
}
return true;
}
return false;

View file

@ -103,25 +103,13 @@ namespace Greenshot.Base.Core
return path;
}
public static string GetFilenameWithoutExtensionFromPattern(string pattern)
{
return GetFilenameWithoutExtensionFromPattern(pattern, null);
}
public static string GetFilenameWithoutExtensionFromPattern(string pattern) => GetFilenameWithoutExtensionFromPattern(pattern, null);
public static string GetFilenameWithoutExtensionFromPattern(string pattern, ICaptureDetails captureDetails)
{
return FillPattern(pattern, captureDetails, true);
}
public static string GetFilenameWithoutExtensionFromPattern(string pattern, ICaptureDetails captureDetails) => FillPattern(pattern, captureDetails, true);
public static string GetFilenameFromPattern(string pattern, OutputFormat imageFormat)
{
return GetFilenameFromPattern(pattern, imageFormat, null);
}
public static string GetFilenameFromPattern(string pattern, OutputFormat imageFormat) => GetFilenameFromPattern(pattern, imageFormat, null);
public static string GetFilenameFromPattern(string pattern, OutputFormat imageFormat, ICaptureDetails captureDetails)
{
return FillPattern(pattern, captureDetails, true) + "." + imageFormat.ToString().ToLower();
}
public static string GetFilenameFromPattern(string pattern, OutputFormat imageFormat, ICaptureDetails captureDetails) => FillPattern(pattern, captureDetails, true) + "." + imageFormat.ToString().ToLower();
/// <summary>
/// Return a filename for the current image format (png,jpg etc) with the default file pattern

View file

@ -31,19 +31,10 @@ namespace Greenshot.Base.Core
{
private static readonly ComponentResourceManager GreenshotResourceManager = new(typeof(GreenshotResources));
public static Image GetImage(string imageName)
{
return (Image)GreenshotResourceManager.GetObject(imageName);
}
public static Image GetImage(string imageName) => (Image)GreenshotResourceManager.GetObject(imageName);
public static Icon GetIcon(string imageName)
{
return (Icon)GreenshotResourceManager.GetObject(imageName);
}
public static Icon GetIcon(string imageName) => (Icon)GreenshotResourceManager.GetObject(imageName);
public static Icon GetGreenshotIcon()
{
return GetIcon("Greenshot.Icon");
}
public static Icon GetGreenshotIcon() => GetIcon("Greenshot.Icon");
}
}

View file

@ -106,10 +106,7 @@ namespace Greenshot.Base.Core
/// </summary>
/// <param name="applicationName">Name of the process</param>
/// <param name="ignoreDoctype">true to ignore the doctype when loading a page</param>
public static void FixBrowserVersion(string applicationName, bool ignoreDoctype = true)
{
FixBrowserVersion(applicationName, GetEmbVersion(ignoreDoctype));
}
public static void FixBrowserVersion(string applicationName, bool ignoreDoctype = true) => FixBrowserVersion(applicationName, GetEmbVersion(ignoreDoctype));
/// <summary>
/// Fix the browser version for the specified application

View file

@ -244,12 +244,9 @@ namespace Greenshot.Base.Core
}
}
if (!(NativePoint.Empty.Equals(min) && max.Equals(new NativePoint(area.Value.Width - 1, area.Value.Height - 1))))
if (!(NativePoint.Empty.Equals(min) && max.Equals(new NativePoint(area.Value.Width - 1, area.Value.Height - 1))) && !(min.X == int.MaxValue || min.Y == int.MaxValue || max.X == int.MinValue || min.X == int.MinValue))
{
if (!(min.X == int.MaxValue || min.Y == int.MaxValue || max.X == int.MinValue || min.X == int.MinValue))
{
cropNativeRect = new NativeRect(min.X, min.Y, max.X - min.X + 1, max.Y - min.Y + 1);
}
cropNativeRect = new NativeRect(min.X, min.Y, max.X - min.X + 1, max.Y - min.Y + 1);
}
return cropNativeRect;
@ -811,16 +808,9 @@ namespace Greenshot.Base.Core
{
Matrix00 = 0,
Matrix11 = 0,
Matrix22 = 0
Matrix22 = 0,
Matrix33 = useGdiBlur ? darkness + 0.1f : darkness
};
if (useGdiBlur)
{
maskMatrix.Matrix33 = darkness + 0.1f;
}
else
{
maskMatrix.Matrix33 = darkness;
}
NativeRect shadowNativeRect = new(new NativePoint(shadowSize, shadowSize), sourceBitmap.Size);
ApplyColorMatrix((Bitmap)sourceBitmap, NativeRect.Empty, returnImage, shadowNativeRect, maskMatrix);
@ -897,10 +887,7 @@ namespace Greenshot.Base.Core
/// </summary>
/// <param name="source">Image to apply matrix to</param>
/// <param name="colorMatrix">ColorMatrix to apply</param>
public static void ApplyColorMatrix(Bitmap source, ColorMatrix colorMatrix)
{
ApplyColorMatrix(source, NativeRect.Empty, source, NativeRect.Empty, colorMatrix);
}
public static void ApplyColorMatrix(Bitmap source, ColorMatrix colorMatrix) => ApplyColorMatrix(source, NativeRect.Empty, source, NativeRect.Empty, colorMatrix);
/// <summary>
/// Apply a color matrix by copying from the source to the destination
@ -1130,23 +1117,17 @@ namespace Greenshot.Base.Core
/// </summary>
/// <param name="pixelformat">PixelFormat to check</param>
/// <returns>bool if we support it</returns>
public static bool SupportsPixelFormat(PixelFormat pixelformat)
{
return pixelformat.Equals(PixelFormat.Format32bppArgb) ||
public static bool SupportsPixelFormat(PixelFormat pixelformat) => pixelformat.Equals(PixelFormat.Format32bppArgb) ||
pixelformat.Equals(PixelFormat.Format32bppPArgb) ||
pixelformat.Equals(PixelFormat.Format32bppRgb) ||
pixelformat.Equals(PixelFormat.Format24bppRgb);
}
/// <summary>
/// Wrapper for just cloning which calls the CloneArea
/// </summary>
/// <param name="sourceImage">Image to clone</param>
/// <returns>Bitmap with clone image data</returns>
public static Image Clone(Image sourceImage)
{
return sourceImage is Metafile ? (Image)sourceImage.Clone() : CloneArea(sourceImage, NativeRect.Empty, PixelFormat.DontCare);
}
public static Image Clone(Image sourceImage) => sourceImage is Metafile ? (Image)sourceImage.Clone() : CloneArea(sourceImage, NativeRect.Empty, PixelFormat.DontCare);
/// <summary>
/// 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="targetFormat">Target Format, use PixelFormat.DontCare if you want the original (or a default if the source PixelFormat is not supported)</param>
/// <returns>Bitmap with clone image data</returns>
public static Bitmap Clone(Image sourceBitmap, PixelFormat targetFormat)
{
return CloneArea(sourceBitmap, NativeRect.Empty, targetFormat);
}
public static Bitmap Clone(Image sourceBitmap, PixelFormat targetFormat) => CloneArea(sourceBitmap, NativeRect.Empty, targetFormat);
/// <summary>
/// Clone an image, taking some rules into account:
@ -1176,14 +1154,9 @@ namespace Greenshot.Base.Core
NativeRect bitmapRect = new(0, 0, sourceImage.Width, sourceImage.Height);
// Make sure the source is not NativeRect.Empty
if (NativeRect.Empty.Equals(sourceRect))
{
sourceRect = new NativeRect(0, 0, sourceImage.Width, sourceImage.Height);
}
else
{
sourceRect = sourceRect.Intersect(bitmapRect);
}
sourceRect = NativeRect.Empty.Equals(sourceRect)
? new NativeRect(0, 0, sourceImage.Width, sourceImage.Height)
: sourceRect.Intersect(bitmapRect);
// If no pixelformat is supplied
if (targetFormat is PixelFormat.DontCare or PixelFormat.Undefined)
@ -1192,13 +1165,9 @@ namespace Greenshot.Base.Core
{
targetFormat = sourceImage.PixelFormat;
}
else if (Image.IsAlphaPixelFormat(sourceImage.PixelFormat))
{
targetFormat = PixelFormat.Format32bppArgb;
}
else
{
targetFormat = PixelFormat.Format24bppRgb;
targetFormat = Image.IsAlphaPixelFormat(sourceImage.PixelFormat) ? PixelFormat.Format32bppArgb : PixelFormat.Format24bppRgb;
}
}
@ -1369,10 +1338,7 @@ namespace Greenshot.Base.Core
/// <param name="newHeight"></param>
/// <param name="matrix"></param>
/// <returns></returns>
public static Image ResizeImage(Image sourceImage, bool maintainAspectRatio, int newWidth, int newHeight, Matrix matrix)
{
return ResizeImage(sourceImage, maintainAspectRatio, false, Color.Empty, newWidth, newHeight, matrix);
}
public static Image ResizeImage(Image sourceImage, bool maintainAspectRatio, int newWidth, int newHeight, Matrix matrix) => ResizeImage(sourceImage, maintainAspectRatio, false, Color.Empty, newWidth, newHeight, matrix);
/// <summary>
/// Count how many times the supplied color exists

View file

@ -84,51 +84,50 @@ namespace Greenshot.Base.Core
while (!done)
{
token = LookAhead(json, index);
if (token == TOKEN_NONE)
switch (token)
{
success = false;
return null;
}
else if (token == TOKEN_COMMA)
{
NextToken(json, ref index);
}
else if (token == TOKEN_CURLY_CLOSE)
{
NextToken(json, ref index);
return table;
}
else
{
// name
string name = ParseString(json, ref index, ref success);
if (!success)
{
case TOKEN_NONE:
success = false;
return null;
}
case TOKEN_COMMA:
NextToken(json, ref index);
break;
case TOKEN_CURLY_CLOSE:
NextToken(json, ref index);
return table;
default:
{
// name
string name = ParseString(json, ref index, ref success);
if (!success)
{
success = false;
return null;
}
// :
token = NextToken(json, ref index);
if (token != TOKEN_COLON)
{
success = false;
return null;
}
// :
token = NextToken(json, ref index);
if (token != TOKEN_COLON)
{
success = false;
return null;
}
// value
object value = ParseValue(json, ref index, ref success);
if (!success)
{
success = false;
return null;
}
// value
object value = ParseValue(json, ref index, ref success);
if (!success)
{
success = false;
return null;
}
table.Add(name, value);
table.Add(name, value);
break;
}
}
}
return table;
// return table;
}
protected static IList<object> ParseArray(char[] json, ref int index, ref bool success)
@ -391,43 +390,34 @@ namespace Greenshot.Base.Core
int remainingLength = json.Length - index;
// false
if (remainingLength >= 5)
{
if (json[index] == 'f' &&
if (remainingLength >= 5 && json[index] == 'f' &&
json[index + 1] == 'a' &&
json[index + 2] == 'l' &&
json[index + 3] == 's' &&
json[index + 4] == 'e')
{
index += 5;
return TOKEN_FALSE;
}
{
index += 5;
return TOKEN_FALSE;
}
// true
if (remainingLength >= 4)
{
if (json[index] == 't' &&
if (remainingLength >= 4 && json[index] == 't' &&
json[index + 1] == 'r' &&
json[index + 2] == 'u' &&
json[index + 3] == 'e')
{
index += 4;
return TOKEN_TRUE;
}
{
index += 4;
return TOKEN_TRUE;
}
// null
if (remainingLength >= 4)
{
if (json[index] == 'n' &&
if (remainingLength >= 4 && json[index] == 'n' &&
json[index + 1] == 'u' &&
json[index + 2] == 'l' &&
json[index + 3] == 'l')
{
index += 4;
return TOKEN_NULL;
}
{
index += 4;
return TOKEN_NULL;
}
return TOKEN_NONE;

View file

@ -328,13 +328,7 @@ namespace Greenshot.Base.Core
/// <summary>
/// Return the path to the help-file
/// </summary>
public static string HelpFilePath
{
get
{
return HelpFiles.ContainsKey(_currentLanguage) ? HelpFiles[_currentLanguage] : HelpFiles[DefaultLanguage];
}
}
public static string HelpFilePath => HelpFiles.ContainsKey(_currentLanguage) ? HelpFiles[_currentLanguage] : HelpFiles[DefaultLanguage];
/// <summary>
/// Load the resources from the language file
@ -573,20 +567,14 @@ namespace Greenshot.Base.Core
/// <param name="prefix"></param>
/// <param name="key"></param>
/// <returns>true if available</returns>
public static bool HasKey(string prefix, string key)
{
return HasKey(prefix + "." + key);
}
public static bool HasKey(string prefix, string key) => HasKey(prefix + "." + key);
/// <summary>
/// Check if a resource with key exists
/// </summary>
/// <param name="key"></param>
/// <returns>true if available</returns>
public static bool HasKey(string key)
{
return key != null && Resources.ContainsKey(key);
}
public static bool HasKey(string key) => key != null && Resources.ContainsKey(key);
/// <summary>
/// TryGet method which combines HasKey & GetString
@ -594,10 +582,7 @@ namespace Greenshot.Base.Core
/// <param name="key"></param>
/// <param name="languageString">out string</param>
/// <returns></returns>
public static bool TryGetString(string key, out string languageString)
{
return Resources.TryGetValue(key, out languageString);
}
public static bool TryGetString(string key, out string languageString) => Resources.TryGetValue(key, out languageString);
/// <summary>
/// TryGet method which combines HasKey & GetString
@ -606,10 +591,7 @@ namespace Greenshot.Base.Core
/// <param name="key">string with key</param>
/// <param name="languageString">out string</param>
/// <returns></returns>
public static bool TryGetString(string prefix, string key, out string languageString)
{
return Resources.TryGetValue(prefix + "." + key, out languageString);
}
public static bool TryGetString(string prefix, string key, out string languageString) => Resources.TryGetValue(prefix + "." + key, out languageString);
/// <summary>
/// TryGet method which combines HasKey & GetString
@ -618,10 +600,7 @@ namespace Greenshot.Base.Core
/// <param name="key">Enum with key</param>
/// <param name="languageString">out string</param>
/// <returns></returns>
public static bool TryGetString(string prefix, Enum key, out string languageString)
{
return Resources.TryGetValue(prefix + "." + key, out languageString);
}
public static bool TryGetString(string prefix, Enum key, out string languageString) => Resources.TryGetValue(prefix + "." + key, out languageString);
/// <summary>
/// Translate
@ -640,10 +619,7 @@ namespace Greenshot.Base.Core
/// </summary>
/// <param name="key">Enum</param>
/// <returns>resource or a "string ###key### not found"</returns>
public static string GetString(Enum key)
{
return key == null ? null : GetString(key.ToString());
}
public static string GetString(Enum key) => key == null ? null : GetString(key.ToString());
/// <summary>
/// Get the resource for prefix.key
@ -651,10 +627,7 @@ namespace Greenshot.Base.Core
/// <param name="prefix">string</param>
/// <param name="key">Enum</param>
/// <returns>resource or a "string ###prefix.key### not found"</returns>
public static string GetString(string prefix, Enum key)
{
return key == null ? null : GetString(prefix + "." + key);
}
public static string GetString(string prefix, Enum key) => key == null ? null : GetString(prefix + "." + key);
/// <summary>
/// Get the resource for prefix.key
@ -662,10 +635,7 @@ namespace Greenshot.Base.Core
/// <param name="prefix">string</param>
/// <param name="key">string</param>
/// <returns>resource or a "string ###prefix.key### not found"</returns>
public static string GetString(string prefix, string key)
{
return GetString(prefix + "." + key);
}
public static string GetString(string prefix, string key) => GetString(prefix + "." + key);
/// <summary>
/// Get the resource for key
@ -688,10 +658,7 @@ namespace Greenshot.Base.Core
/// <param name="key">Enum</param>
/// <param name="param">object</param>
/// <returns>formatted resource or a "string ###key### not found"</returns>
public static string GetFormattedString(Enum key, object param)
{
return GetFormattedString(key.ToString(), param);
}
public static string GetFormattedString(Enum key, object param) => GetFormattedString(key.ToString(), param);
/// <summary>
/// Get the resource for prefix.key, format with with string.format an supply the parameters
@ -700,10 +667,7 @@ namespace Greenshot.Base.Core
/// <param name="key">Enum</param>
/// <param name="param">object</param>
/// <returns>formatted resource or a "string ###prefix.key### not found"</returns>
public static string GetFormattedString(string prefix, Enum key, object param)
{
return GetFormattedString(prefix, key.ToString(), param);
}
public static string GetFormattedString(string prefix, Enum key, object param) => GetFormattedString(prefix, key.ToString(), param);
/// <summary>
/// Get the resource for prefix.key, format with with string.format an supply the parameters
@ -712,10 +676,7 @@ namespace Greenshot.Base.Core
/// <param name="key">string</param>
/// <param name="param">object</param>
/// <returns>formatted resource or a "string ###prefix.key### not found"</returns>
public static string GetFormattedString(string prefix, string key, object param)
{
return GetFormattedString(prefix + "." + key, param);
}
public static string GetFormattedString(string prefix, string key, object param) => GetFormattedString(prefix + "." + key, param);
/// <summary>
/// Get the resource for key, format with with string.format an supply the parameters
@ -723,9 +684,6 @@ namespace Greenshot.Base.Core
/// <param name="key">string</param>
/// <param name="param">object</param>
/// <returns>formatted resource or a "string ###key### not found"</returns>
public static string GetFormattedString(string key, object param)
{
return !Resources.TryGetValue(key, out var returnValue) ? "string ###" + key + "### not found" : string.Format(returnValue, param);
}
public static string GetFormattedString(string key, object param) => !Resources.TryGetValue(key, out var returnValue) ? "string ###" + key + "### not found" : string.Format(returnValue, param);
}
}

View file

@ -214,10 +214,7 @@ namespace Greenshot.Base.Core
/// </summary>
/// <param name="uri">string with uri to connect to</param>
/// <returns>WebRequest</returns>
public static HttpWebRequest CreateWebRequest(string uri)
{
return CreateWebRequest(new Uri(uri));
}
public static HttpWebRequest CreateWebRequest(string uri) => CreateWebRequest(new Uri(uri));
/// <summary>
/// Helper method to create a web request with a lot of default settings
@ -225,10 +222,7 @@ namespace Greenshot.Base.Core
/// <param name="uri">string with uri to connect to</param>
/// /// <param name="method">Method to use</param>
/// <returns>WebRequest</returns>
public static HttpWebRequest CreateWebRequest(string uri, HTTPMethod method)
{
return CreateWebRequest(new Uri(uri), method);
}
public static HttpWebRequest CreateWebRequest(string uri, HTTPMethod method) => CreateWebRequest(new Uri(uri), method);
/// <summary>
/// Helper method to create a web request with a lot of default settings
@ -593,10 +587,7 @@ namespace Greenshot.Base.Core
/// <param name="webRequest">The request object.</param>
/// <returns>The response data.</returns>
/// TODO: This method should handle the StatusCode better!
public static string GetResponseAsString(HttpWebRequest webRequest)
{
return GetResponseAsString(webRequest, false);
}
public static string GetResponseAsString(HttpWebRequest webRequest) => GetResponseAsString(webRequest, false);
/// <summary>
/// Read the response as string
@ -766,11 +757,9 @@ namespace Greenshot.Base.Core
/// A plain "write data to stream"
/// </summary>
/// <param name="dataStream"></param>
public void WriteToStream(Stream dataStream)
{
public void WriteToStream(Stream dataStream) =>
// Write the file data directly to the Stream, rather than serializing it to a string.
ImageIO.SaveToStream(_surface, dataStream, _outputSettings);
}
/// <summary>
/// Upload the Surface as image to the webrequest

View file

@ -71,13 +71,7 @@ Greenshot received information from CloudServiceName. You can close this browser
/// <summary>
/// The URL to redirect to
/// </summary>
protected string RedirectUri
{
get
{
return !string.IsNullOrEmpty(_redirectUri) ? _redirectUri : (_redirectUri = string.Format(LoopbackCallbackUrl, GetRandomUnusedPort()));
}
}
protected string RedirectUri => !string.IsNullOrEmpty(_redirectUri) ? _redirectUri : (_redirectUri = string.Format(LoopbackCallbackUrl, GetRandomUnusedPort()));
private string _cloudServiceName;

View file

@ -135,12 +135,9 @@ namespace Greenshot.Base.Core.OAuth
{
var expiresIn = callbackParameters[ExpiresIn];
settings.AccessTokenExpires = DateTimeOffset.MaxValue;
if (expiresIn != null)
if (expiresIn != null && double.TryParse(expiresIn, out var seconds))
{
if (double.TryParse(expiresIn, out var seconds))
{
settings.AccessTokenExpires = DateTimeOffset.Now.AddSeconds(seconds);
}
settings.AccessTokenExpires = DateTimeOffset.Now.AddSeconds(seconds);
}
}
@ -393,12 +390,9 @@ namespace Greenshot.Base.Core.OAuth
public static void CheckAndAuthenticateOrRefresh(OAuth2Settings settings)
{
// Get Refresh / Access token
if (string.IsNullOrEmpty(settings.RefreshToken))
if (string.IsNullOrEmpty(settings.RefreshToken) && !Authorize(settings))
{
if (!Authorize(settings))
{
throw new Exception("Authentication cancelled");
}
throw new Exception("Authentication cancelled");
}
if (settings.IsAccessTokenExpired)

View file

@ -29,6 +29,7 @@ using System.Text;
using System.Threading;
using Greenshot.Base.Controls;
using log4net;
using System.Linq;
namespace Greenshot.Base.Core.OAuth
{
@ -219,11 +220,9 @@ namespace Greenshot.Base.Core.OAuth
/// Generate a nonce
/// </summary>
/// <returns></returns>
public static string GenerateNonce()
{
public static string GenerateNonce() =>
// Just a simple implementation of a random number between 123400 and 9999999
return random.Next(123400, 9999999).ToString();
}
random.Next(123400, 9999999).ToString();
/// <summary>
/// Get the request token using the consumer key and secret. Also initializes tokensecret
@ -270,19 +269,16 @@ namespace Greenshot.Base.Core.OAuth
Log.DebugFormat("Opening AuthorizationLink: {0}", AuthorizationLink);
OAuthLoginForm oAuthLoginForm = new(LoginTitle, BrowserSize, AuthorizationLink, CallbackUrl);
oAuthLoginForm.ShowDialog();
if (oAuthLoginForm.IsOk)
if (oAuthLoginForm.IsOk && oAuthLoginForm.CallbackParameters != null)
{
if (oAuthLoginForm.CallbackParameters != null)
if (oAuthLoginForm.CallbackParameters.TryGetValue(OAUTH_TOKEN_KEY, out var tokenValue))
{
if (oAuthLoginForm.CallbackParameters.TryGetValue(OAUTH_TOKEN_KEY, out var tokenValue))
{
Token = tokenValue;
}
Token = tokenValue;
}
if (oAuthLoginForm.CallbackParameters.TryGetValue(OAUTH_VERIFIER_KEY, out var verifierValue))
{
Verifier = verifierValue;
}
if (oAuthLoginForm.CallbackParameters.TryGetValue(OAUTH_VERIFIER_KEY, out var verifierValue))
{
Verifier = verifierValue;
}
}
@ -383,10 +379,7 @@ namespace Greenshot.Base.Core.OAuth
/// <param name="postData">Data to post (MemoryStream)</param>
/// <returns>The web server response.</returns>
public string MakeOAuthRequest(HTTPMethod method, string requestUrl, IDictionary<string, object> parametersToSign, IDictionary<string, object> additionalParameters,
IBinaryContainer postData)
{
return MakeOAuthRequest(method, requestUrl, requestUrl, null, parametersToSign, additionalParameters, postData);
}
IBinaryContainer postData) => MakeOAuthRequest(method, requestUrl, requestUrl, null, parametersToSign, additionalParameters, postData);
/// <summary>
/// Submit a web request using oAuth.
@ -399,10 +392,7 @@ namespace Greenshot.Base.Core.OAuth
/// <param name="postData">Data to post (MemoryStream)</param>
/// <returns>The web server response.</returns>
public string MakeOAuthRequest(HTTPMethod method, string requestUrl, IDictionary<string, string> headers, IDictionary<string, object> parametersToSign,
IDictionary<string, object> additionalParameters, IBinaryContainer postData)
{
return MakeOAuthRequest(method, requestUrl, requestUrl, headers, parametersToSign, additionalParameters, postData);
}
IDictionary<string, object> additionalParameters, IBinaryContainer postData) => MakeOAuthRequest(method, requestUrl, requestUrl, headers, parametersToSign, additionalParameters, postData);
/// <summary>
/// Submit a web request using oAuth.
@ -415,10 +405,7 @@ namespace Greenshot.Base.Core.OAuth
/// <param name="postData">Data to post (MemoryStream)</param>
/// <returns>The web server response.</returns>
public string MakeOAuthRequest(HTTPMethod method, string signUrl, string requestUrl, IDictionary<string, object> parametersToSign,
IDictionary<string, object> additionalParameters, IBinaryContainer postData)
{
return MakeOAuthRequest(method, signUrl, requestUrl, null, parametersToSign, additionalParameters, postData);
}
IDictionary<string, object> additionalParameters, IBinaryContainer postData) => MakeOAuthRequest(method, signUrl, requestUrl, null, parametersToSign, additionalParameters, postData);
/// <summary>
/// Submit a web request using oAuth.
@ -444,12 +431,9 @@ namespace Greenshot.Base.Core.OAuth
while (retries-- > 0)
{
// If we are not trying to get a Authorization or Accestoken, and we don't have a token, create one
if (string.IsNullOrEmpty(Token))
if (string.IsNullOrEmpty(Token) && (!AutoLogin || !Authorize()))
{
if (!AutoLogin || !Authorize())
{
throw new Exception("Not authorized");
}
throw new Exception("Not authorized");
}
try
@ -480,14 +464,9 @@ namespace Greenshot.Base.Core.OAuth
TokenSecret = null;
// Remove oauth keys, so they aren't added double
List<string> keysToDelete = new();
foreach (string parameterKey in parametersToSign.Keys)
{
if (parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX))
{
keysToDelete.Add(parameterKey);
}
}
keysToDelete.AddRange(from string parameterKey in parametersToSign.Keys
where parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX)
select parameterKey);
foreach (string keyToDelete in keysToDelete)
{
parametersToSign.Remove(keyToDelete);
@ -632,13 +611,10 @@ namespace Greenshot.Base.Core.OAuth
requestParameters = parameters;
}
if (HTTPMethod.GET == method || postData != null)
if ((HTTPMethod.GET == method || postData != null) && requestParameters.Count > 0)
{
if (requestParameters.Count > 0)
{
// Add the parameters to the request
requestUrl += "?" + NetworkHelper.GenerateQueryParameters(requestParameters);
}
// Add the parameters to the request
requestUrl += "?" + NetworkHelper.GenerateQueryParameters(requestParameters);
}
// Create webrequest

View file

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

View file

@ -113,13 +113,10 @@ namespace Greenshot.Base.Core
protected virtual void Dispose(bool disposing)
{
if (disposing)
if (disposing && resultBitmap != null)
{
if (resultBitmap != null)
{
resultBitmap.Dispose();
resultBitmap = null;
}
resultBitmap.Dispose();
resultBitmap = null;
}
}
@ -174,15 +171,9 @@ namespace Greenshot.Base.Core
{
for (int x = 0; x < sourceFastBitmap.Width; x++)
{
Color color;
if (sourceFastBitmap is not IFastBitmapWithBlend sourceFastBitmapWithBlend)
{
color = sourceFastBitmap.GetColorAt(x, y);
}
else
{
color = sourceFastBitmapWithBlend.GetBlendedColorAt(x, y);
}
Color color = sourceFastBitmap is not IFastBitmapWithBlend sourceFastBitmapWithBlend
? sourceFastBitmap.GetColorAt(x, y)
: sourceFastBitmapWithBlend.GetBlendedColorAt(x, y);
// To count the colors
int index = color.ToArgb() & 0x00ffffff;
@ -216,10 +207,7 @@ namespace Greenshot.Base.Core
/// <summary>
/// See <see cref="IColorQuantizer.Prepare"/> for more details.
/// </summary>
public int GetColorCount()
{
return colorCount;
}
public int GetColorCount() => colorCount;
/// <summary>
/// Reindex the 24/32 BPP (A)RGB image to a 8BPP
@ -240,16 +228,7 @@ namespace Greenshot.Base.Core
{
for (int x = 0; x < bbbSrc.Width; x++)
{
Color color;
if (bbbSrc is IFastBitmapWithBlend bbbSrcBlend)
{
color = bbbSrcBlend.GetBlendedColorAt(x, y);
}
else
{
color = bbbSrc.GetColorAt(x, y);
}
Color color = bbbSrc is IFastBitmapWithBlend bbbSrcBlend ? bbbSrcBlend.GetBlendedColorAt(x, y) : bbbSrc.GetColorAt(x, y);
if (lookup.ContainsKey(color))
{
index = lookup[color];
@ -271,14 +250,7 @@ namespace Greenshot.Base.Core
Color[] entries = imagePalette.Entries;
for (int paletteIndex = 0; paletteIndex < 256; paletteIndex++)
{
if (paletteIndex < colorCount)
{
entries[paletteIndex] = colors[paletteIndex];
}
else
{
entries[paletteIndex] = Color.Black;
}
entries[paletteIndex] = paletteIndex < colorCount ? colors[paletteIndex] : Color.Black;
}
resultBitmap.Palette = imagePalette;
@ -527,9 +499,7 @@ namespace Greenshot.Base.Core
/// <summary>
/// Computes the volume of the cube in a specific moment.
/// </summary>
private static long Volume(WuColorCube cube, long[,,] moment)
{
return moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] -
private static long Volume(WuColorCube cube, long[,,] moment) => moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] -
moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] -
moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] +
moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] -
@ -537,14 +507,11 @@ namespace Greenshot.Base.Core
moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] +
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] -
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum];
}
/// <summary>
/// Computes the volume of the cube in a specific moment. For the floating-point values.
/// </summary>
private static float VolumeFloat(WuColorCube cube, float[,,] moment)
{
return moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] -
private static float VolumeFloat(WuColorCube cube, float[,,] moment) => moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMaximum] -
moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] -
moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] +
moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] -
@ -552,53 +519,46 @@ namespace Greenshot.Base.Core
moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] +
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] -
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum];
}
/// <summary>
/// Splits the cube in given position, and color direction.
/// </summary>
private static long Top(WuColorCube cube, int direction, int position, long[,,] moment)
private static long Top(WuColorCube cube, int direction, int position, long[,,] moment) => direction switch
{
return direction switch
{
RED => moment[position, cube.GreenMaximum, cube.BlueMaximum] -
moment[position, cube.GreenMaximum, cube.BlueMinimum] -
moment[position, cube.GreenMinimum, cube.BlueMaximum] +
moment[position, cube.GreenMinimum, cube.BlueMinimum],
GREEN => moment[cube.RedMaximum, position, cube.BlueMaximum] -
moment[cube.RedMaximum, position, cube.BlueMinimum] -
moment[cube.RedMinimum, position, cube.BlueMaximum] +
moment[cube.RedMinimum, position, cube.BlueMinimum],
BLUE => moment[cube.RedMaximum, cube.GreenMaximum, position] -
moment[cube.RedMaximum, cube.GreenMinimum, position] -
moment[cube.RedMinimum, cube.GreenMaximum, position] +
moment[cube.RedMinimum, cube.GreenMinimum, position],
_ => 0,
};
}
RED => moment[position, cube.GreenMaximum, cube.BlueMaximum] -
moment[position, cube.GreenMaximum, cube.BlueMinimum] -
moment[position, cube.GreenMinimum, cube.BlueMaximum] +
moment[position, cube.GreenMinimum, cube.BlueMinimum],
GREEN => moment[cube.RedMaximum, position, cube.BlueMaximum] -
moment[cube.RedMaximum, position, cube.BlueMinimum] -
moment[cube.RedMinimum, position, cube.BlueMaximum] +
moment[cube.RedMinimum, position, cube.BlueMinimum],
BLUE => moment[cube.RedMaximum, cube.GreenMaximum, position] -
moment[cube.RedMaximum, cube.GreenMinimum, position] -
moment[cube.RedMinimum, cube.GreenMaximum, position] +
moment[cube.RedMinimum, cube.GreenMinimum, position],
_ => 0,
};
/// <summary>
/// Splits the cube in a given color direction at its minimum.
/// </summary>
private static long Bottom(WuColorCube cube, int direction, long[,,] moment)
private static long Bottom(WuColorCube cube, int direction, long[,,] moment) => direction switch
{
return direction switch
{
RED => -moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMaximum] +
moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] +
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] -
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum],
GREEN => -moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] +
moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] +
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] -
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum],
BLUE => -moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] +
moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] +
moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] -
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum],
_ => 0
};
}
RED => -moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMaximum] +
moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] +
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] -
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum],
GREEN => -moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMaximum] +
moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] +
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMaximum] -
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum],
BLUE => -moment[cube.RedMaximum, cube.GreenMaximum, cube.BlueMinimum] +
moment[cube.RedMaximum, cube.GreenMinimum, cube.BlueMinimum] +
moment[cube.RedMinimum, cube.GreenMaximum, cube.BlueMinimum] -
moment[cube.RedMinimum, cube.GreenMinimum, cube.BlueMinimum],
_ => 0
};
/// <summary>
/// Calculates statistical variance for a given cube.
@ -703,14 +663,7 @@ namespace Greenshot.Base.Core
}
else
{
if ((maxGreen >= maxRed) && (maxGreen >= maxBlue))
{
direction = GREEN;
}
else
{
direction = BLUE;
}
direction = (maxGreen >= maxRed) && (maxGreen >= maxBlue) ? GREEN : BLUE;
}
second.RedMaximum = first.RedMaximum;

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();
}
public TService GetInstance<TService>()
{
return GetAllInstances<TService>().SingleOrDefault();
}
public TService GetInstance<TService>() => GetAllInstances<TService>().SingleOrDefault();
public void AddService<TService>(IEnumerable<TService> services)
{
@ -45,9 +42,6 @@ namespace Greenshot.Base.Core
}
}
public void AddService<TService>(params TService[] services)
{
AddService(services.AsEnumerable());
}
public void AddService<TService>(params TService[] services) => AddService(services.AsEnumerable());
}
}

View file

@ -41,10 +41,7 @@ namespace Greenshot.Base.Core
/// <param name="format">String with formatting, like {name}</param>
/// <param name="source">Object used for the formatting</param>
/// <returns>Formatted string</returns>
public static string FormatWith(this string format, object source)
{
return FormatWith(format, null, source);
}
public static string FormatWith(this string format, object source) => FormatWith(format, null, source);
/// <summary>
/// Format the string "format" with the source
@ -85,7 +82,7 @@ namespace Greenshot.Base.Core
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
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 propertyGroup = m.Groups["property"];

View file

@ -41,6 +41,7 @@ using Dapplo.Windows.User32.Structs;
using Greenshot.Base.IniFile;
using Greenshot.Base.Interfaces;
using log4net;
using System.Linq;
namespace Greenshot.Base.Core
{
@ -59,10 +60,7 @@ namespace Greenshot.Base.Core
/// <returns>
/// Point with cursor location, relative to the top left corner of the monitor setup (which itself might actually not be on any screen)
/// </returns>
public static NativePoint GetCursorLocationRelativeToScreenBounds()
{
return GetLocationRelativeToScreenBounds(User32Api.GetCursorLocation());
}
public static NativePoint GetCursorLocationRelativeToScreenBounds() => GetLocationRelativeToScreenBounds(User32Api.GetCursorLocation());
/// <summary>
/// Converts locationRelativeToScreenOrigin to be relative to top left corner of all screen bounds, which might
@ -338,13 +336,9 @@ namespace Greenshot.Base.Core
{
// Collect all screens inside this capture
List<Screen> screensInsideCapture = new();
foreach (Screen screen in Screen.AllScreens)
{
if (screen.Bounds.IntersectsWith(captureBounds))
{
screensInsideCapture.Add(screen);
}
}
screensInsideCapture.AddRange(from Screen screen in Screen.AllScreens
where screen.Bounds.IntersectsWith(captureBounds)
select screen);
// Check all all screens are of an equal size
bool offscreenContent;

View file

@ -78,10 +78,7 @@ namespace Greenshot.Base.Core
}
}
internal static bool IsIgnoreHandle(IntPtr handle)
{
return IgnoreHandles.Contains(handle);
}
internal static bool IsIgnoreHandle(IntPtr handle) => IgnoreHandles.Contains(handle);
private IList<WindowDetails> _childWindows;
private IntPtr _parentHandle = IntPtr.Zero;
@ -106,15 +103,9 @@ namespace Greenshot.Base.Core
/// objects for the same Window will be equal.
/// </summary>
/// <returns>The Window Handle for this window</returns>
public override int GetHashCode()
{
return Handle.ToInt32();
}
public override int GetHashCode() => Handle.ToInt32();
public override bool Equals(object right)
{
return Equals(right as WindowDetails);
}
public override bool Equals(object right) => Equals(right as WindowDetails);
/// <summary>
/// Compare two windows details
@ -144,18 +135,12 @@ namespace Greenshot.Base.Core
/// <summary>
/// Freeze information updates
/// </summary>
public void FreezeDetails()
{
_frozen = true;
}
public void FreezeDetails() => _frozen = true;
/// <summary>
/// Make the information update again.
/// </summary>
public void UnfreezeDetails()
{
_frozen = false;
}
public void UnfreezeDetails() => _frozen = false;
/// <summary>
/// Get the file path to the exe for the process which owns this window
@ -270,19 +255,13 @@ namespace Greenshot.Base.Core
/// Use this to make remove internal windows, like the mainform and the captureforms, invisible
/// </summary>
/// <param name="ignoreHandle"></param>
public static void RegisterIgnoreHandle(IntPtr ignoreHandle)
{
IgnoreHandles.Add(ignoreHandle);
}
public static void RegisterIgnoreHandle(IntPtr ignoreHandle) => IgnoreHandles.Add(ignoreHandle);
/// <summary>
/// Use this to remove the with RegisterIgnoreHandle registered handle
/// </summary>
/// <param name="ignoreHandle"></param>
public static void UnregisterIgnoreHandle(IntPtr ignoreHandle)
{
IgnoreHandles.Remove(ignoreHandle);
}
public static void UnregisterIgnoreHandle(IntPtr ignoreHandle) => IgnoreHandles.Remove(ignoreHandle);
public IList<WindowDetails> Children
{
@ -302,12 +281,11 @@ namespace Greenshot.Base.Core
/// </summary>
public WindowDetails GetChild(string childClassname)
{
foreach (var child in Children)
foreach (var child in from child in Children
where childClassname.Equals(child.ClassName)
select child)
{
if (childClassname.Equals(child.ClassName))
{
return child;
}
return child;
}
return null;
@ -361,10 +339,7 @@ namespace Greenshot.Base.Core
/// Retrieve all the children, this only stores the children internally.
/// One should normally use the getter "Children"
/// </summary>
public IList<WindowDetails> GetChildren()
{
return _childWindows ?? GetChildren(0);
}
public IList<WindowDetails> GetChildren() => _childWindows ?? GetChildren(0);
/// <summary>
/// Retrieve all the children, this only stores the children internally, use the "Children" property for the value
@ -467,22 +442,14 @@ namespace Greenshot.Base.Core
/// <summary>
/// Returns if this window is cloaked
/// </summary>
public bool IsCloaked
{
get => DwmApi.IsWindowCloaked(Handle);
}
public bool IsCloaked => DwmApi.IsWindowCloaked(Handle);
/// <summary>
/// Gets whether the window is visible.
/// </summary>
public bool Visible
{
get
{
public bool Visible =>
// Tip from Raymond Chen https://devblogs.microsoft.com/oldnewthing/20200302-00/?p=103507
return !IsCloaked && User32Api.IsWindowVisible(Handle);
}
}
!IsCloaked && User32Api.IsWindowVisible(Handle);
public bool HasParent
{
@ -543,14 +510,11 @@ namespace Greenshot.Base.Core
if (DwmApi.IsDwmEnabled)
{
bool gotFrameBounds = GetExtendedFrameBounds(out windowRect);
if (IsWin10App)
// Pre-Cache for maximized call, this is only on Windows 8 apps (full screen)
if (IsWin10App && gotFrameBounds)
{
// Pre-Cache for maximized call, this is only on Windows 8 apps (full screen)
if (gotFrameBounds)
{
_previousWindowRectangle = windowRect;
_lastWindowRectangleRetrieveTime = now;
}
_previousWindowRectangle = windowRect;
_lastWindowRectangleRetrieveTime = now;
}
if (gotFrameBounds && WindowsVersion.IsWindows10OrLater && !Maximised)
@ -564,13 +528,10 @@ namespace Greenshot.Base.Core
}
}
if (windowRect.IsEmpty)
if (windowRect.IsEmpty && !GetWindowRect(out windowRect))
{
if (!GetWindowRect(out windowRect))
{
Win32Error error = Win32.GetLastErrorCode();
Log.WarnFormat("Couldn't retrieve the windows rectangle: {0}", Win32.GetMessage(error));
}
Win32Error error = Win32.GetLastErrorCode();
Log.WarnFormat("Couldn't retrieve the windows rectangle: {0}", Win32.GetMessage(error));
}
_lastWindowRectangleRetrieveTime = now;
@ -588,18 +549,12 @@ namespace Greenshot.Base.Core
/// <summary>
/// Gets the location of the window relative to the screen.
/// </summary>
public NativePoint Location
{
get => WindowRectangle.Location;
}
public NativePoint Location => WindowRectangle.Location;
/// <summary>
/// Gets the size of the window.
/// </summary>
public NativeSize Size
{
get => WindowRectangle.Size;
}
public NativeSize Size => WindowRectangle.Size;
/// <summary>
/// Get the client rectangle, this is the part of the window inside the borders (drawable area)
@ -623,10 +578,7 @@ namespace Greenshot.Base.Core
/// </summary>
/// <param name="p">Point with the coordinates to check</param>
/// <returns>true if the point lies within</returns>
public bool Contains(NativePoint p)
{
return WindowRectangle.Contains(p);
}
public bool Contains(NativePoint p) => WindowRectangle.Contains(p);
/// <summary>
/// Restores and Brings the window to the front,
@ -796,18 +748,15 @@ namespace Greenshot.Base.Core
captureRectangle = captureRectangle.Inflate(Conf.Win10BorderCrop);
}
if (autoMode)
// check if the capture fits
if (autoMode && !doesCaptureFit)
{
// check if the capture fits
if (!doesCaptureFit)
// if GDI is allowed.. (a screenshot won't be better than we comes if we continue)
using Process thisWindowProcess = Process;
if (WindowCapture.IsGdiAllowed(thisWindowProcess))
{
// if GDI is allowed.. (a screenshot won't be better than we comes if we continue)
using Process thisWindowProcess = Process;
if (WindowCapture.IsGdiAllowed(thisWindowProcess))
{
// we return null which causes the capturing code to try another method.
return null;
}
// we return null which causes the capturing code to try another method.
return null;
}
}
}
@ -894,26 +843,20 @@ namespace Greenshot.Base.Core
capturedBitmap = WindowCapture.CaptureRectangle(captureRectangle);
}
if (capturedBitmap != null)
// Only if the Inivalue is set, not maximized and it's not a tool window.
// Not needed for Windows 8
if (capturedBitmap != null && !WindowsVersion.IsWindows8OrLater && Conf.WindowCaptureRemoveCorners && !Maximised && (ExtendedWindowStyle & ExtendedWindowStyleFlags.WS_EX_TOOLWINDOW) == 0)
{
// Not needed for Windows 8
if (!WindowsVersion.IsWindows8OrLater)
// Remove corners
if (!Image.IsAlphaPixelFormat(capturedBitmap.PixelFormat))
{
// 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)
{
// Remove corners
if (!Image.IsAlphaPixelFormat(capturedBitmap.PixelFormat))
{
Log.Debug("Changing pixelformat to Alpha for the RemoveCorners");
Bitmap tmpBitmap = ImageHelper.Clone(capturedBitmap, PixelFormat.Format32bppArgb);
capturedBitmap.Dispose();
capturedBitmap = tmpBitmap;
}
RemoveCorners(capturedBitmap);
}
Log.Debug("Changing pixelformat to Alpha for the RemoveCorners");
Bitmap tmpBitmap = ImageHelper.Clone(capturedBitmap, PixelFormat.Format32bppArgb);
capturedBitmap.Dispose();
capturedBitmap = tmpBitmap;
}
RemoveCorners(capturedBitmap);
}
}
finally
@ -1076,14 +1019,7 @@ namespace Greenshot.Base.Core
var windowInfo = new WindowInfo();
// Get the Window Info for this window
bool result = User32Api.GetWindowInfo(Handle, ref windowInfo);
if (IsHidden(windowInfo.Bounds))
{
rectangle = NativeRect.Empty;
}
else
{
rectangle = result ? windowInfo.Bounds : NativeRect.Empty;
}
rectangle = IsHidden(windowInfo.Bounds) ? NativeRect.Empty : result ? windowInfo.Bounds : NativeRect.Empty;
return result;
}
@ -1146,10 +1082,7 @@ namespace Greenshot.Base.Core
/// <summary>
/// Set the window as foreground window
/// </summary>
public void ToForeground()
{
ToForeground(Handle);
}
public void ToForeground() => ToForeground(Handle);
/// <summary>
/// Get the region for a window
@ -1178,7 +1111,7 @@ namespace Greenshot.Base.Core
return false;
}
if (titleOrProcessname.ToLower().Contains("greenshot"))
if (titleOrProcessname.IndexOf("greenshot", StringComparison.CurrentCultureIgnoreCase) >= 0)
{
return false;
}
@ -1339,10 +1272,7 @@ namespace Greenshot.Base.Core
/// the specified Window Handle.
/// </summary>
/// <param name="hWnd">The Window Handle</param>
public WindowDetails(IntPtr hWnd)
{
Handle = hWnd;
}
public WindowDetails(IntPtr hWnd) => Handle = hWnd;
/// <summary>
/// Gets an instance of the current active foreground window
@ -1370,28 +1300,19 @@ namespace Greenshot.Base.Core
/// Gets the Desktop window
/// </summary>
/// <returns>WindowDetails for the desktop window</returns>
public static WindowDetails GetDesktopWindow()
{
return new WindowDetails(User32Api.GetDesktopWindow());
}
public static WindowDetails GetDesktopWindow() => new(User32Api.GetDesktopWindow());
/// <summary>
/// Get all the top level windows
/// </summary>
/// <returns>List of WindowDetails with all the top level windows</returns>
public static IList<WindowDetails> GetAllWindows()
{
return GetAllWindows(null);
}
public static IList<WindowDetails> GetAllWindows() => GetAllWindows(null);
/// <summary>
/// Get all the top level windows, with matching classname
/// </summary>
/// <returns>List WindowDetails with all the top level windows</returns>
public static IList<WindowDetails> GetAllWindows(string classname)
{
return new WindowsEnumerator().GetWindows(IntPtr.Zero, classname).Items;
}
public static IList<WindowDetails> GetAllWindows(string classname) => new WindowsEnumerator().GetWindows(IntPtr.Zero, classname).Items;
/// <summary>
/// Recursive "find children which"
@ -1618,13 +1539,7 @@ namespace Greenshot.Base.Core
/// Return true if the metro-app-launcher is visible
/// </summary>
/// <returns></returns>
public static bool IsAppLauncherVisible
{
get
{
return AppVisibility != null && AppVisibility.IsLauncherVisible;
}
}
public static bool IsAppLauncherVisible => AppVisibility?.IsLauncherVisible == true;
/// <summary>
/// Make a string representation of the window details

View file

@ -62,9 +62,6 @@ namespace Greenshot.Base.Core
/// </summary>
/// <param name="minimalBuildNumber">int</param>
/// <returns>bool</returns>
public static bool IsWindows10BuildOrLater(int minimalBuildNumber)
{
return IsWindows10 && WinVersion.Build >= minimalBuildNumber;
}
public static bool IsWindows10BuildOrLater(int minimalBuildNumber) => IsWindows10 && WinVersion.Build >= minimalBuildNumber;
}
}

View file

@ -38,10 +38,7 @@ namespace Greenshot.Base.Core
/// </summary>
/// <param name="m">Message</param>
/// <returns>true if the message should be filtered</returns>
public bool PreFilterMessage(ref Message m)
{
return PreFilterMessageExternal(ref m);
}
public bool PreFilterMessage(ref Message m) => PreFilterMessageExternal(ref m);
/// <summary>
/// Also used in the MainForm WndProc

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -34,17 +34,11 @@ namespace Greenshot.Base.Effects
{
private static readonly ILog Log = LogManager.GetLogger(typeof(ReduceColorsEffect));
public ReduceColorsEffect()
{
Reset();
}
public ReduceColorsEffect() => Reset();
public int Colors { get; set; }
public void Reset()
{
Colors = 256;
}
public void Reset() => Colors = 256;
public Image Apply(Image sourceImage, Matrix matrix)
{

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -26,6 +26,7 @@ using System.Reflection;
using System.Text;
using System.Threading;
using log4net;
using System.Linq;
namespace Greenshot.Base.IniFile
{
@ -152,15 +153,9 @@ namespace Greenshot.Base.IniFile
/// <summary>
/// Get the location of the configuration
/// </summary>
public static string ConfigLocation
{
get
{
return IsInitialized
public static string ConfigLocation => IsInitialized
? CreateIniLocation(_configName + IniExtension, false)
: throw new InvalidOperationException("Ini configuration was not initialized!");
}
}
/// <summary>
/// Create the location of the configuration file
@ -325,12 +320,11 @@ namespace Greenshot.Base.IniFile
return;
}
foreach (string fixedPropertyKey in fixedPropertiesForSection.Keys)
foreach (var fixedPropertyKey in from string fixedPropertyKey in fixedPropertiesForSection.Keys
where section.Values.ContainsKey(fixedPropertyKey)
select fixedPropertyKey)
{
if (section.Values.ContainsKey(fixedPropertyKey))
{
section.Values[fixedPropertyKey].IsFixed = true;
}
section.Values[fixedPropertyKey].IsFixed = true;
}
}
@ -409,10 +403,7 @@ namespace Greenshot.Base.IniFile
/// </summary>
/// <typeparam name="T">IniSection Type to get the configuration for</typeparam>
/// <returns>Filled instance of IniSection type which was supplied</returns>
public static T GetIniSection<T>() where T : IniSection
{
return GetIniSection<T>(true);
}
public static T GetIniSection<T>() where T : IniSection => GetIniSection<T>(true);
/// <summary>
///

View file

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

View file

@ -59,7 +59,7 @@ namespace Greenshot.Base.IniFile
{
get
{
return Attributes != null && Attributes.FixedValue;
return Attributes?.FixedValue == true;
}
set
{
@ -77,7 +77,7 @@ namespace Greenshot.Base.IniFile
{
get
{
return Attributes != null && Attributes.Expert;
return Attributes?.Expert == true;
}
set
{
@ -98,13 +98,7 @@ namespace Greenshot.Base.IniFile
/// </summary>
public bool IsVisible => !IsExpert;
public MemberInfo MemberInfo
{
get
{
return _propertyInfo == null ? _fieldInfo : _propertyInfo;
}
}
public MemberInfo MemberInfo => _propertyInfo == null ? _fieldInfo : _propertyInfo;
/// <summary>
/// Returns the IniSection this value is contained in
@ -193,12 +187,9 @@ namespace Greenshot.Base.IniFile
}
}
if (myValue == null)
if (myValue == null && Attributes.ExcludeIfNull)
{
if (Attributes.ExcludeIfNull)
{
return;
}
return;
}
if (!onlyProperties)
@ -520,10 +511,7 @@ namespace Greenshot.Base.IniFile
/// Override of ToString which calls the ConvertValueToString
/// </summary>
/// <returns>string representation of this</returns>
public override string ToString()
{
return ConvertValueToString(ValueType, Value, Attributes.Separator);
}
public override string ToString() => ConvertValueToString(ValueType, Value, Attributes.Separator);
/// <summary>
/// Convert the supplied value to a string

View file

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

View file

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

View file

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

View file

@ -41,20 +41,11 @@ namespace Greenshot.Base.Interfaces.Plugin
ReduceColors = CoreConfig.OutputFileReduceColors;
}
public SurfaceOutputSettings(OutputFormat format) : this()
{
Format = format;
}
public SurfaceOutputSettings(OutputFormat format) : this() => Format = format;
public SurfaceOutputSettings(OutputFormat format, int quality) : this(format)
{
JPGQuality = quality;
}
public SurfaceOutputSettings(OutputFormat format, int quality) : this(format) => JPGQuality = quality;
public SurfaceOutputSettings(OutputFormat format, int quality, bool reduceColors) : this(format, quality)
{
ReduceColors = reduceColors;
}
public SurfaceOutputSettings(OutputFormat format, int quality, bool reduceColors) : this(format, quality) => ReduceColors = reduceColors;
/// <summary>
/// BUG-2056 reported a logical issue, using greenshot format as the default causes issues with the external commands.
@ -84,7 +75,7 @@ namespace Greenshot.Base.Interfaces.Plugin
get
{
// 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; }
}

View file

@ -232,10 +232,7 @@ namespace Greenshot.Base.Interop
/// <returns>
/// The full name of the intercepted type.
/// </returns>
public override string ToString()
{
return _interceptType.FullName;
}
public override string ToString() => _interceptType.FullName;
/// <summary>
/// Returns the hash code of the wrapped object.
@ -243,10 +240,7 @@ namespace Greenshot.Base.Interop
/// <returns>
/// The hash code of the wrapped object.
/// </returns>
public override int GetHashCode()
{
return _comObject.GetHashCode();
}
public override int GetHashCode() => _comObject.GetHashCode();
/// <summary>
/// Compares this object to another.
@ -259,12 +253,9 @@ namespace Greenshot.Base.Interop
/// </returns>
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);
@ -559,24 +550,21 @@ namespace Greenshot.Base.Interop
{
arg = Enum.Parse(byValType, arg.ToString());
}
else if (byValType.IsInterface)
else if (byValType.IsInterface && Marshal.IsComObject(arg))
{
if (Marshal.IsComObject(arg))
wrapper = originalArgs[i];
if (wrapper != null && wrapper._comObject != arg)
{
wrapper = originalArgs[i];
if (wrapper != null && wrapper._comObject != arg)
{
wrapper.Dispose();
wrapper = null;
}
if (wrapper == null)
{
wrapper = new COMWrapper(arg, byValType, _targetName);
}
arg = wrapper.GetTransparentProxy();
wrapper.Dispose();
wrapper = null;
}
if (wrapper == null)
{
wrapper = new COMWrapper(arg, byValType, _targetName);
}
arg = wrapper.GetTransparentProxy();
}
outArgs[i] = arg;

View file

@ -70,10 +70,7 @@ namespace Greenshot.Base.Interop
/// <summary>Constructor</summary>
/// <param name="value">The COM ProgID.</param>
public ComProgIdAttribute(string value)
{
Value = value;
}
public ComProgIdAttribute(string value) => Value = value;
/// <summary>
/// Returns the COM ProgID

View file

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

View file

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

View file

@ -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.")]
public string LanguageKey { get; set; }
public ColorButton()
{
Click += ColorButtonClick;
}
public ColorButton() => Click += ColorButtonClick;
public Color SelectedColor
{
@ -53,16 +50,7 @@ namespace Greenshot.Editor.Controls
{
_selectedColor = value;
Brush brush;
if (value != Color.Transparent)
{
brush = new SolidBrush(value);
}
else
{
brush = new HatchBrush(HatchStyle.Percent50, Color.White, Color.Gray);
}
Brush brush = value != Color.Transparent ? new SolidBrush(value) : new HatchBrush(HatchStyle.Percent50, Color.White, Color.Gray);
if (Image != null)
{
using Graphics graphics = Graphics.FromImage(Image);

View file

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

View file

@ -29,12 +29,10 @@ namespace Greenshot.Editor.Controls
/// </summary>
public class NonJumpingPanel : Panel
{
protected override Point ScrollToControl(Control activeControl)
{
protected override Point ScrollToControl(Control activeControl) =>
// Returning the current location prevents the panel from
// scrolling to the active control when the panel loses and regains focus
return DisplayRectangle.Location;
}
DisplayRectangle.Location;
/// <summary>
/// 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>
/// The bulk of the clean-up code is implemented in Dispose(bool)
/// </summary>
public new void Dispose()
{
Dispose(true);
}
public new void Dispose() => Dispose(true);
/// <summary>
/// This Dispose is called from the Dispose and the Destructor.
@ -176,15 +173,9 @@ namespace Greenshot.Editor.Controls
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;
@ -195,9 +186,6 @@ namespace Greenshot.Editor.Controls
{
public Color Color;
public PipetteUsedArgs(Color c)
{
Color = c;
}
public PipetteUsedArgs(Color c) => Color = c;
}
}

View file

@ -39,10 +39,7 @@ namespace Greenshot.Editor.Controls
private Color _selectedColor = Color.Transparent;
public ToolStripColorButton()
{
Click += ColorButtonClick;
}
public ToolStripColorButton() => Click += ColorButtonClick;
public Color SelectedColor
{
@ -51,16 +48,7 @@ namespace Greenshot.Editor.Controls
{
_selectedColor = value;
Brush brush;
if (value != Color.Transparent)
{
brush = new SolidBrush(value);
}
else
{
brush = new HatchBrush(HatchStyle.Percent50, Color.White, Color.Gray);
}
Brush brush = value != Color.Transparent ? new SolidBrush(value) : new HatchBrush(HatchStyle.Percent50, Color.White, Color.Gray);
if (Image != null)
{
using Graphics graphics = Graphics.FromImage(Image);

View file

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

View file

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

View file

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

View file

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

View file

@ -59,10 +59,7 @@ namespace Greenshot.Editor.Drawing
Horizontal
}
public CropContainer(ISurface parent) : base(parent)
{
Init();
}
public CropContainer(ISurface parent) : base(parent) => Init();
protected override void OnDeserialized(StreamingContext streamingContext)
{
@ -133,22 +130,13 @@ namespace Greenshot.Editor.Drawing
AddField(GetType(), FieldType.CROPMODE, CropModes.Default);
}
public override void Invalidate()
{
_parent?.Invalidate();
}
public override void Invalidate() => _parent?.Invalidate();
/// <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 create a transparent brown over the complete picture)
/// </summary>
public override NativeRect DrawingBounds
{
get
{
return _parent?.Image is { } image ? new NativeRect(0, 0, image.Width, image.Height) : NativeRect.Empty;
}
}
public override NativeRect DrawingBounds => _parent?.Image is { } image ? new NativeRect(0, 0, image.Width, image.Height) : NativeRect.Empty;
public override void Draw(Graphics g, RenderMode rm)
{
@ -195,17 +183,14 @@ namespace Greenshot.Editor.Drawing
/// </summary>
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
CropModes.Horizontal => base.HandleMouseDown(0, y),
//force vertical crop to top edge
CropModes.Vertical => base.HandleMouseDown(x, 0),
_ => base.HandleMouseDown(x, y),
};
}
//force horizontal crop to left edge
CropModes.Horizontal => base.HandleMouseDown(0, y),
//force vertical crop to top edge
CropModes.Vertical => base.HandleMouseDown(x, 0),
_ => base.HandleMouseDown(x, y),
};
public override bool HandleMouseMove(int x, int y)
{

View file

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

View file

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

View file

@ -53,15 +53,9 @@ namespace Greenshot.Editor.Drawing
{
}
public DrawableContainerList(IEnumerable<IDrawableContainer> elements)
{
AddRange(elements);
}
public DrawableContainerList(IEnumerable<IDrawableContainer> elements) => AddRange(elements);
public DrawableContainerList(Guid parentId)
{
ParentID = parentId;
}
public DrawableContainerList(Guid parentId) => ParentID = parentId;
public EditStatus Status
{
@ -78,10 +72,7 @@ namespace Greenshot.Editor.Drawing
public List<IDrawableContainer> AsIDrawableContainerList()
{
List<IDrawableContainer> interfaceList = new();
foreach (IDrawableContainer container in this)
{
interfaceList.Add(container);
}
interfaceList.AddRange(this);
return interfaceList;
}
@ -275,12 +266,11 @@ namespace Greenshot.Editor.Drawing
/// <returns></returns>
public bool IntersectsWith(NativeRect clipRectangle)
{
foreach (var dc in this)
foreach (var _ in from dc in this
where dc.DrawingBounds.IntersectsWith(clipRectangle)
select new { })
{
if (dc.DrawingBounds.IntersectsWith(clipRectangle))
{
return true;
}
return true;
}
return false;
@ -758,11 +748,9 @@ namespace Greenshot.Editor.Drawing
}
// 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.
Dispose(true);
}
/// <summary>
/// Adjust UI elements to the supplied DPI settings

View file

@ -38,10 +38,7 @@ namespace Greenshot.Editor.Drawing
[Serializable()]
public class EllipseContainer : DrawableContainer
{
public EllipseContainer(ISurface parent) : base(parent)
{
Init();
}
public EllipseContainer(ISurface parent) : base(parent) => Init();
protected override void OnDeserialized(StreamingContext streamingContext)
{
@ -49,10 +46,7 @@ namespace Greenshot.Editor.Drawing
Init();
}
private void Init()
{
CreateDefaultAdorners();
}
private void Init() => CreateDefaultAdorners();
protected override void InitializeFields()
{
@ -124,10 +118,7 @@ namespace Greenshot.Editor.Drawing
}
}
public override bool Contains(int x, int y)
{
return EllipseContains(this, x, y);
}
public override bool Contains(int x, int y) => EllipseContains(this, x, y);
/// <summary>
/// Allow the code to be used externally
@ -141,7 +132,7 @@ namespace Greenshot.Editor.Drawing
double xDistanceFromCenter = x - (caller.Left + (caller.Width / 2));
double yDistanceFromCenter = y - (caller.Top + (caller.Height / 2));
// 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)
@ -155,12 +146,9 @@ namespace Greenshot.Editor.Drawing
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 (!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

View file

@ -69,10 +69,7 @@ namespace Greenshot.Editor.Drawing.Fields
}
}
public void AddField(Type requestingType, IFieldType fieldType, object fieldValue)
{
AddField(EditorConfig.CreateField(requestingType, fieldType, fieldValue));
}
public void AddField(Type requestingType, IFieldType fieldType, object fieldValue) => AddField(EditorConfig.CreateField(requestingType, fieldType, fieldValue));
public virtual void AddField(IField field)
{
@ -82,12 +79,9 @@ namespace Greenshot.Editor.Drawing.Fields
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;
@ -104,10 +98,7 @@ namespace Greenshot.Editor.Drawing.Fields
_handlers.Remove(field);
}
public IList<IField> GetFields()
{
return fields;
}
public IList<IField> GetFields() => fields;
public IField GetField(IFieldType fieldType)
{
@ -121,55 +112,25 @@ namespace Greenshot.Editor.Drawing.Fields
}
}
public object GetFieldValue(IFieldType fieldType)
{
return GetField(fieldType)?.Value;
}
public object GetFieldValue(IFieldType fieldType) => GetField(fieldType)?.Value;
public string GetFieldValueAsString(IFieldType fieldType)
{
return Convert.ToString(GetFieldValue(fieldType));
}
public string GetFieldValueAsString(IFieldType fieldType) => Convert.ToString(GetFieldValue(fieldType));
public int GetFieldValueAsInt(IFieldType fieldType)
{
return Convert.ToInt32(GetFieldValue(fieldType));
}
public int GetFieldValueAsInt(IFieldType fieldType) => Convert.ToInt32(GetFieldValue(fieldType));
public decimal GetFieldValueAsDecimal(IFieldType fieldType)
{
return Convert.ToDecimal(GetFieldValue(fieldType));
}
public decimal GetFieldValueAsDecimal(IFieldType fieldType) => Convert.ToDecimal(GetFieldValue(fieldType));
public double GetFieldValueAsDouble(IFieldType fieldType)
{
return Convert.ToDouble(GetFieldValue(fieldType));
}
public double GetFieldValueAsDouble(IFieldType fieldType) => Convert.ToDouble(GetFieldValue(fieldType));
public float GetFieldValueAsFloat(IFieldType fieldType)
{
return Convert.ToSingle(GetFieldValue(fieldType));
}
public float GetFieldValueAsFloat(IFieldType fieldType) => Convert.ToSingle(GetFieldValue(fieldType));
public bool GetFieldValueAsBool(IFieldType fieldType)
{
return Convert.ToBoolean(GetFieldValue(fieldType));
}
public bool GetFieldValueAsBool(IFieldType fieldType) => Convert.ToBoolean(GetFieldValue(fieldType));
public Color GetFieldValueAsColor(IFieldType fieldType, Color defaultColor = default)
{
return (Color)(GetFieldValue(fieldType) ?? defaultColor);
}
public Color GetFieldValueAsColor(IFieldType fieldType, Color defaultColor = default) => (Color)(GetFieldValue(fieldType) ?? defaultColor);
public bool HasField(IFieldType fieldType)
{
return _fieldsByType.ContainsKey(fieldType);
}
public bool HasField(IFieldType fieldType) => _fieldsByType.ContainsKey(fieldType);
public bool HasFieldValue(IFieldType fieldType)
{
return HasField(fieldType) && _fieldsByType[fieldType].HasValue;
}
public bool HasFieldValue(IFieldType fieldType) => HasField(fieldType) && _fieldsByType[fieldType].HasValue;
public void SetFieldValue(IFieldType fieldType, object value)
{
@ -183,9 +144,6 @@ namespace Greenshot.Editor.Drawing.Fields
}
}
protected void OnFieldChanged(object sender, FieldChangedEventArgs e)
{
_fieldChanged?.Invoke(sender, e);
}
protected void OnFieldChanged(object sender, FieldChangedEventArgs e) => _fieldChanged?.Invoke(sender, e);
}
}

View file

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

View file

@ -28,15 +28,12 @@ namespace Greenshot.Editor.Drawing.Fields.Binding
/// </summary>
public abstract class AbstractBindingConverter<T1, T2> : IBindingConverter
{
public object convert(object o)
public object convert(object o) => o switch
{
return o switch
{
null => null,
T1 => convert((T1)o),
_ => o is T2 t ? (object)convert(t) : throw new ArgumentException("Cannot handle argument of type " + o.GetType())
};
}
null => null,
T1 => convert((T1)o),
_ => 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 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="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,
IBindingConverter converter) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName)
{
Converter = converter;
}
IBindingConverter converter) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) => Converter = converter;
/// <summary>
/// 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="validator">validator to intercept synchronization if the value does not match certain criteria</param>
public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName,
IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName)
{
_validator = validator;
}
IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName) => _validator = validator;
/// <summary>
/// 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="validator">validator to intercept synchronization if the value does not match certain criteria</param>
public BidirectionalBinding(INotifyPropertyChanged controlObject, string controlPropertyName, INotifyPropertyChanged fieldObject, string fieldPropertyName,
IBindingConverter converter, IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName, converter)
{
_validator = validator;
}
IBindingConverter converter, IBindingValidator validator) : this(controlObject, controlPropertyName, fieldObject, fieldPropertyName, converter) => _validator = validator;
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)
{
return Convert.ToDecimal(o) * 100;
}
protected override decimal convert(double o) => Convert.ToDecimal(o) * 100;
protected override double convert(decimal o)
{
return Convert.ToDouble(o) / 100;
}
protected override double convert(decimal o) => Convert.ToDouble(o) / 100;
public static DecimalDoublePercentageConverter GetInstance()
{
return _uniqueInstance ??= new DecimalDoublePercentageConverter();
}
public static DecimalDoublePercentageConverter GetInstance() => _uniqueInstance ??= new DecimalDoublePercentageConverter();
}
}

View file

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

View file

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

View file

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

View file

@ -44,7 +44,7 @@ namespace Greenshot.Editor.Drawing.Fields
if (!Equals(_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;
}
public Field(IFieldType fieldType)
{
FieldType = fieldType;
}
public Field(IFieldType fieldType) => FieldType = fieldType;
/// <summary>
/// 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.
/// </summary>
/// <returns></returns>
public Field Clone()
public Field Clone() => new(FieldType, Scope)
{
return new Field(FieldType, Scope)
{
Value = Value
};
}
Value = Value
};
public override int GetHashCode()
{
@ -110,14 +104,8 @@ namespace Greenshot.Editor.Drawing.Fields
return hashCode;
}
public override bool Equals(object obj)
{
return obj is Field other && FieldType == other.FieldType && Equals(Scope, other.Scope);
}
public override bool Equals(object obj) => obj is Field other && FieldType == other.FieldType && Equals(Scope, other.Scope);
public override string ToString()
{
return string.Format("[Field FieldType={1} Value={0} Scope={2}]", _myValue, FieldType, Scope);
}
public override string ToString() => string.Format("[Field FieldType={1} Value={0} Scope={2}]", _myValue, FieldType, Scope);
}
}

View file

@ -164,29 +164,26 @@ namespace Greenshot.Editor.Drawing.Fields
private IList<IField> FindCommonFields()
{
IList<IField> returnFields = null;
if (_boundContainers.Count > 0)
// take all fields from the least selected container...
if (_boundContainers.Count > 0 && _boundContainers[_boundContainers.Count - 1] is DrawableContainer leastSelectedContainer)
{
// take all fields from the least selected container...
if (_boundContainers[_boundContainers.Count - 1] is DrawableContainer leastSelectedContainer)
returnFields = leastSelectedContainer.GetFields();
for (int i = 0; i < _boundContainers.Count - 1; i++)
{
returnFields = leastSelectedContainer.GetFields();
for (int i = 0; i < _boundContainers.Count - 1; i++)
if (_boundContainers[i] is not DrawableContainer dc) continue;
IList<IField> fieldsToRemove = new List<IField>();
foreach (IField field in returnFields)
{
if (_boundContainers[i] is not DrawableContainer dc) continue;
IList<IField> fieldsToRemove = new List<IField>();
foreach (IField field in returnFields)
// ... throw out those that do not apply to one of the other containers
if (!dc.HasField(field.FieldType))
{
// ... throw out those that do not apply to one of the other containers
if (!dc.HasField(field.FieldType))
{
fieldsToRemove.Add(field);
}
fieldsToRemove.Add(field);
}
}
foreach (var field in fieldsToRemove)
{
returnFields.Remove(field);
}
foreach (var field in fieldsToRemove)
{
returnFields.Remove(field);
}
}
}

View file

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

View file

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

View file

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

View file

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

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